Carmelo Cascone | 6b32c99 | 2016-04-13 11:53:09 -0700 | [diff] [blame] | 1 | /* |
Brian O'Connor | a09fe5b | 2017-08-03 21:12:30 -0700 | [diff] [blame] | 2 | * Copyright 2016-present Open Networking Foundation |
Carmelo Cascone | 6b32c99 | 2016-04-13 11:53:09 -0700 | [diff] [blame] | 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 | |
| 17 | package org.onlab.util; |
| 18 | |
Carmelo Cascone | 6b32c99 | 2016-04-13 11:53:09 -0700 | [diff] [blame] | 19 | import com.google.common.base.Objects; |
| 20 | |
| 21 | import java.nio.ByteBuffer; |
| 22 | import java.nio.ByteOrder; |
Carmelo Cascone | aa8b629 | 2016-04-13 14:27:06 -0700 | [diff] [blame] | 23 | import java.util.Arrays; |
Carmelo Cascone | 6b32c99 | 2016-04-13 11:53:09 -0700 | [diff] [blame] | 24 | |
| 25 | import static com.google.common.base.Preconditions.checkArgument; |
Carmelo Cascone | 00a5996 | 2017-06-16 17:51:49 +0900 | [diff] [blame] | 26 | import static com.google.common.base.Preconditions.checkNotNull; |
| 27 | import static java.lang.String.format; |
Carmelo Cascone | 6b32c99 | 2016-04-13 11:53:09 -0700 | [diff] [blame] | 28 | import 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 | */ |
| 41 | public 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 Cascone | aa8b629 | 2016-04-13 14:27:06 -0700 | [diff] [blame] | 67 | * @return a new immutable byte sequence |
Carmelo Cascone | 6b32c99 | 2016-04-13 11:53:09 -0700 | [diff] [blame] | 68 | */ |
| 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 Cascone | 17fc9e4 | 2016-05-31 11:29:21 -0700 | [diff] [blame] | 77 | * 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 Milkey | bb23e0b | 2016-08-02 17:00:21 -0700 | [diff] [blame] | 81 | * @param fromIdx starting index |
| 82 | * @param toIdx ending index |
Carmelo Cascone | 17fc9e4 | 2016-05-31 11:29:21 -0700 | [diff] [blame] | 83 | * @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 Cascone | 6b32c99 | 2016-04-13 11:53:09 -0700 | [diff] [blame] | 97 | * 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 Cascone | aa8b629 | 2016-04-13 14:27:06 -0700 | [diff] [blame] | 126 | * @return a new immutable byte sequence |
Carmelo Cascone | 6b32c99 | 2016-04-13 11:53:09 -0700 | [diff] [blame] | 127 | */ |
| 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 Cascone | aa8b629 | 2016-04-13 14:27:06 -0700 | [diff] [blame] | 137 | * @return a new immutable byte sequence |
Carmelo Cascone | 6b32c99 | 2016-04-13 11:53:09 -0700 | [diff] [blame] | 138 | */ |
| 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 Cascone | aa8b629 | 2016-04-13 14:27:06 -0700 | [diff] [blame] | 148 | * @return a new immutable byte sequence |
Carmelo Cascone | 6b32c99 | 2016-04-13 11:53:09 -0700 | [diff] [blame] | 149 | */ |
| 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 Cascone | aa8b629 | 2016-04-13 14:27:06 -0700 | [diff] [blame] | 159 | * @return a new immutable byte sequence |
Carmelo Cascone | 6b32c99 | 2016-04-13 11:53:09 -0700 | [diff] [blame] | 160 | */ |
| 161 | public static ImmutableByteSequence copyFrom(byte original) { |
| 162 | return new ImmutableByteSequence( |
| 163 | ByteBuffer.allocate(Byte.BYTES).put(original)); |
| 164 | } |
| 165 | |
| 166 | /** |
Brian O'Connor | 6489385 | 2017-08-17 12:21:48 -0700 | [diff] [blame] | 167 | * Creates a new byte sequence of the given size where all bits are 0. |
Carmelo Cascone | aa8b629 | 2016-04-13 14:27:06 -0700 | [diff] [blame] | 168 | * |
| 169 | * @param size number of bytes |
| 170 | * @return a new immutable byte sequence |
| 171 | */ |
| 172 | public static ImmutableByteSequence ofZeros(int size) { |
Brian O'Connor | 6489385 | 2017-08-17 12:21:48 -0700 | [diff] [blame] | 173 | // array is initialized to all 0's by default |
| 174 | return new ImmutableByteSequence(ByteBuffer.wrap(new byte[size])); |
Carmelo Cascone | aa8b629 | 2016-04-13 14:27:06 -0700 | [diff] [blame] | 175 | } |
| 176 | |
| 177 | /** |
Brian O'Connor | 6489385 | 2017-08-17 12:21:48 -0700 | [diff] [blame] | 178 | * Creates a new byte sequence of the given size where all bits are 1. |
Carmelo Cascone | aa8b629 | 2016-04-13 14:27:06 -0700 | [diff] [blame] | 179 | * |
| 180 | * @param size number of bytes |
| 181 | * @return a new immutable byte sequence |
| 182 | */ |
| 183 | public static ImmutableByteSequence ofOnes(int size) { |
| 184 | byte[] bytes = new byte[size]; |
| 185 | Arrays.fill(bytes, (byte) 0xFF); |
| 186 | return new ImmutableByteSequence(ByteBuffer.wrap(bytes)); |
| 187 | } |
| 188 | |
| 189 | /** |
Brian O'Connor | 6489385 | 2017-08-17 12:21:48 -0700 | [diff] [blame] | 190 | * Creates a new byte sequence that is prefixed with specified number of |
| 191 | * zeros if val = 0 or ones if val = 0xff. |
| 192 | * |
| 193 | * @param size number of total bytes |
| 194 | * @param prefixBits number of bits in prefix |
| 195 | * @param val 0 for prefix of zeros; 0xff for prefix of ones |
| 196 | * @return new immutable byte sequence |
| 197 | */ |
| 198 | static ImmutableByteSequence prefix(int size, long prefixBits, byte val) { |
| 199 | checkArgument(val == 0 || val == (byte) 0xff, "Val must be 0 or 0xff"); |
| 200 | byte[] bytes = new byte[size]; |
| 201 | int prefixBytes = (int) (prefixBits / Byte.SIZE); |
| 202 | Arrays.fill(bytes, 0, prefixBytes, val); |
| 203 | Arrays.fill(bytes, prefixBytes, bytes.length, (byte) ~val); |
| 204 | int partialBits = (int) (prefixBits % Byte.SIZE); |
| 205 | if (partialBits != 0) { |
| 206 | bytes[prefixBytes] = val == 0 ? |
| 207 | (byte) (0xff >> partialBits) : (byte) (0xff << Byte.SIZE - partialBits); |
| 208 | } |
| 209 | return new ImmutableByteSequence(ByteBuffer.wrap(bytes)); |
| 210 | } |
| 211 | |
| 212 | /** |
| 213 | * Creates a new byte sequence that is prefixed with specified number of zeros. |
| 214 | * |
| 215 | * @param size number of total bytes |
| 216 | * @param prefixBits number of bits in prefix |
| 217 | * @return new immutable byte sequence |
| 218 | */ |
| 219 | public static ImmutableByteSequence prefixZeros(int size, long prefixBits) { |
| 220 | return prefix(size, prefixBits, (byte) 0); |
| 221 | } |
| 222 | |
| 223 | /** |
| 224 | * Creates a new byte sequence that is prefixed with specified number of ones. |
| 225 | * |
| 226 | * @param size number of total bytes |
| 227 | * @param prefixBits number of bits in prefix |
| 228 | * @return new immutable byte sequence |
| 229 | */ |
| 230 | public static ImmutableByteSequence prefixOnes(int size, long prefixBits) { |
| 231 | return prefix(size, prefixBits, (byte) 0xff); |
| 232 | } |
| 233 | |
| 234 | /** |
Carmelo Cascone | 6b32c99 | 2016-04-13 11:53:09 -0700 | [diff] [blame] | 235 | * Returns a view of this sequence as a read-only {@link ByteBuffer}. |
| 236 | * <p> |
| 237 | * The returned buffer will have position 0, while limit and capacity will |
| 238 | * be set to this sequence {@link #size()}. The buffer order will be |
| 239 | * big-endian. |
| 240 | * |
| 241 | * @return a read-only byte buffer |
| 242 | */ |
| 243 | public ByteBuffer asReadOnlyBuffer() { |
| 244 | // position, limit and capacity set rewind at constructor |
| 245 | return value.asReadOnlyBuffer(); |
| 246 | } |
| 247 | |
| 248 | /** |
| 249 | * Gets the number of bytes in this sequence. |
| 250 | * |
| 251 | * @return an integer value |
| 252 | */ |
| 253 | public int size() { |
| 254 | return this.value.capacity(); |
| 255 | } |
| 256 | |
| 257 | /** |
| 258 | * Creates a new byte array view of this sequence. |
| 259 | * |
| 260 | * @return a new byte array |
| 261 | */ |
| 262 | public byte[] asArray() { |
| 263 | ByteBuffer bb = asReadOnlyBuffer(); |
| 264 | byte[] bytes = new byte[size()]; |
| 265 | bb.get(bytes); |
| 266 | return bytes; |
| 267 | } |
| 268 | |
| 269 | @Override |
| 270 | public int hashCode() { |
| 271 | return value.hashCode(); |
| 272 | } |
| 273 | |
| 274 | @Override |
| 275 | public boolean equals(Object obj) { |
| 276 | if (this == obj) { |
| 277 | return true; |
| 278 | } |
| 279 | if (obj == null || getClass() != obj.getClass()) { |
| 280 | return false; |
| 281 | } |
| 282 | final ImmutableByteSequence other = (ImmutableByteSequence) obj; |
| 283 | return Objects.equal(this.value, other.value); |
| 284 | } |
| 285 | |
| 286 | @Override |
| 287 | public String toString() { |
Carmelo Cascone | 804c001 | 2016-06-23 13:05:40 -0700 | [diff] [blame] | 288 | return HexString.toHexString(value.array()); |
Carmelo Cascone | 6b32c99 | 2016-04-13 11:53:09 -0700 | [diff] [blame] | 289 | } |
Carmelo Cascone | 00a5996 | 2017-06-16 17:51:49 +0900 | [diff] [blame] | 290 | |
| 291 | /** |
| 292 | * Trims or expands the given byte sequence so to fit a given bit-width. When trimming, the |
| 293 | * operations is deemed to be safe only if the trimmed bits are zero, otherwise an exception |
| 294 | * will be thrown. When expanding, the sequence will be padded with zeros. The returned byte |
| 295 | * sequence will have minimum size to contain the given bit-width. |
| 296 | * |
| 297 | * @param original a byte sequence |
| 298 | * @param bitWidth a non-zero positive integer |
| 299 | * @return a new byte sequence |
| 300 | * @throws ByteSequenceTrimException if the byte sequence cannot be fitted |
| 301 | */ |
| 302 | public static ImmutableByteSequence fit(ImmutableByteSequence original, int bitWidth) |
| 303 | throws ByteSequenceTrimException { |
| 304 | |
| 305 | checkNotNull(original, "byte sequence cannot be null"); |
| 306 | checkArgument(bitWidth > 0, "bit-width must be a non-zero positive integer"); |
| 307 | |
| 308 | int newByteWidth = (int) Math.ceil((double) bitWidth / 8); |
| 309 | |
| 310 | byte[] originalBytes = original.asArray(); |
| 311 | |
| 312 | if (newByteWidth > original.size()) { |
| 313 | // pad missing bytes with zeros |
| 314 | return ImmutableByteSequence.copyFrom(Arrays.copyOf(originalBytes, newByteWidth)); |
| 315 | } |
| 316 | |
| 317 | byte[] newBytes = new byte[newByteWidth]; |
| 318 | // ImmutableByteSequence is always big-endian, hence check the array in reverse order |
| 319 | int diff = originalBytes.length - newByteWidth; |
| 320 | for (int i = originalBytes.length - 1; i >= 0; i--) { |
| 321 | byte ob = originalBytes[i]; // original byte |
| 322 | byte nb; // new byte |
| 323 | if (i > diff) { |
| 324 | // no need to truncate, copy as is |
| 325 | nb = ob; |
| 326 | } else if (i == diff) { |
| 327 | // truncate this byte, check if we're loosing something |
| 328 | byte mask = (byte) ((1 >> ((bitWidth % 8) + 1)) - 1); |
| 329 | if ((ob & ~mask) != 0) { |
| 330 | throw new ByteSequenceTrimException(originalBytes, bitWidth); |
| 331 | } else { |
| 332 | nb = (byte) (ob & mask); |
| 333 | } |
| 334 | } else { |
| 335 | // drop this byte, check if we're loosing something |
| 336 | if (originalBytes[i] != 0) { |
| 337 | throw new ByteSequenceTrimException(originalBytes, bitWidth); |
| 338 | } else { |
| 339 | continue; |
| 340 | } |
| 341 | } |
| 342 | newBytes[i - diff] = nb; |
| 343 | } |
| 344 | |
| 345 | return ImmutableByteSequence.copyFrom(newBytes); |
| 346 | } |
| 347 | |
| 348 | /** |
| 349 | * Signals that a byte sequence cannot be trimmed. |
| 350 | */ |
| 351 | public static class ByteSequenceTrimException extends Exception { |
| 352 | ByteSequenceTrimException(byte[] bytes, int bitWidth) { |
| 353 | super(format("cannot trim %s into a %d long bits value", |
| 354 | HexString.toHexString(bytes), bitWidth)); |
| 355 | } |
| 356 | } |
Ray Milkey | bb23e0b | 2016-08-02 17:00:21 -0700 | [diff] [blame] | 357 | } |