Skip to content

Commit 8c3095f

Browse files
committed
rlp: fix encoding of arrays with byte element type
1 parent 410b35e commit 8c3095f

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

‎rlp/encode.go‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,8 +301,10 @@ func makeWriter(typ reflect.Type) (writer, error) {
301301
return writeUint, nil
302302
case kind == reflect.String:
303303
return writeString, nil
304-
case kind == reflect.Slice && typ.Elem().Kind() == reflect.Uint8 && !typ.Elem().Implements(encoderInterface):
304+
case kind == reflect.Slice && isByte(typ.Elem()):
305305
return writeBytes, nil
306+
case kind == reflect.Array && isByte(typ.Elem()):
307+
return writeByteArray, nil
306308
case kind == reflect.Slice || kind == reflect.Array:
307309
return makeSliceWriter(typ)
308310
case kind == reflect.Struct:
@@ -314,6 +316,10 @@ func makeWriter(typ reflect.Type) (writer, error) {
314316
}
315317
}
316318

319+
func isByte(typ reflect.Type) bool {
320+
return typ.Kind() == reflect.Uint8 && !typ.Implements(encoderInterface)
321+
}
322+
317323
func writeUint(val reflect.Value, w *encbuf) error {
318324
i := val.Uint()
319325
if i == 0 {
@@ -358,6 +364,20 @@ func writeBytes(val reflect.Value, w *encbuf) error {
358364
return nil
359365
}
360366

367+
func writeByteArray(val reflect.Value, w *encbuf) error {
368+
if !val.CanAddr() {
369+
// Slice requires the value to be addressable.
370+
// Make it addressable by copying.
371+
copy := reflect.New(val.Type()).Elem()
372+
copy.Set(val)
373+
val = copy
374+
}
375+
size := val.Len()
376+
slice := val.Slice(0, size).Bytes()
377+
w.encodeString(slice)
378+
return nil
379+
}
380+
361381
func writeString(val reflect.Value, w *encbuf) error {
362382
s := val.String()
363383
w.encodeStringHeader(len(s))

‎rlp/encode_test.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ func (e *encodableReader) Read(b []byte) (int, error) {
4040
panic("called")
4141
}
4242

43+
type namedByteType byte
44+
4345
var (
4446
_ = Encoder(&testEncoder{})
4547
_ = Encoder(byteEncoder(0))
@@ -102,6 +104,10 @@ var encTests = []encTest{
102104
// byte slices, strings
103105
{val: []byte{}, output: "80"},
104106
{val: []byte{1, 2, 3}, output: "83010203"},
107+
108+
{val: []namedByteType{1, 2, 3}, output: "83010203"},
109+
{val: [...]namedByteType{1, 2, 3}, output: "83010203"},
110+
105111
{val: "", output: "80"},
106112
{val: "dog", output: "83646F67"},
107113
{

0 commit comments

Comments
 (0)