blob: 1db1d666d4a1030e7b324a21ade097f7cf1b25df [file] [log] [blame]
Carmelo Cascone6b32c992016-04-13 11:53:09 -07001/*
2 * Copyright 2016-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onlab.util;
18
Carmelo Cascone6b32c992016-04-13 11:53:09 -070019import com.google.common.base.Objects;
20
21import java.nio.ByteBuffer;
22import java.nio.ByteOrder;
Carmelo Casconeaa8b6292016-04-13 14:27:06 -070023import java.util.Arrays;
Carmelo Cascone6b32c992016-04-13 11:53:09 -070024
25import static com.google.common.base.Preconditions.checkArgument;
Carmelo Cascone00a59962017-06-16 17:51:49 +090026import static com.google.common.base.Preconditions.checkNotNull;
27import static java.lang.String.format;
Carmelo Cascone6b32c992016-04-13 11:53:09 -070028import static org.apache.commons.lang3.ArrayUtils.reverse;
29
30/**
31 * Immutable sequence of bytes, assumed to represent a value in
32 * {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN} order.
33 * <p>
34 * Sequences can be created copying from an already existing representation of a
35 * sequence of bytes, such as {@link ByteBuffer} or {@code byte[]}; or by
36 * copying bytes from a primitive data type, such as {@code long}, {@code int}
37 * or {@code short}. In the first case, bytes are assumed to be already given in
38 * big-endian order, while in the second case big-endianness is enforced by this
39 * class.
40 */
41public final class ImmutableByteSequence {
42
43 /*
44 Actual bytes are backed by a byte buffer.
45 The order of a newly-created byte buffer is always BIG_ENDIAN.
46 */
47 private ByteBuffer value;
48
49 /**
50 * Private constructor.
51 * Creates a new byte sequence object backed by the passed ByteBuffer.
52 *
53 * @param value a byte buffer
54 */
55 private ImmutableByteSequence(ByteBuffer value) {
56 this.value = value;
57 // Rewind buffer so it's ready to be read.
58 // No write operation should be performed on it from now on.
59 this.value.rewind();
60 }
61
62 /**
63 * Creates a new immutable byte sequence with the same content and order of
64 * the passed byte array.
65 *
66 * @param original a byte array value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -070067 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -070068 */
69 public static ImmutableByteSequence copyFrom(byte[] original) {
70 checkArgument(original != null && original.length > 0,
71 "Cannot copy from an empty or null array");
72 return new ImmutableByteSequence(
73 ByteBuffer.allocate(original.length).put(original));
74 }
75
76 /**
Carmelo Cascone17fc9e42016-05-31 11:29:21 -070077 * Creates a new immutable byte sequence with the same content and order of
78 * the passed byte array, from/to the given indexes (inclusive).
79 *
80 * @param original a byte array value
Ray Milkeybb23e0b2016-08-02 17:00:21 -070081 * @param fromIdx starting index
82 * @param toIdx ending index
Carmelo Cascone17fc9e42016-05-31 11:29:21 -070083 * @return a new immutable byte sequence
84 */
85 public static ImmutableByteSequence copyFrom(byte[] original, int fromIdx, int toIdx) {
86 checkArgument(original != null && original.length > 0,
87 "Cannot copy from an empty or null array");
88 checkArgument(toIdx >= fromIdx && toIdx < original.length, "invalid indexes");
89 ByteBuffer buffer = ByteBuffer.allocate((toIdx - fromIdx) + 1);
90 for (int i = fromIdx; i <= toIdx; i++) {
91 buffer.put(original[i]);
92 }
93 return new ImmutableByteSequence(buffer);
94 }
95
96 /**
Carmelo Cascone6b32c992016-04-13 11:53:09 -070097 * Creates a new immutable byte sequence copying bytes from the given
98 * ByteBuffer {@link ByteBuffer}. If the byte buffer order is not big-endian
99 * bytes will be copied in reverse order.
100 *
101 * @param original a byte buffer
102 * @return a new byte buffer object
103 */
104 public static ImmutableByteSequence copyFrom(ByteBuffer original) {
105 checkArgument(original != null && original.capacity() > 0,
106 "Cannot copy from an empty or null byte buffer");
107
108 byte[] bytes = new byte[original.capacity()];
109
110 // copy bytes from original buffer
111 original.rewind();
112 original.get(bytes);
113
114 if (original.order() == ByteOrder.LITTLE_ENDIAN) {
115 // FIXME: this can be improved, e.g. read bytes in reverse order from original
116 reverse(bytes);
117 }
118
119 return new ImmutableByteSequence(ByteBuffer.wrap(bytes));
120 }
121
122 /**
123 * Creates a new byte sequence of 8 bytes containing the given long value.
124 *
125 * @param original a long value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700126 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700127 */
128 public static ImmutableByteSequence copyFrom(long original) {
129 return new ImmutableByteSequence(
130 ByteBuffer.allocate(Long.BYTES).putLong(original));
131 }
132
133 /**
134 * Creates a new byte sequence of 4 bytes containing the given int value.
135 *
136 * @param original an int value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700137 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700138 */
139 public static ImmutableByteSequence copyFrom(int original) {
140 return new ImmutableByteSequence(
141 ByteBuffer.allocate(Integer.BYTES).putInt(original));
142 }
143
144 /**
145 * Creates a new byte sequence of 2 bytes containing the given short value.
146 *
147 * @param original a short value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700148 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700149 */
150 public static ImmutableByteSequence copyFrom(short original) {
151 return new ImmutableByteSequence(
152 ByteBuffer.allocate(Short.BYTES).putShort(original));
153 }
154
155 /**
156 * Creates a new byte sequence of 1 byte containing the given value.
157 *
158 * @param original a byte value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700159 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700160 */
161 public static ImmutableByteSequence copyFrom(byte original) {
162 return new ImmutableByteSequence(
163 ByteBuffer.allocate(Byte.BYTES).put(original));
164 }
165
166 /**
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700167 * Creates a new byte sequence of the given size where alla bits are 0.
168 *
169 * @param size number of bytes
170 * @return a new immutable byte sequence
171 */
172 public static ImmutableByteSequence ofZeros(int size) {
173 byte[] bytes = new byte[size];
174 Arrays.fill(bytes, (byte) 0);
175 return new ImmutableByteSequence(ByteBuffer.wrap(bytes));
176 }
177
178 /**
179 * Creates a new byte sequence of the given size where alla bits are 1.
180 *
181 * @param size number of bytes
182 * @return a new immutable byte sequence
183 */
184 public static ImmutableByteSequence ofOnes(int size) {
185 byte[] bytes = new byte[size];
186 Arrays.fill(bytes, (byte) 0xFF);
187 return new ImmutableByteSequence(ByteBuffer.wrap(bytes));
188 }
189
190 /**
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700191 * Returns a view of this sequence as a read-only {@link ByteBuffer}.
192 * <p>
193 * The returned buffer will have position 0, while limit and capacity will
194 * be set to this sequence {@link #size()}. The buffer order will be
195 * big-endian.
196 *
197 * @return a read-only byte buffer
198 */
199 public ByteBuffer asReadOnlyBuffer() {
200 // position, limit and capacity set rewind at constructor
201 return value.asReadOnlyBuffer();
202 }
203
204 /**
205 * Gets the number of bytes in this sequence.
206 *
207 * @return an integer value
208 */
209 public int size() {
210 return this.value.capacity();
211 }
212
213 /**
214 * Creates a new byte array view of this sequence.
215 *
216 * @return a new byte array
217 */
218 public byte[] asArray() {
219 ByteBuffer bb = asReadOnlyBuffer();
220 byte[] bytes = new byte[size()];
221 bb.get(bytes);
222 return bytes;
223 }
224
225 @Override
226 public int hashCode() {
227 return value.hashCode();
228 }
229
230 @Override
231 public boolean equals(Object obj) {
232 if (this == obj) {
233 return true;
234 }
235 if (obj == null || getClass() != obj.getClass()) {
236 return false;
237 }
238 final ImmutableByteSequence other = (ImmutableByteSequence) obj;
239 return Objects.equal(this.value, other.value);
240 }
241
242 @Override
243 public String toString() {
Carmelo Cascone804c0012016-06-23 13:05:40 -0700244 return HexString.toHexString(value.array());
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700245 }
Carmelo Cascone00a59962017-06-16 17:51:49 +0900246
247 /**
248 * Trims or expands the given byte sequence so to fit a given bit-width. When trimming, the
249 * operations is deemed to be safe only if the trimmed bits are zero, otherwise an exception
250 * will be thrown. When expanding, the sequence will be padded with zeros. The returned byte
251 * sequence will have minimum size to contain the given bit-width.
252 *
253 * @param original a byte sequence
254 * @param bitWidth a non-zero positive integer
255 * @return a new byte sequence
256 * @throws ByteSequenceTrimException if the byte sequence cannot be fitted
257 */
258 public static ImmutableByteSequence fit(ImmutableByteSequence original, int bitWidth)
259 throws ByteSequenceTrimException {
260
261 checkNotNull(original, "byte sequence cannot be null");
262 checkArgument(bitWidth > 0, "bit-width must be a non-zero positive integer");
263
264 int newByteWidth = (int) Math.ceil((double) bitWidth / 8);
265
266 byte[] originalBytes = original.asArray();
267
268 if (newByteWidth > original.size()) {
269 // pad missing bytes with zeros
270 return ImmutableByteSequence.copyFrom(Arrays.copyOf(originalBytes, newByteWidth));
271 }
272
273 byte[] newBytes = new byte[newByteWidth];
274 // ImmutableByteSequence is always big-endian, hence check the array in reverse order
275 int diff = originalBytes.length - newByteWidth;
276 for (int i = originalBytes.length - 1; i >= 0; i--) {
277 byte ob = originalBytes[i]; // original byte
278 byte nb; // new byte
279 if (i > diff) {
280 // no need to truncate, copy as is
281 nb = ob;
282 } else if (i == diff) {
283 // truncate this byte, check if we're loosing something
284 byte mask = (byte) ((1 >> ((bitWidth % 8) + 1)) - 1);
285 if ((ob & ~mask) != 0) {
286 throw new ByteSequenceTrimException(originalBytes, bitWidth);
287 } else {
288 nb = (byte) (ob & mask);
289 }
290 } else {
291 // drop this byte, check if we're loosing something
292 if (originalBytes[i] != 0) {
293 throw new ByteSequenceTrimException(originalBytes, bitWidth);
294 } else {
295 continue;
296 }
297 }
298 newBytes[i - diff] = nb;
299 }
300
301 return ImmutableByteSequence.copyFrom(newBytes);
302 }
303
304 /**
305 * Signals that a byte sequence cannot be trimmed.
306 */
307 public static class ByteSequenceTrimException extends Exception {
308 ByteSequenceTrimException(byte[] bytes, int bitWidth) {
309 super(format("cannot trim %s into a %d long bits value",
310 HexString.toHexString(bytes), bitWidth));
311 }
312 }
Ray Milkeybb23e0b2016-08-02 17:00:21 -0700313}