Skip to content

Commit

Permalink
♻️ [pkg/io] Skip encoding/decoding of data for 0-length binary data
Browse files Browse the repository at this point in the history
- 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 <[email protected]>
  • Loading branch information
Manoranjith committed Dec 6, 2021
1 parent e5a5fcb commit eca5f70
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion pkg/io/serialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit eca5f70

Please sign in to comment.