Carmelo Cascone
Committed by Gerrit Code Review

New utils class for immutable byte sequences

Helpful when dealing with protocol-independent header match and actions

Change-Id: Iccfc6e09a9ea434caccc198f27e8869db42309c9
/*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onlab.util;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang3.ArrayUtils.reverse;
/**
* Immutable sequence of bytes, assumed to represent a value in
* {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN} order.
* <p>
* Sequences can be created copying from an already existing representation of a
* sequence of bytes, such as {@link ByteBuffer} or {@code byte[]}; or by
* copying bytes from a primitive data type, such as {@code long}, {@code int}
* or {@code short}. In the first case, bytes are assumed to be already given in
* big-endian order, while in the second case big-endianness is enforced by this
* class.
*/
public final class ImmutableByteSequence {
/*
Actual bytes are backed by a byte buffer.
The order of a newly-created byte buffer is always BIG_ENDIAN.
*/
private ByteBuffer value;
/**
* Private constructor.
* Creates a new byte sequence object backed by the passed ByteBuffer.
*
* @param value a byte buffer
*/
private ImmutableByteSequence(ByteBuffer value) {
this.value = value;
// Rewind buffer so it's ready to be read.
// No write operation should be performed on it from now on.
this.value.rewind();
}
/**
* Creates a new immutable byte sequence with the same content and order of
* the passed byte array.
*
* @param original a byte array value
* @return a new immutable byte buffer
*/
public static ImmutableByteSequence copyFrom(byte[] original) {
checkArgument(original != null && original.length > 0,
"Cannot copy from an empty or null array");
return new ImmutableByteSequence(
ByteBuffer.allocate(original.length).put(original));
}
/**
* Creates a new immutable byte sequence copying bytes from the given
* ByteBuffer {@link ByteBuffer}. If the byte buffer order is not big-endian
* bytes will be copied in reverse order.
*
* @param original a byte buffer
* @return a new byte buffer object
*/
public static ImmutableByteSequence copyFrom(ByteBuffer original) {
checkArgument(original != null && original.capacity() > 0,
"Cannot copy from an empty or null byte buffer");
byte[] bytes = new byte[original.capacity()];
// copy bytes from original buffer
original.rewind();
original.get(bytes);
if (original.order() == ByteOrder.LITTLE_ENDIAN) {
// FIXME: this can be improved, e.g. read bytes in reverse order from original
reverse(bytes);
}
return new ImmutableByteSequence(ByteBuffer.wrap(bytes));
}
/**
* Creates a new byte sequence of 8 bytes containing the given long value.
*
* @param original a long value
* @return a new immutable byte buffer
*/
public static ImmutableByteSequence copyFrom(long original) {
return new ImmutableByteSequence(
ByteBuffer.allocate(Long.BYTES).putLong(original));
}
/**
* Creates a new byte sequence of 4 bytes containing the given int value.
*
* @param original an int value
* @return a new immutable byte buffer
*/
public static ImmutableByteSequence copyFrom(int original) {
return new ImmutableByteSequence(
ByteBuffer.allocate(Integer.BYTES).putInt(original));
}
/**
* Creates a new byte sequence of 2 bytes containing the given short value.
*
* @param original a short value
* @return a new immutable byte buffer
*/
public static ImmutableByteSequence copyFrom(short original) {
return new ImmutableByteSequence(
ByteBuffer.allocate(Short.BYTES).putShort(original));
}
/**
* Creates a new byte sequence of 1 byte containing the given value.
*
* @param original a byte value
* @return a new immutable byte buffer
*/
public static ImmutableByteSequence copyFrom(byte original) {
return new ImmutableByteSequence(
ByteBuffer.allocate(Byte.BYTES).put(original));
}
/**
* Returns a view of this sequence as a read-only {@link ByteBuffer}.
* <p>
* The returned buffer will have position 0, while limit and capacity will
* be set to this sequence {@link #size()}. The buffer order will be
* big-endian.
*
* @return a read-only byte buffer
*/
public ByteBuffer asReadOnlyBuffer() {
// position, limit and capacity set rewind at constructor
return value.asReadOnlyBuffer();
}
/**
* Gets the number of bytes in this sequence.
*
* @return an integer value
*/
public int size() {
return this.value.capacity();
}
/**
* Creates a new byte array view of this sequence.
*
* @return a new byte array
*/
public byte[] asArray() {
ByteBuffer bb = asReadOnlyBuffer();
byte[] bytes = new byte[size()];
bb.get(bytes);
return bytes;
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final ImmutableByteSequence other = (ImmutableByteSequence) obj;
return Objects.equal(this.value, other.value);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.addValue(HexString.toHexString(asArray()))
.toString();
}
}
\ No newline at end of file
/*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onlab.util;
import com.google.common.testing.EqualsTester;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Random;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
public class ImmutableByteSequenceTest {
@Test
public void testCopy() throws Exception {
byte byteValue = (byte) 1;
short shortValue = (short) byteValue;
int intValue = (int) byteValue;
long longValue = (long) byteValue;
byte[] arrayValue = new byte[64];
arrayValue[63] = byteValue;
ByteBuffer bufferValue = ByteBuffer.allocate(64).put(arrayValue);
ImmutableByteSequence bsByte = ImmutableByteSequence.copyFrom(byteValue);
ImmutableByteSequence bsShort = ImmutableByteSequence.copyFrom(shortValue);
ImmutableByteSequence bsInt = ImmutableByteSequence.copyFrom(intValue);
ImmutableByteSequence bsLong = ImmutableByteSequence.copyFrom(longValue);
ImmutableByteSequence bsArray = ImmutableByteSequence.copyFrom(arrayValue);
ImmutableByteSequence bsBuffer = ImmutableByteSequence.copyFrom(bufferValue);
assertThat("byte sequence of a byte value must have size 1",
bsByte.size(), is(equalTo(1)));
assertThat("byte sequence of a short value must have size 2",
bsShort.size(), is(equalTo(2)));
assertThat("byte sequence of an int value must have size 4",
bsInt.size(), is(equalTo(4)));
assertThat("byte sequence of a long value must have size 8",
bsLong.size(), is(equalTo(8)));
assertThat("byte sequence of a byte array value must have same size of the array",
bsArray.size(), is(equalTo(arrayValue.length)));
assertThat("byte sequence of a byte buffer value must have same size of the buffer",
bsBuffer.size(), is(equalTo(bufferValue.capacity())));
String errStr = "incorrect byte sequence value";
assertThat(errStr, bsByte.asArray()[0], is(equalTo(byteValue)));
assertThat(errStr, bsShort.asArray()[1], is(equalTo(byteValue)));
assertThat(errStr, bsInt.asArray()[3], is(equalTo(byteValue)));
assertThat(errStr, bsLong.asArray()[7], is(equalTo(byteValue)));
assertThat(errStr, bsArray.asArray()[63], is(equalTo(byteValue)));
assertThat(errStr, bsBuffer.asArray()[63], is(equalTo(byteValue)));
}
@Test
public void testEndianness() throws Exception {
long longValue = new Random().nextLong();
// creates a new sequence from a big-endian buffer
ByteBuffer bbBigEndian = ByteBuffer
.allocate(8)
.order(ByteOrder.BIG_ENDIAN)
.putLong(longValue);
ImmutableByteSequence bsBufferCopyBigEndian =
ImmutableByteSequence.copyFrom(bbBigEndian);
// creates a new sequence from a little-endian buffer
ByteBuffer bbLittleEndian = ByteBuffer
.allocate(8)
.order(ByteOrder.LITTLE_ENDIAN)
.putLong(longValue);
ImmutableByteSequence bsBufferCopyLittleEndian =
ImmutableByteSequence.copyFrom(bbLittleEndian);
// creates a new sequence from primitive type
ImmutableByteSequence bsLongCopy =
ImmutableByteSequence.copyFrom(longValue);
new EqualsTester()
// big-endian byte array cannot be equal to little-endian array
.addEqualityGroup(bbBigEndian.array())
.addEqualityGroup(bbLittleEndian.array())
// all byte sequences must be equal
.addEqualityGroup(bsBufferCopyBigEndian,
bsBufferCopyLittleEndian,
bsLongCopy)
// byte buffer views of all sequences must be equal
.addEqualityGroup(bsBufferCopyBigEndian.asReadOnlyBuffer(),
bsBufferCopyLittleEndian.asReadOnlyBuffer(),
bsLongCopy.asReadOnlyBuffer())
// byte buffer orders of all sequences must be ByteOrder.BIG_ENDIAN
.addEqualityGroup(bsBufferCopyBigEndian.asReadOnlyBuffer().order(),
bsBufferCopyLittleEndian.asReadOnlyBuffer().order(),
bsLongCopy.asReadOnlyBuffer().order(),
ByteOrder.BIG_ENDIAN)
.testEquals();
}
}
\ No newline at end of file