Skip to content

Commit 181a21c

Browse files
committed
rlp: encode nil array pointers as empty list or string
1 parent ff5578f commit 181a21c

2 files changed

Lines changed: 28 additions & 8 deletions

File tree

‎rlp/encode.go‎

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ func (e flatenc) EncodeRLP(out io.Writer) error {
8787
// To encode a pointer, the value being pointed to is encoded. For nil
8888
// pointers, Encode will encode the zero value of the type. A nil
8989
// pointer to a struct type always encodes as an empty RLP list.
90+
// A nil pointer to an array encodes as an empty list (or empty string
91+
// if the array has element type byte).
9092
//
9193
// Struct values are encoded as an RLP list of all their encoded
9294
// public fields. Recursive struct types are supported.
@@ -532,21 +534,37 @@ func makePtrWriter(typ reflect.Type) (writer, error) {
532534
if err != nil {
533535
return nil, err
534536
}
535-
zero := reflect.Zero(typ.Elem())
537+
538+
// determine nil pointer handler
539+
var nilfunc func(*encbuf) error
536540
kind := typ.Elem().Kind()
537-
writer := func(val reflect.Value, w *encbuf) error {
538-
switch {
539-
case !val.IsNil():
540-
return etypeinfo.writer(val.Elem(), w)
541-
case kind == reflect.Struct:
542-
// encoding the zero value of a struct could trigger
541+
switch {
542+
case kind == reflect.Array && isByte(typ.Elem().Elem()):
543+
nilfunc = func(w *encbuf) error {
544+
w.str = append(w.str, 0x80)
545+
return nil
546+
}
547+
case kind == reflect.Struct || kind == reflect.Array:
548+
nilfunc = func(w *encbuf) error {
549+
// encoding the zero value of a struct/array could trigger
543550
// infinite recursion, avoid that.
544551
w.listEnd(w.list())
545552
return nil
546-
default:
553+
}
554+
default:
555+
zero := reflect.Zero(typ.Elem())
556+
nilfunc = func(w *encbuf) error {
547557
return etypeinfo.writer(zero, w)
548558
}
549559
}
560+
561+
writer := func(val reflect.Value, w *encbuf) error {
562+
if val.IsNil() {
563+
return nilfunc(w)
564+
} else {
565+
return etypeinfo.writer(val.Elem(), w)
566+
}
567+
}
550568
return writer, err
551569
}
552570

‎rlp/encode_test.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,8 +202,10 @@ var encTests = []encTest{
202202
{val: (*uint)(nil), output: "80"},
203203
{val: (*string)(nil), output: "80"},
204204
{val: (*[]byte)(nil), output: "80"},
205+
{val: (*[10]byte)(nil), output: "80"},
205206
{val: (*big.Int)(nil), output: "80"},
206207
{val: (*[]string)(nil), output: "C0"},
208+
{val: (*[10]string)(nil), output: "C0"},
207209
{val: (*[]interface{})(nil), output: "C0"},
208210
{val: (*[]struct{ uint })(nil), output: "C0"},
209211
{val: (*interface{})(nil), output: "C0"},

0 commit comments

Comments
 (0)