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 n, err := io.ReadFull(r, 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 if state.b.Len() == 0 {
566 errorf("decoding array or slice: length exceeds input size (%d elements)", length)
568 up := unsafe.Pointer(p)
570 up = decIndirect(up, elemIndir)
572 elemOp(instr, state, up)
573 p += uintptr(elemWid)
577 // decodeArray decodes an array and stores it through p, that is, p points to the zeroth element.
578 // The length is an unsigned integer preceding the elements. Even though the length is redundant
579 // (it's part of the type), it's a useful check and is included in the encoding.
580 func (dec *Decoder) decodeArray(atyp reflect.Type, state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, length, indir, elemIndir int, ovfl error) {
582 p = allocate(atyp, p, 1) // All but the last level has been allocated by dec.Indirect
584 if n := state.decodeUint(); n != uint64(length) {
585 errorf("length mismatch in decodeArray")
587 dec.decodeArrayHelper(state, p, elemOp, elemWid, length, elemIndir, ovfl)
590 // decodeIntoValue is a helper for map decoding. Since maps are decoded using reflection,
591 // unlike the other items we can't use a pointer directly.
592 func decodeIntoValue(state *decoderState, op decOp, indir int, v reflect.Value, ovfl error) reflect.Value {
593 instr := &decInstr{op, 0, indir, 0, ovfl}
594 up := unsafe.Pointer(unsafeAddr(v))
596 up = decIndirect(up, indir)
602 // decodeMap decodes a map and stores its header through p.
603 // Maps are encoded as a length followed by key:value pairs.
604 // Because the internals of maps are not visible to us, we must
605 // use reflection rather than pointer magic.
606 func (dec *Decoder) decodeMap(mtyp reflect.Type, state *decoderState, p uintptr, keyOp, elemOp decOp, indir, keyIndir, elemIndir int, ovfl error) {
608 p = allocate(mtyp, p, 1) // All but the last level has been allocated by dec.Indirect
610 up := unsafe.Pointer(p)
611 if *(*unsafe.Pointer)(up) == nil { // maps are represented as a pointer in the runtime
613 *(*unsafe.Pointer)(up) = unsafe.Pointer(reflect.MakeMap(mtyp).Pointer())
615 // Maps cannot be accessed by moving addresses around the way
616 // that slices etc. can. We must recover a full reflection value for
618 v := reflect.NewAt(mtyp, unsafe.Pointer(p)).Elem()
619 n := int(state.decodeUint())
620 for i := 0; i < n; i++ {
621 key := decodeIntoValue(state, keyOp, keyIndir, allocValue(mtyp.Key()), ovfl)
622 elem := decodeIntoValue(state, elemOp, elemIndir, allocValue(mtyp.Elem()), ovfl)
623 v.SetMapIndex(key, elem)
627 // ignoreArrayHelper does the work for discarding arrays and slices.
628 func (dec *Decoder) ignoreArrayHelper(state *decoderState, elemOp decOp, length int) {
629 instr := &decInstr{elemOp, 0, 0, 0, errors.New("no error")}
630 for i := 0; i < length; i++ {
631 elemOp(instr, state, nil)
635 // ignoreArray discards the data for an array value with no destination.
636 func (dec *Decoder) ignoreArray(state *decoderState, elemOp decOp, length int) {
637 if n := state.decodeUint(); n != uint64(length) {
638 errorf("length mismatch in ignoreArray")
640 dec.ignoreArrayHelper(state, elemOp, length)
643 // ignoreMap discards the data for a map value with no destination.
644 func (dec *Decoder) ignoreMap(state *decoderState, keyOp, elemOp decOp) {
645 n := int(state.decodeUint())
646 keyInstr := &decInstr{keyOp, 0, 0, 0, errors.New("no error")}
647 elemInstr := &decInstr{elemOp, 0, 0, 0, errors.New("no error")}
648 for i := 0; i < n; i++ {
649 keyOp(keyInstr, state, nil)
650 elemOp(elemInstr, state, nil)
654 // decodeSlice decodes a slice and stores the slice header through p.
655 // Slices are encoded as an unsigned length followed by the elements.
656 func (dec *Decoder) decodeSlice(atyp reflect.Type, state *decoderState, p uintptr, elemOp decOp, elemWid uintptr, indir, elemIndir int, ovfl error) {
657 nr := state.decodeUint()
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.
711 p = allocate(ityp, p, 1) // All but the last level has been allocated by dec.Indirect
713 *(*[2]uintptr)(unsafe.Pointer(p)) = ivalue.InterfaceData()
716 if len(name) > 1024 {
717 errorf("name too long (%d bytes): %.20q...", len(name), name)
719 // The concrete type must be registered.
721 typ, ok := nameToConcreteType[name]
722 registerLock.RUnlock()
724 errorf("name not registered for interface: %q", name)
726 // Read the type id of the concrete value.
727 concreteId := dec.decodeTypeSequence(true)
731 // Byte count of value is next; we don't care what it is (it's there
732 // in case we want to ignore the value by skipping it completely).
734 // Read the concrete value.
735 value := allocValue(typ)
736 dec.decodeValue(concreteId, value)
740 // Allocate the destination interface value.
742 p = allocate(ityp, p, 1) // All but the last level has been allocated by dec.Indirect
744 // Assign the concrete value to the interface.
745 // Tread carefully; it might not satisfy the interface.
746 setInterfaceValue(ivalue, value)
747 // Copy the representation of the interface value to the target.
748 // This is horribly unsafe and special.
749 *(*[2]uintptr)(unsafe.Pointer(p)) = ivalue.InterfaceData()
752 // ignoreInterface discards the data for an interface value with no destination.
753 func (dec *Decoder) ignoreInterface(state *decoderState) {
754 // Read the name of the concrete type.
755 b := make([]byte, state.decodeUint())
756 _, err := state.b.Read(b)
760 id := dec.decodeTypeSequence(true)
764 // At this point, the decoder buffer contains a delimited value. Just toss it.
765 state.b.Next(int(state.decodeUint()))
768 // decodeGobDecoder decodes something implementing the GobDecoder interface.
769 // The data is encoded as a byte slice.
770 func (dec *Decoder) decodeGobDecoder(state *decoderState, v reflect.Value) {
771 // Read the bytes for the value.
772 b := make([]byte, state.decodeUint())
773 _, err := state.b.Read(b)
777 // We know it's a GobDecoder, so just call the method directly.
778 err = v.Interface().(GobDecoder).GobDecode(b)
784 // ignoreGobDecoder discards the data for a GobDecoder value with no destination.
785 func (dec *Decoder) ignoreGobDecoder(state *decoderState) {
786 // Read the bytes for the value.
787 b := make([]byte, state.decodeUint())
788 _, err := state.b.Read(b)
794 // Index by Go types.
795 var decOpTable = [...]decOp{
796 reflect.Bool: decBool,
797 reflect.Int8: decInt8,
798 reflect.Int16: decInt16,
799 reflect.Int32: decInt32,
800 reflect.Int64: decInt64,
801 reflect.Uint8: decUint8,
802 reflect.Uint16: decUint16,
803 reflect.Uint32: decUint32,
804 reflect.Uint64: decUint64,
805 reflect.Float32: decFloat32,
806 reflect.Float64: decFloat64,
807 reflect.Complex64: decComplex64,
808 reflect.Complex128: decComplex128,
809 reflect.String: decString,
812 // Indexed by gob types. tComplex will be added during type.init().
813 var decIgnoreOpMap = map[typeId]decOp{
818 tBytes: ignoreUint8Array,
819 tString: ignoreUint8Array,
820 tComplex: ignoreTwoUints,
823 // decOpFor returns the decoding op for the base type under rt and
824 // the indirection count to reach it.
825 func (dec *Decoder) decOpFor(wireId typeId, rt reflect.Type, name string, inProgress map[reflect.Type]*decOp) (*decOp, int) {
827 // If the type implements GobEncoder, we handle it without further processing.
829 return dec.gobDecodeOpFor(ut)
831 // If this type is already in progress, it's a recursive type (e.g. map[string]*T).
832 // Return the pointer to the op we're already building.
833 if opPtr := inProgress[rt]; opPtr != nil {
834 return opPtr, ut.indir
840 if int(k) < len(decOpTable) {
846 switch t := typ; t.Kind() {
848 name = "element of " + name
849 elemId := dec.wireType[wireId].ArrayT.Elem
850 elemOp, elemIndir := dec.decOpFor(elemId, t.Elem(), name, inProgress)
851 ovfl := overflow(name)
852 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
853 state.dec.decodeArray(t, state, uintptr(p), *elemOp, t.Elem().Size(), t.Len(), i.indir, elemIndir, ovfl)
857 keyId := dec.wireType[wireId].MapT.Key
858 elemId := dec.wireType[wireId].MapT.Elem
859 keyOp, keyIndir := dec.decOpFor(keyId, t.Key(), "key of "+name, inProgress)
860 elemOp, elemIndir := dec.decOpFor(elemId, t.Elem(), "element of "+name, inProgress)
861 ovfl := overflow(name)
862 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
863 up := unsafe.Pointer(p)
864 state.dec.decodeMap(t, state, uintptr(up), *keyOp, *elemOp, i.indir, keyIndir, elemIndir, ovfl)
868 name = "element of " + name
869 if t.Elem().Kind() == reflect.Uint8 {
874 if tt, ok := builtinIdToType[wireId]; ok {
875 elemId = tt.(*sliceType).Elem
877 elemId = dec.wireType[wireId].SliceT.Elem
879 elemOp, elemIndir := dec.decOpFor(elemId, t.Elem(), name, inProgress)
880 ovfl := overflow(name)
881 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
882 state.dec.decodeSlice(t, state, uintptr(p), *elemOp, t.Elem().Size(), i.indir, elemIndir, ovfl)
886 // Generate a closure that calls out to the engine for the nested type.
887 enginePtr, err := dec.getDecEnginePtr(wireId, userType(typ))
891 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
892 // indirect through enginePtr to delay evaluation for recursive structs.
893 dec.decodeStruct(*enginePtr, userType(typ), uintptr(p), i.indir)
895 case reflect.Interface:
896 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
897 state.dec.decodeInterface(t, state, uintptr(p), i.indir)
902 errorf("decode can't handle type %s", rt)
907 // decIgnoreOpFor returns the decoding op for a field that has no destination.
908 func (dec *Decoder) decIgnoreOpFor(wireId typeId) decOp {
909 op, ok := decIgnoreOpMap[wireId]
911 if wireId == tInterface {
912 // Special case because it's a method: the ignored item might
913 // define types and we need to record their state in the decoder.
914 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
915 state.dec.ignoreInterface(state)
920 wire := dec.wireType[wireId]
923 errorf("bad data: undefined type %s", wireId.string())
924 case wire.ArrayT != nil:
925 elemId := wire.ArrayT.Elem
926 elemOp := dec.decIgnoreOpFor(elemId)
927 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
928 state.dec.ignoreArray(state, elemOp, wire.ArrayT.Len)
931 case wire.MapT != nil:
932 keyId := dec.wireType[wireId].MapT.Key
933 elemId := dec.wireType[wireId].MapT.Elem
934 keyOp := dec.decIgnoreOpFor(keyId)
935 elemOp := dec.decIgnoreOpFor(elemId)
936 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
937 state.dec.ignoreMap(state, keyOp, elemOp)
940 case wire.SliceT != nil:
941 elemId := wire.SliceT.Elem
942 elemOp := dec.decIgnoreOpFor(elemId)
943 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
944 state.dec.ignoreSlice(state, elemOp)
947 case wire.StructT != nil:
948 // Generate a closure that calls out to the engine for the nested type.
949 enginePtr, err := dec.getIgnoreEnginePtr(wireId)
953 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
954 // indirect through enginePtr to delay evaluation for recursive structs
955 state.dec.ignoreStruct(*enginePtr)
958 case wire.GobEncoderT != nil:
959 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
960 state.dec.ignoreGobDecoder(state)
965 errorf("bad data: ignore can't handle type %s", wireId.string())
970 // gobDecodeOpFor returns the op for a type that is known to implement
972 func (dec *Decoder) gobDecodeOpFor(ut *userTypeInfo) (*decOp, int) {
974 if ut.decIndir == -1 {
975 rcvrType = reflect.PtrTo(rcvrType)
976 } else if ut.decIndir > 0 {
977 for i := int8(0); i < ut.decIndir; i++ {
978 rcvrType = rcvrType.Elem()
982 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
983 // Caller has gotten us to within one indirection of our value.
985 if *(*unsafe.Pointer)(p) == nil {
986 *(*unsafe.Pointer)(p) = unsafe.Pointer(reflect.New(ut.base).Pointer())
989 // Now p is a pointer to the base type. Do we need to climb out to
990 // get to the receiver type?
992 if ut.decIndir == -1 {
993 v = reflect.NewAt(rcvrType, unsafe.Pointer(&p)).Elem()
995 v = reflect.NewAt(rcvrType, p).Elem()
997 state.dec.decodeGobDecoder(state, v)
999 return &op, int(ut.indir)
1003 // compatibleType asks: Are these two gob Types compatible?
1004 // Answers the question for basic types, arrays, maps and slices, plus
1005 // GobEncoder/Decoder pairs.
1006 // Structs are considered ok; fields will be checked later.
1007 func (dec *Decoder) compatibleType(fr reflect.Type, fw typeId, inProgress map[reflect.Type]typeId) bool {
1008 if rhs, ok := inProgress[fr]; ok {
1013 wire, ok := dec.wireType[fw]
1014 // If fr is a GobDecoder, the wire type must be GobEncoder.
1015 // And if fr is not a GobDecoder, the wire type must not be either.
1016 if ut.isGobDecoder != (ok && wire.GobEncoderT != nil) { // the parentheses look odd but are correct.
1019 if ut.isGobDecoder { // This test trumps all others.
1022 switch t := ut.base; t.Kind() {
1024 // chan, etc: cannot handle.
1028 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1030 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
1032 case reflect.Float32, reflect.Float64:
1034 case reflect.Complex64, reflect.Complex128:
1035 return fw == tComplex
1036 case reflect.String:
1037 return fw == tString
1038 case reflect.Interface:
1039 return fw == tInterface
1041 if !ok || wire.ArrayT == nil {
1044 array := wire.ArrayT
1045 return t.Len() == array.Len && dec.compatibleType(t.Elem(), array.Elem, inProgress)
1047 if !ok || wire.MapT == nil {
1050 MapType := wire.MapT
1051 return dec.compatibleType(t.Key(), MapType.Key, inProgress) && dec.compatibleType(t.Elem(), MapType.Elem, inProgress)
1053 // Is it an array of bytes?
1054 if t.Elem().Kind() == reflect.Uint8 {
1057 // Extract and compare element types.
1059 if tt, ok := builtinIdToType[fw]; ok {
1060 sw, _ = tt.(*sliceType)
1061 } else if wire != nil {
1064 elem := userType(t.Elem()).base
1065 return sw != nil && dec.compatibleType(elem, sw.Elem, inProgress)
1066 case reflect.Struct:
1072 // typeString returns a human-readable description of the type identified by remoteId.
1073 func (dec *Decoder) typeString(remoteId typeId) string {
1074 if t := idToType[remoteId]; t != nil {
1075 // globally known type.
1078 return dec.wireType[remoteId].string()
1081 // compileSingle compiles the decoder engine for a non-struct top-level value, including
1083 func (dec *Decoder) compileSingle(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) {
1085 engine = new(decEngine)
1086 engine.instr = make([]decInstr, 1) // one item
1087 name := rt.String() // best we can do
1088 if !dec.compatibleType(rt, remoteId, make(map[reflect.Type]typeId)) {
1089 remoteType := dec.typeString(remoteId)
1090 // Common confusing case: local interface type, remote concrete type.
1091 if ut.base.Kind() == reflect.Interface && remoteId != tInterface {
1092 return nil, errors.New("gob: local interface type " + name + " can only be decoded from remote interface type; received concrete type " + remoteType)
1094 return nil, errors.New("gob: decoding into local type " + name + ", received remote type " + remoteType)
1096 op, indir := dec.decOpFor(remoteId, rt, name, make(map[reflect.Type]*decOp))
1097 ovfl := errors.New(`value for "` + name + `" out of range`)
1098 engine.instr[singletonField] = decInstr{*op, singletonField, indir, 0, ovfl}
1103 // compileIgnoreSingle compiles the decoder engine for a non-struct top-level value that will be discarded.
1104 func (dec *Decoder) compileIgnoreSingle(remoteId typeId) (engine *decEngine, err error) {
1105 engine = new(decEngine)
1106 engine.instr = make([]decInstr, 1) // one item
1107 op := dec.decIgnoreOpFor(remoteId)
1108 ovfl := overflow(dec.typeString(remoteId))
1109 engine.instr[0] = decInstr{op, 0, 0, 0, ovfl}
1114 // compileDec compiles the decoder engine for a value. If the value is not a struct,
1115 // it calls out to compileSingle.
1116 func (dec *Decoder) compileDec(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) {
1119 if srt.Kind() != reflect.Struct ||
1121 return dec.compileSingle(remoteId, ut)
1123 var wireStruct *structType
1124 // Builtin types can come from global pool; the rest must be defined by the decoder.
1125 // Also we know we're decoding a struct now, so the client must have sent one.
1126 if t, ok := builtinIdToType[remoteId]; ok {
1127 wireStruct, _ = t.(*structType)
1129 wire := dec.wireType[remoteId]
1133 wireStruct = wire.StructT
1135 if wireStruct == nil {
1136 errorf("type mismatch in decoder: want struct type %s; got non-struct", rt)
1138 engine = new(decEngine)
1139 engine.instr = make([]decInstr, len(wireStruct.Field))
1140 seen := make(map[reflect.Type]*decOp)
1141 // Loop over the fields of the wire type.
1142 for fieldnum := 0; fieldnum < len(wireStruct.Field); fieldnum++ {
1143 wireField := wireStruct.Field[fieldnum]
1144 if wireField.Name == "" {
1145 errorf("empty name for remote field of type %s", wireStruct.Name)
1147 ovfl := overflow(wireField.Name)
1148 // Find the field of the local type with the same name.
1149 localField, present := srt.FieldByName(wireField.Name)
1150 // TODO(r): anonymous names
1151 if !present || !isExported(wireField.Name) {
1152 op := dec.decIgnoreOpFor(wireField.Id)
1153 engine.instr[fieldnum] = decInstr{op, fieldnum, 0, 0, ovfl}
1156 if !dec.compatibleType(localField.Type, wireField.Id, make(map[reflect.Type]typeId)) {
1157 errorf("wrong type (%s) for received field %s.%s", localField.Type, wireStruct.Name, wireField.Name)
1159 op, indir := dec.decOpFor(wireField.Id, localField.Type, localField.Name, seen)
1160 engine.instr[fieldnum] = decInstr{*op, fieldnum, indir, uintptr(localField.Offset), ovfl}
1166 // getDecEnginePtr returns the engine for the specified type.
1167 func (dec *Decoder) getDecEnginePtr(remoteId typeId, ut *userTypeInfo) (enginePtr **decEngine, err error) {
1169 decoderMap, ok := dec.decoderCache[rt]
1171 decoderMap = make(map[typeId]**decEngine)
1172 dec.decoderCache[rt] = decoderMap
1174 if enginePtr, ok = decoderMap[remoteId]; !ok {
1175 // To handle recursive types, mark this engine as underway before compiling.
1176 enginePtr = new(*decEngine)
1177 decoderMap[remoteId] = enginePtr
1178 *enginePtr, err = dec.compileDec(remoteId, ut)
1180 delete(decoderMap, remoteId)
1186 // emptyStruct is the type we compile into when ignoring a struct value.
1187 type emptyStruct struct{}
1189 var emptyStructType = reflect.TypeOf(emptyStruct{})
1191 // getDecEnginePtr returns the engine for the specified type when the value is to be discarded.
1192 func (dec *Decoder) getIgnoreEnginePtr(wireId typeId) (enginePtr **decEngine, err error) {
1194 if enginePtr, ok = dec.ignorerCache[wireId]; !ok {
1195 // To handle recursive types, mark this engine as underway before compiling.
1196 enginePtr = new(*decEngine)
1197 dec.ignorerCache[wireId] = enginePtr
1198 wire := dec.wireType[wireId]
1199 if wire != nil && wire.StructT != nil {
1200 *enginePtr, err = dec.compileDec(wireId, userType(emptyStructType))
1202 *enginePtr, err = dec.compileIgnoreSingle(wireId)
1205 delete(dec.ignorerCache, wireId)
1211 // decodeValue decodes the data stream representing a value and stores it in val.
1212 func (dec *Decoder) decodeValue(wireId typeId, val reflect.Value) {
1213 defer catchError(&dec.err)
1214 // If the value is nil, it means we should just ignore this item.
1216 dec.decodeIgnoredValue(wireId)
1219 // Dereference down to the underlying type.
1220 ut := userType(val.Type())
1222 var enginePtr **decEngine
1223 enginePtr, dec.err = dec.getDecEnginePtr(wireId, ut)
1227 engine := *enginePtr
1228 if st := base; st.Kind() == reflect.Struct && !ut.isGobDecoder {
1229 if engine.numInstr == 0 && st.NumField() > 0 && len(dec.wireType[wireId].StructT.Field) > 0 {
1231 errorf("type mismatch: no fields matched compiling decoder for %s", name)
1233 dec.decodeStruct(engine, ut, uintptr(unsafeAddr(val)), ut.indir)
1235 dec.decodeSingle(engine, ut, uintptr(unsafeAddr(val)))
1239 // decodeIgnoredValue decodes the data stream representing a value of the specified type and discards it.
1240 func (dec *Decoder) decodeIgnoredValue(wireId typeId) {
1241 var enginePtr **decEngine
1242 enginePtr, dec.err = dec.getIgnoreEnginePtr(wireId)
1246 wire := dec.wireType[wireId]
1247 if wire != nil && wire.StructT != nil {
1248 dec.ignoreStruct(*enginePtr)
1250 dec.ignoreSingle(*enginePtr)
1256 switch reflect.TypeOf(int(0)).Bits() {
1264 panic("gob: unknown size of int/uint")
1266 decOpTable[reflect.Int] = iop
1267 decOpTable[reflect.Uint] = uop
1270 switch reflect.TypeOf(uintptr(0)).Bits() {
1276 panic("gob: unknown size of uintptr")
1278 decOpTable[reflect.Uintptr] = uop
1281 // Gob assumes it can call UnsafeAddr on any Value
1282 // in order to get a pointer it can copy data from.
1283 // Values that have just been created and do not point
1284 // into existing structs or slices cannot be addressed,
1285 // so simulate it by returning a pointer to a copy.
1286 // Each call allocates once.
1287 func unsafeAddr(v reflect.Value) uintptr {
1289 return v.UnsafeAddr()
1291 x := reflect.New(v.Type()).Elem()
1293 return x.UnsafeAddr()
1296 // Gob depends on being able to take the address
1297 // of zeroed Values it creates, so use this wrapper instead
1298 // of the standard reflect.Zero.
1299 // Each call allocates once.
1300 func allocValue(t reflect.Type) reflect.Value {
1301 return reflect.New(t).Elem()