Add a defensive sanity check to protobuf marshal

This prevents programmer error from resulting in objects serialized to the wire that are incorrectly designed. The normal path guards against this, but the runtime.Unknown NestedMarshalTo fast path (which avoids an allocation) doesn't have the same defensive guard.
parent a167a6b4
...@@ -16,6 +16,10 @@ limitations under the License. ...@@ -16,6 +16,10 @@ limitations under the License.
package runtime package runtime
import (
"fmt"
)
type ProtobufMarshaller interface { type ProtobufMarshaller interface {
MarshalTo(data []byte) (int, error) MarshalTo(data []byte) (int, error)
} }
...@@ -44,6 +48,11 @@ func (m *Unknown) NestedMarshalTo(data []byte, b ProtobufMarshaller, size uint64 ...@@ -44,6 +48,11 @@ func (m *Unknown) NestedMarshalTo(data []byte, b ProtobufMarshaller, size uint64
if err != nil { if err != nil {
return 0, err return 0, err
} }
if uint64(n2) != size {
// programmer error: the Size() method for protobuf does not match the results of MarshalTo, which means the proto
// struct returned would be wrong.
return 0, fmt.Errorf("the Size() value of %T was %d, but NestedMarshalTo wrote %d bytes to data", b, size, n2)
}
i += n2 i += n2
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment