bencode: Fix marshalling of []byte(nil)

Also fixes #293.
This commit is contained in:
Matt Joiner 2018-11-27 08:57:17 +11:00
parent 35642c832b
commit e236cbf145
3 changed files with 13 additions and 4 deletions

View File

@ -159,15 +159,15 @@ func (e *Encoder) reflectValue(v reflect.Value) {
}
e.writeString("e")
case reflect.Slice:
if v.IsNil() {
e.writeString("le")
break
}
if v.Type().Elem().Kind() == reflect.Uint8 {
s := v.Bytes()
e.reflectByteSlice(s)
break
}
if v.IsNil() {
e.writeString("le")
break
}
fallthrough
case reflect.Array:
e.writeString("l")

View File

@ -53,6 +53,7 @@ var random_encode_tests = []random_encode_test{
{[4]byte{1, 2, 3, 4}, "li1ei2ei3ei4ee"},
{nil, ""},
{[]byte{}, "0:"},
{[]byte(nil), "0:"},
{"", "0:"},
{[]int{}, "le"},
{map[string]int{}, "de"},

View File

@ -15,3 +15,11 @@ func TestUnmarshalPex(t *testing.T) {
require.EqualValues(t, 1286, pem.Added[0].Port)
require.EqualValues(t, 0x100*0xb+0xc, pem.Added[1].Port)
}
func TestEmptyPexMsg(t *testing.T) {
pm := PexMsg{}
b, err := bencode.Marshal(pm)
t.Logf("%q", b)
require.NoError(t, err)
require.NoError(t, bencode.Unmarshal(b, &pm))
}