encode.go 15 KB

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