github.com/asifdxtreme/cli@v6.1.3-0.20150123051144-9ead8700b4ae+incompatible/Godeps/_workspace/src/code.google.com/p/gogoprotobuf/proto/decode.go (about) 1 // Go support for Protocol Buffers - Google's data interchange format 2 // 3 // Copyright 2010 The Go Authors. All rights reserved. 4 // http://code.google.com/p/goprotobuf/ 5 // 6 // Redistribution and use in source and binary forms, with or without 7 // modification, are permitted provided that the following conditions are 8 // met: 9 // 10 // * Redistributions of source code must retain the above copyright 11 // notice, this list of conditions and the following disclaimer. 12 // * Redistributions in binary form must reproduce the above 13 // copyright notice, this list of conditions and the following disclaimer 14 // in the documentation and/or other materials provided with the 15 // distribution. 16 // * Neither the name of Google Inc. nor the names of its 17 // contributors may be used to endorse or promote products derived from 18 // this software without specific prior written permission. 19 // 20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 32 package proto 33 34 /* 35 * Routines for decoding protocol buffer data to construct in-memory representations. 36 */ 37 38 import ( 39 "errors" 40 "fmt" 41 "io" 42 "os" 43 "reflect" 44 ) 45 46 // errOverflow is returned when an integer is too large to be represented. 47 var errOverflow = errors.New("proto: integer overflow") 48 49 // The fundamental decoders that interpret bytes on the wire. 50 // Those that take integer types all return uint64 and are 51 // therefore of type valueDecoder. 52 53 // DecodeVarint reads a varint-encoded integer from the slice. 54 // It returns the integer and the number of bytes consumed, or 55 // zero if there is not enough. 56 // This is the format for the 57 // int32, int64, uint32, uint64, bool, and enum 58 // protocol buffer types. 59 func DecodeVarint(buf []byte) (x uint64, n int) { 60 // x, n already 0 61 for shift := uint(0); shift < 64; shift += 7 { 62 if n >= len(buf) { 63 return 0, 0 64 } 65 b := uint64(buf[n]) 66 n++ 67 x |= (b & 0x7F) << shift 68 if (b & 0x80) == 0 { 69 return x, n 70 } 71 } 72 73 // The number is too large to represent in a 64-bit value. 74 return 0, 0 75 } 76 77 // DecodeVarint reads a varint-encoded integer from the Buffer. 78 // This is the format for the 79 // int32, int64, uint32, uint64, bool, and enum 80 // protocol buffer types. 81 func (p *Buffer) DecodeVarint() (x uint64, err error) { 82 // x, err already 0 83 84 i := p.index 85 l := len(p.buf) 86 87 for shift := uint(0); shift < 64; shift += 7 { 88 if i >= l { 89 err = io.ErrUnexpectedEOF 90 return 91 } 92 b := p.buf[i] 93 i++ 94 x |= (uint64(b) & 0x7F) << shift 95 if b < 0x80 { 96 p.index = i 97 return 98 } 99 } 100 101 // The number is too large to represent in a 64-bit value. 102 err = errOverflow 103 return 104 } 105 106 // DecodeFixed64 reads a 64-bit integer from the Buffer. 107 // This is the format for the 108 // fixed64, sfixed64, and double protocol buffer types. 109 func (p *Buffer) DecodeFixed64() (x uint64, err error) { 110 // x, err already 0 111 i := p.index + 8 112 if i < 0 || i > len(p.buf) { 113 err = io.ErrUnexpectedEOF 114 return 115 } 116 p.index = i 117 118 x = uint64(p.buf[i-8]) 119 x |= uint64(p.buf[i-7]) << 8 120 x |= uint64(p.buf[i-6]) << 16 121 x |= uint64(p.buf[i-5]) << 24 122 x |= uint64(p.buf[i-4]) << 32 123 x |= uint64(p.buf[i-3]) << 40 124 x |= uint64(p.buf[i-2]) << 48 125 x |= uint64(p.buf[i-1]) << 56 126 return 127 } 128 129 // DecodeFixed32 reads a 32-bit integer from the Buffer. 130 // This is the format for the 131 // fixed32, sfixed32, and float protocol buffer types. 132 func (p *Buffer) DecodeFixed32() (x uint64, err error) { 133 // x, err already 0 134 i := p.index + 4 135 if i < 0 || i > len(p.buf) { 136 err = io.ErrUnexpectedEOF 137 return 138 } 139 p.index = i 140 141 x = uint64(p.buf[i-4]) 142 x |= uint64(p.buf[i-3]) << 8 143 x |= uint64(p.buf[i-2]) << 16 144 x |= uint64(p.buf[i-1]) << 24 145 return 146 } 147 148 // DecodeZigzag64 reads a zigzag-encoded 64-bit integer 149 // from the Buffer. 150 // This is the format used for the sint64 protocol buffer type. 151 func (p *Buffer) DecodeZigzag64() (x uint64, err error) { 152 x, err = p.DecodeVarint() 153 if err != nil { 154 return 155 } 156 x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) 157 return 158 } 159 160 // DecodeZigzag32 reads a zigzag-encoded 32-bit integer 161 // from the Buffer. 162 // This is the format used for the sint32 protocol buffer type. 163 func (p *Buffer) DecodeZigzag32() (x uint64, err error) { 164 x, err = p.DecodeVarint() 165 if err != nil { 166 return 167 } 168 x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) 169 return 170 } 171 172 // These are not ValueDecoders: they produce an array of bytes or a string. 173 // bytes, embedded messages 174 175 // DecodeRawBytes reads a count-delimited byte buffer from the Buffer. 176 // This is the format used for the bytes protocol buffer 177 // type and for embedded messages. 178 func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { 179 n, err := p.DecodeVarint() 180 if err != nil { 181 return 182 } 183 184 nb := int(n) 185 if nb < 0 { 186 return nil, fmt.Errorf("proto: bad byte length %d", nb) 187 } 188 end := p.index + nb 189 if end < p.index || end > len(p.buf) { 190 return nil, io.ErrUnexpectedEOF 191 } 192 193 if !alloc { 194 // todo: check if can get more uses of alloc=false 195 buf = p.buf[p.index:end] 196 p.index += nb 197 return 198 } 199 200 buf = make([]byte, nb) 201 copy(buf, p.buf[p.index:]) 202 p.index += nb 203 return 204 } 205 206 // DecodeStringBytes reads an encoded string from the Buffer. 207 // This is the format used for the proto2 string type. 208 func (p *Buffer) DecodeStringBytes() (s string, err error) { 209 buf, err := p.DecodeRawBytes(false) 210 if err != nil { 211 return 212 } 213 return string(buf), nil 214 } 215 216 // Skip the next item in the buffer. Its wire type is decoded and presented as an argument. 217 // If the protocol buffer has extensions, and the field matches, add it as an extension. 218 // Otherwise, if the XXX_unrecognized field exists, append the skipped data there. 219 func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error { 220 oi := o.index 221 222 err := o.skip(t, tag, wire) 223 if err != nil { 224 return err 225 } 226 227 if !unrecField.IsValid() { 228 return nil 229 } 230 231 ptr := structPointer_Bytes(base, unrecField) 232 233 // Add the skipped field to struct field 234 obuf := o.buf 235 236 o.buf = *ptr 237 o.EncodeVarint(uint64(tag<<3 | wire)) 238 *ptr = append(o.buf, obuf[oi:o.index]...) 239 240 o.buf = obuf 241 242 return nil 243 } 244 245 // Skip the next item in the buffer. Its wire type is decoded and presented as an argument. 246 func (o *Buffer) skip(t reflect.Type, tag, wire int) error { 247 248 var u uint64 249 var err error 250 251 switch wire { 252 case WireVarint: 253 _, err = o.DecodeVarint() 254 case WireFixed64: 255 _, err = o.DecodeFixed64() 256 case WireBytes: 257 _, err = o.DecodeRawBytes(false) 258 case WireFixed32: 259 _, err = o.DecodeFixed32() 260 case WireStartGroup: 261 for { 262 u, err = o.DecodeVarint() 263 if err != nil { 264 break 265 } 266 fwire := int(u & 0x7) 267 if fwire == WireEndGroup { 268 break 269 } 270 ftag := int(u >> 3) 271 err = o.skip(t, ftag, fwire) 272 if err != nil { 273 break 274 } 275 } 276 default: 277 err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t) 278 } 279 return err 280 } 281 282 // Unmarshaler is the interface representing objects that can 283 // unmarshal themselves. The method should reset the receiver before 284 // decoding starts. The argument points to data that may be 285 // overwritten, so implementations should not keep references to the 286 // buffer. 287 type Unmarshaler interface { 288 Unmarshal([]byte) error 289 } 290 291 // Unmarshal parses the protocol buffer representation in buf and places the 292 // decoded result in pb. If the struct underlying pb does not match 293 // the data in buf, the results can be unpredictable. 294 // 295 // Unmarshal resets pb before starting to unmarshal, so any 296 // existing data in pb is always removed. Use UnmarshalMerge 297 // to preserve and append to existing data. 298 func Unmarshal(buf []byte, pb Message) error { 299 pb.Reset() 300 return UnmarshalMerge(buf, pb) 301 } 302 303 // UnmarshalMerge parses the protocol buffer representation in buf and 304 // writes the decoded result to pb. If the struct underlying pb does not match 305 // the data in buf, the results can be unpredictable. 306 // 307 // UnmarshalMerge merges into existing data in pb. 308 // Most code should use Unmarshal instead. 309 func UnmarshalMerge(buf []byte, pb Message) error { 310 // If the object can unmarshal itself, let it. 311 if u, ok := pb.(Unmarshaler); ok { 312 return u.Unmarshal(buf) 313 } 314 return NewBuffer(buf).Unmarshal(pb) 315 } 316 317 // Unmarshal parses the protocol buffer representation in the 318 // Buffer and places the decoded result in pb. If the struct 319 // underlying pb does not match the data in the buffer, the results can be 320 // unpredictable. 321 func (p *Buffer) Unmarshal(pb Message) error { 322 // If the object can unmarshal itself, let it. 323 if u, ok := pb.(Unmarshaler); ok { 324 err := u.Unmarshal(p.buf[p.index:]) 325 p.index = len(p.buf) 326 return err 327 } 328 329 typ, base, err := getbase(pb) 330 if err != nil { 331 return err 332 } 333 334 err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base) 335 336 if collectStats { 337 stats.Decode++ 338 } 339 340 return err 341 } 342 343 // unmarshalType does the work of unmarshaling a structure. 344 func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error { 345 var state errorState 346 required, reqFields := prop.reqCount, uint64(0) 347 348 var err error 349 for err == nil && o.index < len(o.buf) { 350 oi := o.index 351 var u uint64 352 u, err = o.DecodeVarint() 353 if err != nil { 354 break 355 } 356 wire := int(u & 0x7) 357 if wire == WireEndGroup { 358 if is_group { 359 return nil // input is satisfied 360 } 361 return fmt.Errorf("proto: %s: wiretype end group for non-group", st) 362 } 363 tag := int(u >> 3) 364 if tag <= 0 { 365 return fmt.Errorf("proto: %s: illegal tag %d", st, tag) 366 } 367 fieldnum, ok := prop.decoderTags.get(tag) 368 if !ok { 369 // Maybe it's an extension? 370 if prop.extendable { 371 if e := structPointer_Interface(base, st).(extendableProto); isExtensionField(e, int32(tag)) { 372 if err = o.skip(st, tag, wire); err == nil { 373 if ee, ok := e.(extensionsMap); ok { 374 ext := ee.ExtensionMap()[int32(tag)] // may be missing 375 ext.enc = append(ext.enc, o.buf[oi:o.index]...) 376 ee.ExtensionMap()[int32(tag)] = ext 377 } else if ee, ok := e.(extensionsBytes); ok { 378 ext := ee.GetExtensions() 379 *ext = append(*ext, o.buf[oi:o.index]...) 380 } 381 } 382 continue 383 } 384 } 385 err = o.skipAndSave(st, tag, wire, base, prop.unrecField) 386 continue 387 } 388 p := prop.Prop[fieldnum] 389 390 if p.dec == nil { 391 fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name) 392 continue 393 } 394 dec := p.dec 395 if wire != WireStartGroup && wire != p.WireType { 396 if wire == WireBytes && p.packedDec != nil { 397 // a packable field 398 dec = p.packedDec 399 } else { 400 err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType) 401 continue 402 } 403 } 404 decErr := dec(o, p, base) 405 if decErr != nil && !state.shouldContinue(decErr, p) { 406 err = decErr 407 } 408 if err == nil && p.Required { 409 // Successfully decoded a required field. 410 if tag <= 64 { 411 // use bitmap for fields 1-64 to catch field reuse. 412 var mask uint64 = 1 << uint64(tag-1) 413 if reqFields&mask == 0 { 414 // new required field 415 reqFields |= mask 416 required-- 417 } 418 } else { 419 // This is imprecise. It can be fooled by a required field 420 // with a tag > 64 that is encoded twice; that's very rare. 421 // A fully correct implementation would require allocating 422 // a data structure, which we would like to avoid. 423 required-- 424 } 425 } 426 } 427 if err == nil { 428 if is_group { 429 return io.ErrUnexpectedEOF 430 } 431 if state.err != nil { 432 return state.err 433 } 434 if required > 0 { 435 // Not enough information to determine the exact field. If we use extra 436 // CPU, we could determine the field only if the missing required field 437 // has a tag <= 64 and we check reqFields. 438 return &RequiredNotSetError{"{Unknown}"} 439 } 440 } 441 return err 442 } 443 444 // Individual type decoders 445 // For each, 446 // u is the decoded value, 447 // v is a pointer to the field (pointer) in the struct 448 449 // Sizes of the pools to allocate inside the Buffer. 450 // The goal is modest amortization and allocation 451 // on at least 16-byte boundaries. 452 const ( 453 boolPoolSize = 16 454 uint32PoolSize = 8 455 uint64PoolSize = 4 456 ) 457 458 // Decode a bool. 459 func (o *Buffer) dec_bool(p *Properties, base structPointer) error { 460 u, err := p.valDec(o) 461 if err != nil { 462 return err 463 } 464 if len(o.bools) == 0 { 465 o.bools = make([]bool, boolPoolSize) 466 } 467 o.bools[0] = u != 0 468 *structPointer_Bool(base, p.field) = &o.bools[0] 469 o.bools = o.bools[1:] 470 return nil 471 } 472 473 // Decode an int32. 474 func (o *Buffer) dec_int32(p *Properties, base structPointer) error { 475 u, err := p.valDec(o) 476 if err != nil { 477 return err 478 } 479 word32_Set(structPointer_Word32(base, p.field), o, uint32(u)) 480 return nil 481 } 482 483 // Decode an int64. 484 func (o *Buffer) dec_int64(p *Properties, base structPointer) error { 485 u, err := p.valDec(o) 486 if err != nil { 487 return err 488 } 489 word64_Set(structPointer_Word64(base, p.field), o, u) 490 return nil 491 } 492 493 // Decode a string. 494 func (o *Buffer) dec_string(p *Properties, base structPointer) error { 495 s, err := o.DecodeStringBytes() 496 if err != nil { 497 return err 498 } 499 sp := new(string) 500 *sp = s 501 *structPointer_String(base, p.field) = sp 502 return nil 503 } 504 505 // Decode a slice of bytes ([]byte). 506 func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error { 507 b, err := o.DecodeRawBytes(true) 508 if err != nil { 509 return err 510 } 511 *structPointer_Bytes(base, p.field) = b 512 return nil 513 } 514 515 // Decode a slice of bools ([]bool). 516 func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error { 517 u, err := p.valDec(o) 518 if err != nil { 519 return err 520 } 521 v := structPointer_BoolSlice(base, p.field) 522 *v = append(*v, u != 0) 523 return nil 524 } 525 526 // Decode a slice of bools ([]bool) in packed format. 527 func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error { 528 v := structPointer_BoolSlice(base, p.field) 529 530 nn, err := o.DecodeVarint() 531 if err != nil { 532 return err 533 } 534 nb := int(nn) // number of bytes of encoded bools 535 536 y := *v 537 for i := 0; i < nb; i++ { 538 u, err := p.valDec(o) 539 if err != nil { 540 return err 541 } 542 y = append(y, u != 0) 543 } 544 545 *v = y 546 return nil 547 } 548 549 // Decode a slice of int32s ([]int32). 550 func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error { 551 u, err := p.valDec(o) 552 if err != nil { 553 return err 554 } 555 structPointer_Word32Slice(base, p.field).Append(uint32(u)) 556 return nil 557 } 558 559 // Decode a slice of int32s ([]int32) in packed format. 560 func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error { 561 v := structPointer_Word32Slice(base, p.field) 562 563 nn, err := o.DecodeVarint() 564 if err != nil { 565 return err 566 } 567 nb := int(nn) // number of bytes of encoded int32s 568 569 fin := o.index + nb 570 if fin < o.index { 571 return errOverflow 572 } 573 for o.index < fin { 574 u, err := p.valDec(o) 575 if err != nil { 576 return err 577 } 578 v.Append(uint32(u)) 579 } 580 return nil 581 } 582 583 // Decode a slice of int64s ([]int64). 584 func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error { 585 u, err := p.valDec(o) 586 if err != nil { 587 return err 588 } 589 590 structPointer_Word64Slice(base, p.field).Append(u) 591 return nil 592 } 593 594 // Decode a slice of int64s ([]int64) in packed format. 595 func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error { 596 v := structPointer_Word64Slice(base, p.field) 597 598 nn, err := o.DecodeVarint() 599 if err != nil { 600 return err 601 } 602 nb := int(nn) // number of bytes of encoded int64s 603 604 fin := o.index + nb 605 if fin < o.index { 606 return errOverflow 607 } 608 for o.index < fin { 609 u, err := p.valDec(o) 610 if err != nil { 611 return err 612 } 613 v.Append(u) 614 } 615 return nil 616 } 617 618 // Decode a slice of strings ([]string). 619 func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error { 620 s, err := o.DecodeStringBytes() 621 if err != nil { 622 return err 623 } 624 v := structPointer_StringSlice(base, p.field) 625 *v = append(*v, s) 626 return nil 627 } 628 629 // Decode a slice of slice of bytes ([][]byte). 630 func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error { 631 b, err := o.DecodeRawBytes(true) 632 if err != nil { 633 return err 634 } 635 v := structPointer_BytesSlice(base, p.field) 636 *v = append(*v, b) 637 return nil 638 } 639 640 // Decode a group. 641 func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error { 642 bas := structPointer_GetStructPointer(base, p.field) 643 if structPointer_IsNil(bas) { 644 // allocate new nested message 645 bas = toStructPointer(reflect.New(p.stype)) 646 structPointer_SetStructPointer(base, p.field, bas) 647 } 648 return o.unmarshalType(p.stype, p.sprop, true, bas) 649 } 650 651 // Decode an embedded message. 652 func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) { 653 raw, e := o.DecodeRawBytes(false) 654 if e != nil { 655 return e 656 } 657 658 bas := structPointer_GetStructPointer(base, p.field) 659 if structPointer_IsNil(bas) { 660 // allocate new nested message 661 bas = toStructPointer(reflect.New(p.stype)) 662 structPointer_SetStructPointer(base, p.field, bas) 663 } 664 665 // If the object can unmarshal itself, let it. 666 if p.isUnmarshaler { 667 iv := structPointer_Interface(bas, p.stype) 668 return iv.(Unmarshaler).Unmarshal(raw) 669 } 670 671 obuf := o.buf 672 oi := o.index 673 o.buf = raw 674 o.index = 0 675 676 err = o.unmarshalType(p.stype, p.sprop, false, bas) 677 o.buf = obuf 678 o.index = oi 679 680 return err 681 } 682 683 // Decode a slice of embedded messages. 684 func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error { 685 return o.dec_slice_struct(p, false, base) 686 } 687 688 // Decode a slice of embedded groups. 689 func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error { 690 return o.dec_slice_struct(p, true, base) 691 } 692 693 // Decode a slice of structs ([]*struct). 694 func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error { 695 v := reflect.New(p.stype) 696 bas := toStructPointer(v) 697 structPointer_StructPointerSlice(base, p.field).Append(bas) 698 699 if is_group { 700 err := o.unmarshalType(p.stype, p.sprop, is_group, bas) 701 return err 702 } 703 704 raw, err := o.DecodeRawBytes(false) 705 if err != nil { 706 return err 707 } 708 709 // If the object can unmarshal itself, let it. 710 if p.isUnmarshaler { 711 iv := v.Interface() 712 return iv.(Unmarshaler).Unmarshal(raw) 713 } 714 715 obuf := o.buf 716 oi := o.index 717 o.buf = raw 718 o.index = 0 719 720 err = o.unmarshalType(p.stype, p.sprop, is_group, bas) 721 722 o.buf = obuf 723 o.index = oi 724 725 return err 726 }