OSDN Git Service

1d526e35c0f918baad25a6df52758cc548b63ffe
[pf3gnuchains/gcc-fork.git] / libgo / go / gob / decoder.go
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.
4
5 package gob
6
7 import (
8         "bufio"
9         "bytes"
10         "io"
11         "os"
12         "reflect"
13         "sync"
14 )
15
16 // A Decoder manages the receipt of type and data information read from the
17 // remote side of a connection.
18 type Decoder struct {
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
28         err          os.Error
29 }
30
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
33 // bufio.Reader.
34 func NewDecoder(r io.Reader) *Decoder {
35         dec := new(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)
39         }
40         dec.r = 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
45
46         return dec
47 }
48
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 = os.NewError("gob: duplicate type received")
54                 return
55         }
56
57         // Type:
58         wire := new(wireType)
59         dec.decodeValue(tWireType, reflect.ValueOf(wire))
60         if dec.err != nil {
61                 return
62         }
63         // Remember we've seen this type.
64         dec.wireType[id] = wire
65 }
66
67 var errBadCount = os.NewError("invalid message length")
68
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 {
72         // Read a count.
73         nbytes, _, err := decodeUintReader(dec.r, dec.countBuf)
74         if err != nil {
75                 dec.err = err
76                 return false
77         }
78         if nbytes >= 1<<31 {
79                 dec.err = errBadCount
80                 return false
81         }
82         dec.readMessage(int(nbytes))
83         return dec.err == nil
84 }
85
86 // readMessage reads the next nbytes bytes from the input.
87 func (dec *Decoder) readMessage(nbytes int) {
88         // Allocate the buffer.
89         if cap(dec.tmp) < nbytes {
90                 dec.tmp = make([]byte, nbytes+100) // room to grow
91         }
92         dec.tmp = dec.tmp[:nbytes]
93
94         // Read the data
95         _, dec.err = io.ReadFull(dec.r, dec.tmp)
96         if dec.err != nil {
97                 if dec.err == os.EOF {
98                         dec.err = io.ErrUnexpectedEOF
99                 }
100                 return
101         }
102         dec.buf.Write(dec.tmp)
103 }
104
105 // toInt turns an encoded uint64 into an int, according to the marshaling rules.
106 func toInt(x uint64) int64 {
107         i := int64(x >> 1)
108         if x&1 != 0 {
109                 i = ^i
110         }
111         return i
112 }
113
114 func (dec *Decoder) nextInt() int64 {
115         n, _, err := decodeUintReader(&dec.buf, dec.countBuf)
116         if err != nil {
117                 dec.err = err
118         }
119         return toInt(n)
120 }
121
122 func (dec *Decoder) nextUint() uint64 {
123         n, _, err := decodeUintReader(&dec.buf, dec.countBuf)
124         if err != nil {
125                 dec.err = err
126         }
127         return n
128 }
129
130 // decodeTypeSequence parses:
131 // TypeSequence
132 //      (TypeDefinition DelimitedTypeDefinition*)?
133 // and returns the type id of the next value.  It returns -1 at
134 // EOF.  Upon return, the remainder of dec.buf is the value to be
135 // decoded.  If this is an interface value, it can be ignored by
136 // simply resetting that buffer.
137 func (dec *Decoder) decodeTypeSequence(isInterface bool) typeId {
138         for dec.err == nil {
139                 if dec.buf.Len() == 0 {
140                         if !dec.recvMessage() {
141                                 break
142                         }
143                 }
144                 // Receive a type id.
145                 id := typeId(dec.nextInt())
146                 if id >= 0 {
147                         // Value follows.
148                         return id
149                 }
150                 // Type definition for (-id) follows.
151                 dec.recvType(-id)
152                 // When decoding an interface, after a type there may be a
153                 // DelimitedValue still in the buffer.  Skip its count.
154                 // (Alternatively, the buffer is empty and the byte count
155                 // will be absorbed by recvMessage.)
156                 if dec.buf.Len() > 0 {
157                         if !isInterface {
158                                 dec.err = os.NewError("extra data in buffer")
159                                 break
160                         }
161                         dec.nextUint()
162                 }
163         }
164         return -1
165 }
166
167 // Decode reads the next value from the connection and stores
168 // it in the data represented by the empty interface value.
169 // If e is nil, the value will be discarded. Otherwise,
170 // the value underlying e must be a pointer to the
171 // correct type for the next data item received.
172 func (dec *Decoder) Decode(e interface{}) os.Error {
173         if e == nil {
174                 return dec.DecodeValue(reflect.Value{})
175         }
176         value := reflect.ValueOf(e)
177         // If e represents a value as opposed to a pointer, the answer won't
178         // get back to the caller.  Make sure it's a pointer.
179         if value.Type().Kind() != reflect.Ptr {
180                 dec.err = os.NewError("gob: attempt to decode into a non-pointer")
181                 return dec.err
182         }
183         return dec.DecodeValue(value)
184 }
185
186 // DecodeValue reads the next value from the connection.
187 // If v is the zero reflect.Value (v.Kind() == Invalid), DecodeValue discards the value.
188 // Otherwise, it stores the value into v.  In that case, v must represent
189 // a non-nil pointer to data or be an assignable reflect.Value (v.CanSet())
190 func (dec *Decoder) DecodeValue(v reflect.Value) os.Error {
191         if v.IsValid() {
192                 if v.Kind() == reflect.Ptr && !v.IsNil() {
193                         // That's okay, we'll store through the pointer.
194                 } else if !v.CanSet() {
195                         return os.NewError("gob: DecodeValue of unassignable value")
196                 }
197         }
198         // Make sure we're single-threaded through here.
199         dec.mutex.Lock()
200         defer dec.mutex.Unlock()
201
202         dec.buf.Reset() // In case data lingers from previous invocation.
203         dec.err = nil
204         id := dec.decodeTypeSequence(false)
205         if dec.err == nil {
206                 dec.decodeValue(id, v)
207         }
208         return dec.err
209 }
210
211 // If debug.go is compiled into the program , debugFunc prints a human-readable
212 // representation of the gob data read from r by calling that file's Debug function.
213 // Otherwise it is nil.
214 var debugFunc func(io.Reader)