github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/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 uintptr, elemOp decOp, elemWid uintptr, indir, elemIndir int, ovfl error) { 658 nr := state.decodeUint() 659 n := int(nr) 660 if indir > 0 { 661 up := unsafe.Pointer(p) 662 if *(*unsafe.Pointer)(up) == nil { 663 // Allocate the slice header. 664 *(*unsafe.Pointer)(up) = unsafe.Pointer(new([]unsafe.Pointer)) 665 } 666 p = *(*uintptr)(up) 667 } 668 // Allocate storage for the slice elements, that is, the underlying array, 669 // if the existing slice does not have the capacity. 670 // Always write a header at p. 671 hdrp := (*reflect.SliceHeader)(unsafe.Pointer(p)) 672 if hdrp.Cap < n { 673 hdrp.Data = reflect.MakeSlice(atyp, n, n).Pointer() 674 hdrp.Cap = n 675 } 676 hdrp.Len = n 677 dec.decodeArrayHelper(state, unsafe.Pointer(hdrp.Data), elemOp, elemWid, n, elemIndir, ovfl) 678 } 679 680 // ignoreSlice skips over the data for a slice value with no destination. 681 func (dec *Decoder) ignoreSlice(state *decoderState, elemOp decOp) { 682 dec.ignoreArrayHelper(state, elemOp, int(state.decodeUint())) 683 } 684 685 // setInterfaceValue sets an interface value to a concrete value, 686 // but first it checks that the assignment will succeed. 687 func setInterfaceValue(ivalue reflect.Value, value reflect.Value) { 688 if !value.Type().AssignableTo(ivalue.Type()) { 689 errorf("cannot assign value of type %s to %s", value.Type(), ivalue.Type()) 690 } 691 ivalue.Set(value) 692 } 693 694 // decodeInterface decodes an interface value and stores it through p. 695 // Interfaces are encoded as the name of a concrete type followed by a value. 696 // If the name is empty, the value is nil and no value is sent. 697 func (dec *Decoder) decodeInterface(ityp reflect.Type, state *decoderState, p unsafe.Pointer, indir int) { 698 // Create a writable interface reflect.Value. We need one even for the nil case. 699 ivalue := allocValue(ityp) 700 // Read the name of the concrete type. 701 nr := state.decodeUint() 702 if nr < 0 || nr > 1<<31 { // zero is permissible for anonymous types 703 errorf("invalid type name length %d", nr) 704 } 705 b := make([]byte, nr) 706 state.b.Read(b) 707 name := string(b) 708 if name == "" { 709 // Copy the representation of the nil interface value to the target. 710 // This is horribly unsafe and special. 711 if indir > 0 { 712 p = allocate(ityp, p, 1) // All but the last level has been allocated by dec.Indirect 713 } 714 *(*[2]uintptr)(unsafe.Pointer(p)) = ivalue.InterfaceData() 715 return 716 } 717 if len(name) > 1024 { 718 errorf("name too long (%d bytes): %.20q...", len(name), name) 719 } 720 // The concrete type must be registered. 721 registerLock.RLock() 722 typ, ok := nameToConcreteType[name] 723 registerLock.RUnlock() 724 if !ok { 725 errorf("name not registered for interface: %q", name) 726 } 727 // Read the type id of the concrete value. 728 concreteId := dec.decodeTypeSequence(true) 729 if concreteId < 0 { 730 error_(dec.err) 731 } 732 // Byte count of value is next; we don't care what it is (it's there 733 // in case we want to ignore the value by skipping it completely). 734 state.decodeUint() 735 // Read the concrete value. 736 value := allocValue(typ) 737 dec.decodeValue(concreteId, value) 738 if dec.err != nil { 739 error_(dec.err) 740 } 741 // Allocate the destination interface value. 742 if indir > 0 { 743 p = allocate(ityp, p, 1) // All but the last level has been allocated by dec.Indirect 744 } 745 // Assign the concrete value to the interface. 746 // Tread carefully; it might not satisfy the interface. 747 setInterfaceValue(ivalue, value) 748 // Copy the representation of the interface value to the target. 749 // This is horribly unsafe and special. 750 *(*[2]uintptr)(unsafe.Pointer(p)) = ivalue.InterfaceData() 751 } 752 753 // ignoreInterface discards the data for an interface value with no destination. 754 func (dec *Decoder) ignoreInterface(state *decoderState) { 755 // Read the name of the concrete type. 756 b := make([]byte, state.decodeUint()) 757 _, err := state.b.Read(b) 758 if err != nil { 759 error_(err) 760 } 761 id := dec.decodeTypeSequence(true) 762 if id < 0 { 763 error_(dec.err) 764 } 765 // At this point, the decoder buffer contains a delimited value. Just toss it. 766 state.b.Next(int(state.decodeUint())) 767 } 768 769 // decodeGobDecoder decodes something implementing the GobDecoder interface. 770 // The data is encoded as a byte slice. 771 func (dec *Decoder) decodeGobDecoder(ut *userTypeInfo, state *decoderState, v reflect.Value) { 772 // Read the bytes for the value. 773 b := make([]byte, state.decodeUint()) 774 _, err := state.b.Read(b) 775 if err != nil { 776 error_(err) 777 } 778 // We know it's one of these. 779 switch ut.externalDec { 780 case xGob: 781 err = v.Interface().(GobDecoder).GobDecode(b) 782 case xBinary: 783 err = v.Interface().(encoding.BinaryUnmarshaler).UnmarshalBinary(b) 784 case xText: 785 err = v.Interface().(encoding.TextUnmarshaler).UnmarshalText(b) 786 } 787 if err != nil { 788 error_(err) 789 } 790 } 791 792 // ignoreGobDecoder discards the data for a GobDecoder value with no destination. 793 func (dec *Decoder) ignoreGobDecoder(state *decoderState) { 794 // Read the bytes for the value. 795 b := make([]byte, state.decodeUint()) 796 _, err := state.b.Read(b) 797 if err != nil { 798 error_(err) 799 } 800 } 801 802 // Index by Go types. 803 var decOpTable = [...]decOp{ 804 reflect.Bool: decBool, 805 reflect.Int8: decInt8, 806 reflect.Int16: decInt16, 807 reflect.Int32: decInt32, 808 reflect.Int64: decInt64, 809 reflect.Uint8: decUint8, 810 reflect.Uint16: decUint16, 811 reflect.Uint32: decUint32, 812 reflect.Uint64: decUint64, 813 reflect.Float32: decFloat32, 814 reflect.Float64: decFloat64, 815 reflect.Complex64: decComplex64, 816 reflect.Complex128: decComplex128, 817 reflect.String: decString, 818 } 819 820 // Indexed by gob types. tComplex will be added during type.init(). 821 var decIgnoreOpMap = map[typeId]decOp{ 822 tBool: ignoreUint, 823 tInt: ignoreUint, 824 tUint: ignoreUint, 825 tFloat: ignoreUint, 826 tBytes: ignoreUint8Array, 827 tString: ignoreUint8Array, 828 tComplex: ignoreTwoUints, 829 } 830 831 // decOpFor returns the decoding op for the base type under rt and 832 // the indirection count to reach it. 833 func (dec *Decoder) decOpFor(wireId typeId, rt reflect.Type, name string, inProgress map[reflect.Type]*decOp) (*decOp, int) { 834 ut := userType(rt) 835 // If the type implements GobEncoder, we handle it without further processing. 836 if ut.externalDec != 0 { 837 return dec.gobDecodeOpFor(ut) 838 } 839 840 // If this type is already in progress, it's a recursive type (e.g. map[string]*T). 841 // Return the pointer to the op we're already building. 842 if opPtr := inProgress[rt]; opPtr != nil { 843 return opPtr, ut.indir 844 } 845 typ := ut.base 846 indir := ut.indir 847 var op decOp 848 k := typ.Kind() 849 if int(k) < len(decOpTable) { 850 op = decOpTable[k] 851 } 852 if op == nil { 853 inProgress[rt] = &op 854 // Special cases 855 switch t := typ; t.Kind() { 856 case reflect.Array: 857 name = "element of " + name 858 elemId := dec.wireType[wireId].ArrayT.Elem 859 elemOp, elemIndir := dec.decOpFor(elemId, t.Elem(), name, inProgress) 860 ovfl := overflow(name) 861 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 862 state.dec.decodeArray(t, state, p, *elemOp, t.Elem().Size(), t.Len(), i.indir, elemIndir, ovfl) 863 } 864 865 case reflect.Map: 866 keyId := dec.wireType[wireId].MapT.Key 867 elemId := dec.wireType[wireId].MapT.Elem 868 keyOp, keyIndir := dec.decOpFor(keyId, t.Key(), "key of "+name, inProgress) 869 elemOp, elemIndir := dec.decOpFor(elemId, t.Elem(), "element of "+name, inProgress) 870 ovfl := overflow(name) 871 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 872 state.dec.decodeMap(t, state, p, *keyOp, *elemOp, i.indir, keyIndir, elemIndir, ovfl) 873 } 874 875 case reflect.Slice: 876 name = "element of " + name 877 if t.Elem().Kind() == reflect.Uint8 { 878 op = decUint8Slice 879 break 880 } 881 var elemId typeId 882 if tt, ok := builtinIdToType[wireId]; ok { 883 elemId = tt.(*sliceType).Elem 884 } else { 885 elemId = dec.wireType[wireId].SliceT.Elem 886 } 887 elemOp, elemIndir := dec.decOpFor(elemId, t.Elem(), name, inProgress) 888 ovfl := overflow(name) 889 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 890 state.dec.decodeSlice(t, state, uintptr(p), *elemOp, t.Elem().Size(), i.indir, elemIndir, ovfl) 891 } 892 893 case reflect.Struct: 894 // Generate a closure that calls out to the engine for the nested type. 895 enginePtr, err := dec.getDecEnginePtr(wireId, userType(typ)) 896 if err != nil { 897 error_(err) 898 } 899 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 900 // indirect through enginePtr to delay evaluation for recursive structs. 901 dec.decodeStruct(*enginePtr, userType(typ), p, i.indir) 902 } 903 case reflect.Interface: 904 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 905 state.dec.decodeInterface(t, state, p, i.indir) 906 } 907 } 908 } 909 if op == nil { 910 errorf("decode can't handle type %s", rt) 911 } 912 return &op, indir 913 } 914 915 // decIgnoreOpFor returns the decoding op for a field that has no destination. 916 func (dec *Decoder) decIgnoreOpFor(wireId typeId) decOp { 917 op, ok := decIgnoreOpMap[wireId] 918 if !ok { 919 if wireId == tInterface { 920 // Special case because it's a method: the ignored item might 921 // define types and we need to record their state in the decoder. 922 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 923 state.dec.ignoreInterface(state) 924 } 925 return op 926 } 927 // Special cases 928 wire := dec.wireType[wireId] 929 switch { 930 case wire == nil: 931 errorf("bad data: undefined type %s", wireId.string()) 932 case wire.ArrayT != nil: 933 elemId := wire.ArrayT.Elem 934 elemOp := dec.decIgnoreOpFor(elemId) 935 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 936 state.dec.ignoreArray(state, elemOp, wire.ArrayT.Len) 937 } 938 939 case wire.MapT != nil: 940 keyId := dec.wireType[wireId].MapT.Key 941 elemId := dec.wireType[wireId].MapT.Elem 942 keyOp := dec.decIgnoreOpFor(keyId) 943 elemOp := dec.decIgnoreOpFor(elemId) 944 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 945 state.dec.ignoreMap(state, keyOp, elemOp) 946 } 947 948 case wire.SliceT != nil: 949 elemId := wire.SliceT.Elem 950 elemOp := dec.decIgnoreOpFor(elemId) 951 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 952 state.dec.ignoreSlice(state, elemOp) 953 } 954 955 case wire.StructT != nil: 956 // Generate a closure that calls out to the engine for the nested type. 957 enginePtr, err := dec.getIgnoreEnginePtr(wireId) 958 if err != nil { 959 error_(err) 960 } 961 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 962 // indirect through enginePtr to delay evaluation for recursive structs 963 state.dec.ignoreStruct(*enginePtr) 964 } 965 966 case wire.GobEncoderT != nil, wire.BinaryMarshalerT != nil, wire.TextMarshalerT != nil: 967 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 968 state.dec.ignoreGobDecoder(state) 969 } 970 } 971 } 972 if op == nil { 973 errorf("bad data: ignore can't handle type %s", wireId.string()) 974 } 975 return op 976 } 977 978 // gobDecodeOpFor returns the op for a type that is known to implement 979 // GobDecoder. 980 func (dec *Decoder) gobDecodeOpFor(ut *userTypeInfo) (*decOp, int) { 981 rcvrType := ut.user 982 if ut.decIndir == -1 { 983 rcvrType = reflect.PtrTo(rcvrType) 984 } else if ut.decIndir > 0 { 985 for i := int8(0); i < ut.decIndir; i++ { 986 rcvrType = rcvrType.Elem() 987 } 988 } 989 var op decOp 990 op = func(i *decInstr, state *decoderState, p unsafe.Pointer) { 991 // Caller has gotten us to within one indirection of our value. 992 if i.indir > 0 { 993 if *(*unsafe.Pointer)(p) == nil { 994 *(*unsafe.Pointer)(p) = unsafe.Pointer(reflect.New(ut.base).Pointer()) 995 } 996 } 997 // Now p is a pointer to the base type. Do we need to climb out to 998 // get to the receiver type? 999 var v reflect.Value 1000 if ut.decIndir == -1 { 1001 v = reflect.NewAt(rcvrType, unsafe.Pointer(&p)).Elem() 1002 } else { 1003 v = reflect.NewAt(rcvrType, p).Elem() 1004 } 1005 state.dec.decodeGobDecoder(ut, state, v) 1006 } 1007 return &op, int(ut.indir) 1008 1009 } 1010 1011 // compatibleType asks: Are these two gob Types compatible? 1012 // Answers the question for basic types, arrays, maps and slices, plus 1013 // GobEncoder/Decoder pairs. 1014 // Structs are considered ok; fields will be checked later. 1015 func (dec *Decoder) compatibleType(fr reflect.Type, fw typeId, inProgress map[reflect.Type]typeId) bool { 1016 if rhs, ok := inProgress[fr]; ok { 1017 return rhs == fw 1018 } 1019 inProgress[fr] = fw 1020 ut := userType(fr) 1021 wire, ok := dec.wireType[fw] 1022 // If wire was encoded with an encoding method, fr must have that method. 1023 // And if not, it must not. 1024 // At most one of the booleans in ut is set. 1025 // We could possibly relax this constraint in the future in order to 1026 // choose the decoding method using the data in the wireType. 1027 // The parentheses look odd but are correct. 1028 if (ut.externalDec == xGob) != (ok && wire.GobEncoderT != nil) || 1029 (ut.externalDec == xBinary) != (ok && wire.BinaryMarshalerT != nil) || 1030 (ut.externalDec == xText) != (ok && wire.TextMarshalerT != nil) { 1031 return false 1032 } 1033 if ut.externalDec != 0 { // This test trumps all others. 1034 return true 1035 } 1036 switch t := ut.base; t.Kind() { 1037 default: 1038 // chan, etc: cannot handle. 1039 return false 1040 case reflect.Bool: 1041 return fw == tBool 1042 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 1043 return fw == tInt 1044 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 1045 return fw == tUint 1046 case reflect.Float32, reflect.Float64: 1047 return fw == tFloat 1048 case reflect.Complex64, reflect.Complex128: 1049 return fw == tComplex 1050 case reflect.String: 1051 return fw == tString 1052 case reflect.Interface: 1053 return fw == tInterface 1054 case reflect.Array: 1055 if !ok || wire.ArrayT == nil { 1056 return false 1057 } 1058 array := wire.ArrayT 1059 return t.Len() == array.Len && dec.compatibleType(t.Elem(), array.Elem, inProgress) 1060 case reflect.Map: 1061 if !ok || wire.MapT == nil { 1062 return false 1063 } 1064 MapType := wire.MapT 1065 return dec.compatibleType(t.Key(), MapType.Key, inProgress) && dec.compatibleType(t.Elem(), MapType.Elem, inProgress) 1066 case reflect.Slice: 1067 // Is it an array of bytes? 1068 if t.Elem().Kind() == reflect.Uint8 { 1069 return fw == tBytes 1070 } 1071 // Extract and compare element types. 1072 var sw *sliceType 1073 if tt, ok := builtinIdToType[fw]; ok { 1074 sw, _ = tt.(*sliceType) 1075 } else if wire != nil { 1076 sw = wire.SliceT 1077 } 1078 elem := userType(t.Elem()).base 1079 return sw != nil && dec.compatibleType(elem, sw.Elem, inProgress) 1080 case reflect.Struct: 1081 return true 1082 } 1083 } 1084 1085 // typeString returns a human-readable description of the type identified by remoteId. 1086 func (dec *Decoder) typeString(remoteId typeId) string { 1087 if t := idToType[remoteId]; t != nil { 1088 // globally known type. 1089 return t.string() 1090 } 1091 return dec.wireType[remoteId].string() 1092 } 1093 1094 // compileSingle compiles the decoder engine for a non-struct top-level value, including 1095 // GobDecoders. 1096 func (dec *Decoder) compileSingle(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) { 1097 rt := ut.user 1098 engine = new(decEngine) 1099 engine.instr = make([]decInstr, 1) // one item 1100 name := rt.String() // best we can do 1101 if !dec.compatibleType(rt, remoteId, make(map[reflect.Type]typeId)) { 1102 remoteType := dec.typeString(remoteId) 1103 // Common confusing case: local interface type, remote concrete type. 1104 if ut.base.Kind() == reflect.Interface && remoteId != tInterface { 1105 return nil, errors.New("gob: local interface type " + name + " can only be decoded from remote interface type; received concrete type " + remoteType) 1106 } 1107 return nil, errors.New("gob: decoding into local type " + name + ", received remote type " + remoteType) 1108 } 1109 op, indir := dec.decOpFor(remoteId, rt, name, make(map[reflect.Type]*decOp)) 1110 ovfl := errors.New(`value for "` + name + `" out of range`) 1111 engine.instr[singletonField] = decInstr{*op, singletonField, indir, 0, ovfl} 1112 engine.numInstr = 1 1113 return 1114 } 1115 1116 // compileIgnoreSingle compiles the decoder engine for a non-struct top-level value that will be discarded. 1117 func (dec *Decoder) compileIgnoreSingle(remoteId typeId) (engine *decEngine, err error) { 1118 engine = new(decEngine) 1119 engine.instr = make([]decInstr, 1) // one item 1120 op := dec.decIgnoreOpFor(remoteId) 1121 ovfl := overflow(dec.typeString(remoteId)) 1122 engine.instr[0] = decInstr{op, 0, 0, 0, ovfl} 1123 engine.numInstr = 1 1124 return 1125 } 1126 1127 // compileDec compiles the decoder engine for a value. If the value is not a struct, 1128 // it calls out to compileSingle. 1129 func (dec *Decoder) compileDec(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) { 1130 rt := ut.base 1131 srt := rt 1132 if srt.Kind() != reflect.Struct || ut.externalDec != 0 { 1133 return dec.compileSingle(remoteId, ut) 1134 } 1135 var wireStruct *structType 1136 // Builtin types can come from global pool; the rest must be defined by the decoder. 1137 // Also we know we're decoding a struct now, so the client must have sent one. 1138 if t, ok := builtinIdToType[remoteId]; ok { 1139 wireStruct, _ = t.(*structType) 1140 } else { 1141 wire := dec.wireType[remoteId] 1142 if wire == nil { 1143 error_(errBadType) 1144 } 1145 wireStruct = wire.StructT 1146 } 1147 if wireStruct == nil { 1148 errorf("type mismatch in decoder: want struct type %s; got non-struct", rt) 1149 } 1150 engine = new(decEngine) 1151 engine.instr = make([]decInstr, len(wireStruct.Field)) 1152 seen := make(map[reflect.Type]*decOp) 1153 // Loop over the fields of the wire type. 1154 for fieldnum := 0; fieldnum < len(wireStruct.Field); fieldnum++ { 1155 wireField := wireStruct.Field[fieldnum] 1156 if wireField.Name == "" { 1157 errorf("empty name for remote field of type %s", wireStruct.Name) 1158 } 1159 ovfl := overflow(wireField.Name) 1160 // Find the field of the local type with the same name. 1161 localField, present := srt.FieldByName(wireField.Name) 1162 // TODO(r): anonymous names 1163 if !present || !isExported(wireField.Name) { 1164 op := dec.decIgnoreOpFor(wireField.Id) 1165 engine.instr[fieldnum] = decInstr{op, fieldnum, 0, 0, ovfl} 1166 continue 1167 } 1168 if !dec.compatibleType(localField.Type, wireField.Id, make(map[reflect.Type]typeId)) { 1169 errorf("wrong type (%s) for received field %s.%s", localField.Type, wireStruct.Name, wireField.Name) 1170 } 1171 op, indir := dec.decOpFor(wireField.Id, localField.Type, localField.Name, seen) 1172 engine.instr[fieldnum] = decInstr{*op, fieldnum, indir, uintptr(localField.Offset), ovfl} 1173 engine.numInstr++ 1174 } 1175 return 1176 } 1177 1178 // getDecEnginePtr returns the engine for the specified type. 1179 func (dec *Decoder) getDecEnginePtr(remoteId typeId, ut *userTypeInfo) (enginePtr **decEngine, err error) { 1180 rt := ut.user 1181 decoderMap, ok := dec.decoderCache[rt] 1182 if !ok { 1183 decoderMap = make(map[typeId]**decEngine) 1184 dec.decoderCache[rt] = decoderMap 1185 } 1186 if enginePtr, ok = decoderMap[remoteId]; !ok { 1187 // To handle recursive types, mark this engine as underway before compiling. 1188 enginePtr = new(*decEngine) 1189 decoderMap[remoteId] = enginePtr 1190 *enginePtr, err = dec.compileDec(remoteId, ut) 1191 if err != nil { 1192 delete(decoderMap, remoteId) 1193 } 1194 } 1195 return 1196 } 1197 1198 // emptyStruct is the type we compile into when ignoring a struct value. 1199 type emptyStruct struct{} 1200 1201 var emptyStructType = reflect.TypeOf(emptyStruct{}) 1202 1203 // getDecEnginePtr returns the engine for the specified type when the value is to be discarded. 1204 func (dec *Decoder) getIgnoreEnginePtr(wireId typeId) (enginePtr **decEngine, err error) { 1205 var ok bool 1206 if enginePtr, ok = dec.ignorerCache[wireId]; !ok { 1207 // To handle recursive types, mark this engine as underway before compiling. 1208 enginePtr = new(*decEngine) 1209 dec.ignorerCache[wireId] = enginePtr 1210 wire := dec.wireType[wireId] 1211 if wire != nil && wire.StructT != nil { 1212 *enginePtr, err = dec.compileDec(wireId, userType(emptyStructType)) 1213 } else { 1214 *enginePtr, err = dec.compileIgnoreSingle(wireId) 1215 } 1216 if err != nil { 1217 delete(dec.ignorerCache, wireId) 1218 } 1219 } 1220 return 1221 } 1222 1223 // decodeValue decodes the data stream representing a value and stores it in val. 1224 func (dec *Decoder) decodeValue(wireId typeId, val reflect.Value) { 1225 defer catchError(&dec.err) 1226 // If the value is nil, it means we should just ignore this item. 1227 if !val.IsValid() { 1228 dec.decodeIgnoredValue(wireId) 1229 return 1230 } 1231 // Dereference down to the underlying type. 1232 ut := userType(val.Type()) 1233 base := ut.base 1234 var enginePtr **decEngine 1235 enginePtr, dec.err = dec.getDecEnginePtr(wireId, ut) 1236 if dec.err != nil { 1237 return 1238 } 1239 engine := *enginePtr 1240 if st := base; st.Kind() == reflect.Struct && ut.externalDec == 0 { 1241 if engine.numInstr == 0 && st.NumField() > 0 && len(dec.wireType[wireId].StructT.Field) > 0 { 1242 name := base.Name() 1243 errorf("type mismatch: no fields matched compiling decoder for %s", name) 1244 } 1245 dec.decodeStruct(engine, ut, unsafeAddr(val), ut.indir) 1246 } else { 1247 dec.decodeSingle(engine, ut, unsafeAddr(val)) 1248 } 1249 } 1250 1251 // decodeIgnoredValue decodes the data stream representing a value of the specified type and discards it. 1252 func (dec *Decoder) decodeIgnoredValue(wireId typeId) { 1253 var enginePtr **decEngine 1254 enginePtr, dec.err = dec.getIgnoreEnginePtr(wireId) 1255 if dec.err != nil { 1256 return 1257 } 1258 wire := dec.wireType[wireId] 1259 if wire != nil && wire.StructT != nil { 1260 dec.ignoreStruct(*enginePtr) 1261 } else { 1262 dec.ignoreSingle(*enginePtr) 1263 } 1264 } 1265 1266 func init() { 1267 var iop, uop decOp 1268 switch reflect.TypeOf(int(0)).Bits() { 1269 case 32: 1270 iop = decInt32 1271 uop = decUint32 1272 case 64: 1273 iop = decInt64 1274 uop = decUint64 1275 default: 1276 panic("gob: unknown size of int/uint") 1277 } 1278 decOpTable[reflect.Int] = iop 1279 decOpTable[reflect.Uint] = uop 1280 1281 // Finally uintptr 1282 switch reflect.TypeOf(uintptr(0)).Bits() { 1283 case 32: 1284 uop = decUint32 1285 case 64: 1286 uop = decUint64 1287 default: 1288 panic("gob: unknown size of uintptr") 1289 } 1290 decOpTable[reflect.Uintptr] = uop 1291 } 1292 1293 // Gob assumes it can call UnsafeAddr on any Value 1294 // in order to get a pointer it can copy data from. 1295 // Values that have just been created and do not point 1296 // into existing structs or slices cannot be addressed, 1297 // so simulate it by returning a pointer to a copy. 1298 // Each call allocates once. 1299 func unsafeAddr(v reflect.Value) unsafe.Pointer { 1300 if v.CanAddr() { 1301 return unsafe.Pointer(v.UnsafeAddr()) 1302 } 1303 x := reflect.New(v.Type()).Elem() 1304 x.Set(v) 1305 return unsafe.Pointer(x.UnsafeAddr()) 1306 } 1307 1308 // Gob depends on being able to take the address 1309 // of zeroed Values it creates, so use this wrapper instead 1310 // of the standard reflect.Zero. 1311 // Each call allocates once. 1312 func allocValue(t reflect.Type) reflect.Value { 1313 return reflect.New(t).Elem() 1314 }