bencode/bytes.go | 7 +++++++ bencode/bytes_test.go | 39 +++++++++++++++++++++++++++++++++++++++ diff --git a/bencode/bytes.go b/bencode/bytes.go index 5e1018e406779879197bcb3502c31b880c77b41a..c3a51cd0e285370cfde9517a449cba3566c281f7 100644 --- a/bencode/bytes.go +++ b/bencode/bytes.go @@ -1,5 +1,9 @@ package bencode +import ( + "errors" +) + type Bytes []byte var ( @@ -14,5 +18,8 @@ return nil } func (me Bytes) MarshalBencode() ([]byte, error) { + if len(me) == 0 { + return nil, errors.New("marshalled Bytes should not be zero-length") + } return me, nil } diff --git a/bencode/bytes_test.go b/bencode/bytes_test.go new file mode 100644 index 0000000000000000000000000000000000000000..08b4f98ba0b38f5e7a239e3575671dd439634895 --- /dev/null +++ b/bencode/bytes_test.go @@ -0,0 +1,39 @@ +package bencode + +import ( + "testing" + + qt "github.com/frankban/quicktest" +) + +func TestBytesMarshalNil(t *testing.T) { + var b Bytes + Marshal(b) +} + +type structWithBytes struct { + A Bytes + B Bytes +} + +func TestMarshalNilStructBytes(t *testing.T) { + _, err := Marshal(structWithBytes{B: Bytes("i42e")}) + c := qt.New(t) + c.Assert(err, qt.IsNotNil) +} + +type structWithOmitEmptyBytes struct { + A Bytes `bencode:",omitempty"` + B Bytes `bencode:",omitempty"` +} + +func TestMarshalNilStructBytesOmitEmpty(t *testing.T) { + c := qt.New(t) + b, err := Marshal(structWithOmitEmptyBytes{B: Bytes("i42e")}) + c.Assert(err, qt.IsNil) + t.Logf("%q", b) + var s structWithBytes + err = Unmarshal(b, &s) + c.Assert(err, qt.IsNil) + c.Check(s.B, qt.DeepEquals, Bytes("i42e")) +}