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