From: Matt Joiner Date: Tue, 2 Nov 2021 06:28:05 +0000 (+1100) Subject: bencode.Bytes: Tests and stricter checks X-Git-Tag: v1.36.0~8 X-Git-Url: http://www.git.stargrave.org/?a=commitdiff_plain;h=68fdd41d897c43bea7132c8761afcb3125567daa;p=btrtrc.git bencode.Bytes: Tests and stricter checks --- diff --git a/bencode/bytes.go b/bencode/bytes.go index 5e1018e4..c3a51cd0 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 @@ func (me *Bytes) UnmarshalBencode(b []byte) error { } 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 00000000..08b4f98b --- /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")) +}