encode.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  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. keys := v.MapKeys()
  983. sort.Sort(mapKeys(keys))
  984. for _, key := range keys {
  985. val := v.MapIndex(key)
  986. keycopy.Set(key)
  987. valcopy.Set(val)
  988. o.buf = append(o.buf, p.tagcode...)
  989. if err := o.enc_len_thing(enc, &state); err != nil {
  990. return err
  991. }
  992. }
  993. return nil
  994. }
  995. func size_new_map(p *Properties, base structPointer) int {
  996. v := structPointer_Map(base, p.field, p.mtype).Elem() // map[K]V
  997. keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
  998. n := 0
  999. for _, key := range v.MapKeys() {
  1000. val := v.MapIndex(key)
  1001. keycopy.Set(key)
  1002. valcopy.Set(val)
  1003. // Tag codes are two bytes per map entry.
  1004. n += 2
  1005. n += p.mkeyprop.size(p.mkeyprop, keybase)
  1006. n += p.mvalprop.size(p.mvalprop, valbase)
  1007. }
  1008. return n
  1009. }
  1010. // mapEncodeScratch returns a new reflect.Value matching the map's value type,
  1011. // and a structPointer suitable for passing to an encoder or sizer.
  1012. func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) {
  1013. // Prepare addressable doubly-indirect placeholders for the key and value types.
  1014. // This is needed because the element-type encoders expect **T, but the map iteration produces T.
  1015. keycopy = reflect.New(mapType.Key()).Elem() // addressable K
  1016. keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K
  1017. keyptr.Set(keycopy.Addr()) //
  1018. keybase = toStructPointer(keyptr.Addr()) // **K
  1019. // Value types are more varied and require special handling.
  1020. switch mapType.Elem().Kind() {
  1021. case reflect.Slice:
  1022. // []byte
  1023. var dummy []byte
  1024. valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte
  1025. valbase = toStructPointer(valcopy.Addr())
  1026. case reflect.Ptr:
  1027. // message; the generated field type is map[K]*Msg (so V is *Msg),
  1028. // so we only need one level of indirection.
  1029. valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
  1030. valbase = toStructPointer(valcopy.Addr())
  1031. default:
  1032. // everything else
  1033. valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
  1034. valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V
  1035. valptr.Set(valcopy.Addr()) //
  1036. valbase = toStructPointer(valptr.Addr()) // **V
  1037. }
  1038. return
  1039. }
  1040. // Encode a struct.
  1041. func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error {
  1042. var state errorState
  1043. // Encode fields in tag order so that decoders may use optimizations
  1044. // that depend on the ordering.
  1045. // https://developers.google.com/protocol-buffers/docs/encoding#order
  1046. for _, i := range prop.order {
  1047. p := prop.Prop[i]
  1048. if p.enc != nil {
  1049. err := p.enc(o, p, base)
  1050. if err != nil {
  1051. if err == ErrNil {
  1052. if p.Required && state.err == nil {
  1053. state.err = &RequiredNotSetError{p.Name}
  1054. }
  1055. } else if !state.shouldContinue(err, p) {
  1056. return err
  1057. }
  1058. }
  1059. }
  1060. }
  1061. // Add unrecognized fields at the end.
  1062. if prop.unrecField.IsValid() {
  1063. v := *structPointer_Bytes(base, prop.unrecField)
  1064. if len(v) > 0 {
  1065. o.buf = append(o.buf, v...)
  1066. }
  1067. }
  1068. return state.err
  1069. }
  1070. func size_struct(prop *StructProperties, base structPointer) (n int) {
  1071. for _, i := range prop.order {
  1072. p := prop.Prop[i]
  1073. if p.size != nil {
  1074. n += p.size(p, base)
  1075. }
  1076. }
  1077. // Add unrecognized fields at the end.
  1078. if prop.unrecField.IsValid() {
  1079. v := *structPointer_Bytes(base, prop.unrecField)
  1080. n += len(v)
  1081. }
  1082. return
  1083. }
  1084. var zeroes [20]byte // longer than any conceivable sizeVarint
  1085. // Encode a struct, preceded by its encoded length (as a varint).
  1086. func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error {
  1087. return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state)
  1088. }
  1089. // Encode something, preceded by its encoded length (as a varint).
  1090. func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error {
  1091. iLen := len(o.buf)
  1092. o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length
  1093. iMsg := len(o.buf)
  1094. err := enc()
  1095. if err != nil && !state.shouldContinue(err, nil) {
  1096. return err
  1097. }
  1098. lMsg := len(o.buf) - iMsg
  1099. lLen := sizeVarint(uint64(lMsg))
  1100. switch x := lLen - (iMsg - iLen); {
  1101. case x > 0: // actual length is x bytes larger than the space we reserved
  1102. // Move msg x bytes right.
  1103. o.buf = append(o.buf, zeroes[:x]...)
  1104. copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
  1105. case x < 0: // actual length is x bytes smaller than the space we reserved
  1106. // Move msg x bytes left.
  1107. copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
  1108. o.buf = o.buf[:len(o.buf)+x] // x is negative
  1109. }
  1110. // Encode the length in the reserved space.
  1111. o.buf = o.buf[:iLen]
  1112. o.EncodeVarint(uint64(lMsg))
  1113. o.buf = o.buf[:len(o.buf)+lMsg]
  1114. return state.err
  1115. }
  1116. // errorState maintains the first error that occurs and updates that error
  1117. // with additional context.
  1118. type errorState struct {
  1119. err error
  1120. }
  1121. // shouldContinue reports whether encoding should continue upon encountering the
  1122. // given error. If the error is RequiredNotSetError, shouldContinue returns true
  1123. // and, if this is the first appearance of that error, remembers it for future
  1124. // reporting.
  1125. //
  1126. // If prop is not nil, it may update any error with additional context about the
  1127. // field with the error.
  1128. func (s *errorState) shouldContinue(err error, prop *Properties) bool {
  1129. // Ignore unset required fields.
  1130. reqNotSet, ok := err.(*RequiredNotSetError)
  1131. if !ok {
  1132. return false
  1133. }
  1134. if s.err == nil {
  1135. if prop != nil {
  1136. err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field}
  1137. }
  1138. s.err = err
  1139. }
  1140. return true
  1141. }