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/protocols/p4runtime/utils/src/main/java/org/onosproject/p4runtime/ctl/codec/ActionCodec.java b/protocols/p4runtime/utils/src/main/java/org/onosproject/p4runtime/ctl/codec/ActionCodec.java
index d0a285e..daf91f5 100644
--- a/protocols/p4runtime/utils/src/main/java/org/onosproject/p4runtime/ctl/codec/ActionCodec.java
+++ b/protocols/p4runtime/utils/src/main/java/org/onosproject/p4runtime/ctl/codec/ActionCodec.java
@@ -28,6 +28,8 @@
 import p4.v1.P4RuntimeOuterClass;
 
 import static java.lang.String.format;
+import static org.onlab.util.ImmutableByteSequence.copyAndFit;
+import static org.onlab.util.ImmutableByteSequence.copyFrom;
 import static org.onosproject.p4runtime.ctl.codec.Utils.assertSize;
 
 /**
@@ -65,7 +67,7 @@
     protected PiAction decode(
             P4RuntimeOuterClass.Action message, Object ignored,
             PiPipeconf pipeconf, P4InfoBrowser browser)
-            throws P4InfoBrowser.NotFoundException {
+            throws P4InfoBrowser.NotFoundException, CodecException {
         final P4InfoBrowser.EntityBrowser<P4InfoOuterClass.Action.Param> paramInfo =
                 browser.actionParams(message.getActionId());
         final String actionName = browser.actions()
@@ -77,11 +79,17 @@
             final P4InfoOuterClass.Action.Param actionParam = paramInfo.getById(p.getParamId());
             final ImmutableByteSequence value;
             if (browser.isTypeString(actionParam.getTypeName())) {
-                value = ImmutableByteSequence.copyFrom(new String(p.getValue().toByteArray()));
+                value = copyFrom(new String(p.getValue().toByteArray()));
             } else {
-                value = ImmutableByteSequence.copyFrom(p.getValue().toByteArray());
+                try {
+                    value = copyAndFit(p.getValue().asReadOnlyByteBuffer(),
+                                       actionParam.getBitwidth());
+                } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
+                    throw new CodecException(e.getMessage());
+                }
             }
-            builder.withParameter(new PiActionParam(PiActionParamId.of(actionParam.getName()), value));
+            builder.withParameter(new PiActionParam(
+                    PiActionParamId.of(actionParam.getName()), value));
         }
         return builder.build();
     }
diff --git a/protocols/p4runtime/utils/src/main/java/org/onosproject/p4runtime/ctl/codec/FieldMatchCodec.java b/protocols/p4runtime/utils/src/main/java/org/onosproject/p4runtime/ctl/codec/FieldMatchCodec.java
index 6b01546..48baa17 100644
--- a/protocols/p4runtime/utils/src/main/java/org/onosproject/p4runtime/ctl/codec/FieldMatchCodec.java
+++ b/protocols/p4runtime/utils/src/main/java/org/onosproject/p4runtime/ctl/codec/FieldMatchCodec.java
@@ -31,6 +31,7 @@
 import p4.v1.P4RuntimeOuterClass;
 
 import static java.lang.String.format;
+import static org.onlab.util.ImmutableByteSequence.copyAndFit;
 import static org.onlab.util.ImmutableByteSequence.copyFrom;
 import static org.onosproject.p4runtime.ctl.codec.Utils.assertPrefixLen;
 import static org.onosproject.p4runtime.ctl.codec.Utils.assertSize;
@@ -155,48 +156,66 @@
         final P4InfoOuterClass.MatchField matchField =
                 browser.matchFields(tablePreamble.getId())
                         .getById(message.getFieldId());
+        final int fieldBitwidth = matchField.getBitwidth();
         final PiMatchFieldId headerFieldId = PiMatchFieldId.of(matchField.getName());
         final boolean isSdnString = browser.isTypeString(matchField.getTypeName());
 
-        P4RuntimeOuterClass.FieldMatch.FieldMatchTypeCase typeCase = message.getFieldMatchTypeCase();
-
-        switch (typeCase) {
-            case EXACT:
-                P4RuntimeOuterClass.FieldMatch.Exact exactFieldMatch = message.getExact();
-                ImmutableByteSequence exactValue;
-                if (isSdnString) {
-                    exactValue = copyFrom(new String(exactFieldMatch.getValue().toByteArray()));
-                } else {
-                    exactValue = copyFrom(exactFieldMatch.getValue().asReadOnlyByteBuffer());
-                }
-                return new PiExactFieldMatch(headerFieldId, exactValue);
-            case TERNARY:
-                P4RuntimeOuterClass.FieldMatch.Ternary ternaryFieldMatch = message.getTernary();
-                ImmutableByteSequence ternaryValue = copyFrom(ternaryFieldMatch.getValue().asReadOnlyByteBuffer());
-                ImmutableByteSequence ternaryMask = copyFrom(ternaryFieldMatch.getMask().asReadOnlyByteBuffer());
-                return new PiTernaryFieldMatch(headerFieldId, ternaryValue, ternaryMask);
-            case LPM:
-                P4RuntimeOuterClass.FieldMatch.LPM lpmFieldMatch = message.getLpm();
-                ImmutableByteSequence lpmValue = copyFrom(lpmFieldMatch.getValue().asReadOnlyByteBuffer());
-                int lpmPrefixLen = lpmFieldMatch.getPrefixLen();
-                return new PiLpmFieldMatch(headerFieldId, lpmValue, lpmPrefixLen);
-            case RANGE:
-                P4RuntimeOuterClass.FieldMatch.Range rangeFieldMatch = message.getRange();
-                ImmutableByteSequence rangeHighValue = copyFrom(rangeFieldMatch.getHigh().asReadOnlyByteBuffer());
-                ImmutableByteSequence rangeLowValue = copyFrom(rangeFieldMatch.getLow().asReadOnlyByteBuffer());
-                return new PiRangeFieldMatch(headerFieldId, rangeLowValue, rangeHighValue);
-            case OPTIONAL:
-                P4RuntimeOuterClass.FieldMatch.Optional optionalFieldMatch = message.getOptional();
-                ImmutableByteSequence optionalValue;
-                if (isSdnString) {
-                    optionalValue = copyFrom(new String(optionalFieldMatch.getValue().toByteArray()));
-                } else {
-                    optionalValue = copyFrom(optionalFieldMatch.getValue().asReadOnlyByteBuffer());
-                }
-                return new PiOptionalFieldMatch(headerFieldId, optionalValue);
-            default:
-                throw new CodecException(format(
-                        "Decoding of field match type '%s' not implemented", typeCase.name()));
+        final P4RuntimeOuterClass.FieldMatch.FieldMatchTypeCase typeCase = message.getFieldMatchTypeCase();
+        try {
+            switch (typeCase) {
+                case EXACT:
+                    P4RuntimeOuterClass.FieldMatch.Exact exactFieldMatch = message.getExact();
+                    final ImmutableByteSequence exactValue;
+                    if (isSdnString) {
+                        exactValue = copyFrom(new String(exactFieldMatch.getValue().toByteArray()));
+                    } else {
+                        exactValue = copyAndFit(
+                                exactFieldMatch.getValue().asReadOnlyByteBuffer(),
+                                fieldBitwidth);
+                    }
+                    return new PiExactFieldMatch(headerFieldId, exactValue);
+                case TERNARY:
+                    P4RuntimeOuterClass.FieldMatch.Ternary ternaryFieldMatch = message.getTernary();
+                    ImmutableByteSequence ternaryValue = copyAndFit(
+                            ternaryFieldMatch.getValue().asReadOnlyByteBuffer(),
+                            fieldBitwidth);
+                    ImmutableByteSequence ternaryMask = copyAndFit(
+                            ternaryFieldMatch.getMask().asReadOnlyByteBuffer(),
+                            fieldBitwidth);
+                    return new PiTernaryFieldMatch(headerFieldId, ternaryValue, ternaryMask);
+                case LPM:
+                    P4RuntimeOuterClass.FieldMatch.LPM lpmFieldMatch = message.getLpm();
+                    ImmutableByteSequence lpmValue = copyAndFit(
+                            lpmFieldMatch.getValue().asReadOnlyByteBuffer(),
+                            fieldBitwidth);
+                    int lpmPrefixLen = lpmFieldMatch.getPrefixLen();
+                    return new PiLpmFieldMatch(headerFieldId, lpmValue, lpmPrefixLen);
+                case RANGE:
+                    P4RuntimeOuterClass.FieldMatch.Range rangeFieldMatch = message.getRange();
+                    ImmutableByteSequence rangeHighValue = copyAndFit(
+                            rangeFieldMatch.getHigh().asReadOnlyByteBuffer(),
+                            fieldBitwidth);
+                    ImmutableByteSequence rangeLowValue = copyAndFit(
+                            rangeFieldMatch.getLow().asReadOnlyByteBuffer(),
+                            fieldBitwidth);
+                    return new PiRangeFieldMatch(headerFieldId, rangeLowValue, rangeHighValue);
+                case OPTIONAL:
+                    P4RuntimeOuterClass.FieldMatch.Optional optionalFieldMatch = message.getOptional();
+                    final ImmutableByteSequence optionalValue;
+                    if (isSdnString) {
+                        optionalValue = copyFrom(new String(optionalFieldMatch.getValue().toByteArray()));
+                    } else {
+                        optionalValue = copyAndFit(
+                                optionalFieldMatch.getValue().asReadOnlyByteBuffer(),
+                                fieldBitwidth);
+                    }
+                    return new PiOptionalFieldMatch(headerFieldId, optionalValue);
+                default:
+                    throw new CodecException(format(
+                            "Decoding of field match type '%s' not implemented", typeCase.name()));
+            }
+        } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
+            throw new CodecException(e.getMessage());
         }
     }
 }
diff --git a/protocols/p4runtime/utils/src/main/java/org/onosproject/p4runtime/ctl/codec/PacketMetadataCodec.java b/protocols/p4runtime/utils/src/main/java/org/onosproject/p4runtime/ctl/codec/PacketMetadataCodec.java
index 876f84c..ab29e62 100644
--- a/protocols/p4runtime/utils/src/main/java/org/onosproject/p4runtime/ctl/codec/PacketMetadataCodec.java
+++ b/protocols/p4runtime/utils/src/main/java/org/onosproject/p4runtime/ctl/codec/PacketMetadataCodec.java
@@ -25,6 +25,7 @@
 import p4.config.v1.P4InfoOuterClass;
 import p4.v1.P4RuntimeOuterClass;
 
+import static org.onlab.util.ImmutableByteSequence.copyAndFit;
 import static org.onlab.util.ImmutableByteSequence.copyFrom;
 
 /**
@@ -54,18 +55,23 @@
             P4RuntimeOuterClass.PacketMetadata message,
             P4InfoOuterClass.Preamble ctrlPktMetaPreamble,
             PiPipeconf pipeconf, P4InfoBrowser browser)
-            throws P4InfoBrowser.NotFoundException {
-        final P4InfoOuterClass.ControllerPacketMetadata.Metadata packetMetadata =
+            throws P4InfoBrowser.NotFoundException, CodecException {
+        final P4InfoOuterClass.ControllerPacketMetadata.Metadata pktMeta =
                 browser.packetMetadatas(ctrlPktMetaPreamble.getId())
-                .getById(message.getMetadataId());
+                        .getById(message.getMetadataId());
         final ImmutableByteSequence value;
-        if (browser.isTypeString(packetMetadata.getTypeName())) {
+        if (browser.isTypeString(pktMeta.getTypeName())) {
             value = copyFrom(new String(message.getValue().toByteArray()));
         } else {
-            value = copyFrom(message.getValue().asReadOnlyByteBuffer());
+            try {
+                value = copyAndFit(message.getValue().asReadOnlyByteBuffer(),
+                                   pktMeta.getBitwidth());
+            } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
+                throw new CodecException(e.getMessage());
+            }
         }
         return PiPacketMetadata.builder()
-                .withId(PiPacketMetadataId.of(packetMetadata.getName()))
+                .withId(PiPacketMetadataId.of(pktMeta.getName()))
                 .withValue(value)
                 .build();
     }