libgo: update to go1.9
[official-gcc.git] / libgo / go / encoding / gob / decode.go
blob8dece42e908b87b8ad014eede09b004aab3131ad
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.
5 //go:generate go run decgen.go -output dec_helpers.go
7 package gob
9 import (
10 "encoding"
11 "errors"
12 "io"
13 "math"
14 "math/bits"
15 "reflect"
18 var (
19 errBadUint = errors.New("gob: encoded unsigned integer out of range")
20 errBadType = errors.New("gob: unknown type id or corrupted data")
21 errRange = errors.New("gob: bad data: field numbers out of bounds")
24 type decHelper func(state *decoderState, v reflect.Value, length int, ovfl error) bool
26 // decoderState is the execution state of an instance of the decoder. A new state
27 // is created for nested objects.
28 type decoderState struct {
29 dec *Decoder
30 // The buffer is stored with an extra indirection because it may be replaced
31 // if we load a type during decode (when reading an interface value).
32 b *decBuffer
33 fieldnum int // the last field number read.
34 next *decoderState // for free list
37 // decBuffer is an extremely simple, fast implementation of a read-only byte buffer.
38 // It is initialized by calling Size and then copying the data into the slice returned by Bytes().
39 type decBuffer struct {
40 data []byte
41 offset int // Read offset.
44 func (d *decBuffer) Read(p []byte) (int, error) {
45 n := copy(p, d.data[d.offset:])
46 if n == 0 && len(p) != 0 {
47 return 0, io.EOF
49 d.offset += n
50 return n, nil
53 func (d *decBuffer) Drop(n int) {
54 if n > d.Len() {
55 panic("drop")
57 d.offset += n
60 // Size grows the buffer to exactly n bytes, so d.Bytes() will
61 // return a slice of length n. Existing data is first discarded.
62 func (d *decBuffer) Size(n int) {
63 d.Reset()
64 if cap(d.data) < n {
65 d.data = make([]byte, n)
66 } else {
67 d.data = d.data[0:n]
71 func (d *decBuffer) ReadByte() (byte, error) {
72 if d.offset >= len(d.data) {
73 return 0, io.EOF
75 c := d.data[d.offset]
76 d.offset++
77 return c, nil
80 func (d *decBuffer) Len() int {
81 return len(d.data) - d.offset
84 func (d *decBuffer) Bytes() []byte {
85 return d.data[d.offset:]
88 func (d *decBuffer) Reset() {
89 d.data = d.data[0:0]
90 d.offset = 0
93 // We pass the bytes.Buffer separately for easier testing of the infrastructure
94 // without requiring a full Decoder.
95 func (dec *Decoder) newDecoderState(buf *decBuffer) *decoderState {
96 d := dec.freeList
97 if d == nil {
98 d = new(decoderState)
99 d.dec = dec
100 } else {
101 dec.freeList = d.next
103 d.b = buf
104 return d
107 func (dec *Decoder) freeDecoderState(d *decoderState) {
108 d.next = dec.freeList
109 dec.freeList = d
112 func overflow(name string) error {
113 return errors.New(`value for "` + name + `" out of range`)
116 // decodeUintReader reads an encoded unsigned integer from an io.Reader.
117 // Used only by the Decoder to read the message length.
118 func decodeUintReader(r io.Reader, buf []byte) (x uint64, width int, err error) {
119 width = 1
120 n, err := io.ReadFull(r, buf[0:width])
121 if n == 0 {
122 return
124 b := buf[0]
125 if b <= 0x7f {
126 return uint64(b), width, nil
128 n = -int(int8(b))
129 if n > uint64Size {
130 err = errBadUint
131 return
133 width, err = io.ReadFull(r, buf[0:n])
134 if err != nil {
135 if err == io.EOF {
136 err = io.ErrUnexpectedEOF
138 return
140 // Could check that the high byte is zero but it's not worth it.
141 for _, b := range buf[0:width] {
142 x = x<<8 | uint64(b)
144 width++ // +1 for length byte
145 return
148 // decodeUint reads an encoded unsigned integer from state.r.
149 // Does not check for overflow.
150 func (state *decoderState) decodeUint() (x uint64) {
151 b, err := state.b.ReadByte()
152 if err != nil {
153 error_(err)
155 if b <= 0x7f {
156 return uint64(b)
158 n := -int(int8(b))
159 if n > uint64Size {
160 error_(errBadUint)
162 buf := state.b.Bytes()
163 if len(buf) < n {
164 errorf("invalid uint data length %d: exceeds input size %d", n, len(buf))
166 // Don't need to check error; it's safe to loop regardless.
167 // Could check that the high byte is zero but it's not worth it.
168 for _, b := range buf[0:n] {
169 x = x<<8 | uint64(b)
171 state.b.Drop(n)
172 return x
175 // decodeInt reads an encoded signed integer from state.r.
176 // Does not check for overflow.
177 func (state *decoderState) decodeInt() int64 {
178 x := state.decodeUint()
179 if x&1 != 0 {
180 return ^int64(x >> 1)
182 return int64(x >> 1)
185 // getLength decodes the next uint and makes sure it is a possible
186 // size for a data item that follows, which means it must fit in a
187 // non-negative int and fit in the buffer.
188 func (state *decoderState) getLength() (int, bool) {
189 n := int(state.decodeUint())
190 if n < 0 || state.b.Len() < n || tooBig <= n {
191 return 0, false
193 return n, true
196 // decOp is the signature of a decoding operator for a given type.
197 type decOp func(i *decInstr, state *decoderState, v reflect.Value)
199 // The 'instructions' of the decoding machine
200 type decInstr struct {
201 op decOp
202 field int // field number of the wire type
203 index []int // field access indices for destination type
204 ovfl error // error message for overflow/underflow (for arrays, of the elements)
207 // ignoreUint discards a uint value with no destination.
208 func ignoreUint(i *decInstr, state *decoderState, v reflect.Value) {
209 state.decodeUint()
212 // ignoreTwoUints discards a uint value with no destination. It's used to skip
213 // complex values.
214 func ignoreTwoUints(i *decInstr, state *decoderState, v reflect.Value) {
215 state.decodeUint()
216 state.decodeUint()
219 // Since the encoder writes no zeros, if we arrive at a decoder we have
220 // a value to extract and store. The field number has already been read
221 // (it's how we knew to call this decoder).
222 // Each decoder is responsible for handling any indirections associated
223 // with the data structure. If any pointer so reached is nil, allocation must
224 // be done.
226 // decAlloc takes a value and returns a settable value that can
227 // be assigned to. If the value is a pointer, decAlloc guarantees it points to storage.
228 // The callers to the individual decoders are expected to have used decAlloc.
229 // The individual decoders don't need to it.
230 func decAlloc(v reflect.Value) reflect.Value {
231 for v.Kind() == reflect.Ptr {
232 if v.IsNil() {
233 v.Set(reflect.New(v.Type().Elem()))
235 v = v.Elem()
237 return v
240 // decBool decodes a uint and stores it as a boolean in value.
241 func decBool(i *decInstr, state *decoderState, value reflect.Value) {
242 value.SetBool(state.decodeUint() != 0)
245 // decInt8 decodes an integer and stores it as an int8 in value.
246 func decInt8(i *decInstr, state *decoderState, value reflect.Value) {
247 v := state.decodeInt()
248 if v < math.MinInt8 || math.MaxInt8 < v {
249 error_(i.ovfl)
251 value.SetInt(v)
254 // decUint8 decodes an unsigned integer and stores it as a uint8 in value.
255 func decUint8(i *decInstr, state *decoderState, value reflect.Value) {
256 v := state.decodeUint()
257 if math.MaxUint8 < v {
258 error_(i.ovfl)
260 value.SetUint(v)
263 // decInt16 decodes an integer and stores it as an int16 in value.
264 func decInt16(i *decInstr, state *decoderState, value reflect.Value) {
265 v := state.decodeInt()
266 if v < math.MinInt16 || math.MaxInt16 < v {
267 error_(i.ovfl)
269 value.SetInt(v)
272 // decUint16 decodes an unsigned integer and stores it as a uint16 in value.
273 func decUint16(i *decInstr, state *decoderState, value reflect.Value) {
274 v := state.decodeUint()
275 if math.MaxUint16 < v {
276 error_(i.ovfl)
278 value.SetUint(v)
281 // decInt32 decodes an integer and stores it as an int32 in value.
282 func decInt32(i *decInstr, state *decoderState, value reflect.Value) {
283 v := state.decodeInt()
284 if v < math.MinInt32 || math.MaxInt32 < v {
285 error_(i.ovfl)
287 value.SetInt(v)
290 // decUint32 decodes an unsigned integer and stores it as a uint32 in value.
291 func decUint32(i *decInstr, state *decoderState, value reflect.Value) {
292 v := state.decodeUint()
293 if math.MaxUint32 < v {
294 error_(i.ovfl)
296 value.SetUint(v)
299 // decInt64 decodes an integer and stores it as an int64 in value.
300 func decInt64(i *decInstr, state *decoderState, value reflect.Value) {
301 v := state.decodeInt()
302 value.SetInt(v)
305 // decUint64 decodes an unsigned integer and stores it as a uint64 in value.
306 func decUint64(i *decInstr, state *decoderState, value reflect.Value) {
307 v := state.decodeUint()
308 value.SetUint(v)
311 // Floating-point numbers are transmitted as uint64s holding the bits
312 // of the underlying representation. They are sent byte-reversed, with
313 // the exponent end coming out first, so integer floating point numbers
314 // (for example) transmit more compactly. This routine does the
315 // unswizzling.
316 func float64FromBits(u uint64) float64 {
317 v := bits.ReverseBytes64(u)
318 return math.Float64frombits(v)
321 // float32FromBits decodes an unsigned integer, treats it as a 32-bit floating-point
322 // number, and returns it. It's a helper function for float32 and complex64.
323 // It returns a float64 because that's what reflection needs, but its return
324 // value is known to be accurately representable in a float32.
325 func float32FromBits(u uint64, ovfl error) float64 {
326 v := float64FromBits(u)
327 av := v
328 if av < 0 {
329 av = -av
331 // +Inf is OK in both 32- and 64-bit floats. Underflow is always OK.
332 if math.MaxFloat32 < av && av <= math.MaxFloat64 {
333 error_(ovfl)
335 return v
338 // decFloat32 decodes an unsigned integer, treats it as a 32-bit floating-point
339 // number, and stores it in value.
340 func decFloat32(i *decInstr, state *decoderState, value reflect.Value) {
341 value.SetFloat(float32FromBits(state.decodeUint(), i.ovfl))
344 // decFloat64 decodes an unsigned integer, treats it as a 64-bit floating-point
345 // number, and stores it in value.
346 func decFloat64(i *decInstr, state *decoderState, value reflect.Value) {
347 value.SetFloat(float64FromBits(state.decodeUint()))
350 // decComplex64 decodes a pair of unsigned integers, treats them as a
351 // pair of floating point numbers, and stores them as a complex64 in value.
352 // The real part comes first.
353 func decComplex64(i *decInstr, state *decoderState, value reflect.Value) {
354 real := float32FromBits(state.decodeUint(), i.ovfl)
355 imag := float32FromBits(state.decodeUint(), i.ovfl)
356 value.SetComplex(complex(real, imag))
359 // decComplex128 decodes a pair of unsigned integers, treats them as a
360 // pair of floating point numbers, and stores them as a complex128 in value.
361 // The real part comes first.
362 func decComplex128(i *decInstr, state *decoderState, value reflect.Value) {
363 real := float64FromBits(state.decodeUint())
364 imag := float64FromBits(state.decodeUint())
365 value.SetComplex(complex(real, imag))
368 // decUint8Slice decodes a byte slice and stores in value a slice header
369 // describing the data.
370 // uint8 slices are encoded as an unsigned count followed by the raw bytes.
371 func decUint8Slice(i *decInstr, state *decoderState, value reflect.Value) {
372 n, ok := state.getLength()
373 if !ok {
374 errorf("bad %s slice length: %d", value.Type(), n)
376 if value.Cap() < n {
377 value.Set(reflect.MakeSlice(value.Type(), n, n))
378 } else {
379 value.Set(value.Slice(0, n))
381 if _, err := state.b.Read(value.Bytes()); err != nil {
382 errorf("error decoding []byte: %s", err)
386 // decString decodes byte array and stores in value a string header
387 // describing the data.
388 // Strings are encoded as an unsigned count followed by the raw bytes.
389 func decString(i *decInstr, state *decoderState, value reflect.Value) {
390 n, ok := state.getLength()
391 if !ok {
392 errorf("bad %s slice length: %d", value.Type(), n)
394 // Read the data.
395 data := state.b.Bytes()
396 if len(data) < n {
397 errorf("invalid string length %d: exceeds input size %d", n, len(data))
399 s := string(data[:n])
400 state.b.Drop(n)
401 value.SetString(s)
404 // ignoreUint8Array skips over the data for a byte slice value with no destination.
405 func ignoreUint8Array(i *decInstr, state *decoderState, value reflect.Value) {
406 n, ok := state.getLength()
407 if !ok {
408 errorf("slice length too large")
410 bn := state.b.Len()
411 if bn < n {
412 errorf("invalid slice length %d: exceeds input size %d", n, bn)
414 state.b.Drop(n)
417 // Execution engine
419 // The encoder engine is an array of instructions indexed by field number of the incoming
420 // decoder. It is executed with random access according to field number.
421 type decEngine struct {
422 instr []decInstr
423 numInstr int // the number of active instructions
426 // decodeSingle decodes a top-level value that is not a struct and stores it in value.
427 // Such values are preceded by a zero, making them have the memory layout of a
428 // struct field (although with an illegal field number).
429 func (dec *Decoder) decodeSingle(engine *decEngine, value reflect.Value) {
430 state := dec.newDecoderState(&dec.buf)
431 defer dec.freeDecoderState(state)
432 state.fieldnum = singletonField
433 if state.decodeUint() != 0 {
434 errorf("decode: corrupted data: non-zero delta for singleton")
436 instr := &engine.instr[singletonField]
437 instr.op(instr, state, value)
440 // decodeStruct decodes a top-level struct and stores it in value.
441 // Indir is for the value, not the type. At the time of the call it may
442 // differ from ut.indir, which was computed when the engine was built.
443 // This state cannot arise for decodeSingle, which is called directly
444 // from the user's value, not from the innards of an engine.
445 func (dec *Decoder) decodeStruct(engine *decEngine, value reflect.Value) {
446 state := dec.newDecoderState(&dec.buf)
447 defer dec.freeDecoderState(state)
448 state.fieldnum = -1
449 for state.b.Len() > 0 {
450 delta := int(state.decodeUint())
451 if delta < 0 {
452 errorf("decode: corrupted data: negative delta")
454 if delta == 0 { // struct terminator is zero delta fieldnum
455 break
457 fieldnum := state.fieldnum + delta
458 if fieldnum >= len(engine.instr) {
459 error_(errRange)
460 break
462 instr := &engine.instr[fieldnum]
463 var field reflect.Value
464 if instr.index != nil {
465 // Otherwise the field is unknown to us and instr.op is an ignore op.
466 field = value.FieldByIndex(instr.index)
467 if field.Kind() == reflect.Ptr {
468 field = decAlloc(field)
471 instr.op(instr, state, field)
472 state.fieldnum = fieldnum
476 var noValue reflect.Value
478 // ignoreStruct discards the data for a struct with no destination.
479 func (dec *Decoder) ignoreStruct(engine *decEngine) {
480 state := dec.newDecoderState(&dec.buf)
481 defer dec.freeDecoderState(state)
482 state.fieldnum = -1
483 for state.b.Len() > 0 {
484 delta := int(state.decodeUint())
485 if delta < 0 {
486 errorf("ignore decode: corrupted data: negative delta")
488 if delta == 0 { // struct terminator is zero delta fieldnum
489 break
491 fieldnum := state.fieldnum + delta
492 if fieldnum >= len(engine.instr) {
493 error_(errRange)
495 instr := &engine.instr[fieldnum]
496 instr.op(instr, state, noValue)
497 state.fieldnum = fieldnum
501 // ignoreSingle discards the data for a top-level non-struct value with no
502 // destination. It's used when calling Decode with a nil value.
503 func (dec *Decoder) ignoreSingle(engine *decEngine) {
504 state := dec.newDecoderState(&dec.buf)
505 defer dec.freeDecoderState(state)
506 state.fieldnum = singletonField
507 delta := int(state.decodeUint())
508 if delta != 0 {
509 errorf("decode: corrupted data: non-zero delta for singleton")
511 instr := &engine.instr[singletonField]
512 instr.op(instr, state, noValue)
515 // decodeArrayHelper does the work for decoding arrays and slices.
516 func (dec *Decoder) decodeArrayHelper(state *decoderState, value reflect.Value, elemOp decOp, length int, ovfl error, helper decHelper) {
517 if helper != nil && helper(state, value, length, ovfl) {
518 return
520 instr := &decInstr{elemOp, 0, nil, ovfl}
521 isPtr := value.Type().Elem().Kind() == reflect.Ptr
522 for i := 0; i < length; i++ {
523 if state.b.Len() == 0 {
524 errorf("decoding array or slice: length exceeds input size (%d elements)", length)
526 v := value.Index(i)
527 if isPtr {
528 v = decAlloc(v)
530 elemOp(instr, state, v)
534 // decodeArray decodes an array and stores it in value.
535 // The length is an unsigned integer preceding the elements. Even though the length is redundant
536 // (it's part of the type), it's a useful check and is included in the encoding.
537 func (dec *Decoder) decodeArray(state *decoderState, value reflect.Value, elemOp decOp, length int, ovfl error, helper decHelper) {
538 if n := state.decodeUint(); n != uint64(length) {
539 errorf("length mismatch in decodeArray")
541 dec.decodeArrayHelper(state, value, elemOp, length, ovfl, helper)
544 // decodeIntoValue is a helper for map decoding.
545 func decodeIntoValue(state *decoderState, op decOp, isPtr bool, value reflect.Value, instr *decInstr) reflect.Value {
546 v := value
547 if isPtr {
548 v = decAlloc(value)
551 op(instr, state, v)
552 return value
555 // decodeMap decodes a map and stores it in value.
556 // Maps are encoded as a length followed by key:value pairs.
557 // Because the internals of maps are not visible to us, we must
558 // use reflection rather than pointer magic.
559 func (dec *Decoder) decodeMap(mtyp reflect.Type, state *decoderState, value reflect.Value, keyOp, elemOp decOp, ovfl error) {
560 n := int(state.decodeUint())
561 if value.IsNil() {
562 value.Set(reflect.MakeMapWithSize(mtyp, n))
564 keyIsPtr := mtyp.Key().Kind() == reflect.Ptr
565 elemIsPtr := mtyp.Elem().Kind() == reflect.Ptr
566 keyInstr := &decInstr{keyOp, 0, nil, ovfl}
567 elemInstr := &decInstr{elemOp, 0, nil, ovfl}
568 keyP := reflect.New(mtyp.Key())
569 keyZ := reflect.Zero(mtyp.Key())
570 elemP := reflect.New(mtyp.Elem())
571 elemZ := reflect.Zero(mtyp.Elem())
572 for i := 0; i < n; i++ {
573 key := decodeIntoValue(state, keyOp, keyIsPtr, keyP.Elem(), keyInstr)
574 elem := decodeIntoValue(state, elemOp, elemIsPtr, elemP.Elem(), elemInstr)
575 value.SetMapIndex(key, elem)
576 keyP.Elem().Set(keyZ)
577 elemP.Elem().Set(elemZ)
581 // ignoreArrayHelper does the work for discarding arrays and slices.
582 func (dec *Decoder) ignoreArrayHelper(state *decoderState, elemOp decOp, length int) {
583 instr := &decInstr{elemOp, 0, nil, errors.New("no error")}
584 for i := 0; i < length; i++ {
585 if state.b.Len() == 0 {
586 errorf("decoding array or slice: length exceeds input size (%d elements)", length)
588 elemOp(instr, state, noValue)
592 // ignoreArray discards the data for an array value with no destination.
593 func (dec *Decoder) ignoreArray(state *decoderState, elemOp decOp, length int) {
594 if n := state.decodeUint(); n != uint64(length) {
595 errorf("length mismatch in ignoreArray")
597 dec.ignoreArrayHelper(state, elemOp, length)
600 // ignoreMap discards the data for a map value with no destination.
601 func (dec *Decoder) ignoreMap(state *decoderState, keyOp, elemOp decOp) {
602 n := int(state.decodeUint())
603 keyInstr := &decInstr{keyOp, 0, nil, errors.New("no error")}
604 elemInstr := &decInstr{elemOp, 0, nil, errors.New("no error")}
605 for i := 0; i < n; i++ {
606 keyOp(keyInstr, state, noValue)
607 elemOp(elemInstr, state, noValue)
611 // decodeSlice decodes a slice and stores it in value.
612 // Slices are encoded as an unsigned length followed by the elements.
613 func (dec *Decoder) decodeSlice(state *decoderState, value reflect.Value, elemOp decOp, ovfl error, helper decHelper) {
614 u := state.decodeUint()
615 typ := value.Type()
616 size := uint64(typ.Elem().Size())
617 nBytes := u * size
618 n := int(u)
619 // Take care with overflow in this calculation.
620 if n < 0 || uint64(n) != u || nBytes > tooBig || (size > 0 && nBytes/size != u) {
621 // We don't check n against buffer length here because if it's a slice
622 // of interfaces, there will be buffer reloads.
623 errorf("%s slice too big: %d elements of %d bytes", typ.Elem(), u, size)
625 if value.Cap() < n {
626 value.Set(reflect.MakeSlice(typ, n, n))
627 } else {
628 value.Set(value.Slice(0, n))
630 dec.decodeArrayHelper(state, value, elemOp, n, ovfl, helper)
633 // ignoreSlice skips over the data for a slice value with no destination.
634 func (dec *Decoder) ignoreSlice(state *decoderState, elemOp decOp) {
635 dec.ignoreArrayHelper(state, elemOp, int(state.decodeUint()))
638 // decodeInterface decodes an interface value and stores it in value.
639 // Interfaces are encoded as the name of a concrete type followed by a value.
640 // If the name is empty, the value is nil and no value is sent.
641 func (dec *Decoder) decodeInterface(ityp reflect.Type, state *decoderState, value reflect.Value) {
642 // Read the name of the concrete type.
643 nr := state.decodeUint()
644 if nr > 1<<31 { // zero is permissible for anonymous types
645 errorf("invalid type name length %d", nr)
647 if nr > uint64(state.b.Len()) {
648 errorf("invalid type name length %d: exceeds input size", nr)
650 n := int(nr)
651 name := state.b.Bytes()[:n]
652 state.b.Drop(n)
653 // Allocate the destination interface value.
654 if len(name) == 0 {
655 // Copy the nil interface value to the target.
656 value.Set(reflect.Zero(value.Type()))
657 return
659 if len(name) > 1024 {
660 errorf("name too long (%d bytes): %.20q...", len(name), name)
662 // The concrete type must be registered.
663 typi, ok := nameToConcreteType.Load(string(name))
664 if !ok {
665 errorf("name not registered for interface: %q", name)
667 typ := typi.(reflect.Type)
669 // Read the type id of the concrete value.
670 concreteId := dec.decodeTypeSequence(true)
671 if concreteId < 0 {
672 error_(dec.err)
674 // Byte count of value is next; we don't care what it is (it's there
675 // in case we want to ignore the value by skipping it completely).
676 state.decodeUint()
677 // Read the concrete value.
678 v := allocValue(typ)
679 dec.decodeValue(concreteId, v)
680 if dec.err != nil {
681 error_(dec.err)
683 // Assign the concrete value to the interface.
684 // Tread carefully; it might not satisfy the interface.
685 if !typ.AssignableTo(ityp) {
686 errorf("%s is not assignable to type %s", typ, ityp)
688 // Copy the interface value to the target.
689 value.Set(v)
692 // ignoreInterface discards the data for an interface value with no destination.
693 func (dec *Decoder) ignoreInterface(state *decoderState) {
694 // Read the name of the concrete type.
695 n, ok := state.getLength()
696 if !ok {
697 errorf("bad interface encoding: name too large for buffer")
699 bn := state.b.Len()
700 if bn < n {
701 errorf("invalid interface value length %d: exceeds input size %d", n, bn)
703 state.b.Drop(n)
704 id := dec.decodeTypeSequence(true)
705 if id < 0 {
706 error_(dec.err)
708 // At this point, the decoder buffer contains a delimited value. Just toss it.
709 n, ok = state.getLength()
710 if !ok {
711 errorf("bad interface encoding: data length too large for buffer")
713 state.b.Drop(n)
716 // decodeGobDecoder decodes something implementing the GobDecoder interface.
717 // The data is encoded as a byte slice.
718 func (dec *Decoder) decodeGobDecoder(ut *userTypeInfo, state *decoderState, value reflect.Value) {
719 // Read the bytes for the value.
720 n, ok := state.getLength()
721 if !ok {
722 errorf("GobDecoder: length too large for buffer")
724 b := state.b.Bytes()
725 if len(b) < n {
726 errorf("GobDecoder: invalid data length %d: exceeds input size %d", n, len(b))
728 b = b[:n]
729 state.b.Drop(n)
730 var err error
731 // We know it's one of these.
732 switch ut.externalDec {
733 case xGob:
734 err = value.Interface().(GobDecoder).GobDecode(b)
735 case xBinary:
736 err = value.Interface().(encoding.BinaryUnmarshaler).UnmarshalBinary(b)
737 case xText:
738 err = value.Interface().(encoding.TextUnmarshaler).UnmarshalText(b)
740 if err != nil {
741 error_(err)
745 // ignoreGobDecoder discards the data for a GobDecoder value with no destination.
746 func (dec *Decoder) ignoreGobDecoder(state *decoderState) {
747 // Read the bytes for the value.
748 n, ok := state.getLength()
749 if !ok {
750 errorf("GobDecoder: length too large for buffer")
752 bn := state.b.Len()
753 if bn < n {
754 errorf("GobDecoder: invalid data length %d: exceeds input size %d", n, bn)
756 state.b.Drop(n)
759 // Index by Go types.
760 var decOpTable = [...]decOp{
761 reflect.Bool: decBool,
762 reflect.Int8: decInt8,
763 reflect.Int16: decInt16,
764 reflect.Int32: decInt32,
765 reflect.Int64: decInt64,
766 reflect.Uint8: decUint8,
767 reflect.Uint16: decUint16,
768 reflect.Uint32: decUint32,
769 reflect.Uint64: decUint64,
770 reflect.Float32: decFloat32,
771 reflect.Float64: decFloat64,
772 reflect.Complex64: decComplex64,
773 reflect.Complex128: decComplex128,
774 reflect.String: decString,
777 // Indexed by gob types. tComplex will be added during type.init().
778 var decIgnoreOpMap = map[typeId]decOp{
779 tBool: ignoreUint,
780 tInt: ignoreUint,
781 tUint: ignoreUint,
782 tFloat: ignoreUint,
783 tBytes: ignoreUint8Array,
784 tString: ignoreUint8Array,
785 tComplex: ignoreTwoUints,
788 // decOpFor returns the decoding op for the base type under rt and
789 // the indirection count to reach it.
790 func (dec *Decoder) decOpFor(wireId typeId, rt reflect.Type, name string, inProgress map[reflect.Type]*decOp) *decOp {
791 ut := userType(rt)
792 // If the type implements GobEncoder, we handle it without further processing.
793 if ut.externalDec != 0 {
794 return dec.gobDecodeOpFor(ut)
797 // If this type is already in progress, it's a recursive type (e.g. map[string]*T).
798 // Return the pointer to the op we're already building.
799 if opPtr := inProgress[rt]; opPtr != nil {
800 return opPtr
802 typ := ut.base
803 var op decOp
804 k := typ.Kind()
805 if int(k) < len(decOpTable) {
806 op = decOpTable[k]
808 if op == nil {
809 inProgress[rt] = &op
810 // Special cases
811 switch t := typ; t.Kind() {
812 case reflect.Array:
813 name = "element of " + name
814 elemId := dec.wireType[wireId].ArrayT.Elem
815 elemOp := dec.decOpFor(elemId, t.Elem(), name, inProgress)
816 ovfl := overflow(name)
817 helper := decArrayHelper[t.Elem().Kind()]
818 op = func(i *decInstr, state *decoderState, value reflect.Value) {
819 state.dec.decodeArray(state, value, *elemOp, t.Len(), ovfl, helper)
822 case reflect.Map:
823 keyId := dec.wireType[wireId].MapT.Key
824 elemId := dec.wireType[wireId].MapT.Elem
825 keyOp := dec.decOpFor(keyId, t.Key(), "key of "+name, inProgress)
826 elemOp := dec.decOpFor(elemId, t.Elem(), "element of "+name, inProgress)
827 ovfl := overflow(name)
828 op = func(i *decInstr, state *decoderState, value reflect.Value) {
829 state.dec.decodeMap(t, state, value, *keyOp, *elemOp, ovfl)
832 case reflect.Slice:
833 name = "element of " + name
834 if t.Elem().Kind() == reflect.Uint8 {
835 op = decUint8Slice
836 break
838 var elemId typeId
839 if tt, ok := builtinIdToType[wireId]; ok {
840 elemId = tt.(*sliceType).Elem
841 } else {
842 elemId = dec.wireType[wireId].SliceT.Elem
844 elemOp := dec.decOpFor(elemId, t.Elem(), name, inProgress)
845 ovfl := overflow(name)
846 helper := decSliceHelper[t.Elem().Kind()]
847 op = func(i *decInstr, state *decoderState, value reflect.Value) {
848 state.dec.decodeSlice(state, value, *elemOp, ovfl, helper)
851 case reflect.Struct:
852 // Generate a closure that calls out to the engine for the nested type.
853 ut := userType(typ)
854 enginePtr, err := dec.getDecEnginePtr(wireId, ut)
855 if err != nil {
856 error_(err)
858 op = func(i *decInstr, state *decoderState, value reflect.Value) {
859 // indirect through enginePtr to delay evaluation for recursive structs.
860 dec.decodeStruct(*enginePtr, value)
862 case reflect.Interface:
863 op = func(i *decInstr, state *decoderState, value reflect.Value) {
864 state.dec.decodeInterface(t, state, value)
868 if op == nil {
869 errorf("decode can't handle type %s", rt)
871 return &op
874 // decIgnoreOpFor returns the decoding op for a field that has no destination.
875 func (dec *Decoder) decIgnoreOpFor(wireId typeId, inProgress map[typeId]*decOp) *decOp {
876 // If this type is already in progress, it's a recursive type (e.g. map[string]*T).
877 // Return the pointer to the op we're already building.
878 if opPtr := inProgress[wireId]; opPtr != nil {
879 return opPtr
881 op, ok := decIgnoreOpMap[wireId]
882 if !ok {
883 inProgress[wireId] = &op
884 if wireId == tInterface {
885 // Special case because it's a method: the ignored item might
886 // define types and we need to record their state in the decoder.
887 op = func(i *decInstr, state *decoderState, value reflect.Value) {
888 state.dec.ignoreInterface(state)
890 return &op
892 // Special cases
893 wire := dec.wireType[wireId]
894 switch {
895 case wire == nil:
896 errorf("bad data: undefined type %s", wireId.string())
897 case wire.ArrayT != nil:
898 elemId := wire.ArrayT.Elem
899 elemOp := dec.decIgnoreOpFor(elemId, inProgress)
900 op = func(i *decInstr, state *decoderState, value reflect.Value) {
901 state.dec.ignoreArray(state, *elemOp, wire.ArrayT.Len)
904 case wire.MapT != nil:
905 keyId := dec.wireType[wireId].MapT.Key
906 elemId := dec.wireType[wireId].MapT.Elem
907 keyOp := dec.decIgnoreOpFor(keyId, inProgress)
908 elemOp := dec.decIgnoreOpFor(elemId, inProgress)
909 op = func(i *decInstr, state *decoderState, value reflect.Value) {
910 state.dec.ignoreMap(state, *keyOp, *elemOp)
913 case wire.SliceT != nil:
914 elemId := wire.SliceT.Elem
915 elemOp := dec.decIgnoreOpFor(elemId, inProgress)
916 op = func(i *decInstr, state *decoderState, value reflect.Value) {
917 state.dec.ignoreSlice(state, *elemOp)
920 case wire.StructT != nil:
921 // Generate a closure that calls out to the engine for the nested type.
922 enginePtr, err := dec.getIgnoreEnginePtr(wireId)
923 if err != nil {
924 error_(err)
926 op = func(i *decInstr, state *decoderState, value reflect.Value) {
927 // indirect through enginePtr to delay evaluation for recursive structs
928 state.dec.ignoreStruct(*enginePtr)
931 case wire.GobEncoderT != nil, wire.BinaryMarshalerT != nil, wire.TextMarshalerT != nil:
932 op = func(i *decInstr, state *decoderState, value reflect.Value) {
933 state.dec.ignoreGobDecoder(state)
937 if op == nil {
938 errorf("bad data: ignore can't handle type %s", wireId.string())
940 return &op
943 // gobDecodeOpFor returns the op for a type that is known to implement
944 // GobDecoder.
945 func (dec *Decoder) gobDecodeOpFor(ut *userTypeInfo) *decOp {
946 rcvrType := ut.user
947 if ut.decIndir == -1 {
948 rcvrType = reflect.PtrTo(rcvrType)
949 } else if ut.decIndir > 0 {
950 for i := int8(0); i < ut.decIndir; i++ {
951 rcvrType = rcvrType.Elem()
954 var op decOp
955 op = func(i *decInstr, state *decoderState, value reflect.Value) {
956 // We now have the base type. We need its address if the receiver is a pointer.
957 if value.Kind() != reflect.Ptr && rcvrType.Kind() == reflect.Ptr {
958 value = value.Addr()
960 state.dec.decodeGobDecoder(ut, state, value)
962 return &op
965 // compatibleType asks: Are these two gob Types compatible?
966 // Answers the question for basic types, arrays, maps and slices, plus
967 // GobEncoder/Decoder pairs.
968 // Structs are considered ok; fields will be checked later.
969 func (dec *Decoder) compatibleType(fr reflect.Type, fw typeId, inProgress map[reflect.Type]typeId) bool {
970 if rhs, ok := inProgress[fr]; ok {
971 return rhs == fw
973 inProgress[fr] = fw
974 ut := userType(fr)
975 wire, ok := dec.wireType[fw]
976 // If wire was encoded with an encoding method, fr must have that method.
977 // And if not, it must not.
978 // At most one of the booleans in ut is set.
979 // We could possibly relax this constraint in the future in order to
980 // choose the decoding method using the data in the wireType.
981 // The parentheses look odd but are correct.
982 if (ut.externalDec == xGob) != (ok && wire.GobEncoderT != nil) ||
983 (ut.externalDec == xBinary) != (ok && wire.BinaryMarshalerT != nil) ||
984 (ut.externalDec == xText) != (ok && wire.TextMarshalerT != nil) {
985 return false
987 if ut.externalDec != 0 { // This test trumps all others.
988 return true
990 switch t := ut.base; t.Kind() {
991 default:
992 // chan, etc: cannot handle.
993 return false
994 case reflect.Bool:
995 return fw == tBool
996 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
997 return fw == tInt
998 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
999 return fw == tUint
1000 case reflect.Float32, reflect.Float64:
1001 return fw == tFloat
1002 case reflect.Complex64, reflect.Complex128:
1003 return fw == tComplex
1004 case reflect.String:
1005 return fw == tString
1006 case reflect.Interface:
1007 return fw == tInterface
1008 case reflect.Array:
1009 if !ok || wire.ArrayT == nil {
1010 return false
1012 array := wire.ArrayT
1013 return t.Len() == array.Len && dec.compatibleType(t.Elem(), array.Elem, inProgress)
1014 case reflect.Map:
1015 if !ok || wire.MapT == nil {
1016 return false
1018 MapType := wire.MapT
1019 return dec.compatibleType(t.Key(), MapType.Key, inProgress) && dec.compatibleType(t.Elem(), MapType.Elem, inProgress)
1020 case reflect.Slice:
1021 // Is it an array of bytes?
1022 if t.Elem().Kind() == reflect.Uint8 {
1023 return fw == tBytes
1025 // Extract and compare element types.
1026 var sw *sliceType
1027 if tt, ok := builtinIdToType[fw]; ok {
1028 sw, _ = tt.(*sliceType)
1029 } else if wire != nil {
1030 sw = wire.SliceT
1032 elem := userType(t.Elem()).base
1033 return sw != nil && dec.compatibleType(elem, sw.Elem, inProgress)
1034 case reflect.Struct:
1035 return true
1039 // typeString returns a human-readable description of the type identified by remoteId.
1040 func (dec *Decoder) typeString(remoteId typeId) string {
1041 if t := idToType[remoteId]; t != nil {
1042 // globally known type.
1043 return t.string()
1045 return dec.wireType[remoteId].string()
1048 // compileSingle compiles the decoder engine for a non-struct top-level value, including
1049 // GobDecoders.
1050 func (dec *Decoder) compileSingle(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) {
1051 rt := ut.user
1052 engine = new(decEngine)
1053 engine.instr = make([]decInstr, 1) // one item
1054 name := rt.String() // best we can do
1055 if !dec.compatibleType(rt, remoteId, make(map[reflect.Type]typeId)) {
1056 remoteType := dec.typeString(remoteId)
1057 // Common confusing case: local interface type, remote concrete type.
1058 if ut.base.Kind() == reflect.Interface && remoteId != tInterface {
1059 return nil, errors.New("gob: local interface type " + name + " can only be decoded from remote interface type; received concrete type " + remoteType)
1061 return nil, errors.New("gob: decoding into local type " + name + ", received remote type " + remoteType)
1063 op := dec.decOpFor(remoteId, rt, name, make(map[reflect.Type]*decOp))
1064 ovfl := errors.New(`value for "` + name + `" out of range`)
1065 engine.instr[singletonField] = decInstr{*op, singletonField, nil, ovfl}
1066 engine.numInstr = 1
1067 return
1070 // compileIgnoreSingle compiles the decoder engine for a non-struct top-level value that will be discarded.
1071 func (dec *Decoder) compileIgnoreSingle(remoteId typeId) (engine *decEngine, err error) {
1072 engine = new(decEngine)
1073 engine.instr = make([]decInstr, 1) // one item
1074 op := dec.decIgnoreOpFor(remoteId, make(map[typeId]*decOp))
1075 ovfl := overflow(dec.typeString(remoteId))
1076 engine.instr[0] = decInstr{*op, 0, nil, ovfl}
1077 engine.numInstr = 1
1078 return
1081 // compileDec compiles the decoder engine for a value. If the value is not a struct,
1082 // it calls out to compileSingle.
1083 func (dec *Decoder) compileDec(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) {
1084 defer catchError(&err)
1085 rt := ut.base
1086 srt := rt
1087 if srt.Kind() != reflect.Struct || ut.externalDec != 0 {
1088 return dec.compileSingle(remoteId, ut)
1090 var wireStruct *structType
1091 // Builtin types can come from global pool; the rest must be defined by the decoder.
1092 // Also we know we're decoding a struct now, so the client must have sent one.
1093 if t, ok := builtinIdToType[remoteId]; ok {
1094 wireStruct, _ = t.(*structType)
1095 } else {
1096 wire := dec.wireType[remoteId]
1097 if wire == nil {
1098 error_(errBadType)
1100 wireStruct = wire.StructT
1102 if wireStruct == nil {
1103 errorf("type mismatch in decoder: want struct type %s; got non-struct", rt)
1105 engine = new(decEngine)
1106 engine.instr = make([]decInstr, len(wireStruct.Field))
1107 seen := make(map[reflect.Type]*decOp)
1108 // Loop over the fields of the wire type.
1109 for fieldnum := 0; fieldnum < len(wireStruct.Field); fieldnum++ {
1110 wireField := wireStruct.Field[fieldnum]
1111 if wireField.Name == "" {
1112 errorf("empty name for remote field of type %s", wireStruct.Name)
1114 ovfl := overflow(wireField.Name)
1115 // Find the field of the local type with the same name.
1116 localField, present := srt.FieldByName(wireField.Name)
1117 // TODO(r): anonymous names
1118 if !present || !isExported(wireField.Name) {
1119 op := dec.decIgnoreOpFor(wireField.Id, make(map[typeId]*decOp))
1120 engine.instr[fieldnum] = decInstr{*op, fieldnum, nil, ovfl}
1121 continue
1123 if !dec.compatibleType(localField.Type, wireField.Id, make(map[reflect.Type]typeId)) {
1124 errorf("wrong type (%s) for received field %s.%s", localField.Type, wireStruct.Name, wireField.Name)
1126 op := dec.decOpFor(wireField.Id, localField.Type, localField.Name, seen)
1127 engine.instr[fieldnum] = decInstr{*op, fieldnum, localField.Index, ovfl}
1128 engine.numInstr++
1130 return
1133 // getDecEnginePtr returns the engine for the specified type.
1134 func (dec *Decoder) getDecEnginePtr(remoteId typeId, ut *userTypeInfo) (enginePtr **decEngine, err error) {
1135 rt := ut.user
1136 decoderMap, ok := dec.decoderCache[rt]
1137 if !ok {
1138 decoderMap = make(map[typeId]**decEngine)
1139 dec.decoderCache[rt] = decoderMap
1141 if enginePtr, ok = decoderMap[remoteId]; !ok {
1142 // To handle recursive types, mark this engine as underway before compiling.
1143 enginePtr = new(*decEngine)
1144 decoderMap[remoteId] = enginePtr
1145 *enginePtr, err = dec.compileDec(remoteId, ut)
1146 if err != nil {
1147 delete(decoderMap, remoteId)
1150 return
1153 // emptyStruct is the type we compile into when ignoring a struct value.
1154 type emptyStruct struct{}
1156 var emptyStructType = reflect.TypeOf(emptyStruct{})
1158 // getIgnoreEnginePtr returns the engine for the specified type when the value is to be discarded.
1159 func (dec *Decoder) getIgnoreEnginePtr(wireId typeId) (enginePtr **decEngine, err error) {
1160 var ok bool
1161 if enginePtr, ok = dec.ignorerCache[wireId]; !ok {
1162 // To handle recursive types, mark this engine as underway before compiling.
1163 enginePtr = new(*decEngine)
1164 dec.ignorerCache[wireId] = enginePtr
1165 wire := dec.wireType[wireId]
1166 if wire != nil && wire.StructT != nil {
1167 *enginePtr, err = dec.compileDec(wireId, userType(emptyStructType))
1168 } else {
1169 *enginePtr, err = dec.compileIgnoreSingle(wireId)
1171 if err != nil {
1172 delete(dec.ignorerCache, wireId)
1175 return
1178 // decodeValue decodes the data stream representing a value and stores it in value.
1179 func (dec *Decoder) decodeValue(wireId typeId, value reflect.Value) {
1180 defer catchError(&dec.err)
1181 // If the value is nil, it means we should just ignore this item.
1182 if !value.IsValid() {
1183 dec.decodeIgnoredValue(wireId)
1184 return
1186 // Dereference down to the underlying type.
1187 ut := userType(value.Type())
1188 base := ut.base
1189 var enginePtr **decEngine
1190 enginePtr, dec.err = dec.getDecEnginePtr(wireId, ut)
1191 if dec.err != nil {
1192 return
1194 value = decAlloc(value)
1195 engine := *enginePtr
1196 if st := base; st.Kind() == reflect.Struct && ut.externalDec == 0 {
1197 wt := dec.wireType[wireId]
1198 if engine.numInstr == 0 && st.NumField() > 0 &&
1199 wt != nil && len(wt.StructT.Field) > 0 {
1200 name := base.Name()
1201 errorf("type mismatch: no fields matched compiling decoder for %s", name)
1203 dec.decodeStruct(engine, value)
1204 } else {
1205 dec.decodeSingle(engine, value)
1209 // decodeIgnoredValue decodes the data stream representing a value of the specified type and discards it.
1210 func (dec *Decoder) decodeIgnoredValue(wireId typeId) {
1211 var enginePtr **decEngine
1212 enginePtr, dec.err = dec.getIgnoreEnginePtr(wireId)
1213 if dec.err != nil {
1214 return
1216 wire := dec.wireType[wireId]
1217 if wire != nil && wire.StructT != nil {
1218 dec.ignoreStruct(*enginePtr)
1219 } else {
1220 dec.ignoreSingle(*enginePtr)
1224 func init() {
1225 var iop, uop decOp
1226 switch reflect.TypeOf(int(0)).Bits() {
1227 case 32:
1228 iop = decInt32
1229 uop = decUint32
1230 case 64:
1231 iop = decInt64
1232 uop = decUint64
1233 default:
1234 panic("gob: unknown size of int/uint")
1236 decOpTable[reflect.Int] = iop
1237 decOpTable[reflect.Uint] = uop
1239 // Finally uintptr
1240 switch reflect.TypeOf(uintptr(0)).Bits() {
1241 case 32:
1242 uop = decUint32
1243 case 64:
1244 uop = decUint64
1245 default:
1246 panic("gob: unknown size of uintptr")
1248 decOpTable[reflect.Uintptr] = uop
1251 // Gob depends on being able to take the address
1252 // of zeroed Values it creates, so use this wrapper instead
1253 // of the standard reflect.Zero.
1254 // Each call allocates once.
1255 func allocValue(t reflect.Type) reflect.Value {
1256 return reflect.New(t).Elem()