Ensure P4Runtime byte strings are padded to their bit width

The P4Runtime server may send canonical byte strings (i.e.,
non-padded byte strings).
In ONOS we ensure, in the codecs, that all byte strings are
padded to match the model (P4Info) bit width. In this way,
we provide read-write symmetry inside ONOS.
ONOS always pads byte strings when sending messages to the
P4Runtime server.
This patch doesn't enforce read-write symmetry between
P4Runtime client and server on the wire.

N.B.: the current padding implementation works ONLY when
using non-negative integer.

Change-Id: I9f8e43de015bd0929dd543d7688c8e71bf5fe98d
diff --git a/utils/misc/src/main/java/org/onlab/util/ImmutableByteSequence.java b/utils/misc/src/main/java/org/onlab/util/ImmutableByteSequence.java
index 1710d29..32e9d0b 100644
--- a/utils/misc/src/main/java/org/onlab/util/ImmutableByteSequence.java
+++ b/utils/misc/src/main/java/org/onlab/util/ImmutableByteSequence.java
@@ -190,6 +190,53 @@
     }
 
     /**
+     * Creates a new immutable byte sequence while trimming or expanding the
+     * content of the given byte buffer to fit the given bit-width. Calling this
+     * method has the same behavior as
+     * {@code ImmutableByteSequence.copyFrom(original).fit(bitWidth)}.
+     *
+     * @param original a byte buffer value
+     * @param bitWidth a non-zero positive integer
+     * @return a new immutable byte sequence
+     * @throws ByteSequenceTrimException if the byte buffer cannot be fitted
+     */
+    public static ImmutableByteSequence copyAndFit(ByteBuffer original, int bitWidth)
+            throws ByteSequenceTrimException {
+        checkArgument(original != null && original.capacity() > 0,
+                      "Cannot copy from an empty or null byte buffer");
+        checkArgument(bitWidth > 0,
+                      "bit-width must be a non-zero positive integer");
+        if (original.order() == ByteOrder.LITTLE_ENDIAN) {
+            // FIXME: this can be improved, e.g. read bytes in reverse order from original
+            byte[] newBytes = new byte[original.capacity()];
+            original.get(newBytes);
+            reverse(newBytes);
+            return internalCopyAndFit(ByteBuffer.wrap(newBytes), bitWidth);
+        } else {
+            return internalCopyAndFit(original.duplicate(), bitWidth);
+        }
+    }
+
+    private static ImmutableByteSequence internalCopyAndFit(ByteBuffer byteBuf, int bitWidth)
+            throws ByteSequenceTrimException {
+        final int byteWidth = (bitWidth + 7) / 8;
+        final ByteBuffer newByteBuffer = ByteBuffer.allocate(byteWidth);
+        byteBuf.rewind();
+        if (byteWidth >= byteBuf.capacity()) {
+            newByteBuffer.position(byteWidth - byteBuf.capacity());
+            newByteBuffer.put(byteBuf);
+        } else {
+            for (int i = 0; i < byteBuf.capacity() - byteWidth; i++) {
+                if (byteBuf.get(i) != 0) {
+                    throw new ByteSequenceTrimException(byteBuf, bitWidth);
+                }
+            }
+            newByteBuffer.put(byteBuf.position(byteBuf.capacity() - byteWidth));
+        }
+        return new ImmutableByteSequence(newByteBuffer);
+    }
+
+    /**
      * Creates a new byte sequence of the given size where all bits are 0.
      *
      * @param size number of bytes
@@ -500,12 +547,17 @@
     }
 
     /**
-     * Signals that a byte sequence cannot be trimmed.
+     * Signals a trim exception during byte sequence creation.
      */
     public static class ByteSequenceTrimException extends Exception {
         ByteSequenceTrimException(ImmutableByteSequence original, int bitWidth) {
             super(format("cannot trim %s into a %d bits long value",
                          original, bitWidth));
         }
+
+        ByteSequenceTrimException(ByteBuffer original, int bitWidth) {
+            super(format("cannot trim %s (ByteBuffer) into a %d bits long value",
+                         original, bitWidth));
+        }
     }
 }
diff --git a/utils/misc/src/test/java/org/onlab/util/ImmutableByteSequenceTest.java b/utils/misc/src/test/java/org/onlab/util/ImmutableByteSequenceTest.java
index 7e74328..c83c6b2 100644
--- a/utils/misc/src/test/java/org/onlab/util/ImmutableByteSequenceTest.java
+++ b/utils/misc/src/test/java/org/onlab/util/ImmutableByteSequenceTest.java
@@ -25,6 +25,7 @@
 
 import java.nio.ByteBuffer;
 import java.nio.ByteOrder;
+import java.util.Arrays;
 import java.util.Random;
 
 import static java.lang.Integer.max;
@@ -81,6 +82,107 @@
     }
 
     @Test
