decode.go 21 KB

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