Source file src/pkg/encoding/gob/decode.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package gob
6
7 // TODO(rsc): When garbage collector changes, revisit
8 // the allocations in this file that use unsafe.Pointer.
9
10 import (
11 "bytes"
12 "errors"
13 "io"
14 "math"
15 "reflect"
16 "unsafe"
17 )
18
19 var (
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")
23 )
24
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 {
28 dec *Decoder
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).
31 b *bytes.Buffer
32 fieldnum int // the last field number read.
33 buf []byte
34 next *decoderState // for free list
35 }
36
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 {
40 d := dec.freeList
41 if d == nil {
42 d = new(decoderState)
43 d.dec = dec
44 d.buf = make([]byte, uint64Size)
45 } else {
46 dec.freeList = d.next
47 }
48 d.b = buf
49 return d
50 }
51
52 func (dec *Decoder) freeDecoderState(d *decoderState) {
53 d.next = dec.freeList
54 dec.freeList = d
55 }
56
57 func overflow(name string) error {
58 return errors.New(`value for "` + name + `" out of range`)
59 }
60
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) {
64 width = 1
65 _, err = r.Read(buf[0:width])
66 if err != nil {
67 return
68 }
69 b := buf[0]
70 if b <= 0x7f {
71 return uint64(b), width, nil
72 }
73 n := -int(int8(b))
74 if n > uint64Size {
75 err = errBadUint
76 return
77 }
78 width, err = io.ReadFull(r, buf[0:n])
79 if err != nil {
80 if err == io.EOF {
81 err = io.ErrUnexpectedEOF
82 }
83 return
84 }
85 // Could check that the high byte is zero but it's not worth it.
86 for _, b := range buf[0:width] {
87 x = x<<8 | uint64(b)
88 }
89 width++ // +1 for length byte
90 return
91 }
92
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()
97 if err != nil {
98 error_(err)
99 }
100 if b <= 0x7f {
101 return uint64(b)
102 }
103 n := -int(int8(b))
104 if n > uint64Size {
105 error_(errBadUint)
106 }
107 width, err := state.b.Read(state.buf[0:n])
108 if err != nil {
109 error_(err)
110 }
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] {
114 x = x<<8 | uint64(b)
115 }
116 return x
117 }
118
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()
123 if x&1 != 0 {
124 return ^int64(x >> 1)
125 }
126 return int64(x >> 1)
127 }
128
129 // decOp is the signature of a decoding operator for a given type.
130 type decOp func(i *decInstr, state *decoderState, p unsafe.Pointer)
131
132 // The 'instructions' of the decoding machine
133 type decInstr struct {
134 op decOp
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)
139 }
140
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
146 // be done.
147
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))
154 }
155 p = *(*unsafe.Pointer)(p)
156 }
157 return p
158 }
159
160 // ignoreUint discards a uint value with no destination.
161 func ignoreUint(i *decInstr, state *decoderState, p unsafe.Pointer) {
162 state.decodeUint()
163 }
164
165 // ignoreTwoUints discards a uint value with no destination. It's used to skip
166 // complex values.
167 func ignoreTwoUints(i *decInstr, state *decoderState, p unsafe.Pointer) {
168 state.decodeUint()
169 state.decodeUint()
170 }
171
172 // decBool decodes a uint and stores it as a boolean through p.
173 func decBool(i *decInstr, state *decoderState, p unsafe.Pointer) {
174 if i.indir > 0 {
175 if *(*unsafe.Pointer)(p) == nil {
176 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(bool))
177 }
178 p = *(*unsafe.Pointer)(p)
179 }
180 *(*bool)(p) = state.decodeUint() != 0
181 }
182
183 // decInt8 decodes an integer and stores it as an int8 through p.
184 func decInt8(i *decInstr, state *decoderState, p unsafe.Pointer) {
185 if i.indir > 0 {
186 if *(*unsafe.Pointer)(p) == nil {
187 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(int8))
188 }
189 p = *(*unsafe.Pointer)(p)
190 }
191 v := state.decodeInt()
192 if v < math.MinInt8 || math.MaxInt8 < v {
193 error_(i.ovfl)
194 } else {
195 *(*int8)(p) = int8(v)
196 }
197 }
198
199 // decUint8 decodes an unsigned integer and stores it as a uint8 through p.
200 func decUint8(i *decInstr, state *decoderState, p unsafe.Pointer) {
201 if i.indir > 0 {
202 if *(*unsafe.Pointer)(p) == nil {
203 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(uint8))
204 }
205 p = *(*unsafe.Pointer)(p)
206 }
207 v := state.decodeUint()
208 if math.MaxUint8 < v {
209 error_(i.ovfl)
210 } else {
211 *(*uint8)(p) = uint8(v)
212 }
213 }
214
215 // decInt16 decodes an integer and stores it as an int16 through p.
216 func decInt16(i *decInstr, state *decoderState, p unsafe.Pointer) {
217 if i.indir > 0 {
218 if *(*unsafe.Pointer)(p) == nil {
219 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(int16))
220 }
221 p = *(*unsafe.Pointer)(p)
222 }
223 v := state.decodeInt()
224 if v < math.MinInt16 || math.MaxInt16 < v {
225 error_(i.ovfl)
226 } else {
227 *(*int16)(p) = int16(v)
228 }
229 }
230
231 // decUint16 decodes an unsigned integer and stores it as a uint16 through p.
232 func decUint16(i *decInstr, state *decoderState, p unsafe.Pointer) {
233 if i.indir > 0 {
234 if *(*unsafe.Pointer)(p) == nil {
235 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(uint16))
236 }
237 p = *(*unsafe.Pointer)(p)
238 }
239 v := state.decodeUint()
240 if math.MaxUint16 < v {
241 error_(i.ovfl)
242 } else {
243 *(*uint16)(p) = uint16(v)
244 }
245 }
246
247 // decInt32 decodes an integer and stores it as an int32 through p.
248 func decInt32(i *decInstr, state *decoderState, p unsafe.Pointer) {
249 if i.indir > 0 {
250 if *(*unsafe.Pointer)(p) == nil {
251 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(int32))
252 }
253 p = *(*unsafe.Pointer)(p)
254 }
255 v := state.decodeInt()
256 if v < math.MinInt32 || math.MaxInt32 < v {
257 error_(i.ovfl)
258 } else {
259 *(*int32)(p) = int32(v)
260 }
261 }
262
263 // decUint32 decodes an unsigned integer and stores it as a uint32 through p.
264 func decUint32(i *decInstr, state *decoderState, p unsafe.Pointer) {
265 if i.indir > 0 {
266 if *(*unsafe.Pointer)(p) == nil {
267 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(uint32))
268 }
269 p = *(*unsafe.Pointer)(p)
270 }
271 v := state.decodeUint()
272 if math.MaxUint32 < v {
273 error_(i.ovfl)
274 } else {
275 *(*uint32)(p) = uint32(v)
276 }
277 }
278
279 // decInt64 decodes an integer and stores it as an int64 through p.
280 func decInt64(i *decInstr, state *decoderState, p unsafe.Pointer) {
281 if i.indir > 0 {
282 if *(*unsafe.Pointer)(p) == nil {
283 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(int64))
284 }
285 p = *(*unsafe.Pointer)(p)
286 }
287 *(*int64)(p) = int64(state.decodeInt())
288 }
289
290 // decUint64 decodes an unsigned integer and stores it as a uint64 through p.
291 func decUint64(i *decInstr, state *decoderState, p unsafe.Pointer) {
292 if i.indir > 0 {
293 if *(*unsafe.Pointer)(p) == nil {
294 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(uint64))
295 }
296 p = *(*unsafe.Pointer)(p)
297 }
298 *(*uint64)(p) = uint64(state.decodeUint())
299 }
300
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
305 // unswizzling.
306 func floatFromBits(u uint64) float64 {
307 var v uint64
308 for i := 0; i < 8; i++ {
309 v <<= 8
310 v |= u & 0xFF
311 u >>= 8
312 }
313 return math.Float64frombits(v)
314 }
315
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())
320 av := v
321 if av < 0 {
322 av = -av
323 }
324 // +Inf is OK in both 32- and 64-bit floats. Underflow is always OK.
325 if math.MaxFloat32 < av && av <= math.MaxFloat64 {
326 error_(i.ovfl)
327 } else {
328 *(*float32)(p) = float32(v)
329 }
330 }
331
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) {
335 if i.indir > 0 {
336 if *(*unsafe.Pointer)(p) == nil {
337 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(float32))
338 }
339 p = *(*unsafe.Pointer)(p)
340 }
341 storeFloat32(i, state, p)
342 }
343
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) {
347 if i.indir > 0 {
348 if *(*unsafe.Pointer)(p) == nil {
349 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(float64))
350 }
351 p = *(*unsafe.Pointer)(p)
352 }
353 *(*float64)(p) = floatFromBits(uint64(state.decodeUint()))
354 }
355
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) {
360 if i.indir > 0 {
361 if *(*unsafe.Pointer)(p) == nil {
362 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(complex64))
363 }
364 p = *(*unsafe.Pointer)(p)
365 }
366 storeFloat32(i, state, p)
367 storeFloat32(i, state, unsafe.Pointer(uintptr(p)+unsafe.Sizeof(float32(0))))
368 }
369
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) {
374 if i.indir > 0 {
375 if *(*unsafe.Pointer)(p) == nil {
376 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(complex128))
377 }
378 p = *(*unsafe.Pointer)(p)
379 }
380 real := floatFromBits(uint64(state.decodeUint()))
381 imag := floatFromBits(uint64(state.decodeUint()))
382 *(*complex128)(p) = complex(real, imag)
383 }
384
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) {
389 if i.indir > 0 {
390 if *(*unsafe.Pointer)(p) == nil {
391 *(*unsafe.Pointer)(p) = unsafe.Pointer(new([]uint8))
392 }
393 p = *(*unsafe.Pointer)(p)
394 }
395 n := state.decodeUint()
396 if n > uint64(state.b.Len()) {
397 errorf("length of []byte exceeds input size (%d bytes)", n)
398 }
399 slice := (*[]uint8)(p)
400 if uint64(cap(*slice)) < n {
401 *slice = make([]uint8, n)
402 } else {
403 *slice = (*slice)[0:n]
404 }
405 if _, err := state.b.Read(*slice); err != nil {
406 errorf("error decoding []byte: %s", err)
407 }
408 }
409
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) {
414 if i.indir > 0 {
415 if *(*unsafe.Pointer)(p) == nil {
416 *(*unsafe.Pointer)(p) = unsafe.Pointer(new(string))
417 }
418 p = *(*unsafe.Pointer)(p)
419 }
420 n := state.decodeUint()
421 if n > uint64(state.b.Len()) {
422 errorf("string length exceeds input size (%d bytes)", n)
423 }
424 b := make([]byte, n)
425 state.b.Read(b)
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))
434 }
435
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())
439 state.b.Read(b)
440 }
441
442 // Execution engine
443
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 {
447 instr []decInstr
448 numInstr int // the number of active instructions
449 }
450
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 {
454 if indir == 0 {
455 return p
456 }
457 up := unsafe.Pointer(p)
458 if indir > 1 {
459 up = decIndirect(up, indir)
460 }
461 if *(*unsafe.Pointer)(up) == nil {
462 // Allocate object.
463 *(*unsafe.Pointer)(up) = unsafe.Pointer(reflect.New(rtyp).Pointer())
464 }
465 return *(*uintptr)(up)
466 }
467
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())
475 if delta != 0 {
476 errorf("decode: corrupted data: non-zero delta for singleton")
477 }
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)
481 }
482 ptr := unsafe.Pointer(basep) // offset will be zero
483 if instr.indir > 1 {
484 ptr = decIndirect(ptr, instr.indir)
485 }
486 instr.op(instr, state, ptr)
487 dec.freeDecoderState(state)
488 }
489
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)
498 state.fieldnum = -1
499 basep := p
500 for state.b.Len() > 0 {
501 delta := int(state.decodeUint())
502 if delta < 0 {
503 errorf("decode: corrupted data: negative delta")
504 }
505 if delta == 0 { // struct terminator is zero delta fieldnum
506 break
507 }
508 fieldnum := state.fieldnum + delta
509 if fieldnum >= len(engine.instr) {
510 error_(errRange)
511 break
512 }
513 instr := &engine.instr[fieldnum]
514 p := unsafe.Pointer(basep + instr.offset)
515 if instr.indir > 1 {
516 p = decIndirect(p, instr.indir)
517 }
518 instr.op(instr, state, p)
519 state.fieldnum = fieldnum
520 }
521 dec.freeDecoderState(state)
522 }
523
524 // ignoreStruct discards the data for a struct with no destination.
525 func (dec *Decoder) ignoreStruct(engine *decEngine) {
526 state := dec.newDecoderState(&dec.buf)
527 state.fieldnum = -1
528 for state.b.Len() > 0 {
529 delta := int(state.decodeUint())
530 if delta < 0 {
531 errorf("ignore decode: corrupted data: negative delta")
532 }
533 if delta == 0 { // struct terminator is zero delta fieldnum
534 break
535 }
536 fieldnum := state.fieldnum + delta
537 if fieldnum >= len(engine.instr) {
538 error_(errRange)
539 }
540 instr := &engine.instr[fieldnum]
541 instr.op(instr, state, unsafe.Pointer(nil))
542 state.fieldnum = fieldnum
543 }
544 dec.freeDecoderState(state)
545 }
546
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())
553 if delta != 0 {
554 errorf("decode: corrupted data: non-zero delta for singleton")
555 }
556 instr := &engine.instr[singletonField]
557 instr.op(instr, state, unsafe.Pointer(nil))
558 dec.freeDecoderState(state)
559 }
560
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)
566 if elemIndir > 1 {
567 up = decIndirect(up, elemIndir)
568 }
569 elemOp(instr, state, up)
570 p += uintptr(elemWid)
571 }
572 }
573
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) {
578 if indir > 0 {
579 p = allocate(atyp, p, 1) // All but the last level has been allocated by dec.Indirect
580 }
581 if n := state.decodeUint(); n != uint64(length) {
582 errorf("length mismatch in decodeArray")
583 }
584 dec.decodeArrayHelper(state, p, elemOp, elemWid, length, elemIndir, ovfl)
585 }
586
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))
592 if indir > 1 {
593 up = decIndirect(up, indir)
594 }
595 op(instr, state, up)
596 return v
597 }
598
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) {
604 if indir > 0 {
605 p = allocate(mtyp, p, 1) // All but the last level has been allocated by dec.Indirect
606 }
607 up := unsafe.Pointer(p)
608 if *(*unsafe.Pointer)(up) == nil { // maps are represented as a pointer in the runtime
609 // Allocate map.
610 *(*unsafe.Pointer)(up) = unsafe.Pointer(reflect.MakeMap(mtyp).Pointer())
611 }
612 // Maps cannot be accessed by moving addresses around the way
613 // that slices etc. can. We must recover a full reflection value for
614 // the iteration.
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)
621 }
622 }
623
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)
629 }
630 }
631
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")
636 }
637 dec.ignoreArrayHelper(state, elemOp, length)
638 }
639
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)
648 }
649 }
650
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)
657 }
658 n := int(nr)
659 if indir > 0 {
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))
664 }
665 p = *(*uintptr)(up)
666 }
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))
671 if hdrp.Cap < n {
672 hdrp.Data = reflect.MakeSlice(atyp, n, n).Pointer()
673 hdrp.Cap = n
674 }
675 hdrp.Len = n
676 dec.decodeArrayHelper(state, hdrp.Data, elemOp, elemWid, n, elemIndir, ovfl)
677 }
678
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()))
682 }
683
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())
689 }
690 ivalue.Set(value)
691 }
692
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)
703 }
704 b := make([]byte, nr)
705 state.b.Read(b)
706 name := string(b)
707 if name == "" {
708 // Copy the representation of the nil interface value to the target.
709 // This is horribly unsafe and special.
710 if indir > 0 {
711 p = allocate(ityp, p, 1) // All but the last level has been allocated by dec.Indirect
712 }
713 *(*[2]uintptr)(unsafe.Pointer(p)) = ivalue.InterfaceData()
714 return
715 }
716 if len(name) > 1024 {
717 errorf("name too long (%d bytes): %.20q...", len(name), name)
718 }
719 // The concrete type must be registered.
720 typ, ok := nameToConcreteType[name]
721 if !ok {
722 errorf("name not registered for interface: %q", name)
723 }
724 // Read the type id of the concrete value.
725 concreteId := dec.decodeTypeSequence(true)
726 if concreteId < 0 {
727 error_(dec.err)
728 }
729 // Byte count of value is next; we don't care what it is (it's there
730 // in case we want to ignore the value by skipping it completely).
731 state.decodeUint()
732 // Read the concrete value.
733 value := allocValue(typ)
734 dec.decodeValue(concreteId, value)
735 if dec.err != nil {
736 error_(dec.err)
737 }
738 // Allocate the destination interface value.
739 if indir > 0 {
740 p = allocate(ityp, p, 1) // All but the last level has been allocated by dec.Indirect
741 }
742 // Assign the concrete value to the interface.
743 // Tread carefully; it might not satisfy the interface.
744 setInterfaceValue(ivalue, value)
745 // Copy the representation of the interface value to the target.
746 // This is horribly unsafe and special.
747 *(*[2]uintptr)(unsafe.Pointer(p)) = ivalue.InterfaceData()
748 }
749
750 // ignoreInterface discards the data for an interface value with no destination.
751 func (dec *Decoder) ignoreInterface(state *decoderState) {
752 // Read the name of the concrete type.
753 b := make([]byte, state.decodeUint())
754 _, err := state.b.Read(b)
755 if err != nil {
756 error_(err)
757 }
758 id := dec.decodeTypeSequence(true)
759 if id < 0 {
760 error_(dec.err)
761 }
762 // At this point, the decoder buffer contains a delimited value. Just toss it.
763 state.b.Next(int(state.decodeUint()))
764 }
765
766 // decodeGobDecoder decodes something implementing the GobDecoder interface.
767 // The data is encoded as a byte slice.
768 func (dec *Decoder) decodeGobDecoder(state *decoderState, v reflect.Value) {
769 // Read the bytes for the value.
770 b := make([]byte, state.decodeUint())
771 _, err := state.b.Read(b)
772 if err != nil {
773 error_(err)
774 }
775 // We know it's a GobDecoder, so just call the method directly.
776 err = v.Interface().(GobDecoder).GobDecode(b)
777 if err != nil {
778 error_(err)
779 }
780 }
781
782 // ignoreGobDecoder discards the data for a GobDecoder value with no destination.
783 func (dec *Decoder) ignoreGobDecoder(state *decoderState) {
784 // Read the bytes for the value.
785 b := make([]byte, state.decodeUint())
786 _, err := state.b.Read(b)
787 if err != nil {
788 error_(err)
789 }
790 }
791
792 // Index by Go types.
793 var decOpTable = [...]decOp{
794 reflect.Bool: decBool,
795 reflect.Int8: decInt8,
796 reflect.Int16: decInt16,
797 reflect.Int32: decInt32,
798 reflect.Int64: decInt64,
799 reflect.Uint8: decUint8,
800 reflect.Uint16: decUint16,
801 reflect.Uint32: decUint32,
802 reflect.Uint64: decUint64,
803 reflect.Float32: decFloat32,
804 reflect.Float64: decFloat64,
805 reflect.Complex64: decComplex64,
806 reflect.Complex128: decComplex128,
807 reflect.String: decString,
808 }
809
810 // Indexed by gob types. tComplex will be added during type.init().
811 var decIgnoreOpMap = map[typeId]decOp{
812 tBool: ignoreUint,
813 tInt: ignoreUint,
814 tUint: ignoreUint,
815 tFloat: ignoreUint,
816 tBytes: ignoreUint8Array,
817 tString: ignoreUint8Array,
818 tComplex: ignoreTwoUints,
819 }
820
821 // decOpFor returns the decoding op for the base type under rt and
822 // the indirection count to reach it.
823 func (dec *Decoder) decOpFor(wireId typeId, rt reflect.Type, name string, inProgress map[reflect.Type]*decOp) (*decOp, int) {
824 ut := userType(rt)
825 // If the type implements GobEncoder, we handle it without further processing.
826 if ut.isGobDecoder {
827 return dec.gobDecodeOpFor(ut)
828 }
829 // If this type is already in progress, it's a recursive type (e.g. map[string]*T).
830 // Return the pointer to the op we're already building.
831 if opPtr := inProgress[rt]; opPtr != nil {
832 return opPtr, ut.indir
833 }
834 typ := ut.base
835 indir := ut.indir
836 var op decOp
837 k := typ.Kind()
838 if int(k) < len(decOpTable) {
839 op = decOpTable[k]
840 }
841 if op == nil {
842 inProgress[rt] = &op
843 // Special cases
844 switch t := typ; t.Kind() {
845 case reflect.Array:
846 name = "element of " + name
847 elemId := dec.wireType[wireId].ArrayT.Elem
848 elemOp, elemIndir := dec.decOpFor(elemId, t.Elem(), name, inProgress)
849 ovfl := overflow(name)
850 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
851 state.dec.decodeArray(t, state, uintptr(p), *elemOp, t.Elem().Size(), t.Len(), i.indir, elemIndir, ovfl)
852 }
853
854 case reflect.Map:
855 keyId := dec.wireType[wireId].MapT.Key
856 elemId := dec.wireType[wireId].MapT.Elem
857 keyOp, keyIndir := dec.decOpFor(keyId, t.Key(), "key of "+name, inProgress)
858 elemOp, elemIndir := dec.decOpFor(elemId, t.Elem(), "element of "+name, inProgress)
859 ovfl := overflow(name)
860 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
861 up := unsafe.Pointer(p)
862 state.dec.decodeMap(t, state, uintptr(up), *keyOp, *elemOp, i.indir, keyIndir, elemIndir, ovfl)
863 }
864
865 case reflect.Slice:
866 name = "element of " + name
867 if t.Elem().Kind() == reflect.Uint8 {
868 op = decUint8Slice
869 break
870 }
871 var elemId typeId
872 if tt, ok := builtinIdToType[wireId]; ok {
873 elemId = tt.(*sliceType).Elem
874 } else {
875 elemId = dec.wireType[wireId].SliceT.Elem
876 }
877 elemOp, elemIndir := dec.decOpFor(elemId, t.Elem(), name, inProgress)
878 ovfl := overflow(name)
879 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
880 state.dec.decodeSlice(t, state, uintptr(p), *elemOp, t.Elem().Size(), i.indir, elemIndir, ovfl)
881 }
882
883 case reflect.Struct:
884 // Generate a closure that calls out to the engine for the nested type.
885 enginePtr, err := dec.getDecEnginePtr(wireId, userType(typ))
886 if err != nil {
887 error_(err)
888 }
889 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
890 // indirect through enginePtr to delay evaluation for recursive structs.
891 dec.decodeStruct(*enginePtr, userType(typ), uintptr(p), i.indir)
892 }
893 case reflect.Interface:
894 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
895 state.dec.decodeInterface(t, state, uintptr(p), i.indir)
896 }
897 }
898 }
899 if op == nil {
900 errorf("decode can't handle type %s", rt)
901 }
902 return &op, indir
903 }
904
905 // decIgnoreOpFor returns the decoding op for a field that has no destination.
906 func (dec *Decoder) decIgnoreOpFor(wireId typeId) decOp {
907 op, ok := decIgnoreOpMap[wireId]
908 if !ok {
909 if wireId == tInterface {
910 // Special case because it's a method: the ignored item might
911 // define types and we need to record their state in the decoder.
912 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
913 state.dec.ignoreInterface(state)
914 }
915 return op
916 }
917 // Special cases
918 wire := dec.wireType[wireId]
919 switch {
920 case wire == nil:
921 errorf("bad data: undefined type %s", wireId.string())
922 case wire.ArrayT != nil:
923 elemId := wire.ArrayT.Elem
924 elemOp := dec.decIgnoreOpFor(elemId)
925 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
926 state.dec.ignoreArray(state, elemOp, wire.ArrayT.Len)
927 }
928
929 case wire.MapT != nil:
930 keyId := dec.wireType[wireId].MapT.Key
931 elemId := dec.wireType[wireId].MapT.Elem
932 keyOp := dec.decIgnoreOpFor(keyId)
933 elemOp := dec.decIgnoreOpFor(elemId)
934 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
935 state.dec.ignoreMap(state, keyOp, elemOp)
936 }
937
938 case wire.SliceT != nil:
939 elemId := wire.SliceT.Elem
940 elemOp := dec.decIgnoreOpFor(elemId)
941 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
942 state.dec.ignoreSlice(state, elemOp)
943 }
944
945 case wire.StructT != nil:
946 // Generate a closure that calls out to the engine for the nested type.
947 enginePtr, err := dec.getIgnoreEnginePtr(wireId)
948 if err != nil {
949 error_(err)
950 }
951 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
952 // indirect through enginePtr to delay evaluation for recursive structs
953 state.dec.ignoreStruct(*enginePtr)
954 }
955
956 case wire.GobEncoderT != nil:
957 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
958 state.dec.ignoreGobDecoder(state)
959 }
960 }
961 }
962 if op == nil {
963 errorf("bad data: ignore can't handle type %s", wireId.string())
964 }
965 return op
966 }
967
968 // gobDecodeOpFor returns the op for a type that is known to implement
969 // GobDecoder.
970 func (dec *Decoder) gobDecodeOpFor(ut *userTypeInfo) (*decOp, int) {
971 rcvrType := ut.user
972 if ut.decIndir == -1 {
973 rcvrType = reflect.PtrTo(rcvrType)
974 } else if ut.decIndir > 0 {
975 for i := int8(0); i < ut.decIndir; i++ {
976 rcvrType = rcvrType.Elem()
977 }
978 }
979 var op decOp
980 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) {
981 // Caller has gotten us to within one indirection of our value.
982 if i.indir > 0 {
983 if *(*unsafe.Pointer)(p) == nil {
984 *(*unsafe.Pointer)(p) = unsafe.Pointer(reflect.New(ut.base).Pointer())
985 }
986 }
987 // Now p is a pointer to the base type. Do we need to climb out to
988 // get to the receiver type?
989 var v reflect.Value
990 if ut.decIndir == -1 {
991 v = reflect.NewAt(rcvrType, unsafe.Pointer(&p)).Elem()
992 } else {
993 v = reflect.NewAt(rcvrType, p).Elem()
994 }
995 state.dec.decodeGobDecoder(state, v)
996 }
997 return &op, int(ut.indir)
998
999 }
1000
1001 // compatibleType asks: Are these two gob Types compatible?
1002 // Answers the question for basic types, arrays, maps and slices, plus
1003 // GobEncoder/Decoder pairs.
1004 // Structs are considered ok; fields will be checked later.
1005 func (dec *Decoder) compatibleType(fr reflect.Type, fw typeId, inProgress map[reflect.Type]typeId) bool {
1006 if rhs, ok := inProgress[fr]; ok {
1007 return rhs == fw
1008 }
1009 inProgress[fr] = fw
1010 ut := userType(fr)
1011 wire, ok := dec.wireType[fw]
1012 // If fr is a GobDecoder, the wire type must be GobEncoder.
1013 // And if fr is not a GobDecoder, the wire type must not be either.
1014 if ut.isGobDecoder != (ok && wire.GobEncoderT != nil) { // the parentheses look odd but are correct.
1015 return false
1016 }
1017 if ut.isGobDecoder { // This test trumps all others.
1018 return true
1019 }
1020 switch t := ut.base; t.Kind() {
1021 default:
1022 // chan, etc: cannot handle.
1023 return false
1024 case reflect.Bool:
1025 return fw == tBool
1026 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1027 return fw == tInt
1028 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
1029 return fw == tUint
1030 case reflect.Float32, reflect.Float64:
1031 return fw == tFloat
1032 case reflect.Complex64, reflect.Complex128:
1033 return fw == tComplex
1034 case reflect.String:
1035 return fw == tString
1036 case reflect.Interface:
1037 return fw == tInterface
1038 case reflect.Array:
1039 if !ok || wire.ArrayT == nil {
1040 return false
1041 }
1042 array := wire.ArrayT
1043 return t.Len() == array.Len && dec.compatibleType(t.Elem(), array.Elem, inProgress)
1044 case reflect.Map:
1045 if !ok || wire.MapT == nil {
1046 return false
1047 }
1048 MapType := wire.MapT
1049 return dec.compatibleType(t.Key(), MapType.Key, inProgress) && dec.compatibleType(t.Elem(), MapType.Elem, inProgress)
1050 case reflect.Slice:
1051 // Is it an array of bytes?
1052 if t.Elem().Kind() == reflect.Uint8 {
1053 return fw == tBytes
1054 }
1055 // Extract and compare element types.
1056 var sw *sliceType
1057 if tt, ok := builtinIdToType[fw]; ok {
1058 sw, _ = tt.(*sliceType)
1059 } else if wire != nil {
1060 sw = wire.SliceT
1061 }
1062 elem := userType(t.Elem()).base
1063 return sw != nil && dec.compatibleType(elem, sw.Elem, inProgress)
1064 case reflect.Struct:
1065 return true
1066 }
1067 return true
1068 }
1069
1070 // typeString returns a human-readable description of the type identified by remoteId.
1071 func (dec *Decoder) typeString(remoteId typeId) string {
1072 if t := idToType[remoteId]; t != nil {
1073 // globally known type.
1074 return t.string()
1075 }
1076 return dec.wireType[remoteId].string()
1077 }
1078
1079 // compileSingle compiles the decoder engine for a non-struct top-level value, including
1080 // GobDecoders.
1081 func (dec *Decoder) compileSingle(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) {
1082 rt := ut.user
1083 engine = new(decEngine)
1084 engine.instr = make([]decInstr, 1) // one item
1085 name := rt.String() // best we can do
1086 if !dec.compatibleType(rt, remoteId, make(map[reflect.Type]typeId)) {
1087 remoteType := dec.typeString(remoteId)
1088 // Common confusing case: local interface type, remote concrete type.
1089 if ut.base.Kind() == reflect.Interface && remoteId != tInterface {
1090 return nil, errors.New("gob: local interface type " + name + " can only be decoded from remote interface type; received concrete type " + remoteType)
1091 }
1092 return nil, errors.New("gob: decoding into local type " + name + ", received remote type " + remoteType)
1093 }
1094 op, indir := dec.decOpFor(remoteId, rt, name, make(map[reflect.Type]*decOp))
1095 ovfl := errors.New(`value for "` + name + `" out of range`)
1096 engine.instr[singletonField] = decInstr{*op, singletonField, indir, 0, ovfl}
1097 engine.numInstr = 1
1098 return
1099 }
1100
1101 // compileIgnoreSingle compiles the decoder engine for a non-struct top-level value that will be discarded.
1102 func (dec *Decoder) compileIgnoreSingle(remoteId typeId) (engine *decEngine, err error) {
1103 engine = new(decEngine)
1104 engine.instr = make([]decInstr, 1) // one item
1105 op := dec.decIgnoreOpFor(remoteId)
1106 ovfl := overflow(dec.typeString(remoteId))
1107 engine.instr[0] = decInstr{op, 0, 0, 0, ovfl}
1108 engine.numInstr = 1
1109 return
1110 }
1111
1112 // compileDec compiles the decoder engine for a value. If the value is not a struct,
1113 // it calls out to compileSingle.
1114 func (dec *Decoder) compileDec(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) {
1115 rt := ut.base
1116 srt := rt
1117 if srt.Kind() != reflect.Struct ||
1118 ut.isGobDecoder {
1119 return dec.compileSingle(remoteId, ut)
1120 }
1121 var wireStruct *structType
1122 // Builtin types can come from global pool; the rest must be defined by the decoder.
1123 // Also we know we're decoding a struct now, so the client must have sent one.
1124 if t, ok := builtinIdToType[remoteId]; ok {
1125 wireStruct, _ = t.(*structType)
1126 } else {
1127 wire := dec.wireType[remoteId]
1128 if wire == nil {
1129 error_(errBadType)
1130 }
1131 wireStruct = wire.StructT
1132 }
1133 if wireStruct == nil {
1134 errorf("type mismatch in decoder: want struct type %s; got non-struct", rt)
1135 }
1136 engine = new(decEngine)
1137 engine.instr = make([]decInstr, len(wireStruct.Field))
1138 seen := make(map[reflect.Type]*decOp)
1139 // Loop over the fields of the wire type.
1140 for fieldnum := 0; fieldnum < len(wireStruct.Field); fieldnum++ {
1141 wireField := wireStruct.Field[fieldnum]
1142 if wireField.Name == "" {
1143 errorf("empty name for remote field of type %s", wireStruct.Name)
1144 }
1145 ovfl := overflow(wireField.Name)
1146 // Find the field of the local type with the same name.
1147 localField, present := srt.FieldByName(wireField.Name)
1148 // TODO(r): anonymous names
1149 if !present || !isExported(wireField.Name) {
1150 op := dec.decIgnoreOpFor(wireField.Id)
1151 engine.instr[fieldnum] = decInstr{op, fieldnum, 0, 0, ovfl}
1152 continue
1153 }
1154 if !dec.compatibleType(localField.Type, wireField.Id, make(map[reflect.Type]typeId)) {
1155 errorf("wrong type (%s) for received field %s.%s", localField.Type, wireStruct.Name, wireField.Name)
1156 }
1157 op, indir := dec.decOpFor(wireField.Id, localField.Type, localField.Name, seen)
1158 engine.instr[fieldnum] = decInstr{*op, fieldnum, indir, uintptr(localField.Offset), ovfl}
1159 engine.numInstr++
1160 }
1161 return
1162 }
1163
1164 // getDecEnginePtr returns the engine for the specified type.
1165 func (dec *Decoder) getDecEnginePtr(remoteId typeId, ut *userTypeInfo) (enginePtr **decEngine, err error) {
1166 rt := ut.user
1167 decoderMap, ok := dec.decoderCache[rt]
1168 if !ok {
1169 decoderMap = make(map[typeId]**decEngine)
1170 dec.decoderCache[rt] = decoderMap
1171 }
1172 if enginePtr, ok = decoderMap[remoteId]; !ok {
1173 // To handle recursive types, mark this engine as underway before compiling.
1174 enginePtr = new(*decEngine)
1175 decoderMap[remoteId] = enginePtr
1176 *enginePtr, err = dec.compileDec(remoteId, ut)
1177 if err != nil {
1178 delete(decoderMap, remoteId)
1179 }
1180 }
1181 return
1182 }
1183
1184 // emptyStruct is the type we compile into when ignoring a struct value.
1185 type emptyStruct struct{}
1186
1187 var emptyStructType = reflect.TypeOf(emptyStruct{})
1188
1189 // getDecEnginePtr returns the engine for the specified type when the value is to be discarded.
1190 func (dec *Decoder) getIgnoreEnginePtr(wireId typeId) (enginePtr **decEngine, err error) {
1191 var ok bool
1192 if enginePtr, ok = dec.ignorerCache[wireId]; !ok {
1193 // To handle recursive types, mark this engine as underway before compiling.
1194 enginePtr = new(*decEngine)
1195 dec.ignorerCache[wireId] = enginePtr
1196 wire := dec.wireType[wireId]
1197 if wire != nil && wire.StructT != nil {
1198 *enginePtr, err = dec.compileDec(wireId, userType(emptyStructType))
1199 } else {
1200 *enginePtr, err = dec.compileIgnoreSingle(wireId)
1201 }
1202 if err != nil {
1203 delete(dec.ignorerCache, wireId)
1204 }
1205 }
1206 return
1207 }
1208
1209 // decodeValue decodes the data stream representing a value and stores it in val.
1210 func (dec *Decoder) decodeValue(wireId typeId, val reflect.Value) {
1211 defer catchError(&dec.err)
1212 // If the value is nil, it means we should just ignore this item.
1213 if !val.IsValid() {
1214 dec.decodeIgnoredValue(wireId)
1215 return
1216 }
1217 // Dereference down to the underlying type.
1218 ut := userType(val.Type())
1219 base := ut.base
1220 var enginePtr **decEngine
1221 enginePtr, dec.err = dec.getDecEnginePtr(wireId, ut)
1222 if dec.err != nil {
1223 return
1224 }
1225 engine := *enginePtr
1226 if st := base; st.Kind() == reflect.Struct && !ut.isGobDecoder {
1227 if engine.numInstr == 0 && st.NumField() > 0 && len(dec.wireType[wireId].StructT.Field) > 0 {
1228 name := base.Name()
1229 errorf("type mismatch: no fields matched compiling decoder for %s", name)
1230 }
1231 dec.decodeStruct(engine, ut, uintptr(unsafeAddr(val)), ut.indir)
1232 } else {
1233 dec.decodeSingle(engine, ut, uintptr(unsafeAddr(val)))
1234 }
1235 }
1236
1237 // decodeIgnoredValue decodes the data stream representing a value of the specified type and discards it.
1238 func (dec *Decoder) decodeIgnoredValue(wireId typeId) {
1239 var enginePtr **decEngine
1240 enginePtr, dec.err = dec.getIgnoreEnginePtr(wireId)
1241 if dec.err != nil {
1242 return
1243 }
1244 wire := dec.wireType[wireId]
1245 if wire != nil && wire.StructT != nil {
1246 dec.ignoreStruct(*enginePtr)
1247 } else {
1248 dec.ignoreSingle(*enginePtr)
1249 }
1250 }
1251
1252 func init() {
1253 var iop, uop decOp
1254 switch reflect.TypeOf(int(0)).Bits() {
1255 case 32:
1256 iop = decInt32
1257 uop = decUint32
1258 case 64:
1259 iop = decInt64
1260 uop = decUint64
1261 default:
1262 panic("gob: unknown size of int/uint")
1263 }
1264 decOpTable[reflect.Int] = iop
1265 decOpTable[reflect.Uint] = uop
1266
1267 // Finally uintptr
1268 switch reflect.TypeOf(uintptr(0)).Bits() {
1269 case 32:
1270 uop = decUint32
1271 case 64:
1272 uop = decUint64
1273 default:
1274 panic("gob: unknown size of uintptr")
1275 }
1276 decOpTable[reflect.Uintptr] = uop
1277 }
1278
1279 // Gob assumes it can call UnsafeAddr on any Value
1280 // in order to get a pointer it can copy data from.
1281 // Values that have just been created and do not point
1282 // into existing structs or slices cannot be addressed,
1283 // so simulate it by returning a pointer to a copy.
1284 // Each call allocates once.
1285 func unsafeAddr(v reflect.Value) uintptr {
1286 if v.CanAddr() {
1287 return v.UnsafeAddr()
1288 }
1289 x := reflect.New(v.Type()).Elem()
1290 x.Set(v)
1291 return x.UnsafeAddr()
1292 }
1293
1294 // Gob depends on being able to take the address
1295 // of zeroed Values it creates, so use this wrapper instead
1296 // of the standard reflect.Zero.
1297 // Each call allocates once.
1298 func allocValue(t reflect.Type) reflect.Value {
1299 return reflect.New(t).Elem()
1300 }