PageRenderTime 67ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/proto/encode.go

https://code.google.com/p/goprotobuf/
Go | 585 lines | 407 code | 65 blank | 113 comment | 89 complexity | 6b0511308de241422c02f6a8dfdf1db6 MD5 | raw file
Possible License(s): BSD-3-Clause
  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 something other than a pointer to a struct.
  58. ErrNotPtr = errors.New("proto: Marshal called with something other than a pointer to a struct")
  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. structp := *(*unsafe.Pointer)(unsafe.Pointer(base + p.offset))
  245. if structp == nil {
  246. return ErrNil
  247. }
  248. typ := p.stype.Elem()
  249. // Can the object marshal itself?
  250. if p.isMarshaler {
  251. m := reflect.NewAt(typ, structp).Interface().(Marshaler)
  252. data, err := m.Marshal()
  253. if err != nil {
  254. return err
  255. }
  256. o.buf = append(o.buf, p.tagcode...)
  257. o.EncodeRawBytes(data)
  258. return nil
  259. }
  260. // need the length before we can write out the message itself,
  261. // so marshal into a separate byte buffer first.
  262. obuf := o.buf
  263. o.buf = o.bufalloc()
  264. err := o.enc_struct(typ, uintptr(structp))
  265. nbuf := o.buf
  266. o.buf = obuf
  267. if err != nil {
  268. o.buffree(nbuf)
  269. return err
  270. }
  271. o.buf = append(o.buf, p.tagcode...)
  272. o.EncodeRawBytes(nbuf)
  273. o.buffree(nbuf)
  274. return nil
  275. }
  276. // Encode a group struct.
  277. func (o *Buffer) enc_struct_group(p *Properties, base uintptr) error {
  278. v := *(**struct{})(unsafe.Pointer(base + p.offset))
  279. if v == nil {
  280. return ErrNil
  281. }
  282. o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
  283. b := uintptr(unsafe.Pointer(v))
  284. typ := p.stype.Elem()
  285. err := o.enc_struct(typ, 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 uintptr) error {
  294. s := *(*[]uint8)(unsafe.Pointer(base + p.offset))
  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. if x != 0 {
  302. x = 1
  303. }
  304. p.valEnc(o, uint64(x))
  305. }
  306. return nil
  307. }
  308. // Encode a slice of bools ([]bool) in packed format.
  309. func (o *Buffer) enc_slice_packed_bool(p *Properties, base uintptr) error {
  310. s := *(*[]uint8)(unsafe.Pointer(base + p.offset))
  311. l := len(s)
  312. if l == 0 {
  313. return ErrNil
  314. }
  315. o.buf = append(o.buf, p.tagcode...)
  316. o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
  317. for _, x := range s {
  318. if x != 0 {
  319. x = 1
  320. }
  321. p.valEnc(o, uint64(x))
  322. }
  323. return nil
  324. }
  325. // Encode a slice of bytes ([]byte).
  326. func (o *Buffer) enc_slice_byte(p *Properties, base uintptr) error {
  327. s := *(*[]uint8)(unsafe.Pointer(base + p.offset))
  328. if s == nil {
  329. return ErrNil
  330. }
  331. o.buf = append(o.buf, p.tagcode...)
  332. o.EncodeRawBytes(s)
  333. return nil
  334. }
  335. // Encode a slice of int32s ([]int32).
  336. func (o *Buffer) enc_slice_int32(p *Properties, base uintptr) error {
  337. s := *(*[]uint32)(unsafe.Pointer(base + p.offset))
  338. l := len(s)
  339. if l == 0 {
  340. return ErrNil
  341. }
  342. for i := 0; i < l; i++ {
  343. o.buf = append(o.buf, p.tagcode...)
  344. x := s[i]
  345. p.valEnc(o, uint64(x))
  346. }
  347. return nil
  348. }
  349. // Encode a slice of int32s ([]int32) in packed format.
  350. func (o *Buffer) enc_slice_packed_int32(p *Properties, base uintptr) error {
  351. s := *(*[]uint32)(unsafe.Pointer(base + p.offset))
  352. l := len(s)
  353. if l == 0 {
  354. return ErrNil
  355. }
  356. // TODO: Reuse a Buffer.
  357. buf := NewBuffer(nil)
  358. for i := 0; i < l; i++ {
  359. p.valEnc(buf, uint64(s[i]))
  360. }
  361. o.buf = append(o.buf, p.tagcode...)
  362. o.EncodeVarint(uint64(len(buf.buf)))
  363. o.buf = append(o.buf, buf.buf...)
  364. return nil
  365. }
  366. // Encode a slice of int64s ([]int64).
  367. func (o *Buffer) enc_slice_int64(p *Properties, base uintptr) error {
  368. s := *(*[]uint64)(unsafe.Pointer(base + p.offset))
  369. l := len(s)
  370. if l == 0 {
  371. return ErrNil
  372. }
  373. for i := 0; i < l; i++ {
  374. o.buf = append(o.buf, p.tagcode...)
  375. x := s[i]
  376. p.valEnc(o, uint64(x))
  377. }
  378. return nil
  379. }
  380. // Encode a slice of int64s ([]int64) in packed format.
  381. func (o *Buffer) enc_slice_packed_int64(p *Properties, base uintptr) error {
  382. s := *(*[]uint64)(unsafe.Pointer(base + p.offset))
  383. l := len(s)
  384. if l == 0 {
  385. return ErrNil
  386. }
  387. // TODO: Reuse a Buffer.
  388. buf := NewBuffer(nil)
  389. for i := 0; i < l; i++ {
  390. p.valEnc(buf, s[i])
  391. }
  392. o.buf = append(o.buf, p.tagcode...)
  393. o.EncodeVarint(uint64(len(buf.buf)))
  394. o.buf = append(o.buf, buf.buf...)
  395. return nil
  396. }
  397. // Encode a slice of slice of bytes ([][]byte).
  398. func (o *Buffer) enc_slice_slice_byte(p *Properties, base uintptr) error {
  399. ss := *(*[][]uint8)(unsafe.Pointer(base + p.offset))
  400. l := len(ss)
  401. if l == 0 {
  402. return ErrNil
  403. }
  404. for i := 0; i < l; i++ {
  405. o.buf = append(o.buf, p.tagcode...)
  406. s := ss[i]
  407. o.EncodeRawBytes(s)
  408. }
  409. return nil
  410. }
  411. // Encode a slice of strings ([]string).
  412. func (o *Buffer) enc_slice_string(p *Properties, base uintptr) error {
  413. ss := *(*[]string)(unsafe.Pointer(base + p.offset))
  414. l := len(ss)
  415. for i := 0; i < l; i++ {
  416. o.buf = append(o.buf, p.tagcode...)
  417. s := ss[i]
  418. o.EncodeStringBytes(s)
  419. }
  420. return nil
  421. }
  422. // Encode a slice of message structs ([]*struct).
  423. func (o *Buffer) enc_slice_struct_message(p *Properties, base uintptr) error {
  424. s := *(*[]unsafe.Pointer)(unsafe.Pointer(base + p.offset))
  425. l := len(s)
  426. typ := p.stype.Elem()
  427. for i := 0; i < l; i++ {
  428. structp := s[i]
  429. if structp == nil {
  430. return ErrRepeatedHasNil
  431. }
  432. // Can the object marshal itself?
  433. if p.isMarshaler {
  434. m := reflect.NewAt(typ, structp).Interface().(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(typ, uintptr(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 uintptr) error {
  463. s := *(*[]*struct{})(unsafe.Pointer(base + p.offset))
  464. l := len(s)
  465. typ := p.stype.Elem()
  466. for i := 0; i < l; i++ {
  467. v := s[i]
  468. if v == nil {
  469. return ErrRepeatedHasNil
  470. }
  471. o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
  472. b := uintptr(unsafe.Pointer(v))
  473. err := o.enc_struct(typ, b)
  474. if err != nil {
  475. if err == ErrNil {
  476. return ErrRepeatedHasNil
  477. }
  478. return err
  479. }
  480. o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
  481. }
  482. return nil
  483. }
  484. // Encode an extension map.
  485. func (o *Buffer) enc_map(p *Properties, base uintptr) error {
  486. v := *(*map[int32]Extension)(unsafe.Pointer(base + p.offset))
  487. if err := encodeExtensionMap(v); err != nil {
  488. return err
  489. }
  490. for _, e := range v {
  491. o.buf = append(o.buf, e.enc...)
  492. }
  493. return nil
  494. }
  495. // Encode a struct.
  496. func (o *Buffer) enc_struct(t reflect.Type, base uintptr) error {
  497. prop := GetProperties(t)
  498. required := prop.reqCount
  499. // Encode fields in tag order so that decoders may use optimizations
  500. // that depend on the ordering.
  501. // http://code.google.com/apis/protocolbuffers/docs/encoding.html#order
  502. for _, i := range prop.order {
  503. p := prop.Prop[i]
  504. if p.enc != nil {
  505. err := p.enc(o, p, base)
  506. if err != nil {
  507. if err != ErrNil {
  508. return err
  509. }
  510. } else if p.Required {
  511. required--
  512. }
  513. }
  514. }
  515. // See if we encoded all required fields.
  516. if required > 0 {
  517. return &ErrRequiredNotSet{t}
  518. }
  519. return nil
  520. }