encode.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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. package proto
  32. /*
  33. * Routines for encoding data into the wire format for protocol buffers.
  34. */
  35. import (
  36. "errors"
  37. "fmt"
  38. "reflect"
  39. "sort"
  40. )
  41. // ErrRequiredNotSet is the error returned if Marshal is called with
  42. // a protocol buffer struct whose required fields have not
  43. // all been initialized. It is also the error returned if Unmarshal is
  44. // called with an encoded protocol buffer that does not include all the
  45. // required fields.
  46. //
  47. // When printed, ErrRequiredNotSet reports the first unset required field in a
  48. // message. If the field cannot be precisely determined, it is reported as
  49. // "{Unknown}".
  50. type ErrRequiredNotSet struct {
  51. field string
  52. }
  53. func (e *ErrRequiredNotSet) Error() string {
  54. return fmt.Sprintf("proto: required field %q not set", e.field)
  55. }
  56. var (
  57. // ErrRepeatedHasNil is the error returned if Marshal is called with
  58. // a struct with a repeated field containing a nil element.
  59. ErrRepeatedHasNil = errors.New("proto: repeated field has nil element")
  60. // ErrNil is the error returned if Marshal is called with nil.
  61. ErrNil = errors.New("proto: Marshal called with nil")
  62. )
  63. // The fundamental encoders that put bytes on the wire.
  64. // Those that take integer types all accept uint64 and are
  65. // therefore of type valueEncoder.
  66. const maxVarintBytes = 10 // maximum length of a varint
  67. // EncodeVarint returns the varint encoding of x.
  68. // This is the format for the
  69. // int32, int64, uint32, uint64, bool, and enum
  70. // protocol buffer types.
  71. // Not used by the package itself, but helpful to clients
  72. // wishing to use the same encoding.
  73. func EncodeVarint(x uint64) []byte {
  74. var buf [maxVarintBytes]byte
  75. var n int
  76. for n = 0; x > 127; n++ {
  77. buf[n] = 0x80 | uint8(x&0x7F)
  78. x >>= 7
  79. }
  80. buf[n] = uint8(x)
  81. n++
  82. return buf[0:n]
  83. }
  84. // EncodeVarint writes a varint-encoded integer to the Buffer.
  85. // This is the format for the
  86. // int32, int64, uint32, uint64, bool, and enum
  87. // protocol buffer types.
  88. func (p *Buffer) EncodeVarint(x uint64) error {
  89. for x >= 1<<7 {
  90. p.buf = append(p.buf, uint8(x&0x7f|0x80))
  91. x >>= 7
  92. }
  93. p.buf = append(p.buf, uint8(x))
  94. return nil
  95. }
  96. // EncodeFixed64 writes a 64-bit integer to the Buffer.
  97. // This is the format for the
  98. // fixed64, sfixed64, and double protocol buffer types.
  99. func (p *Buffer) EncodeFixed64(x uint64) error {
  100. p.buf = append(p.buf,
  101. uint8(x),
  102. uint8(x>>8),
  103. uint8(x>>16),
  104. uint8(x>>24),
  105. uint8(x>>32),
  106. uint8(x>>40),
  107. uint8(x>>48),
  108. uint8(x>>56))
  109. return nil
  110. }
  111. // EncodeFixed32 writes a 32-bit integer to the Buffer.
  112. // This is the format for the
  113. // fixed32, sfixed32, and float protocol buffer types.
  114. func (p *Buffer) EncodeFixed32(x uint64) error {
  115. p.buf = append(p.buf,
  116. uint8(x),
  117. uint8(x>>8),
  118. uint8(x>>16),
  119. uint8(x>>24))
  120. return nil
  121. }
  122. // EncodeZigzag64 writes a zigzag-encoded 64-bit integer
  123. // to the Buffer.
  124. // This is the format used for the sint64 protocol buffer type.
  125. func (p *Buffer) EncodeZigzag64(x uint64) error {
  126. // use signed number to get arithmetic right shift.
  127. return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
  128. }
  129. // EncodeZigzag32 writes a zigzag-encoded 32-bit integer
  130. // to the Buffer.
  131. // This is the format used for the sint32 protocol buffer type.
  132. func (p *Buffer) EncodeZigzag32(x uint64) error {
  133. // use signed number to get arithmetic right shift.
  134. return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
  135. }
  136. // EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
  137. // This is the format used for the bytes protocol buffer
  138. // type and for embedded messages.
  139. func (p *Buffer) EncodeRawBytes(b []byte) error {
  140. p.EncodeVarint(uint64(len(b)))
  141. p.buf = append(p.buf, b...)
  142. return nil
  143. }
  144. // EncodeStringBytes writes an encoded string to the Buffer.
  145. // This is the format used for the proto2 string type.
  146. func (p *Buffer) EncodeStringBytes(s string) error {
  147. p.EncodeVarint(uint64(len(s)))
  148. p.buf = append(p.buf, s...)
  149. return nil
  150. }
  151. // Marshaler is the interface representing objects that can marshal themselves.
  152. type Marshaler interface {
  153. Marshal() ([]byte, error)
  154. }
  155. // Marshal takes the protocol buffer
  156. // and encodes it into the wire format, returning the data.
  157. func Marshal(pb Message) ([]byte, error) {
  158. // Can the object marshal itself?
  159. if m, ok := pb.(Marshaler); ok {
  160. return m.Marshal()
  161. }
  162. p := NewBuffer(nil)
  163. err := p.Marshal(pb)
  164. var state errorState
  165. if err != nil && !state.shouldContinue(err, nil) {
  166. return nil, err
  167. }
  168. return p.buf, err
  169. }
  170. // Marshal takes the protocol buffer
  171. // and encodes it into the wire format, writing the result to the
  172. // Buffer.
  173. func (p *Buffer) Marshal(pb Message) error {
  174. // Can the object marshal itself?
  175. if m, ok := pb.(Marshaler); ok {
  176. data, err := m.Marshal()
  177. if err != nil {
  178. return err
  179. }
  180. p.buf = append(p.buf, data...)
  181. return nil
  182. }
  183. t, base, err := getbase(pb)
  184. if structPointer_IsNil(base) {
  185. return ErrNil
  186. }
  187. if err == nil {
  188. err = p.enc_struct(t.Elem(), GetProperties(t.Elem()), base)
  189. }
  190. if collectStats {
  191. stats.Encode++
  192. }
  193. return err
  194. }
  195. // Individual type encoders.
  196. // Encode a bool.
  197. func (o *Buffer) enc_bool(p *Properties, base structPointer) error {
  198. v := *structPointer_Bool(base, p.field)
  199. if v == nil {
  200. return ErrNil
  201. }
  202. x := 0
  203. if *v {
  204. x = 1
  205. }
  206. o.buf = append(o.buf, p.tagcode...)
  207. p.valEnc(o, uint64(x))
  208. return nil
  209. }
  210. // Encode an int32.
  211. func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
  212. v := structPointer_Word32(base, p.field)
  213. if word32_IsNil(v) {
  214. return ErrNil
  215. }
  216. x := word32_Get(v)
  217. o.buf = append(o.buf, p.tagcode...)
  218. p.valEnc(o, uint64(x))
  219. return nil
  220. }
  221. // Encode an int64.
  222. func (o *Buffer) enc_int64(p *Properties, base structPointer) error {
  223. v := structPointer_Word64(base, p.field)
  224. if word64_IsNil(v) {
  225. return ErrNil
  226. }
  227. x := word64_Get(v)
  228. o.buf = append(o.buf, p.tagcode...)
  229. p.valEnc(o, x)
  230. return nil
  231. }
  232. // Encode a string.
  233. func (o *Buffer) enc_string(p *Properties, base structPointer) error {
  234. v := *structPointer_String(base, p.field)
  235. if v == nil {
  236. return ErrNil
  237. }
  238. x := *v
  239. o.buf = append(o.buf, p.tagcode...)
  240. o.EncodeStringBytes(x)
  241. return nil
  242. }
  243. // All protocol buffer fields are nillable, but be careful.
  244. func isNil(v reflect.Value) bool {
  245. switch v.Kind() {
  246. case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
  247. return v.IsNil()
  248. }
  249. return false
  250. }
  251. // Encode a message struct.
  252. func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
  253. var state errorState
  254. structp := structPointer_GetStructPointer(base, p.field)
  255. if structPointer_IsNil(structp) {
  256. return ErrNil
  257. }
  258. // Can the object marshal itself?
  259. if p.isMarshaler {
  260. m := structPointer_Interface(structp, p.stype).(Marshaler)
  261. data, err := m.Marshal()
  262. if err != nil && !state.shouldContinue(err, nil) {
  263. return err
  264. }
  265. o.buf = append(o.buf, p.tagcode...)
  266. o.EncodeRawBytes(data)
  267. return nil
  268. }
  269. // need the length before we can write out the message itself,
  270. // so marshal into a separate byte buffer first.
  271. obuf := o.buf
  272. o.buf = o.bufalloc()
  273. err := o.enc_struct(p.stype, p.sprop, structp)
  274. nbuf := o.buf
  275. o.buf = obuf
  276. if err != nil && !state.shouldContinue(err, nil) {
  277. o.buffree(nbuf)
  278. return err
  279. }
  280. o.buf = append(o.buf, p.tagcode...)
  281. o.EncodeRawBytes(nbuf)
  282. o.buffree(nbuf)
  283. return state.err
  284. }
  285. // Encode a group struct.
  286. func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error {
  287. var state errorState
  288. b := structPointer_GetStructPointer(base, p.field)
  289. if structPointer_IsNil(b) {
  290. return ErrNil
  291. }
  292. o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
  293. err := o.enc_struct(p.stype, p.sprop, b)
  294. if err != nil && !state.shouldContinue(err, nil) {
  295. return err
  296. }
  297. o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
  298. return state.err
  299. }
  300. // Encode a slice of bools ([]bool).
  301. func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
  302. s := *structPointer_BoolSlice(base, p.field)
  303. l := len(s)
  304. if l == 0 {
  305. return ErrNil
  306. }
  307. for _, x := range s {
  308. o.buf = append(o.buf, p.tagcode...)
  309. v := uint64(0)
  310. if x {
  311. v = 1
  312. }
  313. p.valEnc(o, v)
  314. }
  315. return nil
  316. }
  317. // Encode a slice of bools ([]bool) in packed format.
  318. func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error {
  319. s := *structPointer_BoolSlice(base, p.field)
  320. l := len(s)
  321. if l == 0 {
  322. return ErrNil
  323. }
  324. o.buf = append(o.buf, p.tagcode...)
  325. o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
  326. for _, x := range s {
  327. v := uint64(0)
  328. if x {
  329. v = 1
  330. }
  331. p.valEnc(o, v)
  332. }
  333. return nil
  334. }
  335. // Encode a slice of bytes ([]byte).
  336. func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
  337. s := *structPointer_Bytes(base, p.field)
  338. if s == nil {
  339. return ErrNil
  340. }
  341. o.buf = append(o.buf, p.tagcode...)
  342. o.EncodeRawBytes(s)
  343. return nil
  344. }
  345. // Encode a slice of int32s ([]int32).
  346. func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error {
  347. s := structPointer_Word32Slice(base, p.field)
  348. l := s.Len()
  349. if l == 0 {
  350. return ErrNil
  351. }
  352. for i := 0; i < l; i++ {
  353. o.buf = append(o.buf, p.tagcode...)
  354. x := s.Index(i)
  355. p.valEnc(o, uint64(x))
  356. }
  357. return nil
  358. }
  359. // Encode a slice of int32s ([]int32) in packed format.
  360. func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error {
  361. s := structPointer_Word32Slice(base, p.field)
  362. l := s.Len()
  363. if l == 0 {
  364. return ErrNil
  365. }
  366. // TODO: Reuse a Buffer.
  367. buf := NewBuffer(nil)
  368. for i := 0; i < l; i++ {
  369. p.valEnc(buf, uint64(s.Index(i)))
  370. }
  371. o.buf = append(o.buf, p.tagcode...)
  372. o.EncodeVarint(uint64(len(buf.buf)))
  373. o.buf = append(o.buf, buf.buf...)
  374. return nil
  375. }
  376. // Encode a slice of int64s ([]int64).
  377. func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error {
  378. s := structPointer_Word64Slice(base, p.field)
  379. l := s.Len()
  380. if l == 0 {
  381. return ErrNil
  382. }
  383. for i := 0; i < l; i++ {
  384. o.buf = append(o.buf, p.tagcode...)
  385. p.valEnc(o, s.Index(i))
  386. }
  387. return nil
  388. }
  389. // Encode a slice of int64s ([]int64) in packed format.
  390. func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error {
  391. s := structPointer_Word64Slice(base, p.field)
  392. l := s.Len()
  393. if l == 0 {
  394. return ErrNil
  395. }
  396. // TODO: Reuse a Buffer.
  397. buf := NewBuffer(nil)
  398. for i := 0; i < l; i++ {
  399. p.valEnc(buf, s.Index(i))
  400. }
  401. o.buf = append(o.buf, p.tagcode...)
  402. o.EncodeVarint(uint64(len(buf.buf)))
  403. o.buf = append(o.buf, buf.buf...)
  404. return nil
  405. }
  406. // Encode a slice of slice of bytes ([][]byte).
  407. func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
  408. ss := *structPointer_BytesSlice(base, p.field)
  409. l := len(ss)
  410. if l == 0 {
  411. return ErrNil
  412. }
  413. for i := 0; i < l; i++ {
  414. o.buf = append(o.buf, p.tagcode...)
  415. s := ss[i]
  416. o.EncodeRawBytes(s)
  417. }
  418. return nil
  419. }
  420. // Encode a slice of strings ([]string).
  421. func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
  422. ss := *structPointer_StringSlice(base, p.field)
  423. l := len(ss)
  424. for i := 0; i < l; i++ {
  425. o.buf = append(o.buf, p.tagcode...)
  426. s := ss[i]
  427. o.EncodeStringBytes(s)
  428. }
  429. return nil
  430. }
  431. // Encode a slice of message structs ([]*struct).
  432. func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error {
  433. var state errorState
  434. s := structPointer_StructPointerSlice(base, p.field)
  435. l := s.Len()
  436. for i := 0; i < l; i++ {
  437. structp := s.Index(i)
  438. if structPointer_IsNil(structp) {
  439. return ErrRepeatedHasNil
  440. }
  441. // Can the object marshal itself?
  442. if p.isMarshaler {
  443. m := structPointer_Interface(structp, p.stype).(Marshaler)
  444. data, err := m.Marshal()
  445. if err != nil && !state.shouldContinue(err, nil) {
  446. return err
  447. }
  448. o.buf = append(o.buf, p.tagcode...)
  449. o.EncodeRawBytes(data)
  450. continue
  451. }
  452. obuf := o.buf
  453. o.buf = o.bufalloc()
  454. err := o.enc_struct(p.stype, p.sprop, structp)
  455. nbuf := o.buf
  456. o.buf = obuf
  457. if err != nil && !state.shouldContinue(err, nil) {
  458. o.buffree(nbuf)
  459. if err == ErrNil {
  460. return ErrRepeatedHasNil
  461. }
  462. return err
  463. }
  464. o.buf = append(o.buf, p.tagcode...)
  465. o.EncodeRawBytes(nbuf)
  466. o.buffree(nbuf)
  467. }
  468. return state.err
  469. }
  470. // Encode a slice of group structs ([]*struct).
  471. func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error {
  472. var state errorState
  473. s := structPointer_StructPointerSlice(base, p.field)
  474. l := s.Len()
  475. for i := 0; i < l; i++ {
  476. b := s.Index(i)
  477. if structPointer_IsNil(b) {
  478. return ErrRepeatedHasNil
  479. }
  480. o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
  481. err := o.enc_struct(p.stype, p.sprop, b)
  482. if err != nil && !state.shouldContinue(err, nil) {
  483. if err == ErrNil {
  484. return ErrRepeatedHasNil
  485. }
  486. return err
  487. }
  488. o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
  489. }
  490. return state.err
  491. }
  492. // Encode an extension map.
  493. func (o *Buffer) enc_map(p *Properties, base structPointer) error {
  494. v := *structPointer_ExtMap(base, p.field)
  495. if err := encodeExtensionMap(v); err != nil {
  496. return err
  497. }
  498. // Fast-path for common cases: zero or one extensions.
  499. if len(v) <= 1 {
  500. for _, e := range v {
  501. o.buf = append(o.buf, e.enc...)
  502. }
  503. return nil
  504. }
  505. // Sort keys to provide a deterministic encoding.
  506. keys := make([]int, 0, len(v))
  507. for k := range v {
  508. keys = append(keys, int(k))
  509. }
  510. sort.Ints(keys)
  511. for _, k := range keys {
  512. o.buf = append(o.buf, v[int32(k)].enc...)
  513. }
  514. return nil
  515. }
  516. // Encode a struct.
  517. func (o *Buffer) enc_struct(t reflect.Type, prop *StructProperties, base structPointer) error {
  518. var state errorState
  519. // Encode fields in tag order so that decoders may use optimizations
  520. // that depend on the ordering.
  521. // http://code.google.com/apis/protocolbuffers/docs/encoding.html#order
  522. for _, i := range prop.order {
  523. p := prop.Prop[i]
  524. if p.enc != nil {
  525. err := p.enc(o, p, base)
  526. if err != nil && !state.shouldContinue(err, p) {
  527. if err != ErrNil {
  528. return err
  529. } else if p.Required && state.err == nil {
  530. state.err = &ErrRequiredNotSet{p.Name}
  531. }
  532. }
  533. }
  534. }
  535. // Add unrecognized fields at the end.
  536. if prop.unrecField.IsValid() {
  537. v := *structPointer_Bytes(base, prop.unrecField)
  538. if len(v) > 0 {
  539. o.buf = append(o.buf, v...)
  540. }
  541. }
  542. return state.err
  543. }
  544. // errorState maintains the first error that occurs and updates that error
  545. // with additional context.
  546. type errorState struct {
  547. err error
  548. }
  549. // shouldContinue reports whether encoding should continue upon encountering the
  550. // given error. If the error is ErrRequiredNotSet, shouldContinue returns true
  551. // and, if this is the first appearance of that error, remembers it for future
  552. // reporting.
  553. //
  554. // If prop is not nil, it may update any error with additional context about the
  555. // field with the error.
  556. func (s *errorState) shouldContinue(err error, prop *Properties) bool {
  557. // Ignore unset required fields.
  558. reqNotSet, ok := err.(*ErrRequiredNotSet)
  559. if !ok {
  560. return false
  561. }
  562. if s.err == nil {
  563. if prop != nil {
  564. err = &ErrRequiredNotSet{prop.Name + "." + reqNotSet.field}
  565. }
  566. s.err = err
  567. }
  568. return true
  569. }