Skip to content

Commit 4a81e5a

Browse files
rlp: add more tests for nil pointer / optional field encoding (#26077)
1 parent 621b423 commit 4a81e5a

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

rlp/decode_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,16 @@ type optionalPtrField struct {
439439
B *[3]byte `rlp:"optional"`
440440
}
441441

442+
type nonOptionalPtrField struct {
443+
A uint
444+
B *[3]byte
445+
}
446+
447+
type multipleOptionalFields struct {
448+
A *[3]byte `rlp:"optional"`
449+
B *[3]byte `rlp:"optional"`
450+
}
451+
442452
type optionalPtrFieldNil struct {
443453
A uint
444454
B *[3]byte `rlp:"optional,nil"`
@@ -744,6 +754,30 @@ var decodeTests = []decodeTest{
744754
ptr: new(optionalPtrField),
745755
value: optionalPtrField{A: 1, B: &[3]byte{1, 2, 3}},
746756
},
757+
{
758+
// all optional fields nil
759+
input: "C0",
760+
ptr: new(multipleOptionalFields),
761+
value: multipleOptionalFields{A: nil, B: nil},
762+
},
763+
{
764+
// all optional fields set
765+
input: "C88301020383010203",
766+
ptr: new(multipleOptionalFields),
767+
value: multipleOptionalFields{A: &[3]byte{1, 2, 3}, B: &[3]byte{1, 2, 3}},
768+
},
769+
{
770+
// nil optional field appears before a non-nil one
771+
input: "C58083010203",
772+
ptr: new(multipleOptionalFields),
773+
error: "rlp: input string too short for [3]uint8, decoding into (rlp.multipleOptionalFields).A",
774+
},
775+
{
776+
// decode a nil ptr into a ptr that is not nil or not optional
777+
input: "C20180",
778+
ptr: new(nonOptionalPtrField),
779+
error: "rlp: input string too short for [3]uint8, decoding into (rlp.nonOptionalPtrField).B",
780+
},
747781
{
748782
input: "C101",
749783
ptr: new(optionalPtrFieldNil),

rlp/encode_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,10 @@ var encTests = []encTest{
290290
{val: &optionalBigIntField{A: 1}, output: "C101"},
291291
{val: &optionalPtrField{A: 1}, output: "C101"},
292292
{val: &optionalPtrFieldNil{A: 1}, output: "C101"},
293+
{val: &multipleOptionalFields{A: nil, B: nil}, output: "C0"},
294+
{val: &multipleOptionalFields{A: &[3]byte{1, 2, 3}, B: &[3]byte{1, 2, 3}}, output: "C88301020383010203"},
295+
{val: &multipleOptionalFields{A: nil, B: &[3]byte{1, 2, 3}}, output: "C58083010203"}, // encodes without error but decode will fail
296+
{val: &nonOptionalPtrField{A: 1}, output: "C20180"}, // encodes without error but decode will fail
293297

294298
// nil
295299
{val: (*uint)(nil), output: "80"},

0 commit comments

Comments
 (0)