blob: f5f9a599e01f90a6ee203d2cac8bd0243e6af917 [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
19import com.google.common.base.MoreObjects;
20import com.google.common.base.Objects;
21
22import java.nio.ByteBuffer;
23import java.nio.ByteOrder;
Carmelo Casconeaa8b6292016-04-13 14:27:06 -070024import java.util.Arrays;
Carmelo Cascone6b32c992016-04-13 11:53:09 -070025
26import static com.google.common.base.Preconditions.checkArgument;
27import static org.apache.commons.lang3.ArrayUtils.reverse;
28
29/**
30 * Immutable sequence of bytes, assumed to represent a value in
31 * {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN} order.
32 * <p>
33 * Sequences can be created copying from an already existing representation of a
34 * sequence of bytes, such as {@link ByteBuffer} or {@code byte[]}; or by
35 * copying bytes from a primitive data type, such as {@code long}, {@code int}
36 * or {@code short}. In the first case, bytes are assumed to be already given in
37 * big-endian order, while in the second case big-endianness is enforced by this
38 * class.
39 */
40public final class ImmutableByteSequence {
41
42 /*
43 Actual bytes are backed by a byte buffer.
44 The order of a newly-created byte buffer is always BIG_ENDIAN.
45 */
46 private ByteBuffer value;
47
48 /**
49 * Private constructor.
50 * Creates a new byte sequence object backed by the passed ByteBuffer.
51 *
52 * @param value a byte buffer
53 */
54 private ImmutableByteSequence(ByteBuffer value) {
55 this.value = value;
56 // Rewind buffer so it's ready to be read.
57 // No write operation should be performed on it from now on.
58 this.value.rewind();
59 }
60
61 /**
62 * Creates a new immutable byte sequence with the same content and order of
63 * the passed byte array.
64 *
65 * @param original a byte array value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -070066 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -070067 */
68 public static ImmutableByteSequence copyFrom(byte[] original) {
69 checkArgument(original != null && original.length > 0,
70 "Cannot copy from an empty or null array");
71 return new ImmutableByteSequence(
72 ByteBuffer.allocate(original.length).put(original));
73 }
74
75 /**
Carmelo Cascone54650342016-05-31 11:29:21 -070076 * Creates a new immutable byte sequence with the same content and order of
77 * the passed byte array, from/to the given indexes (inclusive).
78 *
79 * @param original a byte array value
80 * @return a new immutable byte sequence
81 */
82 public static ImmutableByteSequence copyFrom(byte[] original, int fromIdx, int toIdx) {
83 checkArgument(original != null && original.length > 0,
84 "Cannot copy from an empty or null array");
85 checkArgument(toIdx >= fromIdx && toIdx < original.length, "invalid indexes");
86 ByteBuffer buffer = ByteBuffer.allocate((toIdx - fromIdx) + 1);
87 for (int i = fromIdx; i <= toIdx; i++) {
88 buffer.put(original[i]);
89 }
90 return new ImmutableByteSequence(buffer);
91 }
92
93 /**
Carmelo Cascone6b32c992016-04-13 11:53:09 -070094 * Creates a new immutable byte sequence copying bytes from the given
95 * ByteBuffer {@link ByteBuffer}. If the byte buffer order is not big-endian
96 * bytes will be copied in reverse order.
97 *
98 * @param original a byte buffer
99 * @return a new byte buffer object
100 */
101 public static ImmutableByteSequence copyFrom(ByteBuffer original) {
102 checkArgument(original != null && original.capacity() > 0,
103 "Cannot copy from an empty or null byte buffer");
104
105 byte[] bytes = new byte[original.capacity()];
106
107 // copy bytes from original buffer
108 original.rewind();
109 original.get(bytes);
110
111 if (original.order() == ByteOrder.LITTLE_ENDIAN) {
112 // FIXME: this can be improved, e.g. read bytes in reverse order from original
113 reverse(bytes);
114 }
115
116 return new ImmutableByteSequence(ByteBuffer.wrap(bytes));
117 }
118
119 /**
120 * Creates a new byte sequence of 8 bytes containing the given long value.
121 *
122 * @param original a long value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700123 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700124 */
125 public static ImmutableByteSequence copyFrom(long original) {
126 return new ImmutableByteSequence(
127 ByteBuffer.allocate(Long.BYTES).putLong(original));
128 }
129
130 /**
131 * Creates a new byte sequence of 4 bytes containing the given int value.
132 *
133 * @param original an int value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700134 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700135 */
136 public static ImmutableByteSequence copyFrom(int original) {
137 return new ImmutableByteSequence(
138 ByteBuffer.allocate(Integer.BYTES).putInt(original));
139 }
140
141 /**
142 * Creates a new byte sequence of 2 bytes containing the given short value.
143 *
144 * @param original a short value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700145 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700146 */
147 public static ImmutableByteSequence copyFrom(short original) {
148 return new ImmutableByteSequence(
149 ByteBuffer.allocate(Short.BYTES).putShort(original));
150 }
151
152 /**
153 * Creates a new byte sequence of 1 byte containing the given value.
154 *
155 * @param original a byte value
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700156 * @return a new immutable byte sequence
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700157 */
158 public static ImmutableByteSequence copyFrom(byte original) {
159 return new ImmutableByteSequence(
160 ByteBuffer.allocate(Byte.BYTES).put(original));
161 }
162
163 /**
Carmelo Casconeaa8b6292016-04-13 14:27:06 -0700164 * Creates a new byte sequence of the given size where alla bits are 0.
165 *
166 * @param size number of bytes
167 * @return a new immutable byte sequence
168 */
169 public static ImmutableByteSequence ofZeros(int size) {
170 byte[] bytes = new byte[size];
171 Arrays.fill(bytes, (byte) 0);
172 return new ImmutableByteSequence(ByteBuffer.wrap(bytes));
173 }
174
175 /**
176 * Creates a new byte sequence of the given size where alla bits are 1.
177 *
178 * @param size number of bytes
179 * @return a new immutable byte sequence
180 */
181 public static ImmutableByteSequence ofOnes(int size) {
182 byte[] bytes = new byte[size];
183 Arrays.fill(bytes, (byte) 0xFF);
184 return new ImmutableByteSequence(ByteBuffer.wrap(bytes));
185 }
186
187 /**
Carmelo Cascone6b32c992016-04-13 11:53:09 -0700188 * Returns a view of this sequence as a read-only {@link ByteBuffer}.
189 * <p>
190 * The returned buffer will have position 0, while limit and capacity will
191 * be set to this sequence {@link #size()}. The buffer order will be
192 * big-endian.
193 *
194 * @return a read-only byte buffer
195 */
196 public ByteBuffer asReadOnlyBuffer() {
197 // position, limit and capacity set rewind at constructor
198 return value.asReadOnlyBuffer();
199 }
200
201 /**
202 * Gets the number of bytes in this sequence.
203 *
204 * @return an integer value
205 */
206 public int size() {
207 return this.value.capacity();
208 }
209
210 /**
211 * Creates a new byte array view of this sequence.
212 *
213 * @return a new byte array
214 */
215 public byte[] asArray() {
216 ByteBuffer bb = asReadOnlyBuffer();
217 byte[] bytes = new byte[size()];
218 bb.get(bytes);
219 return bytes;
220 }
221
222 @Override
223 public int hashCode() {
224 return value.hashCode();
225 }
226
227 @Override
228 public boolean equals(Object obj) {
229 if (this == obj) {
230 return true;
231 }
232 if (obj == null || getClass() != obj.getClass()) {
233 return false;
234 }
235 final ImmutableByteSequence other = (ImmutableByteSequence) obj;
236 return Objects.equal(this.value, other.value);
237 }
238
239 @Override
240 public String toString() {
241 return MoreObjects.toStringHelper(this)
242 .addValue(HexString.toHexString(asArray()))
243 .toString();
244 }
245}