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.
7 // TODO(rsc): When garbage collector changes, revisit
8 // the allocations in this file that use unsafe.Pointer.
20 errBadUint = errors.New("gob: encoded unsigned integer out of range")
21 errBadType = errors.New("gob: unknown type id or corrupted data")
22 errRange = errors.New("gob: bad data: field numbers out of bounds")
25 // decoderState is the execution state of an instance of the decoder. A new state
26 // is created for nested objects.
27 type decoderState struct {
29 // The buffer is stored with an extra indirection because it may be replaced
30 // if we load a type during decode (when reading an interface value).
32 fieldnum int // the last field number read.
34 next *decoderState // for free list
37 // We pass the bytes.Buffer separately for easier testing of the infrastructure
38 // without requiring a full Decoder.
39 func (dec *Decoder) newDecoderState(buf *bytes.Buffer) *decoderState {
44 d.buf = make([]byte, uint64Size)
52 func (dec *Decoder) freeDecoderState(d *decoderState) {
57 func overflow(name string) error {
58 return errors.New(`value for "` + name + `" out of range`)
61 // decodeUintReader reads an encoded unsigned integer from an io.Reader.
62 // Used only by the Decoder to read the message length.
63 func decodeUintReader(r io.Reader, buf []byte) (x uint64, width int, err error) {
65 _, err = r.Read(buf[0:width])
71 return uint64(b), width, nil
78 width, err = io.ReadFull(r, buf[0:n])
81 err = io.ErrUnexpectedEOF
85 // Could check that the high byte is zero but it's not worth it.
86 for _, b := range buf[0:width] {
89 width++ // +1 for length byte
93 // decodeUint reads an encoded unsigned integer from state.r.
94 // Does not check for overflow.
95 func (state *decoderState) decodeUint() (x uint64) {
96 b, err := state.b.ReadByte()
107 width, err := state.b.Read(state.buf[0:n])
111 // Don't need to check error; it's safe to loop regardless.
112 // Could check that the high byte is zero but it's not worth it.
113 for _, b := range state.buf[0:width] {
119 // decodeInt reads an encoded signed integer from state.r.
120 // Does not check for overflow.
121 func (state *decoderState) decodeInt() int64 {
122 x := state.decodeUint()
124 return ^int64(x >> 1)
129 // decOp is the signature of a decoding operator for a given type.
130 type decOp func(i *decInstr, state *decoderState, p unsafe.Pointer)
132 // The 'instructions' of the decoding machine
133 type decInstr struct {
135 field int // field number of the wire type
136 indir int // how many pointer indirections to reach the value in the struct
137 offset uintptr // offset in the structure of the field to encode
138 ovfl error // error message for overflow/underflow (for arrays, of the elements)
141 // Since the encoder writes no zeros, if we arrive at a decoder we have
142 // a value to extract and store. The field number has already been read
143 // (it's how we knew to call this decoder).
144 // Each decoder is responsible for handling any indirections associated
145 // with the data structure. If any pointer so reached is nil, allocation must
148 // Walk the pointer hierarchy, allocating if we find a nil. Stop one before the end.
149 func decIndirect(p unsafe.Pointer, indir int) unsafe.Pointer {
150 for ; indir > 1; indir-- {
151 if *(*unsafe.Pointer)(p) == nil {
152 // Allocation required
153 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(unsafe.Pointer))
155 p = *(*unsafe.Pointer)(p)
160 // ignoreUint discards a uint value with no destination.
161 func ignoreUint(i *decInstr, state *decoderState, p unsafe.Pointer) {
165 // ignoreTwoUints discards a uint value with no destination. It's used to skip
167 func ignoreTwoUints(i *decInstr, state *decoderState, p unsafe.Pointer) {
172 // decBool decodes a uint and stores it as a boolean through p.
173 func decBool(i *decInstr, state *decoderState, p unsafe.Pointer) {
175 if *(*unsafe.Pointer)(p) == nil {
176 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(bool))
178 p = *(*unsafe.Pointer)(p)
180 *(*bool)(p) = state.decodeUint() != 0
183 // decInt8 decodes an integer and stores it as an int8 through p.
184 func decInt8(i *decInstr, state *decoderState, p unsafe.Pointer) {
186 if *(*unsafe.Pointer)(p) == nil {
187 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(int8))
189 p = *(*unsafe.Pointer)(p)
191 v := state.decodeInt()
192 if v < math.MinInt8 || math.MaxInt8 < v {
195 *(*int8)(p) = int8(v)
199 // decUint8 decodes an unsigned integer and stores it as a uint8 through p.
200 func decUint8(i *decInstr, state *decoderState, p unsafe.Pointer) {
202 if *(*unsafe.Pointer)(p) == nil {
203 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(uint8))
205 p = *(*unsafe.Pointer)(p)
207 v := state.decodeUint()
208 if math.MaxUint8 < v {
211 *(*uint8)(p) = uint8(v)
215 // decInt16 decodes an integer and stores it as an int16 through p.
216 func decInt16(i *decInstr, state *decoderState, p unsafe.Pointer) {
218 if *(*unsafe.Pointer)(p) == nil {
219 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(int16))
221 p = *(*unsafe.Pointer)(p)
223 v := state.decodeInt()
224 if v < math.MinInt16 || math.MaxInt16 < v {
227 *(*int16)(p) = int16(v)
231 // decUint16 decodes an unsigned integer and stores it as a uint16 through p.
232 func decUint16(i *decInstr, state *decoderState, p unsafe.Pointer) {
234 if *(*unsafe.Pointer)(p) == nil {
235 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(uint16))
237 p = *(*unsafe.Pointer)(p)
239 v := state.decodeUint()
240 if math.MaxUint16 < v {
243 *(*uint16)(p) = uint16(v)
247 // decInt32 decodes an integer and stores it as an int32 through p.
248 func decInt32(i *decInstr, state *decoderState, p unsafe.Pointer) {
250 if *(*unsafe.Pointer)(p) == nil {
251 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(int32))
253 p = *(*unsafe.Pointer)(p)
255 v := state.decodeInt()
256 if v < math.MinInt32 || math.MaxInt32 < v {
259 *(*int32)(p) = int32(v)
263 // decUint32 decodes an unsigned integer and stores it as a uint32 through p.
264 func decUint32(i *decInstr, state *decoderState, p unsafe.Pointer) {
266 if *(*unsafe.Pointer)(p) == nil {
267 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(uint32))
269 p = *(*unsafe.Pointer)(p)
271 v := state.decodeUint()
272 if math.MaxUint32 < v {
275 *(*uint32)(p) = uint32(v)
279 // decInt64 decodes an integer and stores it as an int64 through p.
280 func decInt64(i *decInstr, state *decoderState, p unsafe.Pointer) {
282 if *(*unsafe.Pointer)(p) == nil {
283 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(int64))
285 p = *(*unsafe.Pointer)(p)
287 *(*int64)(p) = int64(state.decodeInt())
290 // decUint64 decodes an unsigned integer and stores it as a uint64 through p.
291 func decUint64(i *decInstr, state *decoderState, p unsafe.Pointer) {
293 if *(*unsafe.Pointer)(p) == nil {
294 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(uint64))
296 p = *(*unsafe.Pointer)(p)
298 *(*uint64)(p) = uint64(state.decodeUint())
301 // Floating-point numbers are transmitted as uint64s holding the bits
302 // of the underlying representation. They are sent byte-reversed, with
303 // the exponent end coming out first, so integer floating point numbers
304 // (for example) transmit more compactly. This routine does the
306 func floatFromBits(u uint64) float64 {
308 for i := 0; i < 8; i++ {
313 return math.Float64frombits(v)
316 // storeFloat32 decodes an unsigned integer, treats it as a 32-bit floating-point
317 // number, and stores it through p. It's a helper function for float32 and complex64.
318 func storeFloat32(i *decInstr, state *decoderState, p unsafe.Pointer) {
319 v := floatFromBits(state.decodeUint())
324 // +Inf is OK in both 32- and 64-bit floats. Underflow is always OK.
325 if math.MaxFloat32 < av && av <= math.MaxFloat64 {
328 *(*float32)(p) = float32(v)
332 // decFloat32 decodes an unsigned integer, treats it as a 32-bit floating-point
333 // number, and stores it through p.
334 func decFloat32(i *decInstr, state *decoderState, p unsafe.Pointer) {
336 if *(*unsafe.Pointer)(p) == nil {
337 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(float32))
339 p = *(*unsafe.Pointer)(p)
341 storeFloat32(i, state, p)
344 // decFloat64 decodes an unsigned integer, treats it as a 64-bit floating-point
345 // number, and stores it through p.
346 func decFloat64(i *decInstr, state *decoderState, p unsafe.Pointer) {
348 if *(*unsafe.Pointer)(p) == nil {
349 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(float64))
351 p = *(*unsafe.Pointer)(p)
353 *(*float64)(p) = floatFromBits(uint64(state.decodeUint()))
356 // decComplex64 decodes a pair of unsigned integers, treats them as a
357 // pair of floating point numbers, and stores them as a complex64 through p.
358 // The real part comes first.
359 func decComplex64(i *decInstr, state *decoderState, p unsafe.Pointer) {
361 if *(*unsafe.Pointer)(p) == nil {
362 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(complex64))
364 p = *(*unsafe.Pointer)(p)
366 storeFloat32(i, state, p)
367 storeFloat32(i, state, unsafe.Pointer(uintptr(p)+unsafe.Sizeof(float32(0))))
370 // decComplex128 decodes a pair of unsigned integers, treats them as a
371 // pair of floating point numbers, and stores them as a complex128 through p.
372 // The real part comes first.
373 func decComplex128(i *decInstr, state *decoderState, p unsafe.Pointer) {
375 if *(*unsafe.Pointer)(p) == nil {
376 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(complex128))
378 p = *(*unsafe.Pointer)(p)
380 real := floatFromBits(uint64(state.decodeUint()))
381 imag := floatFromBits(uint64(state.decodeUint()))
382 *(*complex128)(p) = complex(real, imag)
385 // decUint8Slice decodes a byte slice and stores through p a slice header
386 // describing the data.
387 // uint8 slices are encoded as an unsigned count followed by the raw bytes.
388 func decUint8Slice(i *decInstr, state *decoderState, p unsafe.Pointer) {
390 if *(*unsafe.Pointer)(p) == nil {
391 *(*unsafe.Pointer)(p) = unsafe.Pointer(new([]uint8))
393 p = *(*unsafe.Pointer)(p)
395 n := state.decodeUint()
396 if n > uint64(state.b.Len()) {
397 errorf("length of []byte exceeds input size (%d bytes)", n)
399 slice := (*[]uint8)(p)
400 if uint64(cap(*slice)) < n {
401 *slice = make([]uint8, n)
403 *slice = (*slice)[0:n]
405 if _, err := state.b.Read(*slice); err != nil {
406 errorf("error decoding []byte: %s", err)
410 // decString decodes byte array and stores through p a string header
411 // describing the data.
412 // Strings are encoded as an unsigned count followed by the raw bytes.
413 func decString(i *decInstr, state *decoderState, p unsafe.Pointer) {
415 if *(*unsafe.Pointer)(p) == nil {
416 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(string))
418 p = *(*unsafe.Pointer)(p)
420 n := state.decodeUint()
421 if n > uint64(state.b.Len()) {
422 errorf("string length exceeds input size (%d bytes)", n)
426 // It would be a shame to do the obvious thing here,
427 // *(*string)(p) = string(b)
428 // because we've already allocated the storage and this would
429 // allocate again and copy. So we do this ugly hack, which is even
430 // even more unsafe than it looks as it depends the memory
431 // representation of a string matching the beginning of the memory
432 // representation of a byte slice (a byte slice is longer).
433 *(*string)(p) = *(*string)(unsafe.Pointer(&b))
436 // ignoreUint8Array skips over the data for a byte slice value with no destination.
437 func ignoreUint8Array(i *decInstr, state *decoderState, p unsafe.Pointer) {
438 b := make([]byte, state.decodeUint())
444 // The encoder engine is an array of instructions indexed by field number of the incoming
445 // decoder. It is executed with random access according to field number.
446 type decEngine struct {
448 numInstr int // the number of active instructions
451 // allocate makes sure storage is available for an object of underlying type rtyp
452 // that is indir levels of indirection through p.
453 func allocate(rtyp reflect.Type, p uintptr, indir int) uintptr {
457 up := unsafe.Pointer(p)
459 up = decIndirect(up, indir)
461 if *(*unsafe.Pointer)(up) == nil {
463 *(*unsafe.Pointer)(up) = unsafe.Pointer(reflect.New(rtyp).Pointer())
465 return *(*uintptr)(up)
468 // decodeSingle decodes a top-level value that is not a struct and stores it through p.
469 // Such values are preceded by a zero, making them have the memory layout of a
470 // struct field (although with an illegal field number).
471 func (dec *Decoder) decodeSingle(engine *decEngine, ut *userTypeInfo, basep uintptr) {
472 state := dec.newDecoderState(&dec.buf)
473 state.fieldnum = singletonField
474 delta := int(state.decodeUint())
476 errorf("decode: corrupted data: non-zero delta for singleton")
478 instr := &engine.instr[singletonField]
479 if instr.indir != ut.indir {
480 errorf("internal error: inconsistent indirection instr %d ut %d", instr.indir, ut.indir)
482 ptr := unsafe.Pointer(basep) // offset will be zero
484 ptr = decIndirect(ptr, instr.indir)
486 instr.op(instr, state, ptr)
487 dec.freeDecoderState(state)
490 // decodeStruct decodes a top-level struct and stores it through p.
491 // Indir is for the value, not the type. At the time of the call it may
492 // differ from ut.indir, which was computed when the engine was built.
493 // This state cannot arise for decodeSingle, which is called directly
494 // from the user's value, not from the innards of an engine.
495 func (dec *Decoder) decodeStruct(engine *decEngine, ut *userTypeInfo, p uintptr, indir int) {
496 p = allocate(ut.base, p, indir)
497 state := dec.newDecoderState(&dec.buf)
500 for state.b.Len() > 0 {
501 delta := int(state.decodeUint())
503 errorf("decode: corrupted data: negative delta")
505 if delta == 0 { // struct terminator is zero delta fieldnum
508 fieldnum := state.fieldnum + delta
509 if fieldnum >= len(engine.instr) {
513 instr := &engine.instr[fieldnum]
514 p := unsafe.Pointer(basep + instr.offset)
516 p = decIndirect(p, instr.indir)
518 instr.op(instr, state, p)
519 state.fieldnum = fieldnum
521 dec.freeDecoderState(state)
524 // ignoreStruct discards the data for a struct with no destination.
525 func (dec *Decoder) ignoreStruct(engine *decEngine) {
526 state := dec.newDecoderState(&dec.buf)
528 for state.b.Len() > 0 {
529 delta := int(state.decodeUint())
531 errorf("ignore decode: corrupted data: negative delta")
533 if delta == 0 { // struct terminator is zero delta fieldnum
536 fieldnum := state.fieldnum + delta
537 if fieldnum >= len(engine.instr) {
540 instr := &engine.instr[fieldnum]
541 instr.op(instr, state, unsafe.Pointer(nil))
542 state.fieldnum = fieldnum
544 dec.freeDecoderState(state)
547 // ignoreSingle discards the data for a top-level non-struct value with no
548 // destination. It's used when calling Decode with a nil value.
549 func (dec *Decoder) ignoreSingle(engine *decEngine) {
550 state := dec.newDecoderState(&dec.buf)
551 state.fieldnum = singletonField
552 delta := int(state.decodeUint())
554 errorf("decode: corrupted data: non-zero delta for singleton")
556 instr := &engine.instr[singletonField]
557 instr.op(instr, state, unsafe.Pointer(nil))
558 dec.freeDecoderState(state)
561 // decodeArrayHelper does the work for decoding arrays and slices.
562 func (dec *Decoder) decodeArrayHelper(state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, length, elemIndir int, ovfl error) {
563 instr := &decInstr{elemOp, 0, elemIndir, 0, ovfl}
564 for i := 0; i < length; i++ {
565 up := unsafe.Pointer(p)
567 up = decIndirect(up, elemIndir)
569 elemOp(instr, state, up)
570 p += uintptr(elemWid)
574 // decodeArray decodes an array and stores it through p, that is, p points to the zeroth element.
575 // The length is an unsigned integer preceding the elements. Even though the length is redundant
576 // (it's part of the type), it's a useful check and is included in the encoding.
577 func (dec *Decoder) decodeArray(atyp reflect.Type, state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, length, indir, elemIndir int, ovfl error) {
579 p = allocate(atyp, p, 1) // All but the last level has been allocated by dec.Indirect
581 if n := state.decodeUint(); n != uint64(length) {
582 errorf("length mismatch in decodeArray")
584 dec.decodeArrayHelper(state, p, elemOp, elemWid, length, elemIndir, ovfl)
587 // decodeIntoValue is a helper for map decoding. Since maps are decoded using reflection,
588 // unlike the other items we can't use a pointer directly.
589 func decodeIntoValue(state *decoderState, op decOp, indir int, v reflect.Value, ovfl error) reflect.Value {
590 instr := &decInstr{op, 0, indir, 0, ovfl}
591 up := unsafe.Pointer(unsafeAddr(v))
593 up = decIndirect(up, indir)
599 // decodeMap decodes a map and stores its header through p.
600 // Maps are encoded as a length followed by key:value pairs.
601 // Because the internals of maps are not visible to us, we must
602 // use reflection rather than pointer magic.
603 func (dec *Decoder) decodeMap(mtyp reflect.Type, state *decoderState, p uintptr, keyOp, elemOp decOp, indir, keyIndir, elemIndir int, ovfl error) {
605 p = allocate(mtyp, p, 1) // All but the last level has been allocated by dec.Indirect
607 up := unsafe.Pointer(p)
608 if *(*unsafe.Pointer)(up) == nil { // maps are represented as a pointer in the runtime
610 *(*unsafe.Pointer)(up) = unsafe.Pointer(reflect.MakeMap(mtyp).Pointer())
612 // Maps cannot be accessed by moving addresses around the way
613 // that slices etc. can. We must recover a full reflection value for
615 v := reflect.NewAt(mtyp, unsafe.Pointer(p)).Elem()
616 n := int(state.decodeUint())
617 for i := 0; i < n; i++ {
618 key := decodeIntoValue(state, keyOp, keyIndir, allocValue(mtyp.Key()), ovfl)
619 elem := decodeIntoValue(state, elemOp, elemIndir, allocValue(mtyp.Elem()), ovfl)
620 v.SetMapIndex(key, elem)
624 // ignoreArrayHelper does the work for discarding arrays and slices.
625 func (dec *Decoder) ignoreArrayHelper(state *decoderState, elemOp decOp, length int) {
626 instr := &decInstr{elemOp, 0, 0, 0, errors.New("no error")}
627 for i := 0; i < length; i++ {
628 elemOp(instr, state, nil)
632 // ignoreArray discards the data for an array value with no destination.
633 func (dec *Decoder) ignoreArray(state *decoderState, elemOp decOp, length int) {
634 if n := state.decodeUint(); n != uint64(length) {
635 errorf("length mismatch in ignoreArray")
637 dec.ignoreArrayHelper(state, elemOp, length)
640 // ignoreMap discards the data for a map value with no destination.
641 func (dec *Decoder) ignoreMap(state *decoderState, keyOp, elemOp decOp) {
642 n := int(state.decodeUint())
643 keyInstr := &decInstr{keyOp, 0, 0, 0, errors.New("no error")}
644 elemInstr := &decInstr{elemOp, 0, 0, 0, errors.New("no error")}
645 for i := 0; i < n; i++ {
646 keyOp(keyInstr, state, nil)
647 elemOp(elemInstr, state, nil)
651 // decodeSlice decodes a slice and stores the slice header through p.
652 // Slices are encoded as an unsigned length followed by the elements.
653 func (dec *Decoder) decodeSlice(atyp reflect.Type, state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, indir, elemIndir int, ovfl error) {
654 nr := state.decodeUint()
655 if nr > uint64(state.b.Len()) {
656 errorf("length of slice exceeds input size (%d elements)", nr)
660 up := unsafe.Pointer(p)
661 if *(*unsafe.Pointer)(up) == nil {
662 // Allocate the slice header.
663 *(*unsafe.Pointer)(up) = unsafe.Pointer(new([]unsafe.Pointer))
667 // Allocate storage for the slice elements, that is, the underlying array,
668 // if the existing slice does not have the capacity.
669 // Always write a header at p.
670 hdrp := (*reflect.SliceHeader)(unsafe.Pointer(p))
672 hdrp.Data = reflect.MakeSlice(atyp, n, n).Pointer()
676 dec.decodeArrayHelper(state, hdrp.Data, elemOp, elemWid, n, elemIndir, ovfl)
679 // ignoreSlice skips over the data for a slice value with no destination.
680 func (dec *Decoder) ignoreSlice(state *decoderState, elemOp decOp) {
681 dec.ignoreArrayHelper(state, elemOp, int(state.decodeUint()))
684 // setInterfaceValue sets an interface value to a concrete value,
685 // but first it checks that the assignment will succeed.
686 func setInterfaceValue(ivalue reflect.Value, value reflect.Value) {
687 if !value.Type().AssignableTo(ivalue.Type()) {
688 errorf("cannot assign value of type %s to %s", value.Type(), ivalue.Type())
693 // decodeInterface decodes an interface value and stores it through p.
694 // Interfaces are encoded as the name of a concrete type followed by a value.
695 // If the name is empty, the value is nil and no value is sent.
696 func (dec *Decoder) decodeInterface(ityp reflect.Type, state *decoderState, p uintptr, indir int) {
697 // Create a writable interface reflect.Value. We need one even for the nil case.
698 ivalue := allocValue(ityp)
699 // Read the name of the concrete type.
700 nr := state.decodeUint()
701 if nr < 0 || nr > 1<<31 { // zero is permissible for anonymous types
702 errorf("invalid type name length %d", nr)
704 b := make([]byte, nr)
708 // Copy the representation of the nil interface value to the target.
709 // This is horribly unsafe and special.
710 *(*[2]uintptr)(unsafe.Pointer(p)) = ivalue.InterfaceData()
713 if len(name) > 1024 {
714 errorf("name too long (%d bytes): %.20q...", len(name), name)
716 // The concrete type must be registered.
717 typ, ok := nameToConcreteType[name]
719 errorf("name not registered for interface: %q", name)
721 // Read the type id of the concrete value.
722 concreteId := dec.decodeTypeSequence(true)
726 // Byte count of value is next; we don't care what it is (it's there
727 // in case we want to ignore the value by skipping it completely).
729 // Read the concrete value.
730 value := allocValue(typ)
731 dec.decodeValue(concreteId, value)
735 // Allocate the destination interface value.
737 p = allocate(ityp, p, 1) // All but the last level has been allocated by dec.Indirect
739 // Assign the concrete value to the interface.
740 // Tread carefully; it might not satisfy the interface.
741 setInterfaceValue(ivalue, value)
742 // Copy the representation of the interface value to the target.
743 // This is horribly unsafe and special.
744 *(*[2]uintptr)(unsafe.Pointer(p)) = ivalue.InterfaceData()
747 // ignoreInterface discards the data for an interface value with no destination.
748 func (dec *Decoder) ignoreInterface(state *decoderState) {
749 // Read the name of the concrete type.
750 b := make([]byte, state.decodeUint())
751 _, err := state.b.Read(b)
755 id := dec.decodeTypeSequence(true)
759 // At this point, the decoder buffer contains a delimited value. Just toss it.
760 state.b.Next(int(state.decodeUint()))
763 // decodeGobDecoder decodes something implementing the GobDecoder interface.
764 // The data is encoded as a byte slice.
765 func (dec *Decoder) decodeGobDecoder(state *decoderState, v reflect.Value) {
766 // Read the bytes for the value.
767 b := make([]byte, state.decodeUint())
768 _, err := state.b.Read(b)
772 // We know it's a GobDecoder, so just call the method directly.
773 err = v.Interface().(GobDecoder).GobDecode(b)
779 // ignoreGobDecoder discards the data for a GobDecoder value with no destination.
780 func (dec *Decoder) ignoreGobDecoder(state *decoderState) {
781 // Read the bytes for the value.
782 b := make([]byte, state.decodeUint())
783 _, err := state.b.Read(b)
789 // Index by Go types.
790 var decOpTable = [...]decOp{
791 reflect.Bool: decBool,
792 reflect.Int8: decInt8,
793 reflect.Int16: decInt16,
794 reflect.Int32: decInt32,
795 reflect.Int64: decInt64,
796 reflect.Uint8: decUint8,
797 reflect.Uint16: decUint16,
798 reflect.Uint32: decUint32,
799 reflect.Uint64: decUint64,
800 reflect.Float32: decFloat32,
801 reflect.Float64: decFloat64,
802 reflect.Complex64: decComplex64,
803 reflect.Complex128: decComplex128,
804 reflect.String: decString,
807 // Indexed by gob types. tComplex will be added during type.init().
808 var decIgnoreOpMap = map[typeId]decOp{
813 tBytes: ignoreUint8Array,
814 tString: ignoreUint8Array,
815 tComplex: ignoreTwoUints,
818 // decOpFor returns the decoding op for the base type under rt and
819 // the indirection count to reach it.
820 func (dec *Decoder) decOpFor(wireId typeId, rt reflect.Type, name string, inProgress map[reflect.Type]*decOp) (*decOp, int) {
822 // If the type implements GobEncoder, we handle it without further processing.
824 return dec.gobDecodeOpFor(ut)
826 // If this type is already in progress, it's a recursive type (e.g. map[string]*T).
827 // Return the pointer to the op we're already building.
828 if opPtr := inProgress[rt]; opPtr != nil {
829 return opPtr, ut.indir
835 if int(k) < len(decOpTable) {
841 switch t := typ; t.Kind() {
843 name = "element of " + name
844 elemId := dec.wireType[wireId].ArrayT.Elem
845 elemOp, elemIndir := dec.decOpFor(elemId, t.Elem(), name, inProgress)
846 ovfl := overflow(name)
847 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
848 state.dec.decodeArray(t, state, uintptr(p), *elemOp, t.Elem().Size(), t.Len(), i.indir, elemIndir, ovfl)
852 keyId := dec.wireType[wireId].MapT.Key
853 elemId := dec.wireType[wireId].MapT.Elem
854 keyOp, keyIndir := dec.decOpFor(keyId, t.Key(), "key of "+name, inProgress)
855 elemOp, elemIndir := dec.decOpFor(elemId, t.Elem(), "element of "+name, inProgress)
856 ovfl := overflow(name)
857 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
858 up := unsafe.Pointer(p)
859 state.dec.decodeMap(t, state, uintptr(up), *keyOp, *elemOp, i.indir, keyIndir, elemIndir, ovfl)
863 name = "element of " + name
864 if t.Elem().Kind() == reflect.Uint8 {
869 if tt, ok := builtinIdToType[wireId]; ok {
870 elemId = tt.(*sliceType).Elem
872 elemId = dec.wireType[wireId].SliceT.Elem
874 elemOp, elemIndir := dec.decOpFor(elemId, t.Elem(), name, inProgress)
875 ovfl := overflow(name)
876 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
877 state.dec.decodeSlice(t, state, uintptr(p), *elemOp, t.Elem().Size(), i.indir, elemIndir, ovfl)
881 // Generate a closure that calls out to the engine for the nested type.
882 enginePtr, err := dec.getDecEnginePtr(wireId, userType(typ))
886 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
887 // indirect through enginePtr to delay evaluation for recursive structs.
888 dec.decodeStruct(*enginePtr, userType(typ), uintptr(p), i.indir)
890 case reflect.Interface:
891 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
892 state.dec.decodeInterface(t, state, uintptr(p), i.indir)
897 errorf("decode can't handle type %s", rt)
902 // decIgnoreOpFor returns the decoding op for a field that has no destination.
903 func (dec *Decoder) decIgnoreOpFor(wireId typeId) decOp {
904 op, ok := decIgnoreOpMap[wireId]
906 if wireId == tInterface {
907 // Special case because it's a method: the ignored item might
908 // define types and we need to record their state in the decoder.
909 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
910 state.dec.ignoreInterface(state)
915 wire := dec.wireType[wireId]
918 errorf("bad data: undefined type %s", wireId.string())
919 case wire.ArrayT != nil:
920 elemId := wire.ArrayT.Elem
921 elemOp := dec.decIgnoreOpFor(elemId)
922 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
923 state.dec.ignoreArray(state, elemOp, wire.ArrayT.Len)
926 case wire.MapT != nil:
927 keyId := dec.wireType[wireId].MapT.Key
928 elemId := dec.wireType[wireId].MapT.Elem
929 keyOp := dec.decIgnoreOpFor(keyId)
930 elemOp := dec.decIgnoreOpFor(elemId)
931 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
932 state.dec.ignoreMap(state, keyOp, elemOp)
935 case wire.SliceT != nil:
936 elemId := wire.SliceT.Elem
937 elemOp := dec.decIgnoreOpFor(elemId)
938 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
939 state.dec.ignoreSlice(state, elemOp)
942 case wire.StructT != nil:
943 // Generate a closure that calls out to the engine for the nested type.
944 enginePtr, err := dec.getIgnoreEnginePtr(wireId)
948 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
949 // indirect through enginePtr to delay evaluation for recursive structs
950 state.dec.ignoreStruct(*enginePtr)
953 case wire.GobEncoderT != nil:
954 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
955 state.dec.ignoreGobDecoder(state)
960 errorf("bad data: ignore can't handle type %s", wireId.string())
965 // gobDecodeOpFor returns the op for a type that is known to implement
967 func (dec *Decoder) gobDecodeOpFor(ut *userTypeInfo) (*decOp, int) {
969 if ut.decIndir == -1 {
970 rcvrType = reflect.PtrTo(rcvrType)
971 } else if ut.decIndir > 0 {
972 for i := int8(0); i < ut.decIndir; i++ {
973 rcvrType = rcvrType.Elem()
977 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
978 // Caller has gotten us to within one indirection of our value.
980 if *(*unsafe.Pointer)(p) == nil {
981 *(*unsafe.Pointer)(p) = unsafe.Pointer(reflect.New(ut.base).Pointer())
984 // Now p is a pointer to the base type. Do we need to climb out to
985 // get to the receiver type?
987 if ut.decIndir == -1 {
988 v = reflect.NewAt(rcvrType, unsafe.Pointer(&p)).Elem()
990 v = reflect.NewAt(rcvrType, p).Elem()
992 state.dec.decodeGobDecoder(state, v)
994 return &op, int(ut.indir)
998 // compatibleType asks: Are these two gob Types compatible?
999 // Answers the question for basic types, arrays, maps and slices, plus
1000 // GobEncoder/Decoder pairs.
1001 // Structs are considered ok; fields will be checked later.
1002 func (dec *Decoder) compatibleType(fr reflect.Type, fw typeId, inProgress map[reflect.Type]typeId) bool {
1003 if rhs, ok := inProgress[fr]; ok {
1008 wire, ok := dec.wireType[fw]
1009 // If fr is a GobDecoder, the wire type must be GobEncoder.
1010 // And if fr is not a GobDecoder, the wire type must not be either.
1011 if ut.isGobDecoder != (ok && wire.GobEncoderT != nil) { // the parentheses look odd but are correct.
1014 if ut.isGobDecoder { // This test trumps all others.
1017 switch t := ut.base; t.Kind() {
1019 // chan, etc: cannot handle.
1023 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1025 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
1027 case reflect.Float32, reflect.Float64:
1029 case reflect.Complex64, reflect.Complex128:
1030 return fw == tComplex
1031 case reflect.String:
1032 return fw == tString
1033 case reflect.Interface:
1034 return fw == tInterface
1036 if !ok || wire.ArrayT == nil {
1039 array := wire.ArrayT
1040 return t.Len() == array.Len && dec.compatibleType(t.Elem(), array.Elem, inProgress)
1042 if !ok || wire.MapT == nil {
1045 MapType := wire.MapT
1046 return dec.compatibleType(t.Key(), MapType.Key, inProgress) && dec.compatibleType(t.Elem(), MapType.Elem, inProgress)
1048 // Is it an array of bytes?
1049 if t.Elem().Kind() == reflect.Uint8 {
1052 // Extract and compare element types.
1054 if tt, ok := builtinIdToType[fw]; ok {
1055 sw, _ = tt.(*sliceType)
1056 } else if wire != nil {
1059 elem := userType(t.Elem()).base
1060 return sw != nil && dec.compatibleType(elem, sw.Elem, inProgress)
1061 case reflect.Struct:
1067 // typeString returns a human-readable description of the type identified by remoteId.
1068 func (dec *Decoder) typeString(remoteId typeId) string {
1069 if t := idToType[remoteId]; t != nil {
1070 // globally known type.
1073 return dec.wireType[remoteId].string()
1076 // compileSingle compiles the decoder engine for a non-struct top-level value, including
1078 func (dec *Decoder) compileSingle(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) {
1080 engine = new(decEngine)
1081 engine.instr = make([]decInstr, 1) // one item
1082 name := rt.String() // best we can do
1083 if !dec.compatibleType(rt, remoteId, make(map[reflect.Type]typeId)) {
1084 remoteType := dec.typeString(remoteId)
1085 // Common confusing case: local interface type, remote concrete type.
1086 if ut.base.Kind() == reflect.Interface && remoteId != tInterface {
1087 return nil, errors.New("gob: local interface type " + name + " can only be decoded from remote interface type; received concrete type " + remoteType)
1089 return nil, errors.New("gob: decoding into local type " + name + ", received remote type " + remoteType)
1091 op, indir := dec.decOpFor(remoteId, rt, name, make(map[reflect.Type]*decOp))
1092 ovfl := errors.New(`value for "` + name + `" out of range`)
1093 engine.instr[singletonField] = decInstr{*op, singletonField, indir, 0, ovfl}
1098 // compileIgnoreSingle compiles the decoder engine for a non-struct top-level value that will be discarded.
1099 func (dec *Decoder) compileIgnoreSingle(remoteId typeId) (engine *decEngine, err error) {
1100 engine = new(decEngine)
1101 engine.instr = make([]decInstr, 1) // one item
1102 op := dec.decIgnoreOpFor(remoteId)
1103 ovfl := overflow(dec.typeString(remoteId))
1104 engine.instr[0] = decInstr{op, 0, 0, 0, ovfl}
1109 // compileDec compiles the decoder engine for a value. If the value is not a struct,
1110 // it calls out to compileSingle.
1111 func (dec *Decoder) compileDec(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) {
1114 if srt.Kind() != reflect.Struct ||
1116 return dec.compileSingle(remoteId, ut)
1118 var wireStruct *structType
1119 // Builtin types can come from global pool; the rest must be defined by the decoder.
1120 // Also we know we're decoding a struct now, so the client must have sent one.
1121 if t, ok := builtinIdToType[remoteId]; ok {
1122 wireStruct, _ = t.(*structType)
1124 wire := dec.wireType[remoteId]
1128 wireStruct = wire.StructT
1130 if wireStruct == nil {
1131 errorf("type mismatch in decoder: want struct type %s; got non-struct", rt)
1133 engine = new(decEngine)
1134 engine.instr = make([]decInstr, len(wireStruct.Field))
1135 seen := make(map[reflect.Type]*decOp)
1136 // Loop over the fields of the wire type.
1137 for fieldnum := 0; fieldnum < len(wireStruct.Field); fieldnum++ {
1138 wireField := wireStruct.Field[fieldnum]
1139 if wireField.Name == "" {
1140 errorf("empty name for remote field of type %s", wireStruct.Name)
1142 ovfl := overflow(wireField.Name)
1143 // Find the field of the local type with the same name.
1144 localField, present := srt.FieldByName(wireField.Name)
1145 // TODO(r): anonymous names
1146 if !present || !isExported(wireField.Name) {
1147 op := dec.decIgnoreOpFor(wireField.Id)
1148 engine.instr[fieldnum] = decInstr{op, fieldnum, 0, 0, ovfl}
1151 if !dec.compatibleType(localField.Type, wireField.Id, make(map[reflect.Type]typeId)) {
1152 errorf("wrong type (%s) for received field %s.%s", localField.Type, wireStruct.Name, wireField.Name)
1154 op, indir := dec.decOpFor(wireField.Id, localField.Type, localField.Name, seen)
1155 engine.instr[fieldnum] = decInstr{*op, fieldnum, indir, uintptr(localField.Offset), ovfl}
1161 // getDecEnginePtr returns the engine for the specified type.
1162 func (dec *Decoder) getDecEnginePtr(remoteId typeId, ut *userTypeInfo) (enginePtr **decEngine, err error) {
1164 decoderMap, ok := dec.decoderCache[rt]
1166 decoderMap = make(map[typeId]**decEngine)
1167 dec.decoderCache[rt] = decoderMap
1169 if enginePtr, ok = decoderMap[remoteId]; !ok {
1170 // To handle recursive types, mark this engine as underway before compiling.
1171 enginePtr = new(*decEngine)
1172 decoderMap[remoteId] = enginePtr
1173 *enginePtr, err = dec.compileDec(remoteId, ut)
1175 delete(decoderMap, remoteId)
1181 // emptyStruct is the type we compile into when ignoring a struct value.
1182 type emptyStruct struct{}
1184 var emptyStructType = reflect.TypeOf(emptyStruct{})
1186 // getDecEnginePtr returns the engine for the specified type when the value is to be discarded.
1187 func (dec *Decoder) getIgnoreEnginePtr(wireId typeId) (enginePtr **decEngine, err error) {
1189 if enginePtr, ok = dec.ignorerCache[wireId]; !ok {
1190 // To handle recursive types, mark this engine as underway before compiling.
1191 enginePtr = new(*decEngine)
1192 dec.ignorerCache[wireId] = enginePtr
1193 wire := dec.wireType[wireId]
1194 if wire != nil && wire.StructT != nil {
1195 *enginePtr, err = dec.compileDec(wireId, userType(emptyStructType))
1197 *enginePtr, err = dec.compileIgnoreSingle(wireId)
1200 delete(dec.ignorerCache, wireId)
1206 // decodeValue decodes the data stream representing a value and stores it in val.
1207 func (dec *Decoder) decodeValue(wireId typeId, val reflect.Value) {
1208 defer catchError(&dec.err)
1209 // If the value is nil, it means we should just ignore this item.
1211 dec.decodeIgnoredValue(wireId)
1214 // Dereference down to the underlying type.
1215 ut := userType(val.Type())
1217 var enginePtr **decEngine
1218 enginePtr, dec.err = dec.getDecEnginePtr(wireId, ut)
1222 engine := *enginePtr
1223 if st := base; st.Kind() == reflect.Struct && !ut.isGobDecoder {
1224 if engine.numInstr == 0 && st.NumField() > 0 && len(dec.wireType[wireId].StructT.Field) > 0 {
1226 errorf("type mismatch: no fields matched compiling decoder for %s", name)
1228 dec.decodeStruct(engine, ut, uintptr(unsafeAddr(val)), ut.indir)
1230 dec.decodeSingle(engine, ut, uintptr(unsafeAddr(val)))
1234 // decodeIgnoredValue decodes the data stream representing a value of the specified type and discards it.
1235 func (dec *Decoder) decodeIgnoredValue(wireId typeId) {
1236 var enginePtr **decEngine
1237 enginePtr, dec.err = dec.getIgnoreEnginePtr(wireId)
1241 wire := dec.wireType[wireId]
1242 if wire != nil && wire.StructT != nil {
1243 dec.ignoreStruct(*enginePtr)
1245 dec.ignoreSingle(*enginePtr)
1251 switch reflect.TypeOf(int(0)).Bits() {
1259 panic("gob: unknown size of int/uint")
1261 decOpTable[reflect.Int] = iop
1262 decOpTable[reflect.Uint] = uop
1265 switch reflect.TypeOf(uintptr(0)).Bits() {
1271 panic("gob: unknown size of uintptr")
1273 decOpTable[reflect.Uintptr] = uop
1276 // Gob assumes it can call UnsafeAddr on any Value
1277 // in order to get a pointer it can copy data from.
1278 // Values that have just been created and do not point
1279 // into existing structs or slices cannot be addressed,
1280 // so simulate it by returning a pointer to a copy.
1281 // Each call allocates once.
1282 func unsafeAddr(v reflect.Value) uintptr {
1284 return v.UnsafeAddr()
1286 x := reflect.New(v.Type()).Elem()
1288 return x.UnsafeAddr()
1291 // Gob depends on being able to take the address
1292 // of zeroed Values it creates, so use this wrapper instead
1293 // of the standard reflect.Zero.
1294 // Each call allocates once.
1295 func allocValue(t reflect.Type) reflect.Value {
1296 return reflect.New(t).Elem()