github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/pkg/encoding/gob/decode.go (about) 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 n, err := io.ReadFull(r, buf[0:width]) 66 if n == 0 { 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 if state.b.Len() == 0 { 566 errorf("decoding array or slice: length exceeds input size (%d elements)", length) 567 } 568 up := unsafe.Pointer(p) 569 if elemIndir > 1 { 570 up = decIndirect(up, elemIndir) 571 } 572 elemOp(instr, state, up) 573 p += uintptr(elemWid) 574 } 575 } 576 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) { 581 if indir > 0 { 582 p = allocate(atyp, p, 1) // All but the last level has been allocated by dec.Indirect 583 } 584 if n := state.decodeUint(); n != uint64(length) { 585 errorf("length mismatch in decodeArray") 586 } 587 dec.decodeArrayHelper(state, p, elemOp, elemWid, length, elemIndir, ovfl) 588 } 589 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)) 595 if indir > 1 { 596 up = decIndirect(up, indir) 597 } 598 op(instr, state, up) 599 return v 600 } 601 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) { 607 if indir > 0 { 608 p = allocate(mtyp, p, 1) // All but the last level has been allocated by dec.Indirect 609 } 610 up := unsafe.Pointer(p) 611 if *(*unsafe.Pointer)(up) == nil { // maps are represented as a pointer in the runtime 612 // Allocate map. 613 *(*unsafe.Pointer)(up) = unsafe.Pointer(reflect.MakeMap(mtyp).Pointer()) 614 } 615 // Maps cannot be accessed by moving addresses around the way 616 // that slices etc. can. We must recover a full reflection value for 617 // the iteration. 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) 624 } 625 } 626 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) 632 } 633 } 634 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") 639 } 640 dec.ignoreArrayHelper(state, elemOp, length) 641 } 642 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) 651 } 652 } 653 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() 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 registerLock.RLock() 721 typ, ok := nameToConcreteType[name] 722 registerLock.RUnlock() 723 if !ok { 724 errorf("name not registered for interface: %q", name) 725 } 726 // Read the type id of the concrete value. 727 concreteId := dec.decodeTypeSequence(true) 728 if concreteId < 0 { 729 error_(dec.err) 730 } 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). 733 state.decodeUint() 734 // Read the concrete value. 735 value := allocValue(typ) 736 dec.decodeValue(concreteId, value) 737 if dec.err != nil { 738 error_(dec.err) 739 } 740 // Allocate the destination interface value. 741 if indir > 0 { 742 p = allocate(ityp, p, 1) // All but the last level has been allocated by dec.Indirect 743 } 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() 750 } 751 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) 757 if err != nil { 758 error_(err) 759 } 760 id := dec.decodeTypeSequence(true) 761 if id < 0 { 762 error_(dec.err) 763 } 764 // At this point, the decoder buffer contains a delimited value. Just toss it. 765 state.b.Next(int(state.decodeUint())) 766 } 767 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) 774 if err != nil { 775 error_(err) 776 } 777 // We know it's a GobDecoder, so just call the method directly. 778 err = v.Interface().(GobDecoder).GobDecode(b) 779 if err != nil { 780 error_(err) 781 } 782 } 783 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) 789 if err != nil { 790 error_(err) 791 } 792 } 793 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, 810 } 811 812 // Indexed by gob types. tComplex will be added during type.init(). 813 var decIgnoreOpMap = map[typeId]decOp{ 814 tBool: ignoreUint, 815 tInt: ignoreUint, 816 tUint: ignoreUint, 817 tFloat: ignoreUint, 818 tBytes: ignoreUint8Array, 819 tString: ignoreUint8Array, 820 tComplex: ignoreTwoUints, 821 } 822 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) { 826 ut := userType(rt) 827 // If the type implements GobEncoder, we handle it without further processing. 828 if ut.isGobDecoder { 829 return dec.gobDecodeOpFor(ut) 830 } 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 835 } 836 typ := ut.base 837 indir := ut.indir 838 var op decOp 839 k := typ.Kind() 840 if int(k) < len(decOpTable) { 841 op = decOpTable[k] 842 } 843 if op == nil { 844 inProgress[rt] = &op 845 // Special cases 846 switch t := typ; t.Kind() { 847 case reflect.Array: 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) 854 } 855 856 case reflect.Map: 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) 865 } 866 867 case reflect.Slice: 868 name = "element of " + name 869 if t.Elem().Kind() == reflect.Uint8 { 870 op = decUint8Slice 871 break 872 } 873 var elemId typeId 874 if tt, ok := builtinIdToType[wireId]; ok { 875 elemId = tt.(*sliceType).Elem 876 } else { 877 elemId = dec.wireType[wireId].SliceT.Elem 878 } 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) 883 } 884 885 case reflect.Struct: 886 // Generate a closure that calls out to the engine for the nested type. 887 enginePtr, err := dec.getDecEnginePtr(wireId, userType(typ)) 888 if err != nil { 889 error_(err) 890 } 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) 894 } 895 case reflect.Interface: 896 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 897 state.dec.decodeInterface(t, state, uintptr(p), i.indir) 898 } 899 } 900 } 901 if op == nil { 902 errorf("decode can't handle type %s", rt) 903 } 904 return &op, indir 905 } 906 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] 910 if !ok { 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) 916 } 917 return op 918 } 919 // Special cases 920 wire := dec.wireType[wireId] 921 switch { 922 case wire == nil: 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) 929 } 930 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) 938 } 939 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) 945 } 946 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) 950 if err != nil { 951 error_(err) 952 } 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) 956 } 957 958 case wire.GobEncoderT != nil: 959 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 960 state.dec.ignoreGobDecoder(state) 961 } 962 } 963 } 964 if op == nil { 965 errorf("bad data: ignore can't handle type %s", wireId.string()) 966 } 967 return op 968 } 969 970 // gobDecodeOpFor returns the op for a type that is known to implement 971 // GobDecoder. 972 func (dec *Decoder) gobDecodeOpFor(ut *userTypeInfo) (*decOp, int) { 973 rcvrType := ut.user 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() 979 } 980 } 981 var op decOp 982 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 983 // Caller has gotten us to within one indirection of our value. 984 if i.indir > 0 { 985 if *(*unsafe.Pointer)(p) == nil { 986 *(*unsafe.Pointer)(p) = unsafe.Pointer(reflect.New(ut.base).Pointer()) 987 } 988 } 989 // Now p is a pointer to the base type. Do we need to climb out to 990 // get to the receiver type? 991 var v reflect.Value 992 if ut.decIndir == -1 { 993 v = reflect.NewAt(rcvrType, unsafe.Pointer(&p)).Elem() 994 } else { 995 v = reflect.NewAt(rcvrType, p).Elem() 996 } 997 state.dec.decodeGobDecoder(state, v) 998 } 999 return &op, int(ut.indir) 1000 1001 } 1002 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 { 1009 return rhs == fw 1010 } 1011 inProgress[fr] = fw 1012 ut := userType(fr) 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. 1017 return false 1018 } 1019 if ut.isGobDecoder { // This test trumps all others. 1020 return true 1021 } 1022 switch t := ut.base; t.Kind() { 1023 default: 1024 // chan, etc: cannot handle. 1025 return false 1026 case reflect.Bool: 1027 return fw == tBool 1028 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 1029 return fw == tInt 1030 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 1031 return fw == tUint 1032 case reflect.Float32, reflect.Float64: 1033 return fw == tFloat 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 1040 case reflect.Array: 1041 if !ok || wire.ArrayT == nil { 1042 return false 1043 } 1044 array := wire.ArrayT 1045 return t.Len() == array.Len && dec.compatibleType(t.Elem(), array.Elem, inProgress) 1046 case reflect.Map: 1047 if !ok || wire.MapT == nil { 1048 return false 1049 } 1050 MapType := wire.MapT 1051 return dec.compatibleType(t.Key(), MapType.Key, inProgress) && dec.compatibleType(t.Elem(), MapType.Elem, inProgress) 1052 case reflect.Slice: 1053 // Is it an array of bytes? 1054 if t.Elem().Kind() == reflect.Uint8 { 1055 return fw == tBytes 1056 } 1057 // Extract and compare element types. 1058 var sw *sliceType 1059 if tt, ok := builtinIdToType[fw]; ok { 1060 sw, _ = tt.(*sliceType) 1061 } else if wire != nil { 1062 sw = wire.SliceT 1063 } 1064 elem := userType(t.Elem()).base 1065 return sw != nil && dec.compatibleType(elem, sw.Elem, inProgress) 1066 case reflect.Struct: 1067 return true 1068 } 1069 } 1070 1071 // typeString returns a human-readable description of the type identified by remoteId. 1072 func (dec *Decoder) typeString(remoteId typeId) string { 1073 if t := idToType[remoteId]; t != nil { 1074 // globally known type. 1075 return t.string() 1076 } 1077 return dec.wireType[remoteId].string() 1078 } 1079 1080 // compileSingle compiles the decoder engine for a non-struct top-level value, including 1081 // GobDecoders. 1082 func (dec *Decoder) compileSingle(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) { 1083 rt := ut.user 1084 engine = new(decEngine) 1085 engine.instr = make([]decInstr, 1) // one item 1086 name := rt.String() // best we can do 1087 if !dec.compatibleType(rt, remoteId, make(map[reflect.Type]typeId)) { 1088 remoteType := dec.typeString(remoteId) 1089 // Common confusing case: local interface type, remote concrete type. 1090 if ut.base.Kind() == reflect.Interface && remoteId != tInterface { 1091 return nil, errors.New("gob: local interface type " + name + " can only be decoded from remote interface type; received concrete type " + remoteType) 1092 } 1093 return nil, errors.New("gob: decoding into local type " + name + ", received remote type " + remoteType) 1094 } 1095 op, indir := dec.decOpFor(remoteId, rt, name, make(map[reflect.Type]*decOp)) 1096 ovfl := errors.New(`value for "` + name + `" out of range`) 1097 engine.instr[singletonField] = decInstr{*op, singletonField, indir, 0, ovfl} 1098 engine.numInstr = 1 1099 return 1100 } 1101 1102 // compileIgnoreSingle compiles the decoder engine for a non-struct top-level value that will be discarded. 1103 func (dec *Decoder) compileIgnoreSingle(remoteId typeId) (engine *decEngine, err error) { 1104 engine = new(decEngine) 1105 engine.instr = make([]decInstr, 1) // one item 1106 op := dec.decIgnoreOpFor(remoteId) 1107 ovfl := overflow(dec.typeString(remoteId)) 1108 engine.instr[0] = decInstr{op, 0, 0, 0, ovfl} 1109 engine.numInstr = 1 1110 return 1111 } 1112 1113 // compileDec compiles the decoder engine for a value. If the value is not a struct, 1114 // it calls out to compileSingle. 1115 func (dec *Decoder) compileDec(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) { 1116 rt := ut.base 1117 srt := rt 1118 if srt.Kind() != reflect.Struct || 1119 ut.isGobDecoder { 1120 return dec.compileSingle(remoteId, ut) 1121 } 1122 var wireStruct *structType 1123 // Builtin types can come from global pool; the rest must be defined by the decoder. 1124 // Also we know we're decoding a struct now, so the client must have sent one. 1125 if t, ok := builtinIdToType[remoteId]; ok { 1126 wireStruct, _ = t.(*structType) 1127 } else { 1128 wire := dec.wireType[remoteId] 1129 if wire == nil { 1130 error_(errBadType) 1131 } 1132 wireStruct = wire.StructT 1133 } 1134 if wireStruct == nil { 1135 errorf("type mismatch in decoder: want struct type %s; got non-struct", rt) 1136 } 1137 engine = new(decEngine) 1138 engine.instr = make([]decInstr, len(wireStruct.Field)) 1139 seen := make(map[reflect.Type]*decOp) 1140 // Loop over the fields of the wire type. 1141 for fieldnum := 0; fieldnum < len(wireStruct.Field); fieldnum++ { 1142 wireField := wireStruct.Field[fieldnum] 1143 if wireField.Name == "" { 1144 errorf("empty name for remote field of type %s", wireStruct.Name) 1145 } 1146 ovfl := overflow(wireField.Name) 1147 // Find the field of the local type with the same name. 1148 localField, present := srt.FieldByName(wireField.Name) 1149 // TODO(r): anonymous names 1150 if !present || !isExported(wireField.Name) { 1151 op := dec.decIgnoreOpFor(wireField.Id) 1152 engine.instr[fieldnum] = decInstr{op, fieldnum, 0, 0, ovfl} 1153 continue 1154 } 1155 if !dec.compatibleType(localField.Type, wireField.Id, make(map[reflect.Type]typeId)) { 1156 errorf("wrong type (%s) for received field %s.%s", localField.Type, wireStruct.Name, wireField.Name) 1157 } 1158 op, indir := dec.decOpFor(wireField.Id, localField.Type, localField.Name, seen) 1159 engine.instr[fieldnum] = decInstr{*op, fieldnum, indir, uintptr(localField.Offset), ovfl} 1160 engine.numInstr++ 1161 } 1162 return 1163 } 1164 1165 // getDecEnginePtr returns the engine for the specified type. 1166 func (dec *Decoder) getDecEnginePtr(remoteId typeId, ut *userTypeInfo) (enginePtr **decEngine, err error) { 1167 rt := ut.user 1168 decoderMap, ok := dec.decoderCache[rt] 1169 if !ok { 1170 decoderMap = make(map[typeId]**decEngine) 1171 dec.decoderCache[rt] = decoderMap 1172 } 1173 if enginePtr, ok = decoderMap[remoteId]; !ok { 1174 // To handle recursive types, mark this engine as underway before compiling. 1175 enginePtr = new(*decEngine) 1176 decoderMap[remoteId] = enginePtr 1177 *enginePtr, err = dec.compileDec(remoteId, ut) 1178 if err != nil { 1179 delete(decoderMap, remoteId) 1180 } 1181 } 1182 return 1183 } 1184 1185 // emptyStruct is the type we compile into when ignoring a struct value. 1186 type emptyStruct struct{} 1187 1188 var emptyStructType = reflect.TypeOf(emptyStruct{}) 1189 1190 // getDecEnginePtr returns the engine for the specified type when the value is to be discarded. 1191 func (dec *Decoder) getIgnoreEnginePtr(wireId typeId) (enginePtr **decEngine, err error) { 1192 var ok bool 1193 if enginePtr, ok = dec.ignorerCache[wireId]; !ok { 1194 // To handle recursive types, mark this engine as underway before compiling. 1195 enginePtr = new(*decEngine) 1196 dec.ignorerCache[wireId] = enginePtr 1197 wire := dec.wireType[wireId] 1198 if wire != nil && wire.StructT != nil { 1199 *enginePtr, err = dec.compileDec(wireId, userType(emptyStructType)) 1200 } else { 1201 *enginePtr, err = dec.compileIgnoreSingle(wireId) 1202 } 1203 if err != nil { 1204 delete(dec.ignorerCache, wireId) 1205 } 1206 } 1207 return 1208 } 1209 1210 // decodeValue decodes the data stream representing a value and stores it in val. 1211 func (dec *Decoder) decodeValue(wireId typeId, val reflect.Value) { 1212 defer catchError(&dec.err) 1213 // If the value is nil, it means we should just ignore this item. 1214 if !val.IsValid() { 1215 dec.decodeIgnoredValue(wireId) 1216 return 1217 } 1218 // Dereference down to the underlying type. 1219 ut := userType(val.Type()) 1220 base := ut.base 1221 var enginePtr **decEngine 1222 enginePtr, dec.err = dec.getDecEnginePtr(wireId, ut) 1223 if dec.err != nil { 1224 return 1225 } 1226 engine := *enginePtr 1227 if st := base; st.Kind() == reflect.Struct && !ut.isGobDecoder { 1228 if engine.numInstr == 0 && st.NumField() > 0 && len(dec.wireType[wireId].StructT.Field) > 0 { 1229 name := base.Name() 1230 errorf("type mismatch: no fields matched compiling decoder for %s", name) 1231 } 1232 dec.decodeStruct(engine, ut, uintptr(unsafeAddr(val)), ut.indir) 1233 } else { 1234 dec.decodeSingle(engine, ut, uintptr(unsafeAddr(val))) 1235 } 1236 } 1237 1238 // decodeIgnoredValue decodes the data stream representing a value of the specified type and discards it. 1239 func (dec *Decoder) decodeIgnoredValue(wireId typeId) { 1240 var enginePtr **decEngine 1241 enginePtr, dec.err = dec.getIgnoreEnginePtr(wireId) 1242 if dec.err != nil { 1243 return 1244 } 1245 wire := dec.wireType[wireId] 1246 if wire != nil && wire.StructT != nil { 1247 dec.ignoreStruct(*enginePtr) 1248 } else { 1249 dec.ignoreSingle(*enginePtr) 1250 } 1251 } 1252 1253 func init() { 1254 var iop, uop decOp 1255 switch reflect.TypeOf(int(0)).Bits() { 1256 case 32: 1257 iop = decInt32 1258 uop = decUint32 1259 case 64: 1260 iop = decInt64 1261 uop = decUint64 1262 default: 1263 panic("gob: unknown size of int/uint") 1264 } 1265 decOpTable[reflect.Int] = iop 1266 decOpTable[reflect.Uint] = uop 1267 1268 // Finally uintptr 1269 switch reflect.TypeOf(uintptr(0)).Bits() { 1270 case 32: 1271 uop = decUint32 1272 case 64: 1273 uop = decUint64 1274 default: 1275 panic("gob: unknown size of uintptr") 1276 } 1277 decOpTable[reflect.Uintptr] = uop 1278 } 1279 1280 // Gob assumes it can call UnsafeAddr on any Value 1281 // in order to get a pointer it can copy data from. 1282 // Values that have just been created and do not point 1283 // into existing structs or slices cannot be addressed, 1284 // so simulate it by returning a pointer to a copy. 1285 // Each call allocates once. 1286 func unsafeAddr(v reflect.Value) uintptr { 1287 if v.CanAddr() { 1288 return v.UnsafeAddr() 1289 } 1290 x := reflect.New(v.Type()).Elem() 1291 x.Set(v) 1292 return x.UnsafeAddr() 1293 } 1294 1295 // Gob depends on being able to take the address 1296 // of zeroed Values it creates, so use this wrapper instead 1297 // of the standard reflect.Zero. 1298 // Each call allocates once. 1299 func allocValue(t reflect.Type) reflect.Value { 1300 return reflect.New(t).Elem() 1301 }