11package rlp
22
33import (
4+ "bufio"
45 "encoding/binary"
56 "errors"
67 "fmt"
@@ -24,8 +25,9 @@ type Decoder interface {
2425 DecodeRLP (* Stream ) error
2526}
2627
27- // Decode parses RLP-encoded data from r and stores the result
28- // in the value pointed to by val. Val must be a non-nil pointer.
28+ // Decode parses RLP-encoded data from r and stores the result in the
29+ // value pointed to by val. Val must be a non-nil pointer. If r does
30+ // not implement ByteReader, Decode will do its own buffering.
2931//
3032// Decode uses the following type-dependent decoding rules:
3133//
@@ -66,7 +68,7 @@ type Decoder interface {
6668//
6769// Non-empty interface types are not supported, nor are bool, float32,
6870// float64, maps, channel types and functions.
69- func Decode (r ByteReader , val interface {}) error {
71+ func Decode (r io. Reader , val interface {}) error {
7072 return NewStream (r ).Decode (val )
7173}
7274
@@ -432,8 +434,14 @@ type Stream struct {
432434
433435type listpos struct { pos , size uint64 }
434436
435- func NewStream (r ByteReader ) * Stream {
436- return & Stream {r : r , uintbuf : make ([]byte , 8 ), kind : - 1 }
437+ // NewStream creates a new stream reading from r.
438+ // If r does not implement ByteReader, the Stream will
439+ // introduce its own buffering.
440+ func NewStream (r io.Reader ) * Stream {
441+ s := new (Stream )
442+ s .Reset (r )
443+ return s
444+ }
437445}
438446
439447// Bytes reads an RLP string and returns its contents as a byte slice.
@@ -543,6 +551,23 @@ func (s *Stream) Decode(val interface{}) error {
543551 return info .decoder (s , rval .Elem ())
544552}
545553
554+ // Reset discards any information about the current decoding context
555+ // and starts reading from r. If r does not also implement ByteReader,
556+ // Stream will do its own buffering.
557+ func (s * Stream ) Reset (r io.Reader ) {
558+ bufr , ok := r .(ByteReader )
559+ if ! ok {
560+ bufr = bufio .NewReader (r )
561+ }
562+ s .r = bufr
563+ s .stack = s .stack [:0 ]
564+ s .size = 0
565+ s .kind = - 1
566+ if s .uintbuf == nil {
567+ s .uintbuf = make ([]byte , 8 )
568+ }
569+ }
570+
546571// Kind returns the kind and size of the next value in the
547572// input stream.
548573//
0 commit comments