2
0
mirror of synced 2025-02-23 22:28:11 +00:00

Support marshalling bencode strings into byte arrays

This commit is contained in:
Matt Joiner 2018-07-11 15:22:29 +10:00
parent de08380464
commit 04fa1b8d4c
2 changed files with 20 additions and 11 deletions

View File

@ -168,26 +168,29 @@ func (d *Decoder) parseString(v reflect.Value) error {
})
}
defer d.buf.Reset()
switch v.Kind() {
case reflect.String:
v.SetString(d.buf.String())
return nil
case reflect.Slice:
if v.Type().Elem().Kind() != reflect.Uint8 {
panic(&UnmarshalTypeError{
Value: "string",
Type: v.Type(),
})
break
}
v.SetBytes(append([]byte(nil), d.buf.Bytes()...))
default:
return &UnmarshalTypeError{
Value: "string",
Type: v.Type(),
return nil
case reflect.Array:
if v.Type().Elem().Kind() != reflect.Uint8 {
break
}
reflect.Copy(v, reflect.ValueOf(d.buf.Bytes()))
return nil
}
// I believe we return here to support "ignore_unmarshal_type_error".
return &UnmarshalTypeError{
Value: "string",
Type: v.Type(),
}
d.buf.Reset()
return nil
}
// Info for parsing a dict value.

View File

@ -167,3 +167,9 @@ func TestUnmarshalUnusedBytes(t *testing.T) {
require.EqualValues(t, ErrUnusedTrailingBytes{1}, Unmarshal([]byte("i42ee"), &i))
assert.EqualValues(t, 42, i)
}
func TestUnmarshalByteArray(t *testing.T) {
var ba [2]byte
assert.NoError(t, Unmarshal([]byte("2:hi"), &ba))
assert.EqualValues(t, "hi", ba[:])
}