encode.go 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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. // RequiredNotSetError 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, RequiredNotSetError 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 RequiredNotSetError struct {
  51. field string
  52. }
  53. func (e *RequiredNotSetError) 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. func sizeVarint(x uint64) (n int) {
  97. for {
  98. n++
  99. x >>= 7
  100. if x == 0 {
  101. break
  102. }
  103. }
  104. return n
  105. }
  106. // EncodeFixed64 writes a 64-bit integer to the Buffer.
  107. // This is the format for the
  108. // fixed64, sfixed64, and double protocol buffer types.
  109. func (p *Buffer) EncodeFixed64(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. uint8(x>>32),
  116. uint8(x>>40),
  117. uint8(x>>48),
  118. uint8(x>>56))
  119. return nil
  120. }
  121. func sizeFixed64(x uint64) int {
  122. return 8
  123. }
  124. // EncodeFixed32 writes a 32-bit integer to the Buffer.
  125. // This is the format for the
  126. // fixed32, sfixed32, and float protocol buffer types.
  127. func (p *Buffer) EncodeFixed32(x uint64) error {
  128. p.buf = append(p.buf,
  129. uint8(x),
  130. uint8(x>>8),
  131. uint8(x>>16),
  132. uint8(x>>24))
  133. return nil
  134. }
  135. func sizeFixed32(x uint64) int {
  136. return 4
  137. }
  138. // EncodeZigzag64 writes a zigzag-encoded 64-bit integer
  139. // to the Buffer.
  140. // This is the format used for the sint64 protocol buffer type.
  141. func (p *Buffer) EncodeZigzag64(x uint64) error {
  142. // use signed number to get arithmetic right shift.
  143. return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
  144. }
  145. func sizeZigzag64(x uint64) int {
  146. return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
  147. }
  148. // EncodeZigzag32 writes a zigzag-encoded 32-bit integer
  149. // to the Buffer.
  150. // This is the format used for the sint32 protocol buffer type.
  151. func (p *Buffer) EncodeZigzag32(x uint64) error {
  152. // use signed number to get arithmetic right shift.
  153. return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
  154. }
  155. func sizeZigzag32(x uint64) int {
  156. return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
  157. }
  158. // EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
  159. // This is the format used for the bytes protocol buffer
  160. // type and for embedded messages.
  161. func (p *Buffer) EncodeRawBytes(b []byte) error {
  162. p.EncodeVarint(uint64(len(b)))
  163. p.buf = append(p.buf, b...)
  164. return nil
  165. }
  166. func sizeRawBytes(b []byte) int {
  167. return sizeVarint(uint64(len(b))) +
  168. len(b)
  169. }
  170. // EncodeStringBytes writes an encoded string to the Buffer.
  171. // This is the format used for the proto2 string type.
  172. func (p *Buffer) EncodeStringBytes(s string) error {
  173. p.EncodeVarint(uint64(len(s)))
  174. p.buf = append(p.buf, s...)
  175. return nil
  176. }
  177. func sizeStringBytes(s string) int {
  178. return sizeVarint(uint64(len(s))) +
  179. len(s)
  180. }
  181. // Marshaler is the interface representing objects that can marshal themselves.
  182. type Marshaler interface {
  183. Marshal() ([]byte, error)
  184. }
  185. // Marshal takes the protocol buffer
  186. // and encodes it into the wire format, returning the data.
  187. func Marshal(pb Message) ([]byte, error) {
  188. // Can the object marshal itself?
  189. if m, ok := pb.(Marshaler); ok {
  190. return m.Marshal()
  191. }
  192. p := NewBuffer(nil)
  193. err := p.Marshal(pb)
  194. var state errorState
  195. if err != nil && !state.shouldContinue(err, nil) {
  196. return nil, err
  197. }
  198. if p.buf == nil && err == nil {
  199. // Return a non-nil slice on success.
  200. return []byte{}, nil
  201. }
  202. return p.buf, err
  203. }
  204. // Marshal takes the protocol buffer
  205. // and encodes it into the wire format, writing the result to the
  206. // Buffer.
  207. func (p *Buffer) Marshal(pb Message) error {
  208. // Can the object marshal itself?
  209. if m, ok := pb.(Marshaler); ok {
  210. data, err := m.Marshal()
  211. if err != nil {
  212. return err
  213. }
  214. p.buf = append(p.buf, data...)
  215. return nil
  216. }
  217. t, base, err := getbase(pb)
  218. if structPointer_IsNil(base) {
  219. return ErrNil
  220. }
  221. if err == nil {
  222. err = p.enc_struct(t.Elem(), GetProperties(t.Elem()), base)
  223. }
  224. if collectStats {
  225. stats.Encode++
  226. }
  227. return err
  228. }
  229. // Size returns the encoded size of a protocol buffer.
  230. func Size(pb Message) (n int) {
  231. // Can the object marshal itself? If so, Size is slow.
  232. // TODO: add Size to Marshaler, or add a Sizer interface.
  233. if m, ok := pb.(Marshaler); ok {
  234. b, _ := m.Marshal()
  235. return len(b)
  236. }
  237. t, base, err := getbase(pb)
  238. if structPointer_IsNil(base) {
  239. return 0
  240. }
  241. if err == nil {
  242. n = size_struct(t.Elem(), GetProperties(t.Elem()), base)
  243. }
  244. if collectStats {
  245. stats.Size++
  246. }
  247. return
  248. }
  249. // Individual type encoders.
  250. // Encode a bool.
  251. func (o *Buffer) enc_bool(p *Properties, base structPointer) error {
  252. v := *structPointer_Bool(base, p.field)
  253. if v == nil {
  254. return ErrNil
  255. }
  256. x := 0
  257. if *v {
  258. x = 1
  259. }
  260. o.buf = append(o.buf, p.tagcode...)
  261. p.valEnc(o, uint64(x))
  262. return nil
  263. }
  264. func size_bool(p *Properties, base structPointer) int {
  265. v := *structPointer_Bool(base, p.field)
  266. if v == nil {
  267. return 0
  268. }
  269. return len(p.tagcode) + 1 // each bool takes exactly one byte
  270. }
  271. // Encode an int32.
  272. func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
  273. v := structPointer_Word32(base, p.field)
  274. if word32_IsNil(v) {
  275. return ErrNil
  276. }
  277. x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
  278. o.buf = append(o.buf, p.tagcode...)
  279. p.valEnc(o, uint64(x))
  280. return nil
  281. }
  282. func size_int32(p *Properties, base structPointer) (n int) {
  283. v := structPointer_Word32(base, p.field)
  284. if word32_IsNil(v) {
  285. return 0
  286. }
  287. x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
  288. n += len(p.tagcode)
  289. n += p.valSize(uint64(x))
  290. return
  291. }
  292. // Encode a uint32.
  293. // Exactly the same as int32, except for no sign extension.
  294. func (o *Buffer) enc_uint32(p *Properties, base structPointer) error {
  295. v := structPointer_Word32(base, p.field)
  296. if word32_IsNil(v) {
  297. return ErrNil
  298. }
  299. x := word32_Get(v)
  300. o.buf = append(o.buf, p.tagcode...)
  301. p.valEnc(o, uint64(x))
  302. return nil
  303. }
  304. func size_uint32(p *Properties, base structPointer) (n int) {
  305. v := structPointer_Word32(base, p.field)
  306. if word32_IsNil(v) {
  307. return 0
  308. }
  309. x := word32_Get(v)
  310. n += len(p.tagcode)
  311. n += p.valSize(uint64(x))
  312. return
  313. }
  314. // Encode an int64.
  315. func (o *Buffer) enc_int64(p *Properties, base structPointer) error {
  316. v := structPointer_Word64(base, p.field)
  317. if word64_IsNil(v) {
  318. return ErrNil
  319. }
  320. x := word64_Get(v)
  321. o.buf = append(o.buf, p.tagcode...)
  322. p.valEnc(o, x)
  323. return nil
  324. }
  325. func size_int64(p *Properties, base structPointer) (n int) {
  326. v := structPointer_Word64(base, p.field)
  327. if word64_IsNil(v) {
  328. return 0
  329. }
  330. x := word64_Get(v)
  331. n += len(p.tagcode)
  332. n += p.valSize(x)
  333. return
  334. }
  335. // Encode a string.
  336. func (o *Buffer) enc_string(p *Properties, base structPointer) error {
  337. v := *structPointer_String(base, p.field)
  338. if v == nil {
  339. return ErrNil
  340. }
  341. x := *v
  342. o.buf = append(o.buf, p.tagcode...)
  343. o.EncodeStringBytes(x)
  344. return nil
  345. }
  346. func size_string(p *Properties, base structPointer) (n int) {
  347. v := *structPointer_String(base, p.field)
  348. if v == nil {
  349. return 0
  350. }
  351. x := *v
  352. n += len(p.tagcode)
  353. n += sizeStringBytes(x)
  354. return
  355. }
  356. // All protocol buffer fields are nillable, but be careful.
  357. func isNil(v reflect.Value) bool {
  358. switch v.Kind() {
  359. case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
  360. return v.IsNil()
  361. }
  362. return false
  363. }
  364. // Encode a message struct.
  365. func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
  366. var state errorState
  367. structp := structPointer_GetStructPointer(base, p.field)
  368. if structPointer_IsNil(structp) {
  369. return ErrNil
  370. }
  371. // Can the object marshal itself?
  372. if p.isMarshaler {
  373. m := structPointer_Interface(structp, p.stype).(Marshaler)
  374. data, err := m.Marshal()
  375. if err != nil && !state.shouldContinue(err, nil) {
  376. return err
  377. }
  378. o.buf = append(o.buf, p.tagcode...)
  379. o.EncodeRawBytes(data)
  380. return nil
  381. }
  382. o.buf = append(o.buf, p.tagcode...)
  383. return o.enc_len_struct(p.stype, p.sprop, structp, &state)
  384. }
  385. func size_struct_message(p *Properties, base structPointer) int {
  386. structp := structPointer_GetStructPointer(base, p.field)
  387. if structPointer_IsNil(structp) {
  388. return 0
  389. }
  390. // Can the object marshal itself?
  391. if p.isMarshaler {
  392. m := structPointer_Interface(structp, p.stype).(Marshaler)
  393. data, _ := m.Marshal()
  394. n0 := len(p.tagcode)
  395. n1 := sizeRawBytes(data)
  396. return n0 + n1
  397. }
  398. n0 := len(p.tagcode)
  399. n1 := size_struct(p.stype, p.sprop, structp)
  400. n2 := sizeVarint(uint64(n1)) // size of encoded length
  401. return n0 + n1 + n2
  402. }
  403. // Encode a group struct.
  404. func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error {
  405. var state errorState
  406. b := structPointer_GetStructPointer(base, p.field)
  407. if structPointer_IsNil(b) {
  408. return ErrNil
  409. }
  410. o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
  411. err := o.enc_struct(p.stype, p.sprop, b)
  412. if err != nil && !state.shouldContinue(err, nil) {
  413. return err
  414. }
  415. o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
  416. return state.err
  417. }
  418. func size_struct_group(p *Properties, base structPointer) (n int) {
  419. b := structPointer_GetStructPointer(base, p.field)
  420. if structPointer_IsNil(b) {
  421. return 0
  422. }
  423. n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup))
  424. n += size_struct(p.stype, p.sprop, b)
  425. n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup))
  426. return
  427. }
  428. // Encode a slice of bools ([]bool).
  429. func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
  430. s := *structPointer_BoolSlice(base, p.field)
  431. l := len(s)
  432. if l == 0 {
  433. return ErrNil
  434. }
  435. for _, x := range s {
  436. o.buf = append(o.buf, p.tagcode...)
  437. v := uint64(0)
  438. if x {
  439. v = 1
  440. }
  441. p.valEnc(o, v)
  442. }
  443. return nil
  444. }
  445. func size_slice_bool(p *Properties, base structPointer) int {
  446. s := *structPointer_BoolSlice(base, p.field)
  447. l := len(s)
  448. if l == 0 {
  449. return 0
  450. }
  451. return l * (len(p.tagcode) + 1) // each bool takes exactly one byte
  452. }
  453. // Encode a slice of bools ([]bool) in packed format.
  454. func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error {
  455. s := *structPointer_BoolSlice(base, p.field)
  456. l := len(s)
  457. if l == 0 {
  458. return ErrNil
  459. }
  460. o.buf = append(o.buf, p.tagcode...)
  461. o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
  462. for _, x := range s {
  463. v := uint64(0)
  464. if x {
  465. v = 1
  466. }
  467. p.valEnc(o, v)
  468. }
  469. return nil
  470. }
  471. func size_slice_packed_bool(p *Properties, base structPointer) (n int) {
  472. s := *structPointer_BoolSlice(base, p.field)
  473. l := len(s)
  474. if l == 0 {
  475. return 0
  476. }
  477. n += len(p.tagcode)
  478. n += sizeVarint(uint64(l))
  479. n += l // each bool takes exactly one byte
  480. return
  481. }
  482. // Encode a slice of bytes ([]byte).
  483. func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
  484. s := *structPointer_Bytes(base, p.field)
  485. if s == nil {
  486. return ErrNil
  487. }
  488. o.buf = append(o.buf, p.tagcode...)
  489. o.EncodeRawBytes(s)
  490. return nil
  491. }
  492. func size_slice_byte(p *Properties, base structPointer) (n int) {
  493. s := *structPointer_Bytes(base, p.field)
  494. if s == nil {
  495. return 0
  496. }
  497. n += len(p.tagcode)
  498. n += sizeRawBytes(s)
  499. return
  500. }
  501. // Encode a slice of int32s ([]int32).
  502. func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error {
  503. s := structPointer_Word32Slice(base, p.field)
  504. l := s.Len()
  505. if l == 0 {
  506. return ErrNil
  507. }
  508. for i := 0; i < l; i++ {
  509. o.buf = append(o.buf, p.tagcode...)
  510. x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
  511. p.valEnc(o, uint64(x))
  512. }
  513. return nil
  514. }
  515. func size_slice_int32(p *Properties, base structPointer) (n int) {
  516. s := structPointer_Word32Slice(base, p.field)
  517. l := s.Len()
  518. if l == 0 {
  519. return 0
  520. }
  521. for i := 0; i < l; i++ {
  522. n += len(p.tagcode)
  523. x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
  524. n += p.valSize(uint64(x))
  525. }
  526. return
  527. }
  528. // Encode a slice of int32s ([]int32) in packed format.
  529. func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error {
  530. s := structPointer_Word32Slice(base, p.field)
  531. l := s.Len()
  532. if l == 0 {
  533. return ErrNil
  534. }
  535. // TODO: Reuse a Buffer.
  536. buf := NewBuffer(nil)
  537. for i := 0; i < l; i++ {
  538. x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
  539. p.valEnc(buf, uint64(x))
  540. }
  541. o.buf = append(o.buf, p.tagcode...)
  542. o.EncodeVarint(uint64(len(buf.buf)))
  543. o.buf = append(o.buf, buf.buf...)
  544. return nil
  545. }
  546. func size_slice_packed_int32(p *Properties, base structPointer) (n int) {
  547. s := structPointer_Word32Slice(base, p.field)
  548. l := s.Len()
  549. if l == 0 {
  550. return 0
  551. }
  552. var bufSize int
  553. for i := 0; i < l; i++ {
  554. x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
  555. bufSize += p.valSize(uint64(x))
  556. }
  557. n += len(p.tagcode)
  558. n += sizeVarint(uint64(bufSize))
  559. n += bufSize
  560. return
  561. }
  562. // Encode a slice of uint32s ([]uint32).
  563. // Exactly the same as int32, except for no sign extension.
  564. func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error {
  565. s := structPointer_Word32Slice(base, p.field)
  566. l := s.Len()
  567. if l == 0 {
  568. return ErrNil
  569. }
  570. for i := 0; i < l; i++ {
  571. o.buf = append(o.buf, p.tagcode...)
  572. x := s.Index(i)
  573. p.valEnc(o, uint64(x))
  574. }
  575. return nil
  576. }
  577. func size_slice_uint32(p *Properties, base structPointer) (n int) {
  578. s := structPointer_Word32Slice(base, p.field)
  579. l := s.Len()
  580. if l == 0 {
  581. return 0
  582. }
  583. for i := 0; i < l; i++ {
  584. n += len(p.tagcode)
  585. x := s.Index(i)
  586. n += p.valSize(uint64(x))
  587. }
  588. return
  589. }
  590. // Encode a slice of uint32s ([]uint32) in packed format.
  591. // Exactly the same as int32, except for no sign extension.
  592. func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error {
  593. s := structPointer_Word32Slice(base, p.field)
  594. l := s.Len()
  595. if l == 0 {
  596. return ErrNil
  597. }
  598. // TODO: Reuse a Buffer.
  599. buf := NewBuffer(nil)
  600. for i := 0; i < l; i++ {
  601. p.valEnc(buf, uint64(s.Index(i)))
  602. }
  603. o.buf = append(o.buf, p.tagcode...)
  604. o.EncodeVarint(uint64(len(buf.buf)))
  605. o.buf = append(o.buf, buf.buf...)
  606. return nil
  607. }
  608. func size_slice_packed_uint32(p *Properties, base structPointer) (n int) {
  609. s := structPointer_Word32Slice(base, p.field)
  610. l := s.Len()
  611. if l == 0 {
  612. return 0
  613. }
  614. var bufSize int
  615. for i := 0; i < l; i++ {
  616. bufSize += p.valSize(uint64(s.Index(i)))
  617. }
  618. n += len(p.tagcode)
  619. n += sizeVarint(uint64(bufSize))
  620. n += bufSize
  621. return
  622. }
  623. // Encode a slice of int64s ([]int64).
  624. func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error {
  625. s := structPointer_Word64Slice(base, p.field)
  626. l := s.Len()
  627. if l == 0 {
  628. return ErrNil
  629. }
  630. for i := 0; i < l; i++ {
  631. o.buf = append(o.buf, p.tagcode...)
  632. p.valEnc(o, s.Index(i))
  633. }
  634. return nil
  635. }
  636. func size_slice_int64(p *Properties, base structPointer) (n int) {
  637. s := structPointer_Word64Slice(base, p.field)
  638. l := s.Len()
  639. if l == 0 {
  640. return 0
  641. }
  642. for i := 0; i < l; i++ {
  643. n += len(p.tagcode)
  644. n += p.valSize(s.Index(i))
  645. }
  646. return
  647. }
  648. // Encode a slice of int64s ([]int64) in packed format.
  649. func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error {
  650. s := structPointer_Word64Slice(base, p.field)
  651. l := s.Len()
  652. if l == 0 {
  653. return ErrNil
  654. }
  655. // TODO: Reuse a Buffer.
  656. buf := NewBuffer(nil)
  657. for i := 0; i < l; i++ {
  658. p.valEnc(buf, s.Index(i))
  659. }
  660. o.buf = append(o.buf, p.tagcode...)
  661. o.EncodeVarint(uint64(len(buf.buf)))
  662. o.buf = append(o.buf, buf.buf...)
  663. return nil
  664. }
  665. func size_slice_packed_int64(p *Properties, base structPointer) (n int) {
  666. s := structPointer_Word64Slice(base, p.field)
  667. l := s.Len()
  668. if l == 0 {
  669. return 0
  670. }
  671. var bufSize int
  672. for i := 0; i < l; i++ {
  673. bufSize += p.valSize(s.Index(i))
  674. }
  675. n += len(p.tagcode)
  676. n += sizeVarint(uint64(bufSize))
  677. n += bufSize
  678. return
  679. }
  680. // Encode a slice of slice of bytes ([][]byte).
  681. func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
  682. ss := *structPointer_BytesSlice(base, p.field)
  683. l := len(ss)
  684. if l == 0 {
  685. return ErrNil
  686. }
  687. for i := 0; i < l; i++ {
  688. o.buf = append(o.buf, p.tagcode...)
  689. o.EncodeRawBytes(ss[i])
  690. }
  691. return nil
  692. }
  693. func size_slice_slice_byte(p *Properties, base structPointer) (n int) {
  694. ss := *structPointer_BytesSlice(base, p.field)
  695. l := len(ss)
  696. if l == 0 {
  697. return 0
  698. }
  699. n += l * len(p.tagcode)
  700. for i := 0; i < l; i++ {
  701. n += sizeRawBytes(ss[i])
  702. }
  703. return
  704. }
  705. // Encode a slice of strings ([]string).
  706. func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
  707. ss := *structPointer_StringSlice(base, p.field)
  708. l := len(ss)
  709. for i := 0; i < l; i++ {
  710. o.buf = append(o.buf, p.tagcode...)
  711. o.EncodeStringBytes(ss[i])
  712. }
  713. return nil
  714. }
  715. func size_slice_string(p *Properties, base structPointer) (n int) {
  716. ss := *structPointer_StringSlice(base, p.field)
  717. l := len(ss)
  718. n += l * len(p.tagcode)
  719. for i := 0; i < l; i++ {
  720. n += sizeStringBytes(ss[i])
  721. }
  722. return
  723. }
  724. // Encode a slice of message structs ([]*struct).
  725. func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error {
  726. var state errorState
  727. s := structPointer_StructPointerSlice(base, p.field)
  728. l := s.Len()
  729. for i := 0; i < l; i++ {
  730. structp := s.Index(i)
  731. if structPointer_IsNil(structp) {
  732. return ErrRepeatedHasNil
  733. }
  734. // Can the object marshal itself?
  735. if p.isMarshaler {
  736. m := structPointer_Interface(structp, p.stype).(Marshaler)
  737. data, err := m.Marshal()
  738. if err != nil && !state.shouldContinue(err, nil) {
  739. return err
  740. }
  741. o.buf = append(o.buf, p.tagcode...)
  742. o.EncodeRawBytes(data)
  743. continue
  744. }
  745. o.buf = append(o.buf, p.tagcode...)
  746. err := o.enc_len_struct(p.stype, p.sprop, structp, &state)
  747. if err != nil && !state.shouldContinue(err, nil) {
  748. if err == ErrNil {
  749. return ErrRepeatedHasNil
  750. }
  751. return err
  752. }
  753. }
  754. return state.err
  755. }
  756. func size_slice_struct_message(p *Properties, base structPointer) (n int) {
  757. s := structPointer_StructPointerSlice(base, p.field)
  758. l := s.Len()
  759. n += l * len(p.tagcode)
  760. for i := 0; i < l; i++ {
  761. structp := s.Index(i)
  762. if structPointer_IsNil(structp) {
  763. return // return the size up to this point
  764. }
  765. // Can the object marshal itself?
  766. if p.isMarshaler {
  767. m := structPointer_Interface(structp, p.stype).(Marshaler)
  768. data, _ := m.Marshal()
  769. n += len(p.tagcode)
  770. n += sizeRawBytes(data)
  771. continue
  772. }
  773. n0 := size_struct(p.stype, p.sprop, structp)
  774. n1 := sizeVarint(uint64(n0)) // size of encoded length
  775. n += n0 + n1
  776. }
  777. return
  778. }
  779. // Encode a slice of group structs ([]*struct).
  780. func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error {
  781. var state errorState
  782. s := structPointer_StructPointerSlice(base, p.field)
  783. l := s.Len()
  784. for i := 0; i < l; i++ {
  785. b := s.Index(i)
  786. if structPointer_IsNil(b) {
  787. return ErrRepeatedHasNil
  788. }
  789. o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
  790. err := o.enc_struct(p.stype, p.sprop, b)
  791. if err != nil && !state.shouldContinue(err, nil) {
  792. if err == ErrNil {
  793. return ErrRepeatedHasNil
  794. }
  795. return err
  796. }
  797. o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
  798. }
  799. return state.err
  800. }
  801. func size_slice_struct_group(p *Properties, base structPointer) (n int) {
  802. s := structPointer_StructPointerSlice(base, p.field)
  803. l := s.Len()
  804. n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup))
  805. n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup))
  806. for i := 0; i < l; i++ {
  807. b := s.Index(i)
  808. if structPointer_IsNil(b) {
  809. return // return size up to this point
  810. }
  811. n += size_struct(p.stype, p.sprop, b)
  812. }
  813. return
  814. }
  815. // Encode an extension map.
  816. func (o *Buffer) enc_map(p *Properties, base structPointer) error {
  817. v := *structPointer_ExtMap(base, p.field)
  818. if err := encodeExtensionMap(v); err != nil {
  819. return err
  820. }
  821. // Fast-path for common cases: zero or one extensions.
  822. if len(v) <= 1 {
  823. for _, e := range v {
  824. o.buf = append(o.buf, e.enc...)
  825. }
  826. return nil
  827. }
  828. // Sort keys to provide a deterministic encoding.
  829. keys := make([]int, 0, len(v))
  830. for k := range v {
  831. keys = append(keys, int(k))
  832. }
  833. sort.Ints(keys)
  834. for _, k := range keys {
  835. o.buf = append(o.buf, v[int32(k)].enc...)
  836. }
  837. return nil
  838. }
  839. func size_map(p *Properties, base structPointer) int {
  840. v := *structPointer_ExtMap(base, p.field)
  841. return sizeExtensionMap(v)
  842. }
  843. // Encode a struct.
  844. func (o *Buffer) enc_struct(t reflect.Type, prop *StructProperties, base structPointer) error {
  845. var state errorState
  846. // Encode fields in tag order so that decoders may use optimizations
  847. // that depend on the ordering.
  848. // http://code.google.com/apis/protocolbuffers/docs/encoding.html#order
  849. for _, i := range prop.order {
  850. p := prop.Prop[i]
  851. if p.enc != nil {
  852. err := p.enc(o, p, base)
  853. if err != nil {
  854. if err == ErrNil {
  855. if p.Required && state.err == nil {
  856. state.err = &RequiredNotSetError{p.Name}
  857. }
  858. } else if !state.shouldContinue(err, p) {
  859. return err
  860. }
  861. }
  862. }
  863. }
  864. // Add unrecognized fields at the end.
  865. if prop.unrecField.IsValid() {
  866. v := *structPointer_Bytes(base, prop.unrecField)
  867. if len(v) > 0 {
  868. o.buf = append(o.buf, v...)
  869. }
  870. }
  871. return state.err
  872. }
  873. func size_struct(t reflect.Type, prop *StructProperties, base structPointer) (n int) {
  874. for _, i := range prop.order {
  875. p := prop.Prop[i]
  876. if p.size != nil {
  877. n += p.size(p, base)
  878. }
  879. }
  880. // Add unrecognized fields at the end.
  881. if prop.unrecField.IsValid() {
  882. v := *structPointer_Bytes(base, prop.unrecField)
  883. n += len(v)
  884. }
  885. return
  886. }
  887. var zeroes [20]byte // longer than any conceivable sizeVarint
  888. // Encode a struct, preceded by its encoded length (as a varint).
  889. func (o *Buffer) enc_len_struct(t reflect.Type, prop *StructProperties, base structPointer, state *errorState) error {
  890. iLen := len(o.buf)
  891. o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length
  892. iMsg := len(o.buf)
  893. err := o.enc_struct(t, prop, base)
  894. if err != nil && !state.shouldContinue(err, nil) {
  895. return err
  896. }
  897. lMsg := len(o.buf) - iMsg
  898. lLen := sizeVarint(uint64(lMsg))
  899. switch x := lLen - (iMsg - iLen); {
  900. case x > 0: // actual length is x bytes larger than the space we reserved
  901. // Move msg x bytes right.
  902. o.buf = append(o.buf, zeroes[:x]...)
  903. copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
  904. case x < 0: // actual length is x bytes smaller than the space we reserved
  905. // Move msg x bytes left.
  906. copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
  907. o.buf = o.buf[:len(o.buf)+x] // x is negative
  908. }
  909. // Encode the length in the reserved space.
  910. o.buf = o.buf[:iLen]
  911. o.EncodeVarint(uint64(lMsg))
  912. o.buf = o.buf[:len(o.buf)+lMsg]
  913. return state.err
  914. }
  915. // errorState maintains the first error that occurs and updates that error
  916. // with additional context.
  917. type errorState struct {
  918. err error
  919. }
  920. // shouldContinue reports whether encoding should continue upon encountering the
  921. // given error. If the error is RequiredNotSetError, shouldContinue returns true
  922. // and, if this is the first appearance of that error, remembers it for future
  923. // reporting.
  924. //
  925. // If prop is not nil, it may update any error with additional context about the
  926. // field with the error.
  927. func (s *errorState) shouldContinue(err error, prop *Properties) bool {
  928. // Ignore unset required fields.
  929. reqNotSet, ok := err.(*RequiredNotSetError)
  930. if !ok {
  931. return false
  932. }
  933. if s.err == nil {
  934. if prop != nil {
  935. err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field}
  936. }
  937. s.err = err
  938. }
  939. return true
  940. }