From eca5f7032ad79411c06b86d8a5af9144bb954cd9 Mon Sep 17 00:00:00 2001 From: Manoranjith Date: Mon, 6 Dec 2021 14:26:53 +0530 Subject: [PATCH] :recycle: [pkg/io] Skip encoding/decoding of data for 0-length binary data - Update pkg/io serializer to encode/decode only the length and skip the data for marshaler/unmarshaler type, when the length is zero. - It is necessary as the GenericSerializer tests for State, Transaction etc., were ocassionally failing due to error in Encoding NoApp,NoData. - Test failed because, in GenericSerializer tests, we use a synchronous read,write pipe for testing. In case of zero length byte array, since nothing needs to be written to or read from the pipe, the decoder occasionally finished reading and closed the pipe before encoder had completed writing. And, this caused the encoder's write to fail. Signed-off-by: Manoranjith --- pkg/io/serialize.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/pkg/io/serialize.go b/pkg/io/serialize.go index dcdebe022..7742410b5 100644 --- a/pkg/io/serialize.go +++ b/pkg/io/serialize.go @@ -31,7 +31,7 @@ var byteOrder = binary.LittleEndian // Encode encodes multiple primitive values into a writer. // All passed values must be copies, not references. -func Encode(writer io.Writer, values ...interface{}) (err error) { +func Encode(writer io.Writer, values ...interface{}) (err error) { //nolint: cyclop for i, value := range values { switch v := value.(type) { case bool, int8, uint8, int16, uint16, int32, uint32, int64, uint64: @@ -62,6 +62,10 @@ func Encode(writer io.Writer, values ...interface{}) (err error) { return errors.WithMessage(err, "writing length of marshalled data") } + // Nothing to be encoded when length is zero. + if length == 0 { + break + } err = ByteSlice(data).Encode(writer) default: if enc, ok := value.(Encoder); ok { @@ -108,6 +112,10 @@ func Decode(reader io.Reader, values ...interface{}) (err error) { return errors.WithMessage(err, "reading length of binary data") } + // Nothing to be decoded when length is zero. + if length == 0 { + break + } var data ByteSlice = make([]byte, length) err = data.Decode(reader) if err != nil {