From b542a5e7a0dc88b0f751818530c5be1686cc6a9a Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Mon, 9 Dec 2019 16:57:25 +0300 Subject: [PATCH] io: add support for pointer receivers in WriteArray() It's actually preferable to have pointer receivers for serializable types, so this should be supported. --- pkg/io/binaryWriter.go | 5 ++++- pkg/io/binaryrw_test.go | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/pkg/io/binaryWriter.go b/pkg/io/binaryWriter.go index 5b6ccade9..d9ea336e2 100644 --- a/pkg/io/binaryWriter.go +++ b/pkg/io/binaryWriter.go @@ -49,7 +49,10 @@ func (w *BinWriter) WriteArray(arr interface{}) { for i := 0; i < val.Len(); i++ { el, ok := val.Index(i).Interface().(encodable) if !ok { - panic(typ.String() + "is not encodable") + el, ok = val.Index(i).Addr().Interface().(encodable) + if !ok { + panic(typ.String() + " is not encodable") + } } el.EncodeBinary(w) diff --git a/pkg/io/binaryrw_test.go b/pkg/io/binaryrw_test.go index 40a6d42f2..a3e55c0eb 100644 --- a/pkg/io/binaryrw_test.go +++ b/pkg/io/binaryrw_test.go @@ -229,6 +229,18 @@ func (t *testSerializable) DecodeBinary(r *BinReader) { r.ReadLE(t) } +type testPtrSerializable uint16 + +// EncodeBinary implements io.Serializable interface. +func (t *testPtrSerializable) EncodeBinary(w *BinWriter) { + w.WriteLE(t) +} + +// DecodeBinary implements io.Serializable interface. +func (t *testPtrSerializable) DecodeBinary(r *BinReader) { + r.ReadLE(t) +} + func TestBinWriter_WriteArray(t *testing.T) { var arr [3]testSerializable for i := range arr { @@ -272,6 +284,16 @@ func TestBinWriter_WriteArray(t *testing.T) { w.Reset() w.Err = errors.New("error") require.Panics(t, func() { w.WriteArray(make(chan testSerializable)) }) + + // Ptr receiver test + var arrPtr [3]testPtrSerializable + for i := range arrPtr { + arrPtr[i] = testPtrSerializable(i) + } + w.Reset() + w.WriteArray(arr[:]) + require.NoError(t, w.Err) + require.Equal(t, expected, w.Bytes()) } func TestBinReader_ReadArray(t *testing.T) {