Skip to content

Commit 5c7136a

Browse files
authored
rlp: remove allocation of bytes.Reader in DecodeBytes (#27987)
1 parent 52219ce commit 5c7136a

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

rlp/decode.go

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ func Decode(r io.Reader, val interface{}) error {
9090
// DecodeBytes parses RLP data from b into val. Please see package-level documentation for
9191
// the decoding rules. The input must contain exactly one value and no trailing data.
9292
func DecodeBytes(b []byte, val interface{}) error {
93-
r := bytes.NewReader(b)
93+
r := (*sliceReader)(&b)
9494

9595
stream := streamPool.Get().(*Stream)
9696
defer streamPool.Put(stream)
@@ -99,7 +99,7 @@ func DecodeBytes(b []byte, val interface{}) error {
9999
if err := stream.Decode(val); err != nil {
100100
return err
101101
}
102-
if r.Len() > 0 {
102+
if len(b) > 0 {
103103
return ErrMoreThanOneValue
104104
}
105105
return nil
@@ -1182,3 +1182,23 @@ func (s *Stream) listLimit() (inList bool, limit uint64) {
11821182
}
11831183
return true, s.stack[len(s.stack)-1]
11841184
}
1185+
1186+
type sliceReader []byte
1187+
1188+
func (sr *sliceReader) Read(b []byte) (int, error) {
1189+
if len(*sr) == 0 {
1190+
return 0, io.EOF
1191+
}
1192+
n := copy(b, *sr)
1193+
*sr = (*sr)[n:]
1194+
return n, nil
1195+
}
1196+
1197+
func (sr *sliceReader) ReadByte() (byte, error) {
1198+
if len(*sr) == 0 {
1199+
return 0, io.EOF
1200+
}
1201+
b := (*sr)[0]
1202+
*sr = (*sr)[1:]
1203+
return b, nil
1204+
}

0 commit comments

Comments
 (0)