blob: 1710d2900385341d6a3245c8e024ae64f95a9c12 [file] [log] [blame]
Carmelo Cascone6b32c992016-04-13 11:53:09 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2016-present Open Networking Foundation
Carmelo Cascone6b32c992016-04-13 11:53:09 -07003 *
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/**
Carmelo Cascone8a571af2018-04-06 23:17:04 -070031 * Immutable sequence of bytes, assumed to represent a value in {@link
32 * ByteOrder#BIG_ENDIAN BIG_ENDIAN} order.
Carmelo Cascone6b32c992016-04-13 11:53:09 -070033 * <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
Carmelo Cascone8a571af2018-04-06 23:17:04 -070043 private enum BitwiseOp {
44 AND,
45 OR,
46 XOR
47 }
48
Carmelo Cascone6b32c992016-04-13 11:53:09 -070049 /*
50 Actual bytes are backed by a byte buffer.
51 The order of a newly-created byte buffer is always BIG_ENDIAN.
52 */
53 private ByteBuffer value;
Daniele Moro787a0642021-02-23 15:28:07 +010054 private boolean isAscii = false;
Carmelo Cascone6b32c992016-04-13 11:53:09 -070055
56 /**
Carmelo Cascone8a571af2018-04-06 23:17:04 -070057 * Private constructor. Creates a new byte sequence object backed by the
58 * passed ByteBuffer.
Carmelo Cascone6b32c992016-04-13 11:53:09 -070059 *
60 * @param value a byte buffer
61 */
62 private ImmutableByteSequence(ByteBuffer value) {
63 this.value = value;
64 // Rewind buffer so it's ready to be read.
65 // No write operation should be performed on it from now on.
66 this.value.rewind();
67 }
68
Daniele Moro787a0642021-02-23 15:28:07 +010069 private ImmutableByteSequence(ByteBuffer value, boolean isAscii) {
70 this(value);
71 this.isAscii = isAscii;
72 }
73
Carmelo Cascone6b32c992016-04-13 11:53:09 -070074 /**
75 * Creates a new immutable byte sequence with the same content and order of
76 * the passed byte array.
77 *
78 * @param original a byte array value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -070079 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -070080 */
81 public static ImmutableByteSequence copyFrom(byte[] original) {
82 checkArgument(original != null && original.length > 0,
83 "Cannot copy from an empty or null array");
84 return new ImmutableByteSequence(
85 ByteBuffer.allocate(original.length).put(original));
86 }
87
88 /**
Carmelo Cascone17fc9e42016-05-31 11:29:21 -070089 * Creates a new immutable byte sequence with the same content and order of
90 * the passed byte array, from/to the given indexes (inclusive).
91 *
92 * @param original a byte array value
Carmelo Casconeb10194c2017-08-23 19:16:51 +020093 * @param fromIdx starting index
94 * @param toIdx ending index
Carmelo Cascone17fc9e42016-05-31 11:29:21 -070095 * @return a new immutable byte sequence
96 */
97 public static ImmutableByteSequence copyFrom(byte[] original, int fromIdx, int toIdx) {
98 checkArgument(original != null && original.length > 0,
99 "Cannot copy from an empty or null array");
100 checkArgument(toIdx >= fromIdx && toIdx < original.length, "invalid indexes");
101 ByteBuffer buffer = ByteBuffer.allocate((toIdx - fromIdx) + 1);
102 for (int i = fromIdx; i <= toIdx; i++) {
103 buffer.put(original[i]);
104 }
105 return new ImmutableByteSequence(buffer);
106 }
107
108 /**
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700109 * Creates a new immutable byte sequence copying bytes from the given
110 * ByteBuffer {@link ByteBuffer}. If the byte buffer order is not big-endian
111 * bytes will be copied in reverse order.
112 *
113 * @param original a byte buffer
114 * @return a new byte buffer object
115 */
116 public static ImmutableByteSequence copyFrom(ByteBuffer original) {
117 checkArgument(original != null && original.capacity() > 0,
118 "Cannot copy from an empty or null byte buffer");
119
120 byte[] bytes = new byte[original.capacity()];
121
122 // copy bytes from original buffer
123 original.rewind();
124 original.get(bytes);
125
126 if (original.order() == ByteOrder.LITTLE_ENDIAN) {
127 // FIXME: this can be improved, e.g. read bytes in reverse order from original
128 reverse(bytes);
129 }
130
131 return new ImmutableByteSequence(ByteBuffer.wrap(bytes));
132 }
133
134 /**
Daniele Moro787a0642021-02-23 15:28:07 +0100135 * Creates a new immutable byte sequence from the given string.
136 *
137 * @param original a string
138 * @return a new byte buffer object
139 */
140 public static ImmutableByteSequence copyFrom(String original) {
141 checkArgument(original != null && original.length() > 0,
142 "Cannot copy from an empty or null string");
143 return new ImmutableByteSequence(ByteBuffer.allocate(original.length())
144 .put(original.getBytes()),
145 true);
146 }
147
148 /**
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700149 * Creates a new byte sequence of 8 bytes containing the given long value.
150 *
151 * @param original a long value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700152 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700153 */
154 public static ImmutableByteSequence copyFrom(long original) {
155 return new ImmutableByteSequence(
156 ByteBuffer.allocate(Long.BYTES).putLong(original));
157 }
158
159 /**
160 * Creates a new byte sequence of 4 bytes containing the given int value.
161 *
162 * @param original an int value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700163 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700164 */
165 public static ImmutableByteSequence copyFrom(int original) {
166 return new ImmutableByteSequence(
167 ByteBuffer.allocate(Integer.BYTES).putInt(original));
168 }
169
170 /**
171 * Creates a new byte sequence of 2 bytes containing the given short value.
172 *
173 * @param original a short value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700174 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700175 */
176 public static ImmutableByteSequence copyFrom(short original) {
177 return new ImmutableByteSequence(
178 ByteBuffer.allocate(Short.BYTES).putShort(original));
179 }
180
181 /**
182 * Creates a new byte sequence of 1 byte containing the given value.
183 *
184 * @param original a byte value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700185 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700186 */
187 public static ImmutableByteSequence copyFrom(byte original) {
188 return new ImmutableByteSequence(
189 ByteBuffer.allocate(Byte.BYTES).put(original));
190 }
191
192 /**
Brian O'Connoraf1d12e2017-08-17 12:21:48 -0700193 * Creates a new byte sequence of the given size where all bits are 0.
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700194 *
195 * @param size number of bytes
196 * @return a new immutable byte sequence
197 */
198 public static ImmutableByteSequence ofZeros(int size) {
Brian O'Connoraf1d12e2017-08-17 12:21:48 -0700199 // array is initialized to all 0's by default
200 return new ImmutableByteSequence(ByteBuffer.wrap(new byte[size]));
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700201 }
202
203 /**
Brian O'Connoraf1d12e2017-08-17 12:21:48 -0700204 * Creates a new byte sequence of the given size where all bits are 1.
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700205 *
206 * @param size number of bytes
207 * @return a new immutable byte sequence
208 */
209 public static ImmutableByteSequence ofOnes(int size) {
210 byte[] bytes = new byte[size];
211 Arrays.fill(bytes, (byte) 0xFF);
212 return new ImmutableByteSequence(ByteBuffer.wrap(bytes));
213 }
214
215 /**
Brian O'Connoraf1d12e2017-08-17 12:21:48 -0700216 * Creates a new byte sequence that is prefixed with specified number of
217 * zeros if val = 0 or ones if val = 0xff.
218 *
Carmelo Casconeb10194c2017-08-23 19:16:51 +0200219 * @param size number of total bytes
Brian O'Connoraf1d12e2017-08-17 12:21:48 -0700220 * @param prefixBits number of bits in prefix
Carmelo Casconeb10194c2017-08-23 19:16:51 +0200221 * @param val 0 for prefix of zeros; 0xff for prefix of ones
Brian O'Connoraf1d12e2017-08-17 12:21:48 -0700222 * @return new immutable byte sequence
223 */
224 static ImmutableByteSequence prefix(int size, long prefixBits, byte val) {
225 checkArgument(val == 0 || val == (byte) 0xff, "Val must be 0 or 0xff");
226 byte[] bytes = new byte[size];
227 int prefixBytes = (int) (prefixBits / Byte.SIZE);
228 Arrays.fill(bytes, 0, prefixBytes, val);
229 Arrays.fill(bytes, prefixBytes, bytes.length, (byte) ~val);
230 int partialBits = (int) (prefixBits % Byte.SIZE);
231 if (partialBits != 0) {
232 bytes[prefixBytes] = val == 0 ?
233 (byte) (0xff >> partialBits) : (byte) (0xff << Byte.SIZE - partialBits);
234 }
235 return new ImmutableByteSequence(ByteBuffer.wrap(bytes));
236 }
237
238 /**
Carmelo Cascone8a571af2018-04-06 23:17:04 -0700239 * Creates a new byte sequence that is prefixed with specified number of
240 * zeros.
Brian O'Connoraf1d12e2017-08-17 12:21:48 -0700241 *
Carmelo Casconeb10194c2017-08-23 19:16:51 +0200242 * @param size number of total bytes
Brian O'Connoraf1d12e2017-08-17 12:21:48 -0700243 * @param prefixBits number of bits in prefix
244 * @return new immutable byte sequence
245 */
246 public static ImmutableByteSequence prefixZeros(int size, long prefixBits) {
247 return prefix(size, prefixBits, (byte) 0);
248 }
249
250 /**
Carmelo Cascone8a571af2018-04-06 23:17:04 -0700251 * Creates a new byte sequence that is prefixed with specified number of
252 * ones.
Brian O'Connoraf1d12e2017-08-17 12:21:48 -0700253 *
Carmelo Casconeb10194c2017-08-23 19:16:51 +0200254 * @param size number of total bytes
Brian O'Connoraf1d12e2017-08-17 12:21:48 -0700255 * @param prefixBits number of bits in prefix
256 * @return new immutable byte sequence
257 */
258 public static ImmutableByteSequence prefixOnes(int size, long prefixBits) {
259 return prefix(size, prefixBits, (byte) 0xff);
260 }
261
262 /**
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700263 * Returns a view of this sequence as a read-only {@link ByteBuffer}.
264 * <p>
265 * The returned buffer will have position 0, while limit and capacity will
266 * be set to this sequence {@link #size()}. The buffer order will be
267 * big-endian.
268 *
269 * @return a read-only byte buffer
270 */
271 public ByteBuffer asReadOnlyBuffer() {
272 // position, limit and capacity set rewind at constructor
273 return value.asReadOnlyBuffer();
274 }
275
276 /**
277 * Gets the number of bytes in this sequence.
278 *
279 * @return an integer value
280 */
281 public int size() {
282 return this.value.capacity();
283 }
284
285 /**
286 * Creates a new byte array view of this sequence.
287 *
288 * @return a new byte array
289 */
290 public byte[] asArray() {
291 ByteBuffer bb = asReadOnlyBuffer();
292 byte[] bytes = new byte[size()];
293 bb.get(bytes);
294 return bytes;
295 }
296
Carmelo Cascone8a571af2018-04-06 23:17:04 -0700297 private ImmutableByteSequence doBitwiseOp(ImmutableByteSequence other, BitwiseOp op) {
298 checkArgument(other != null && this.size() == other.size(),
299 "Other sequence must be non null and with same size as this");
300 byte[] newBytes = new byte[this.size()];
301 byte[] thisBytes = this.asArray();
302 byte[] otherBytes = other.asArray();
303 for (int i = 0; i < this.size(); i++) {
304 switch (op) {
305 case AND:
306 newBytes[i] = (byte) (thisBytes[i] & otherBytes[i]);
307 break;
308 case OR:
309 newBytes[i] = (byte) (thisBytes[i] | otherBytes[i]);
310 break;
311 case XOR:
312 newBytes[i] = (byte) (thisBytes[i] ^ otherBytes[i]);
313 break;
314 default:
315 throw new IllegalArgumentException(
316 "Unknown bitwise operator " + op.name());
317 }
318 }
319 return ImmutableByteSequence.copyFrom(newBytes);
320 }
321
322 /**
323 * Returns a new byte sequence corresponding to the result of a bitwise AND
324 * operation between this sequence and the given other, i.e. {@code this &
325 * other}.
326 *
327 * @param other other byte sequence
328 * @return new byte sequence
329 * @throws IllegalArgumentException if other sequence is null or its size is
330 * different than this sequence size
331 */
332 public ImmutableByteSequence bitwiseAnd(ImmutableByteSequence other) {
333 return doBitwiseOp(other, BitwiseOp.AND);
334 }
335
336 /**
337 * Returns a new byte sequence corresponding to the result of a bitwise OR
338 * operation between this sequence and the given other, i.e. {@code this |
339 * other}.
340 *
341 * @param other other byte sequence
342 * @return new byte sequence
343 * @throws IllegalArgumentException if other sequence is null or its size is
344 * different than this sequence size
345 */
346 public ImmutableByteSequence bitwiseOr(ImmutableByteSequence other) {
347 return doBitwiseOp(other, BitwiseOp.OR);
348 }
349
350 /**
351 * Returns a new byte sequence corresponding to the result of a bitwise XOR
352 * operation between this sequence and the given other, i.e. {@code this ^
353 * other}.
354 *
355 * @param other other byte sequence
356 * @return new byte sequence
357 * @throws IllegalArgumentException if other sequence is null or its size is
358 * different than this sequence size
359 */
360 public ImmutableByteSequence bitwiseXor(ImmutableByteSequence other) {
361 return doBitwiseOp(other, BitwiseOp.XOR);
362 }
363
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700364 @Override
365 public int hashCode() {
366 return value.hashCode();
367 }
368
369 @Override
370 public boolean equals(Object obj) {
371 if (this == obj) {
372 return true;
373 }
374 if (obj == null || getClass() != obj.getClass()) {
375 return false;
376 }
377 final ImmutableByteSequence other = (ImmutableByteSequence) obj;
378 return Objects.equal(this.value, other.value);
379 }
380
Carmelo Casconeb10194c2017-08-23 19:16:51 +0200381 /**
Carmelo Cascone8a571af2018-04-06 23:17:04 -0700382 * Returns the index of the most significant bit (MSB), assuming a bit
383 * numbering scheme of type "LSB 0", i.e. the bit numbering starts at zero
384 * for the least significant bit (LSB). The MSB index of a byte sequence of
385 * zeros will be -1.
Carmelo Casconeb10194c2017-08-23 19:16:51 +0200386 * <p>
Carmelo Cascone8a571af2018-04-06 23:17:04 -0700387 * As an example, the following conditions always hold true: {@code
Carmelo Casconeb10194c2017-08-23 19:16:51 +0200388 * ImmutableByteSequence.copyFrom(0).msbIndex() == -1
389 * ImmutableByteSequence.copyFrom(1).msbIndex() == 0
390 * ImmutableByteSequence.copyFrom(2).msbIndex() == 1
391 * ImmutableByteSequence.copyFrom(3).msbIndex() == 1
392 * ImmutableByteSequence.copyFrom(4).msbIndex() == 2
Carmelo Cascone8a571af2018-04-06 23:17:04 -0700393 * ImmutableByteSequence.copyFrom(512).msbIndex() == 9 }
Carmelo Casconeb10194c2017-08-23 19:16:51 +0200394 *
395 * @return index of the MSB, -1 if the sequence has all bytes set to 0
396 */
397 public int msbIndex() {
398 int index = (size() * 8) - 1;
399 byteLoop:
400 for (int i = 0; i < size(); i++) {
401 byte b = value.get(i);
402 if (b != 0) {
403 for (int j = 7; j >= 0; j--) {
404 byte mask = (byte) ((1 << j) - 1);
405 if ((b & ~mask) != 0) {
406 break byteLoop;
407 }
408 index--;
409 }
410 }
411 index -= 8;
412 }
413 return index;
414 }
415
Carmelo Casconeb5324e72018-11-25 02:26:32 -0800416 /**
Daniele Moro787a0642021-02-23 15:28:07 +0100417 * Returns the ASCII representation of the byte sequence if the content can
418 * be interpreted as an ASCII string, otherwise returns the hexadecimal
419 * representation of this byte sequence, e.g.0xbeef. The length of the
420 * returned string is not representative of the length of the byte sequence,
421 * as all padding zeros are removed.
Carmelo Casconeb5324e72018-11-25 02:26:32 -0800422 *
423 * @return hexadecimal representation
424 */
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700425 @Override
426 public String toString() {
Daniele Moro787a0642021-02-23 15:28:07 +0100427 if (this.isAscii()) {
428 return new String(value.array());
429 } else {
430 return "0x" + HexString
431 .toHexString(value.array(), "")
432 // Remove leading zeros, but leave one if string is all zeros.
433 .replaceFirst("^0+(?!$)", "");
434 }
435 }
436
437 /**
438 * Checks if the content can be interpreted as an ASCII printable string.
439 *
440 * @return True if the content can be interpreted as an ASCII printable
441 * string, false otherwise
442 */
443 public boolean isAscii() {
444 return isAscii;
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700445 }
Carmelo Cascone00a59962017-06-16 17:51:49 +0900446
447 /**
Carmelo Cascone8a571af2018-04-06 23:17:04 -0700448 * Trims or expands a copy of this byte sequence so to fit the given
449 * bit-width. When trimming, the operations is deemed to be safe only if the
450 * trimmed bits are zero, i.e. it is safe to trim only when {@code bitWidth
451 * > msbIndex()}, otherwise an exception will be thrown. When expanding, the
452 * sequence will be padded with zeros. The returned byte sequence will have
453 * minimum size to contain the given bit-width.
454 *
455 * @param bitWidth a non-zero positive integer
456 * @return a new byte sequence
457 * @throws ByteSequenceTrimException if the byte sequence cannot be fitted
458 */
459 public ImmutableByteSequence fit(int bitWidth) throws ByteSequenceTrimException {
460 return doFit(this, bitWidth);
461 }
462
Carmelo Cascone8a571af2018-04-06 23:17:04 -0700463 private static ImmutableByteSequence doFit(ImmutableByteSequence original,
464 int bitWidth)
Carmelo Cascone00a59962017-06-16 17:51:49 +0900465 throws ByteSequenceTrimException {
466
467 checkNotNull(original, "byte sequence cannot be null");
468 checkArgument(bitWidth > 0, "bit-width must be a non-zero positive integer");
469
Daniele Moro6b195682021-05-18 12:20:46 +0200470 int newByteWidth = (bitWidth + 7) / 8;
Carmelo Cascone00a59962017-06-16 17:51:49 +0900471
Carmelo Casconeb10194c2017-08-23 19:16:51 +0200472 if (bitWidth == original.size() * 8) {
473 // No need to fit.
474 return original;
475 }
476
477 ByteBuffer newBuffer = ByteBuffer.allocate(newByteWidth);
Carmelo Cascone00a59962017-06-16 17:51:49 +0900478
479 if (newByteWidth > original.size()) {
Carmelo Casconeb10194c2017-08-23 19:16:51 +0200480 // Pad extra bytes with 0's.
481 int numPadBytes = newByteWidth - original.size();
482 for (int i = 0; i < numPadBytes; i++) {
483 newBuffer.put((byte) 0x00);
484 }
485 newBuffer.put(original.asReadOnlyBuffer());
486 } else {
487 // Trim sequence.
488 if (bitWidth > original.msbIndex()) {
489 int diff = original.size() - newByteWidth;
490 ByteBuffer originalBuffer = original.asReadOnlyBuffer();
491 for (int i = diff; i < original.size(); i++) {
492 newBuffer.put(originalBuffer.get(i));
Carmelo Cascone00a59962017-06-16 17:51:49 +0900493 }
494 } else {
Carmelo Casconeb10194c2017-08-23 19:16:51 +0200495 throw new ByteSequenceTrimException(original, bitWidth);
Carmelo Cascone00a59962017-06-16 17:51:49 +0900496 }
Carmelo Cascone00a59962017-06-16 17:51:49 +0900497 }
498
Carmelo Casconeb10194c2017-08-23 19:16:51 +0200499 return new ImmutableByteSequence(newBuffer);
Carmelo Cascone00a59962017-06-16 17:51:49 +0900500 }
501
502 /**
503 * Signals that a byte sequence cannot be trimmed.
504 */
505 public static class ByteSequenceTrimException extends Exception {
Carmelo Casconeb10194c2017-08-23 19:16:51 +0200506 ByteSequenceTrimException(ImmutableByteSequence original, int bitWidth) {
507 super(format("cannot trim %s into a %d bits long value",
508 original, bitWidth));
Carmelo Cascone00a59962017-06-16 17:51:49 +0900509 }
510 }
Ray Milkeybb23e0b2016-08-02 17:00:21 -0700511}