encode.go 15 KB

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