1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
16 // A Decoder manages the receipt of type and data information read from the
17 // remote side of a connection.
19 mutex sync
.Mutex
// each item must be received atomically
20 r io
.Reader
// source of the data
21 buf bytes
.Buffer
// buffer for more efficient i/o from r
22 wireType
map[typeId
]*wireType
// map from remote ID to local description
23 decoderCache
map[reflect
.Type
]map[typeId
]**decEngine
// cache of compiled engines
24 ignorerCache
map[typeId
]**decEngine
// ditto for ignored objects
25 freeList
*decoderState
// list of free decoderStates; avoids reallocation
26 countBuf
[]byte // used for decoding integers while parsing messages
27 tmp
[]byte // temporary storage for i/o; saves reallocating
31 // NewDecoder returns a new decoder that reads from the io.Reader.
32 // If r does not also implement io.ByteReader, it will be wrapped in a
34 func NewDecoder(r io
.Reader
) *Decoder
{
36 // We use the ability to read bytes as a plausible surrogate for buffering.
37 if _
, ok
:= r
.(io
.ByteReader
); !ok
{
38 r
= bufio
.NewReader(r
)
41 dec
.wireType
= make(map[typeId
]*wireType
)
42 dec
.decoderCache
= make(map[reflect
.Type
]map[typeId
]**decEngine
)
43 dec
.ignorerCache
= make(map[typeId
]**decEngine
)
44 dec
.countBuf
= make([]byte, 9) // counts may be uint64s (unlikely!), require 9 bytes
49 // recvType loads the definition of a type.
50 func (dec
*Decoder
) recvType(id typeId
) {
51 // Have we already seen this type? That's an error
52 if id
< firstUserId || dec
.wireType
[id
] != nil {
53 dec
.err
= errors
.New("gob: duplicate type received")
59 dec
.decodeValue(tWireType
, reflect
.ValueOf(wire
))
63 // Remember we've seen this type.
64 dec
.wireType
[id
] = wire
67 var errBadCount
= errors
.New("invalid message length")
69 // recvMessage reads the next count-delimited item from the input. It is the converse
70 // of Encoder.writeMessage. It returns false on EOF or other error reading the message.
71 func (dec
*Decoder
) recvMessage() bool {
73 nbytes
, _
, err
:= decodeUintReader(dec
.r
, dec
.countBuf
)
78 // Upper limit of 1GB, allowing room to grow a little without overflow.
79 // TODO: We might want more control over this limit.
84 dec
.readMessage(int(nbytes
))
88 // readMessage reads the next nbytes bytes from the input.
89 func (dec
*Decoder
) readMessage(nbytes
int) {
90 // Allocate the dec.tmp buffer, up to 10KB.
91 const maxBuf
= 10 * 1024
96 if cap(dec
.tmp
) < nTmp
{
97 nAlloc
:= nTmp
+ 100 // A little extra for growth.
101 dec
.tmp
= make([]byte, nAlloc
)
103 dec
.tmp
= dec
.tmp
[:nTmp
]
109 dec
.tmp
= dec
.tmp
[:nbytes
]
112 nRead
, dec
.err
= io
.ReadFull(dec
.r
, dec
.tmp
)
114 if dec
.err
== io
.EOF
{
115 dec
.err
= io
.ErrUnexpectedEOF
119 dec
.buf
.Write(dec
.tmp
)
124 // toInt turns an encoded uint64 into an int, according to the marshaling rules.
125 func toInt(x
uint64) int64 {
133 func (dec
*Decoder
) nextInt() int64 {
134 n
, _
, err
:= decodeUintReader(&dec
.buf
, dec
.countBuf
)
141 func (dec
*Decoder
) nextUint() uint64 {
142 n
, _
, err
:= decodeUintReader(&dec
.buf
, dec
.countBuf
)
149 // decodeTypeSequence parses:
151 // (TypeDefinition DelimitedTypeDefinition*)?
152 // and returns the type id of the next value. It returns -1 at
153 // EOF. Upon return, the remainder of dec.buf is the value to be
154 // decoded. If this is an interface value, it can be ignored by
155 // resetting that buffer.
156 func (dec
*Decoder
) decodeTypeSequence(isInterface
bool) typeId
{
158 if dec
.buf
.Len() == 0 {
159 if !dec
.recvMessage() {
163 // Receive a type id.
164 id
:= typeId(dec
.nextInt())
169 // Type definition for (-id) follows.
171 // When decoding an interface, after a type there may be a
172 // DelimitedValue still in the buffer. Skip its count.
173 // (Alternatively, the buffer is empty and the byte count
174 // will be absorbed by recvMessage.)
175 if dec
.buf
.Len() > 0 {
177 dec
.err
= errors
.New("extra data in buffer")
186 // Decode reads the next value from the input stream and stores
187 // it in the data represented by the empty interface value.
188 // If e is nil, the value will be discarded. Otherwise,
189 // the value underlying e must be a pointer to the
190 // correct type for the next data item received.
191 // If the input is at EOF, Decode returns io.EOF and
192 // does not modify e.
193 func (dec
*Decoder
) Decode(e
interface{}) error
{
195 return dec
.DecodeValue(reflect
.Value
{})
197 value
:= reflect
.ValueOf(e
)
198 // If e represents a value as opposed to a pointer, the answer won't
199 // get back to the caller. Make sure it's a pointer.
200 if value
.Type().Kind() != reflect
.Ptr
{
201 dec
.err
= errors
.New("gob: attempt to decode into a non-pointer")
204 return dec
.DecodeValue(value
)
207 // DecodeValue reads the next value from the input stream.
208 // If v is the zero reflect.Value (v.Kind() == Invalid), DecodeValue discards the value.
209 // Otherwise, it stores the value into v. In that case, v must represent
210 // a non-nil pointer to data or be an assignable reflect.Value (v.CanSet())
211 // If the input is at EOF, DecodeValue returns io.EOF and
212 // does not modify e.
213 func (dec
*Decoder
) DecodeValue(v reflect
.Value
) error
{
215 if v
.Kind() == reflect
.Ptr
&& !v
.IsNil() {
216 // That's okay, we'll store through the pointer.
217 } else if !v
.CanSet() {
218 return errors
.New("gob: DecodeValue of unassignable value")
221 // Make sure we're single-threaded through here.
223 defer dec
.mutex
.Unlock()
225 dec
.buf
.Reset() // In case data lingers from previous invocation.
227 id
:= dec
.decodeTypeSequence(false)
229 dec
.decodeValue(id
, v
)
234 // If debug.go is compiled into the program , debugFunc prints a human-readable
235 // representation of the gob data read from r by calling that file's Debug function.
236 // Otherwise it is nil.
237 var debugFunc
func(io
.Reader
)