diff options
author | Felix Lange <fjl@twurst.com> | 2014-11-25 02:01:25 +0800 |
---|---|---|
committer | Felix Lange <fjl@twurst.com> | 2014-11-25 02:03:11 +0800 |
commit | 5a5560f1051b51fae34e799ee8d2dfd8d1094e09 (patch) | |
tree | 7b05772ffcbcf36aef9f8957aba586ead7d6c048 /rlp/decode.go | |
parent | 59b63caf5e4de64ceb7dcdf01551a080f53b1672 (diff) | |
download | dexon-5a5560f1051b51fae34e799ee8d2dfd8d1094e09.tar.gz dexon-5a5560f1051b51fae34e799ee8d2dfd8d1094e09.tar.zst dexon-5a5560f1051b51fae34e799ee8d2dfd8d1094e09.zip |
rlp: add Stream.Reset and accept any reader (for p2p)
Diffstat (limited to 'rlp/decode.go')
-rw-r--r-- | rlp/decode.go | 35 |
1 files changed, 30 insertions, 5 deletions
diff --git a/rlp/decode.go b/rlp/decode.go index 96d912f56..565c84790 100644 --- a/rlp/decode.go +++ b/rlp/decode.go @@ -1,6 +1,7 @@ package rlp import ( + "bufio" "encoding/binary" "errors" "fmt" @@ -24,8 +25,9 @@ type Decoder interface { DecodeRLP(*Stream) error } -// Decode parses RLP-encoded data from r and stores the result -// in the value pointed to by val. Val must be a non-nil pointer. +// Decode parses RLP-encoded data from r and stores the result in the +// value pointed to by val. Val must be a non-nil pointer. If r does +// not implement ByteReader, Decode will do its own buffering. // // Decode uses the following type-dependent decoding rules: // @@ -66,7 +68,7 @@ type Decoder interface { // // Non-empty interface types are not supported, nor are bool, float32, // float64, maps, channel types and functions. -func Decode(r ByteReader, val interface{}) error { +func Decode(r io.Reader, val interface{}) error { return NewStream(r).Decode(val) } @@ -432,8 +434,14 @@ type Stream struct { type listpos struct{ pos, size uint64 } -func NewStream(r ByteReader) *Stream { - return &Stream{r: r, uintbuf: make([]byte, 8), kind: -1} +// NewStream creates a new stream reading from r. +// If r does not implement ByteReader, the Stream will +// introduce its own buffering. +func NewStream(r io.Reader) *Stream { + s := new(Stream) + s.Reset(r) + return s +} } // Bytes reads an RLP string and returns its contents as a byte slice. @@ -543,6 +551,23 @@ func (s *Stream) Decode(val interface{}) error { return info.decoder(s, rval.Elem()) } +// Reset discards any information about the current decoding context +// and starts reading from r. If r does not also implement ByteReader, +// Stream will do its own buffering. +func (s *Stream) Reset(r io.Reader) { + bufr, ok := r.(ByteReader) + if !ok { + bufr = bufio.NewReader(r) + } + s.r = bufr + s.stack = s.stack[:0] + s.size = 0 + s.kind = -1 + if s.uintbuf == nil { + s.uintbuf = make([]byte, 8) + } +} + // Kind returns the kind and size of the next value in the // input stream. // |