encode.go 15 KB

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