]> Sergey Matveev's repositories - btrtrc.git/commitdiff
bencode: Support unmarshalling strings into slices of kind Uint8
authorMatt Joiner <anacrolix@gmail.com>
Mon, 12 Feb 2018 13:44:05 +0000 (00:44 +1100)
committerMatt Joiner <anacrolix@gmail.com>
Mon, 12 Feb 2018 13:44:05 +0000 (00:44 +1100)
bencode/decode.go
bencode/decode_test.go

index 074db675301d253fec1b750719ddefaa8ea10b9c..b07ae580c0761e664548411bce70bdc5e56276e9 100644 (file)
@@ -171,9 +171,7 @@ func (d *Decoder) parseString(v reflect.Value) error {
                                Type:  v.Type(),
                        })
                }
-               sl := make([]byte, len(d.buf.Bytes()))
-               copy(sl, d.buf.Bytes())
-               v.Set(reflect.ValueOf(sl))
+               v.SetBytes(append([]byte(nil), d.buf.Bytes()...))
        default:
                return &UnmarshalTypeError{
                        Value: "string",
index fa5212b9f704620899a7c3cd55eacf88e94ad768..7366102d6baff6e9116907d1ce915e2f826fc2bb 100644 (file)
@@ -147,3 +147,23 @@ func TestIgnoreUnmarshalTypeError(t *testing.T) {
        require.Nil(t, Unmarshal([]byte("d6:Ignorei42ee"), &s))
        assert.EqualValues(t, 42, s.Ignore)
 }
+
+// Test unmarshalling []byte into something that has the same kind but
+// different type.
+func TestDecodeCustomSlice(t *testing.T) {
+       type flag byte
+       var fs3, fs2 []flag
+       // We do a longer slice then a shorter slice to see if the buffers are
+       // shared.
+       d := NewDecoder(bytes.NewBufferString("3:\x01\x10\xff2:\x04\x0f"))
+       require.NoError(t, d.Decode(&fs3))
+       require.NoError(t, d.Decode(&fs2))
+       assert.EqualValues(t, []flag{1, 16, 255}, fs3)
+       assert.EqualValues(t, []flag{4, 15}, fs2)
+}
+
+func TestUnmarshalUnusedBytes(t *testing.T) {
+       var i int
+       require.EqualValues(t, ErrUnusedTrailingBytes{1}, Unmarshal([]byte("i42ee"), &i))
+       assert.EqualValues(t, 42, i)
+}