+    public void testCopyAndFit() throws Exception {
+        int originalByteWidth = 3;
+        int paddedByteWidth = 4;
+        int trimmedByteWidth = 2;
+        int indexFirstNonZeroByte = 1;
+
+        byte byteValue = (byte) 1;
+        byte[] arrayValue = new byte[originalByteWidth];
+        arrayValue[indexFirstNonZeroByte] = byteValue;
+        ByteBuffer bufferValue = ByteBuffer.allocate(originalByteWidth).put(arrayValue);
+
+        ImmutableByteSequence bsBuffer = ImmutableByteSequence.copyAndFit(
+                bufferValue, originalByteWidth * 8);
+        ImmutableByteSequence bsBufferTrimmed = ImmutableByteSequence.copyAndFit(
+                bufferValue, trimmedByteWidth * 8);
+        ImmutableByteSequence bsBufferPadded = ImmutableByteSequence.copyAndFit(
+                bufferValue, paddedByteWidth * 8);
+
+        assertThat("byte sequence of the byte buffer must be 3 bytes long",
+                   bsBuffer.size(), is(equalTo(originalByteWidth)));
+        assertThat("byte sequence of the byte buffer must be 3 bytes long",
+                   bsBufferTrimmed.size(), is(equalTo(trimmedByteWidth)));
+        assertThat("byte sequence of the byte buffer must be 3 bytes long",
+                   bsBufferPadded.size(), is(equalTo(paddedByteWidth)));
+
+        String errStr = "incorrect byte sequence value";
+
+        assertThat(errStr, bsBuffer.asArray()[indexFirstNonZeroByte], is(equalTo(byteValue)));
+        assertThat(errStr, bsBufferTrimmed.asArray()[indexFirstNonZeroByte - 1], is(equalTo(byteValue)));
+        assertThat(errStr, bsBufferPadded.asArray()[indexFirstNonZeroByte + 1], is(equalTo(byteValue)));
+        assertThat(errStr, bsBufferPadded.asArray()[paddedByteWidth - 1], is(equalTo((byte) 0x00)));
+    }
+
+    @Test
+    public void testCopyAndFitEndianness() throws Exception {
+        int originalByteWidth = 4;
+        int indexByteNonZeroBig = 1;
+        int indexByteNonZeroLittle = 2;
+        byte byteValue = (byte) 1;
+
+        ByteBuffer bbBigEndian = ByteBuffer
+                .allocate(originalByteWidth)
+                .order(ByteOrder.BIG_ENDIAN);
+        bbBigEndian.put(indexByteNonZeroBig, byteValue);
+        ImmutableByteSequence bsBufferCopyBigEndian =
+                ImmutableByteSequence.copyAndFit(bbBigEndian, originalByteWidth * 8);
+
+        ByteBuffer bbLittleEndian = ByteBuffer
+                .allocate(originalByteWidth)
+                .order(ByteOrder.LITTLE_ENDIAN);
+        bbLittleEndian.put(indexByteNonZeroLittle, byteValue);
+        ImmutableByteSequence bsBufferCopyLittleEndian =
+                ImmutableByteSequence.copyAndFit(bbLittleEndian, originalByteWidth * 8);
+
+        // creates a new sequence from primitive type
+        byte[] arrayValue = new byte[originalByteWidth];
+        arrayValue[indexByteNonZeroBig] = byteValue;
+        ImmutableByteSequence bsArrayCopy =
+                ImmutableByteSequence.copyFrom(arrayValue);
+
+        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,
+                                  bsArrayCopy)
+                // byte buffer views of all sequences must be equal
+                .addEqualityGroup(bsBufferCopyBigEndian.asReadOnlyBuffer(),
+                                  bsBufferCopyLittleEndian.asReadOnlyBuffer(),
+                                  bsArrayCopy.asReadOnlyBuffer())
+                // byte buffer orders of all sequences must be ByteOrder.BIG_ENDIAN
+                .addEqualityGroup(bsBufferCopyBigEndian.asReadOnlyBuffer().order(),
+                                  bsBufferCopyLittleEndian.asReadOnlyBuffer().order(),
+                                  bsArrayCopy.asReadOnlyBuffer().order(),
+                                  ByteOrder.BIG_ENDIAN)
+                .testEquals();
+    }
+
+    @Test
+    public void testIllegalCopyAndFit() throws Exception {
+        int originalByteWidth = 3;
+        int trimmedByteWidth = 1;
+        int indexFirstNonZeroByte = 1;
+
+        byte byteValue = (byte) 1;
+        byte[] arrayValue = new byte[originalByteWidth];
+        arrayValue[indexFirstNonZeroByte] = byteValue;
+        ByteBuffer bufferValue = ByteBuffer.allocate(originalByteWidth).put(arrayValue);
+
+        try {
+            ImmutableByteSequence.copyAndFit(bufferValue, trimmedByteWidth * 8);
+            Assert.fail(format("Expect ByteSequenceTrimException due to value = %s and bitWidth %d",
+                               Arrays.toString(arrayValue), trimmedByteWidth * 8));
+        } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
+            // We expect this.
+        }
+    }
+
+    @Test
     public void testEndianness() throws Exception {
 
         long longValue = RandomUtils.nextLong();