encode.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2010 The Go Authors. All rights reserved.
  4. // https://github.com/golang/protobuf
  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(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(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 (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error {
  265. v := *structPointer_BoolVal(base, p.field)
  266. if !v {
  267. return ErrNil
  268. }
  269. o.buf = append(o.buf, p.tagcode...)
  270. p.valEnc(o, 1)
  271. return nil
  272. }
  273. func size_bool(p *Properties, base structPointer) int {
  274. v := *structPointer_Bool(base, p.field)
  275. if v == nil {
  276. return 0
  277. }
  278. return len(p.tagcode) + 1 // each bool takes exactly one byte
  279. }
  280. func size_proto3_bool(p *Properties, base structPointer) int {
  281. v := *structPointer_BoolVal(base, p.field)
  282. if !v {
  283. return 0
  284. }
  285. return len(p.tagcode) + 1 // each bool takes exactly one byte
  286. }
  287. // Encode an int32.
  288. func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
  289. v := structPointer_Word32(base, p.field)
  290. if word32_IsNil(v) {
  291. return ErrNil
  292. }
  293. x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
  294. o.buf = append(o.buf, p.tagcode...)
  295. p.valEnc(o, uint64(x))
  296. return nil
  297. }
  298. func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error {
  299. v := structPointer_Word32Val(base, p.field)
  300. x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
  301. if x == 0 {
  302. return ErrNil
  303. }
  304. o.buf = append(o.buf, p.tagcode...)
  305. p.valEnc(o, uint64(x))
  306. return nil
  307. }
  308. func size_int32(p *Properties, base structPointer) (n int) {
  309. v := structPointer_Word32(base, p.field)
  310. if word32_IsNil(v) {
  311. return 0
  312. }
  313. x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
  314. n += len(p.tagcode)
  315. n += p.valSize(uint64(x))
  316. return
  317. }
  318. func size_proto3_int32(p *Properties, base structPointer) (n int) {
  319. v := structPointer_Word32Val(base, p.field)
  320. x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
  321. if x == 0 {
  322. return 0
  323. }
  324. n += len(p.tagcode)
  325. n += p.valSize(uint64(x))
  326. return
  327. }
  328. // Encode a uint32.
  329. // Exactly the same as int32, except for no sign extension.
  330. func (o *Buffer) enc_uint32(p *Properties, base structPointer) error {
  331. v := structPointer_Word32(base, p.field)
  332. if word32_IsNil(v) {
  333. return ErrNil
  334. }
  335. x := word32_Get(v)
  336. o.buf = append(o.buf, p.tagcode...)
  337. p.valEnc(o, uint64(x))
  338. return nil
  339. }
  340. func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error {
  341. v := structPointer_Word32Val(base, p.field)
  342. x := word32Val_Get(v)
  343. if x == 0 {
  344. return ErrNil
  345. }
  346. o.buf = append(o.buf, p.tagcode...)
  347. p.valEnc(o, uint64(x))
  348. return nil
  349. }
  350. func size_uint32(p *Properties, base structPointer) (n int) {
  351. v := structPointer_Word32(base, p.field)
  352. if word32_IsNil(v) {
  353. return 0
  354. }
  355. x := word32_Get(v)
  356. n += len(p.tagcode)
  357. n += p.valSize(uint64(x))
  358. return
  359. }
  360. func size_proto3_uint32(p *Properties, base structPointer) (n int) {
  361. v := structPointer_Word32Val(base, p.field)
  362. x := word32Val_Get(v)
  363. if x == 0 {
  364. return 0
  365. }
  366. n += len(p.tagcode)
  367. n += p.valSize(uint64(x))
  368. return
  369. }
  370. // Encode an int64.
  371. func (o *Buffer) enc_int64(p *Properties, base structPointer) error {
  372. v := structPointer_Word64(base, p.field)
  373. if word64_IsNil(v) {
  374. return ErrNil
  375. }
  376. x := word64_Get(v)
  377. o.buf = append(o.buf, p.tagcode...)
  378. p.valEnc(o, x)
  379. return nil
  380. }
  381. func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error {
  382. v := structPointer_Word64Val(base, p.field)
  383. x := word64Val_Get(v)
  384. if x == 0 {
  385. return ErrNil
  386. }
  387. o.buf = append(o.buf, p.tagcode...)
  388. p.valEnc(o, x)
  389. return nil
  390. }
  391. func size_int64(p *Properties, base structPointer) (n int) {
  392. v := structPointer_Word64(base, p.field)
  393. if word64_IsNil(v) {
  394. return 0
  395. }
  396. x := word64_Get(v)
  397. n += len(p.tagcode)
  398. n += p.valSize(x)
  399. return
  400. }
  401. func size_proto3_int64(p *Properties, base structPointer) (n int) {
  402. v := structPointer_Word64Val(base, p.field)
  403. x := word64Val_Get(v)
  404. if x == 0 {
  405. return 0
  406. }
  407. n += len(p.tagcode)
  408. n += p.valSize(x)
  409. return
  410. }
  411. // Encode a string.
  412. func (o *Buffer) enc_string(p *Properties, base structPointer) error {
  413. v := *structPointer_String(base, p.field)
  414. if v == nil {
  415. return ErrNil
  416. }
  417. x := *v
  418. o.buf = append(o.buf, p.tagcode...)
  419. o.EncodeStringBytes(x)
  420. return nil
  421. }
  422. func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error {
  423. v := *structPointer_StringVal(base, p.field)
  424. if v == "" {
  425. return ErrNil
  426. }
  427. o.buf = append(o.buf, p.tagcode...)
  428. o.EncodeStringBytes(v)
  429. return nil
  430. }
  431. func size_string(p *Properties, base structPointer) (n int) {
  432. v := *structPointer_String(base, p.field)
  433. if v == nil {
  434. return 0
  435. }
  436. x := *v
  437. n += len(p.tagcode)
  438. n += sizeStringBytes(x)
  439. return
  440. }
  441. func size_proto3_string(p *Properties, base structPointer) (n int) {
  442. v := *structPointer_StringVal(base, p.field)
  443. if v == "" {
  444. return 0
  445. }
  446. n += len(p.tagcode)
  447. n += sizeStringBytes(v)
  448. return
  449. }
  450. // All protocol buffer fields are nillable, but be careful.
  451. func isNil(v reflect.Value) bool {
  452. switch v.Kind() {
  453. case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
  454. return v.IsNil()
  455. }
  456. return false
  457. }
  458. // Encode a message struct.
  459. func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
  460. var state errorState
  461. structp := structPointer_GetStructPointer(base, p.field)
  462. if structPointer_IsNil(structp) {
  463. return ErrNil
  464. }
  465. // Can the object marshal itself?
  466. if p.isMarshaler {
  467. m := structPointer_Interface(structp, p.stype).(Marshaler)
  468. data, err := m.Marshal()
  469. if err != nil && !state.shouldContinue(err, nil) {
  470. return err
  471. }
  472. o.buf = append(o.buf, p.tagcode...)
  473. o.EncodeRawBytes(data)
  474. return nil
  475. }
  476. o.buf = append(o.buf, p.tagcode...)
  477. return o.enc_len_struct(p.sprop, structp, &state)
  478. }
  479. func size_struct_message(p *Properties, base structPointer) int {
  480. structp := structPointer_GetStructPointer(base, p.field)
  481. if structPointer_IsNil(structp) {
  482. return 0
  483. }
  484. // Can the object marshal itself?
  485. if p.isMarshaler {
  486. m := structPointer_Interface(structp, p.stype).(Marshaler)
  487. data, _ := m.Marshal()
  488. n0 := len(p.tagcode)
  489. n1 := sizeRawBytes(data)
  490. return n0 + n1
  491. }
  492. n0 := len(p.tagcode)
  493. n1 := size_struct(p.sprop, structp)
  494. n2 := sizeVarint(uint64(n1)) // size of encoded length
  495. return n0 + n1 + n2
  496. }
  497. // Encode a group struct.
  498. func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error {
  499. var state errorState
  500. b := structPointer_GetStructPointer(base, p.field)
  501. if structPointer_IsNil(b) {
  502. return ErrNil
  503. }
  504. o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
  505. err := o.enc_struct(p.sprop, b)
  506. if err != nil && !state.shouldContinue(err, nil) {
  507. return err
  508. }
  509. o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
  510. return state.err
  511. }
  512. func size_struct_group(p *Properties, base structPointer) (n int) {
  513. b := structPointer_GetStructPointer(base, p.field)
  514. if structPointer_IsNil(b) {
  515. return 0
  516. }
  517. n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup))
  518. n += size_struct(p.sprop, b)
  519. n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup))
  520. return
  521. }
  522. // Encode a slice of bools ([]bool).
  523. func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
  524. s := *structPointer_BoolSlice(base, p.field)
  525. l := len(s)
  526. if l == 0 {
  527. return ErrNil
  528. }
  529. for _, x := range s {
  530. o.buf = append(o.buf, p.tagcode...)
  531. v := uint64(0)
  532. if x {
  533. v = 1
  534. }
  535. p.valEnc(o, v)
  536. }
  537. return nil
  538. }
  539. func size_slice_bool(p *Properties, base structPointer) int {
  540. s := *structPointer_BoolSlice(base, p.field)
  541. l := len(s)
  542. if l == 0 {
  543. return 0
  544. }
  545. return l * (len(p.tagcode) + 1) // each bool takes exactly one byte
  546. }
  547. // Encode a slice of bools ([]bool) in packed format.
  548. func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error {
  549. s := *structPointer_BoolSlice(base, p.field)
  550. l := len(s)
  551. if l == 0 {
  552. return ErrNil
  553. }
  554. o.buf = append(o.buf, p.tagcode...)
  555. o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
  556. for _, x := range s {
  557. v := uint64(0)
  558. if x {
  559. v = 1
  560. }
  561. p.valEnc(o, v)
  562. }
  563. return nil
  564. }
  565. func size_slice_packed_bool(p *Properties, base structPointer) (n int) {
  566. s := *structPointer_BoolSlice(base, p.field)
  567. l := len(s)
  568. if l == 0 {
  569. return 0
  570. }
  571. n += len(p.tagcode)
  572. n += sizeVarint(uint64(l))
  573. n += l // each bool takes exactly one byte
  574. return
  575. }
  576. // Encode a slice of bytes ([]byte).
  577. func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
  578. s := *structPointer_Bytes(base, p.field)
  579. if s == nil {
  580. return ErrNil
  581. }
  582. o.buf = append(o.buf, p.tagcode...)
  583. o.EncodeRawBytes(s)
  584. return nil
  585. }
  586. func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error {
  587. s := *structPointer_Bytes(base, p.field)
  588. if len(s) == 0 {
  589. return ErrNil
  590. }
  591. o.buf = append(o.buf, p.tagcode...)
  592. o.EncodeRawBytes(s)
  593. return nil
  594. }
  595. func size_slice_byte(p *Properties, base structPointer) (n int) {
  596. s := *structPointer_Bytes(base, p.field)
  597. if s == nil {
  598. return 0
  599. }
  600. n += len(p.tagcode)
  601. n += sizeRawBytes(s)
  602. return
  603. }
  604. func size_proto3_slice_byte(p *Properties, base structPointer) (n int) {
  605. s := *structPointer_Bytes(base, p.field)
  606. if len(s) == 0 {
  607. return 0
  608. }
  609. n += len(p.tagcode)
  610. n += sizeRawBytes(s)
  611. return
  612. }
  613. // Encode a slice of int32s ([]int32).
  614. func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error {
  615. s := structPointer_Word32Slice(base, p.field)
  616. l := s.Len()
  617. if l == 0 {
  618. return ErrNil
  619. }
  620. for i := 0; i < l; i++ {
  621. o.buf = append(o.buf, p.tagcode...)
  622. x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
  623. p.valEnc(o, uint64(x))
  624. }
  625. return nil
  626. }
  627. func size_slice_int32(p *Properties, base structPointer) (n int) {
  628. s := structPointer_Word32Slice(base, p.field)
  629. l := s.Len()
  630. if l == 0 {
  631. return 0
  632. }
  633. for i := 0; i < l; i++ {
  634. n += len(p.tagcode)
  635. x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
  636. n += p.valSize(uint64(x))
  637. }
  638. return
  639. }
  640. // Encode a slice of int32s ([]int32) in packed format.
  641. func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error {
  642. s := structPointer_Word32Slice(base, p.field)
  643. l := s.Len()
  644. if l == 0 {
  645. return ErrNil
  646. }
  647. // TODO: Reuse a Buffer.
  648. buf := NewBuffer(nil)
  649. for i := 0; i < l; i++ {
  650. x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
  651. p.valEnc(buf, uint64(x))
  652. }
  653. o.buf = append(o.buf, p.tagcode...)
  654. o.EncodeVarint(uint64(len(buf.buf)))
  655. o.buf = append(o.buf, buf.buf...)
  656. return nil
  657. }
  658. func size_slice_packed_int32(p *Properties, base structPointer) (n int) {
  659. s := structPointer_Word32Slice(base, p.field)
  660. l := s.Len()
  661. if l == 0 {
  662. return 0
  663. }
  664. var bufSize int
  665. for i := 0; i < l; i++ {
  666. x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
  667. bufSize += p.valSize(uint64(x))
  668. }
  669. n += len(p.tagcode)
  670. n += sizeVarint(uint64(bufSize))
  671. n += bufSize
  672. return
  673. }
  674. // Encode a slice of uint32s ([]uint32).
  675. // Exactly the same as int32, except for no sign extension.
  676. func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error {
  677. s := structPointer_Word32Slice(base, p.field)
  678. l := s.Len()
  679. if l == 0 {
  680. return ErrNil
  681. }
  682. for i := 0; i < l; i++ {
  683. o.buf = append(o.buf, p.tagcode...)
  684. x := s.Index(i)
  685. p.valEnc(o, uint64(x))
  686. }
  687. return nil
  688. }
  689. func size_slice_uint32(p *Properties, base structPointer) (n int) {
  690. s := structPointer_Word32Slice(base, p.field)
  691. l := s.Len()
  692. if l == 0 {
  693. return 0
  694. }
  695. for i := 0; i < l; i++ {
  696. n += len(p.tagcode)
  697. x := s.Index(i)
  698. n += p.valSize(uint64(x))
  699. }
  700. return
  701. }
  702. // Encode a slice of uint32s ([]uint32) in packed format.
  703. // Exactly the same as int32, except for no sign extension.
  704. func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error {
  705. s := structPointer_Word32Slice(base, p.field)
  706. l := s.Len()
  707. if l == 0 {
  708. return ErrNil
  709. }
  710. // TODO: Reuse a Buffer.
  711. buf := NewBuffer(nil)
  712. for i := 0; i < l; i++ {
  713. p.valEnc(buf, uint64(s.Index(i)))
  714. }
  715. o.buf = append(o.buf, p.tagcode...)
  716. o.EncodeVarint(uint64(len(buf.buf)))
  717. o.buf = append(o.buf, buf.buf...)
  718. return nil
  719. }
  720. func size_slice_packed_uint32(p *Properties, base structPointer) (n int) {
  721. s := structPointer_Word32Slice(base, p.field)
  722. l := s.Len()
  723. if l == 0 {
  724. return 0
  725. }
  726. var bufSize int
  727. for i := 0; i < l; i++ {
  728. bufSize += p.valSize(uint64(s.Index(i)))
  729. }
  730. n += len(p.tagcode)
  731. n += sizeVarint(uint64(bufSize))
  732. n += bufSize
  733. return
  734. }
  735. // Encode a slice of int64s ([]int64).
  736. func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error {
  737. s := structPointer_Word64Slice(base, p.field)
  738. l := s.Len()
  739. if l == 0 {
  740. return ErrNil
  741. }
  742. for i := 0; i < l; i++ {
  743. o.buf = append(o.buf, p.tagcode...)
  744. p.valEnc(o, s.Index(i))
  745. }
  746. return nil
  747. }
  748. func size_slice_int64(p *Properties, base structPointer) (n int) {
  749. s := structPointer_Word64Slice(base, p.field)
  750. l := s.Len()
  751. if l == 0 {
  752. return 0
  753. }
  754. for i := 0; i < l; i++ {
  755. n += len(p.tagcode)
  756. n += p.valSize(s.Index(i))
  757. }
  758. return
  759. }
  760. // Encode a slice of int64s ([]int64) in packed format.
  761. func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error {
  762. s := structPointer_Word64Slice(base, p.field)
  763. l := s.Len()
  764. if l == 0 {
  765. return ErrNil
  766. }
  767. // TODO: Reuse a Buffer.
  768. buf := NewBuffer(nil)
  769. for i := 0; i < l; i++ {
  770. p.valEnc(buf, s.Index(i))
  771. }
  772. o.buf = append(o.buf, p.tagcode...)
  773. o.EncodeVarint(uint64(len(buf.buf)))
  774. o.buf = append(o.buf, buf.buf...)
  775. return nil
  776. }
  777. func size_slice_packed_int64(p *Properties, base structPointer) (n int) {
  778. s := structPointer_Word64Slice(base, p.field)
  779. l := s.Len()
  780. if l == 0 {
  781. return 0
  782. }
  783. var bufSize int
  784. for i := 0; i < l; i++ {
  785. bufSize += p.valSize(s.Index(i))
  786. }
  787. n += len(p.tagcode)
  788. n += sizeVarint(uint64(bufSize))
  789. n += bufSize
  790. return
  791. }
  792. // Encode a slice of slice of bytes ([][]byte).
  793. func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
  794. ss := *structPointer_BytesSlice(base, p.field)
  795. l := len(ss)
  796. if l == 0 {
  797. return ErrNil
  798. }
  799. for i := 0; i < l; i++ {
  800. o.buf = append(o.buf, p.tagcode...)
  801. o.EncodeRawBytes(ss[i])
  802. }
  803. return nil
  804. }
  805. func size_slice_slice_byte(p *Properties, base structPointer) (n int) {
  806. ss := *structPointer_BytesSlice(base, p.field)
  807. l := len(ss)
  808. if l == 0 {
  809. return 0
  810. }
  811. n += l * len(p.tagcode)
  812. for i := 0; i < l; i++ {
  813. n += sizeRawBytes(ss[i])
  814. }
  815. return
  816. }
  817. // Encode a slice of strings ([]string).
  818. func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
  819. ss := *structPointer_StringSlice(base, p.field)
  820. l := len(ss)
  821. for i := 0; i < l; i++ {
  822. o.buf = append(o.buf, p.tagcode...)
  823. o.EncodeStringBytes(ss[i])
  824. }
  825. return nil
  826. }
  827. func size_slice_string(p *Properties, base structPointer) (n int) {
  828. ss := *structPointer_StringSlice(base, p.field)
  829. l := len(ss)
  830. n += l * len(p.tagcode)
  831. for i := 0; i < l; i++ {
  832. n += sizeStringBytes(ss[i])
  833. }
  834. return
  835. }
  836. // Encode a slice of message structs ([]*struct).
  837. func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error {
  838. var state errorState
  839. s := structPointer_StructPointerSlice(base, p.field)
  840. l := s.Len()
  841. for i := 0; i < l; i++ {
  842. structp := s.Index(i)
  843. if structPointer_IsNil(structp) {
  844. return ErrRepeatedHasNil
  845. }
  846. // Can the object marshal itself?
  847. if p.isMarshaler {
  848. m := structPointer_Interface(structp, p.stype).(Marshaler)
  849. data, err := m.Marshal()
  850. if err != nil && !state.shouldContinue(err, nil) {
  851. return err
  852. }
  853. o.buf = append(o.buf, p.tagcode...)
  854. o.EncodeRawBytes(data)
  855. continue
  856. }
  857. o.buf = append(o.buf, p.tagcode...)
  858. err := o.enc_len_struct(p.sprop, structp, &state)
  859. if err != nil && !state.shouldContinue(err, nil) {
  860. if err == ErrNil {
  861. return ErrRepeatedHasNil
  862. }
  863. return err
  864. }
  865. }
  866. return state.err
  867. }
  868. func size_slice_struct_message(p *Properties, base structPointer) (n int) {
  869. s := structPointer_StructPointerSlice(base, p.field)
  870. l := s.Len()
  871. n += l * len(p.tagcode)
  872. for i := 0; i < l; i++ {
  873. structp := s.Index(i)
  874. if structPointer_IsNil(structp) {
  875. return // return the size up to this point
  876. }
  877. // Can the object marshal itself?
  878. if p.isMarshaler {
  879. m := structPointer_Interface(structp, p.stype).(Marshaler)
  880. data, _ := m.Marshal()
  881. n += len(p.tagcode)
  882. n += sizeRawBytes(data)
  883. continue
  884. }
  885. n0 := size_struct(p.sprop, structp)
  886. n1 := sizeVarint(uint64(n0)) // size of encoded length
  887. n += n0 + n1
  888. }
  889. return
  890. }
  891. // Encode a slice of group structs ([]*struct).
  892. func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error {
  893. var state errorState
  894. s := structPointer_StructPointerSlice(base, p.field)
  895. l := s.Len()
  896. for i := 0; i < l; i++ {
  897. b := s.Index(i)
  898. if structPointer_IsNil(b) {
  899. return ErrRepeatedHasNil
  900. }
  901. o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
  902. err := o.enc_struct(p.sprop, b)
  903. if err != nil && !state.shouldContinue(err, nil) {
  904. if err == ErrNil {
  905. return ErrRepeatedHasNil
  906. }
  907. return err
  908. }
  909. o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
  910. }
  911. return state.err
  912. }
  913. func size_slice_struct_group(p *Properties, base structPointer) (n int) {
  914. s := structPointer_StructPointerSlice(base, p.field)
  915. l := s.Len()
  916. n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup))
  917. n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup))
  918. for i := 0; i < l; i++ {
  919. b := s.Index(i)
  920. if structPointer_IsNil(b) {
  921. return // return size up to this point
  922. }
  923. n += size_struct(p.sprop, b)
  924. }
  925. return
  926. }
  927. // Encode an extension map.
  928. func (o *Buffer) enc_map(p *Properties, base structPointer) error {
  929. v := *structPointer_ExtMap(base, p.field)
  930. if err := encodeExtensionMap(v); err != nil {
  931. return err
  932. }
  933. // Fast-path for common cases: zero or one extensions.
  934. if len(v) <= 1 {
  935. for _, e := range v {
  936. o.buf = append(o.buf, e.enc...)
  937. }
  938. return nil
  939. }
  940. // Sort keys to provide a deterministic encoding.
  941. keys := make([]int, 0, len(v))
  942. for k := range v {
  943. keys = append(keys, int(k))
  944. }
  945. sort.Ints(keys)
  946. for _, k := range keys {
  947. o.buf = append(o.buf, v[int32(k)].enc...)
  948. }
  949. return nil
  950. }
  951. func size_map(p *Properties, base structPointer) int {
  952. v := *structPointer_ExtMap(base, p.field)
  953. return sizeExtensionMap(v)
  954. }
  955. // Encode a map field.
  956. func (o *Buffer) enc_new_map(p *Properties, base structPointer) error {
  957. var state errorState // XXX: or do we need to plumb this through?
  958. /*
  959. A map defined as
  960. map<key_type, value_type> map_field = N;
  961. is encoded in the same way as
  962. message MapFieldEntry {
  963. key_type key = 1;
  964. value_type value = 2;
  965. }
  966. repeated MapFieldEntry map_field = N;
  967. */
  968. v := structPointer_Map(base, p.field, p.mtype).Elem() // map[K]V
  969. if v.Len() == 0 {
  970. return nil
  971. }
  972. keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
  973. enc := func() error {
  974. if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil {
  975. return err
  976. }
  977. if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil {
  978. return err
  979. }
  980. return nil
  981. }
  982. for _, key := range v.MapKeys() {
  983. val := v.MapIndex(key)
  984. keycopy.Set(key)
  985. valcopy.Set(val)
  986. o.buf = append(o.buf, p.tagcode...)
  987. if err := o.enc_len_thing(enc, &state); err != nil {
  988. return err
  989. }
  990. }
  991. return nil
  992. }
  993. func size_new_map(p *Properties, base structPointer) int {
  994. v := structPointer_Map(base, p.field, p.mtype).Elem() // map[K]V
  995. keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
  996. n := 0
  997. for _, key := range v.MapKeys() {
  998. val := v.MapIndex(key)
  999. keycopy.Set(key)
  1000. valcopy.Set(val)
  1001. // Tag codes are two bytes per map entry.
  1002. n += 2
  1003. n += p.mkeyprop.size(p.mkeyprop, keybase)
  1004. n += p.mvalprop.size(p.mvalprop, valbase)
  1005. }
  1006. return n
  1007. }
  1008. // mapEncodeScratch returns a new reflect.Value matching the map's value type,
  1009. // and a structPointer suitable for passing to an encoder or sizer.
  1010. func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) {
  1011. // Prepare addressable doubly-indirect placeholders for the key and value types.
  1012. // This is needed because the element-type encoders expect **T, but the map iteration produces T.
  1013. keycopy = reflect.New(mapType.Key()).Elem() // addressable K
  1014. keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K
  1015. keyptr.Set(keycopy.Addr()) //
  1016. keybase = toStructPointer(keyptr.Addr()) // **K
  1017. // Value types are more varied and require special handling.
  1018. switch mapType.Elem().Kind() {
  1019. case reflect.Slice:
  1020. // []byte
  1021. var dummy []byte
  1022. valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte
  1023. valbase = toStructPointer(valcopy.Addr())
  1024. case reflect.Ptr:
  1025. // message; the generated field type is map[K]*Msg (so V is *Msg),
  1026. // so we only need one level of indirection.
  1027. valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
  1028. valbase = toStructPointer(valcopy.Addr())
  1029. default:
  1030. // everything else
  1031. valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
  1032. valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V
  1033. valptr.Set(valcopy.Addr()) //
  1034. valbase = toStructPointer(valptr.Addr()) // **V
  1035. }
  1036. return
  1037. }
  1038. // Encode a struct.
  1039. func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error {
  1040. var state errorState
  1041. // Encode fields in tag order so that decoders may use optimizations
  1042. // that depend on the ordering.
  1043. // https://developers.google.com/protocol-buffers/docs/encoding#order
  1044. for _, i := range prop.order {
  1045. p := prop.Prop[i]
  1046. if p.enc != nil {
  1047. err := p.enc(o, p, base)
  1048. if err != nil {
  1049. if err == ErrNil {
  1050. if p.Required && state.err == nil {
  1051. state.err = &RequiredNotSetError{p.Name}
  1052. }
  1053. } else if !state.shouldContinue(err, p) {
  1054. return err
  1055. }
  1056. }
  1057. }
  1058. }
  1059. // Add unrecognized fields at the end.
  1060. if prop.unrecField.IsValid() {
  1061. v := *structPointer_Bytes(base, prop.unrecField)
  1062. if len(v) > 0 {
  1063. o.buf = append(o.buf, v...)
  1064. }
  1065. }
  1066. return state.err
  1067. }
  1068. func size_struct(prop *StructProperties, base structPointer) (n int) {
  1069. for _, i := range prop.order {
  1070. p := prop.Prop[i]
  1071. if p.size != nil {
  1072. n += p.size(p, base)
  1073. }
  1074. }
  1075. // Add unrecognized fields at the end.
  1076. if prop.unrecField.IsValid() {
  1077. v := *structPointer_Bytes(base, prop.unrecField)
  1078. n += len(v)
  1079. }
  1080. return
  1081. }
  1082. var zeroes [20]byte // longer than any conceivable sizeVarint
  1083. // Encode a struct, preceded by its encoded length (as a varint).
  1084. func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error {
  1085. return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state)
  1086. }
  1087. // Encode something, preceded by its encoded length (as a varint).
  1088. func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error {
  1089. iLen := len(o.buf)
  1090. o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length
  1091. iMsg := len(o.buf)
  1092. err := enc()
  1093. if err != nil && !state.shouldContinue(err, nil) {
  1094. return err
  1095. }
  1096. lMsg := len(o.buf) - iMsg
  1097. lLen := sizeVarint(uint64(lMsg))
  1098. switch x := lLen - (iMsg - iLen); {
  1099. case x > 0: // actual length is x bytes larger than the space we reserved
  1100. // Move msg x bytes right.
  1101. o.buf = append(o.buf, zeroes[:x]...)
  1102. copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
  1103. case x < 0: // actual length is x bytes smaller than the space we reserved
  1104. // Move msg x bytes left.
  1105. copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
  1106. o.buf = o.buf[:len(o.buf)+x] // x is negative
  1107. }
  1108. // Encode the length in the reserved space.
  1109. o.buf = o.buf[:iLen]
  1110. o.EncodeVarint(uint64(lMsg))
  1111. o.buf = o.buf[:len(o.buf)+lMsg]
  1112. return state.err
  1113. }
  1114. // errorState maintains the first error that occurs and updates that error
  1115. // with additional context.
  1116. type errorState struct {
  1117. err error
  1118. }
  1119. // shouldContinue reports whether encoding should continue upon encountering the
  1120. // given error. If the error is RequiredNotSetError, shouldContinue returns true
  1121. // and, if this is the first appearance of that error, remembers it for future
  1122. // reporting.
  1123. //
  1124. // If prop is not nil, it may update any error with additional context about the
  1125. // field with the error.
  1126. func (s *errorState) shouldContinue(err error, prop *Properties) bool {
  1127. // Ignore unset required fields.
  1128. reqNotSet, ok := err.(*RequiredNotSetError)
  1129. if !ok {
  1130. return false
  1131. }
  1132. if s.err == nil {
  1133. if prop != nil {
  1134. err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field}
  1135. }
  1136. s.err = err
  1137. }
  1138. return true
  1139. }