properties.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. // Protocol Buffers for Go with Gadgets
  2. //
  3. // Copyright (c) 2013, The GoGo Authors. All rights reserved.
  4. // http://github.com/gogo/protobuf
  5. //
  6. // Go support for Protocol Buffers - Google's data interchange format
  7. //
  8. // Copyright 2010 The Go Authors. All rights reserved.
  9. // https://github.com/golang/protobuf
  10. //
  11. // Redistribution and use in source and binary forms, with or without
  12. // modification, are permitted provided that the following conditions are
  13. // met:
  14. //
  15. // * Redistributions of source code must retain the above copyright
  16. // notice, this list of conditions and the following disclaimer.
  17. // * Redistributions in binary form must reproduce the above
  18. // copyright notice, this list of conditions and the following disclaimer
  19. // in the documentation and/or other materials provided with the
  20. // distribution.
  21. // * Neither the name of Google Inc. nor the names of its
  22. // contributors may be used to endorse or promote products derived from
  23. // this software without specific prior written permission.
  24. //
  25. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  26. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  27. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  28. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  29. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  30. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  31. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  32. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  33. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  34. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  35. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  36. package proto
  37. /*
  38. * Routines for encoding data into the wire format for protocol buffers.
  39. */
  40. import (
  41. "fmt"
  42. "log"
  43. "os"
  44. "reflect"
  45. "sort"
  46. "strconv"
  47. "strings"
  48. "sync"
  49. )
  50. const debug bool = false
  51. // Constants that identify the encoding of a value on the wire.
  52. const (
  53. WireVarint = 0
  54. WireFixed64 = 1
  55. WireBytes = 2
  56. WireStartGroup = 3
  57. WireEndGroup = 4
  58. WireFixed32 = 5
  59. )
  60. const startSize = 10 // initial slice/string sizes
  61. // Encoders are defined in encode.go
  62. // An encoder outputs the full representation of a field, including its
  63. // tag and encoder type.
  64. type encoder func(p *Buffer, prop *Properties, base structPointer) error
  65. // A valueEncoder encodes a single integer in a particular encoding.
  66. type valueEncoder func(o *Buffer, x uint64) error
  67. // Sizers are defined in encode.go
  68. // A sizer returns the encoded size of a field, including its tag and encoder
  69. // type.
  70. type sizer func(prop *Properties, base structPointer) int
  71. // A valueSizer returns the encoded size of a single integer in a particular
  72. // encoding.
  73. type valueSizer func(x uint64) int
  74. // Decoders are defined in decode.go
  75. // A decoder creates a value from its wire representation.
  76. // Unrecognized subelements are saved in unrec.
  77. type decoder func(p *Buffer, prop *Properties, base structPointer) error
  78. // A valueDecoder decodes a single integer in a particular encoding.
  79. type valueDecoder func(o *Buffer) (x uint64, err error)
  80. // A oneofMarshaler does the marshaling for all oneof fields in a message.
  81. type oneofMarshaler func(Message, *Buffer) error
  82. // A oneofUnmarshaler does the unmarshaling for a oneof field in a message.
  83. type oneofUnmarshaler func(Message, int, int, *Buffer) (bool, error)
  84. // A oneofSizer does the sizing for all oneof fields in a message.
  85. type oneofSizer func(Message) int
  86. // tagMap is an optimization over map[int]int for typical protocol buffer
  87. // use-cases. Encoded protocol buffers are often in tag order with small tag
  88. // numbers.
  89. type tagMap struct {
  90. fastTags []int
  91. slowTags map[int]int
  92. }
  93. // tagMapFastLimit is the upper bound on the tag number that will be stored in
  94. // the tagMap slice rather than its map.
  95. const tagMapFastLimit = 1024
  96. func (p *tagMap) get(t int) (int, bool) {
  97. if t > 0 && t < tagMapFastLimit {
  98. if t >= len(p.fastTags) {
  99. return 0, false
  100. }
  101. fi := p.fastTags[t]
  102. return fi, fi >= 0
  103. }
  104. fi, ok := p.slowTags[t]
  105. return fi, ok
  106. }
  107. func (p *tagMap) put(t int, fi int) {
  108. if t > 0 && t < tagMapFastLimit {
  109. for len(p.fastTags) < t+1 {
  110. p.fastTags = append(p.fastTags, -1)
  111. }
  112. p.fastTags[t] = fi
  113. return
  114. }
  115. if p.slowTags == nil {
  116. p.slowTags = make(map[int]int)
  117. }
  118. p.slowTags[t] = fi
  119. }
  120. // StructProperties represents properties for all the fields of a struct.
  121. // decoderTags and decoderOrigNames should only be used by the decoder.
  122. type StructProperties struct {
  123. Prop []*Properties // properties for each field
  124. reqCount int // required count
  125. decoderTags tagMap // map from proto tag to struct field number
  126. decoderOrigNames map[string]int // map from original name to struct field number
  127. order []int // list of struct field numbers in tag order
  128. unrecField field // field id of the XXX_unrecognized []byte field
  129. extendable bool // is this an extendable proto
  130. oneofMarshaler oneofMarshaler
  131. oneofUnmarshaler oneofUnmarshaler
  132. oneofSizer oneofSizer
  133. stype reflect.Type
  134. // OneofTypes contains information about the oneof fields in this message.
  135. // It is keyed by the original name of a field.
  136. OneofTypes map[string]*OneofProperties
  137. }
  138. // OneofProperties represents information about a specific field in a oneof.
  139. type OneofProperties struct {
  140. Type reflect.Type // pointer to generated struct type for this oneof field
  141. Field int // struct field number of the containing oneof in the message
  142. Prop *Properties
  143. }
  144. // Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
  145. // See encode.go, (*Buffer).enc_struct.
  146. func (sp *StructProperties) Len() int { return len(sp.order) }
  147. func (sp *StructProperties) Less(i, j int) bool {
  148. return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
  149. }
  150. func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }
  151. // Properties represents the protocol-specific behavior of a single struct field.
  152. type Properties struct {
  153. Name string // name of the field, for error messages
  154. OrigName string // original name before protocol compiler (always set)
  155. JSONName string // name to use for JSON; determined by protoc
  156. Wire string
  157. WireType int
  158. Tag int
  159. Required bool
  160. Optional bool
  161. Repeated bool
  162. Packed bool // relevant for repeated primitives only
  163. Enum string // set for enum types only
  164. proto3 bool // whether this is known to be a proto3 field; set for []byte only
  165. oneof bool // whether this is a oneof field
  166. Default string // default value
  167. HasDefault bool // whether an explicit default was provided
  168. CustomType string
  169. StdTime bool
  170. StdDuration bool
  171. enc encoder
  172. valEnc valueEncoder // set for bool and numeric types only
  173. field field
  174. tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType)
  175. tagbuf [8]byte
  176. stype reflect.Type // set for struct types only
  177. sstype reflect.Type // set for slices of structs types only
  178. ctype reflect.Type // set for custom types only
  179. sprop *StructProperties // set for struct types only
  180. isMarshaler bool
  181. isUnmarshaler bool
  182. mtype reflect.Type // set for map types only
  183. mkeyprop *Properties // set for map types only
  184. mvalprop *Properties // set for map types only
  185. size sizer
  186. valSize valueSizer // set for bool and numeric types only
  187. dec decoder
  188. valDec valueDecoder // set for bool and numeric types only
  189. // If this is a packable field, this will be the decoder for the packed version of the field.
  190. packedDec decoder
  191. }
  192. // String formats the properties in the protobuf struct field tag style.
  193. func (p *Properties) String() string {
  194. s := p.Wire
  195. s = ","
  196. s += strconv.Itoa(p.Tag)
  197. if p.Required {
  198. s += ",req"
  199. }
  200. if p.Optional {
  201. s += ",opt"
  202. }
  203. if p.Repeated {
  204. s += ",rep"
  205. }
  206. if p.Packed {
  207. s += ",packed"
  208. }
  209. s += ",name=" + p.OrigName
  210. if p.JSONName != p.OrigName {
  211. s += ",json=" + p.JSONName
  212. }
  213. if p.proto3 {
  214. s += ",proto3"
  215. }
  216. if p.oneof {
  217. s += ",oneof"
  218. }
  219. if len(p.Enum) > 0 {
  220. s += ",enum=" + p.Enum
  221. }
  222. if p.HasDefault {
  223. s += ",def=" + p.Default
  224. }
  225. return s
  226. }
  227. // Parse populates p by parsing a string in the protobuf struct field tag style.
  228. func (p *Properties) Parse(s string) {
  229. // "bytes,49,opt,name=foo,def=hello!"
  230. fields := strings.Split(s, ",") // breaks def=, but handled below.
  231. if len(fields) < 2 {
  232. fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s)
  233. return
  234. }
  235. p.Wire = fields[0]
  236. switch p.Wire {
  237. case "varint":
  238. p.WireType = WireVarint
  239. p.valEnc = (*Buffer).EncodeVarint
  240. p.valDec = (*Buffer).DecodeVarint
  241. p.valSize = sizeVarint
  242. case "fixed32":
  243. p.WireType = WireFixed32
  244. p.valEnc = (*Buffer).EncodeFixed32
  245. p.valDec = (*Buffer).DecodeFixed32
  246. p.valSize = sizeFixed32
  247. case "fixed64":
  248. p.WireType = WireFixed64
  249. p.valEnc = (*Buffer).EncodeFixed64
  250. p.valDec = (*Buffer).DecodeFixed64
  251. p.valSize = sizeFixed64
  252. case "zigzag32":
  253. p.WireType = WireVarint
  254. p.valEnc = (*Buffer).EncodeZigzag32
  255. p.valDec = (*Buffer).DecodeZigzag32
  256. p.valSize = sizeZigzag32
  257. case "zigzag64":
  258. p.WireType = WireVarint
  259. p.valEnc = (*Buffer).EncodeZigzag64
  260. p.valDec = (*Buffer).DecodeZigzag64
  261. p.valSize = sizeZigzag64
  262. case "bytes", "group":
  263. p.WireType = WireBytes
  264. // no numeric converter for non-numeric types
  265. default:
  266. fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s)
  267. return
  268. }
  269. var err error
  270. p.Tag, err = strconv.Atoi(fields[1])
  271. if err != nil {
  272. return
  273. }
  274. for i := 2; i < len(fields); i++ {
  275. f := fields[i]
  276. switch {
  277. case f == "req":
  278. p.Required = true
  279. case f == "opt":
  280. p.Optional = true
  281. case f == "rep":
  282. p.Repeated = true
  283. case f == "packed":
  284. p.Packed = true
  285. case strings.HasPrefix(f, "name="):
  286. p.OrigName = f[5:]
  287. case strings.HasPrefix(f, "json="):
  288. p.JSONName = f[5:]
  289. case strings.HasPrefix(f, "enum="):
  290. p.Enum = f[5:]
  291. case f == "proto3":
  292. p.proto3 = true
  293. case f == "oneof":
  294. p.oneof = true
  295. case strings.HasPrefix(f, "def="):
  296. p.HasDefault = true
  297. p.Default = f[4:] // rest of string
  298. if i+1 < len(fields) {
  299. // Commas aren't escaped, and def is always last.
  300. p.Default += "," + strings.Join(fields[i+1:], ",")
  301. break
  302. }
  303. case strings.HasPrefix(f, "embedded="):
  304. p.OrigName = strings.Split(f, "=")[1]
  305. case strings.HasPrefix(f, "customtype="):
  306. p.CustomType = strings.Split(f, "=")[1]
  307. case f == "stdtime":
  308. p.StdTime = true
  309. case f == "stdduration":
  310. p.StdDuration = true
  311. }
  312. }
  313. }
  314. func logNoSliceEnc(t1, t2 reflect.Type) {
  315. fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2)
  316. }
  317. var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
  318. // Initialize the fields for encoding and decoding.
  319. func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) {
  320. p.enc = nil
  321. p.dec = nil
  322. p.size = nil
  323. isMap := typ.Kind() == reflect.Map
  324. if len(p.CustomType) > 0 && !isMap {
  325. p.setCustomEncAndDec(typ)
  326. p.setTag(lockGetProp)
  327. return
  328. }
  329. if p.StdTime && !isMap {
  330. p.setTimeEncAndDec(typ)
  331. p.setTag(lockGetProp)
  332. return
  333. }
  334. if p.StdDuration && !isMap {
  335. p.setDurationEncAndDec(typ)
  336. p.setTag(lockGetProp)
  337. return
  338. }
  339. switch t1 := typ; t1.Kind() {
  340. default:
  341. fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1)
  342. // proto3 scalar types
  343. case reflect.Bool:
  344. if p.proto3 {
  345. p.enc = (*Buffer).enc_proto3_bool
  346. p.dec = (*Buffer).dec_proto3_bool
  347. p.size = size_proto3_bool
  348. } else {
  349. p.enc = (*Buffer).enc_ref_bool
  350. p.dec = (*Buffer).dec_proto3_bool
  351. p.size = size_ref_bool
  352. }
  353. case reflect.Int32:
  354. if p.proto3 {
  355. p.enc = (*Buffer).enc_proto3_int32
  356. p.dec = (*Buffer).dec_proto3_int32
  357. p.size = size_proto3_int32
  358. } else {
  359. p.enc = (*Buffer).enc_ref_int32
  360. p.dec = (*Buffer).dec_proto3_int32
  361. p.size = size_ref_int32
  362. }
  363. case reflect.Uint32:
  364. if p.proto3 {
  365. p.enc = (*Buffer).enc_proto3_uint32
  366. p.dec = (*Buffer).dec_proto3_int32 // can reuse
  367. p.size = size_proto3_uint32
  368. } else {
  369. p.enc = (*Buffer).enc_ref_uint32
  370. p.dec = (*Buffer).dec_proto3_int32 // can reuse
  371. p.size = size_ref_uint32
  372. }
  373. case reflect.Int64, reflect.Uint64:
  374. if p.proto3 {
  375. p.enc = (*Buffer).enc_proto3_int64
  376. p.dec = (*Buffer).dec_proto3_int64
  377. p.size = size_proto3_int64
  378. } else {
  379. p.enc = (*Buffer).enc_ref_int64
  380. p.dec = (*Buffer).dec_proto3_int64
  381. p.size = size_ref_int64
  382. }
  383. case reflect.Float32:
  384. if p.proto3 {
  385. p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits
  386. p.dec = (*Buffer).dec_proto3_int32
  387. p.size = size_proto3_uint32
  388. } else {
  389. p.enc = (*Buffer).enc_ref_uint32 // can just treat them as bits
  390. p.dec = (*Buffer).dec_proto3_int32
  391. p.size = size_ref_uint32
  392. }
  393. case reflect.Float64:
  394. if p.proto3 {
  395. p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits
  396. p.dec = (*Buffer).dec_proto3_int64
  397. p.size = size_proto3_int64
  398. } else {
  399. p.enc = (*Buffer).enc_ref_int64 // can just treat them as bits
  400. p.dec = (*Buffer).dec_proto3_int64
  401. p.size = size_ref_int64
  402. }
  403. case reflect.String:
  404. if p.proto3 {
  405. p.enc = (*Buffer).enc_proto3_string
  406. p.dec = (*Buffer).dec_proto3_string
  407. p.size = size_proto3_string
  408. } else {
  409. p.enc = (*Buffer).enc_ref_string
  410. p.dec = (*Buffer).dec_proto3_string
  411. p.size = size_ref_string
  412. }
  413. case reflect.Struct:
  414. p.stype = typ
  415. p.isMarshaler = isMarshaler(typ)
  416. p.isUnmarshaler = isUnmarshaler(typ)
  417. if p.Wire == "bytes" {
  418. p.enc = (*Buffer).enc_ref_struct_message
  419. p.dec = (*Buffer).dec_ref_struct_message
  420. p.size = size_ref_struct_message
  421. } else {
  422. fmt.Fprintf(os.Stderr, "proto: no coders for struct %T\n", typ)
  423. }
  424. case reflect.Ptr:
  425. switch t2 := t1.Elem(); t2.Kind() {
  426. default:
  427. fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2)
  428. break
  429. case reflect.Bool:
  430. p.enc = (*Buffer).enc_bool
  431. p.dec = (*Buffer).dec_bool
  432. p.size = size_bool
  433. case reflect.Int32:
  434. p.enc = (*Buffer).enc_int32
  435. p.dec = (*Buffer).dec_int32
  436. p.size = size_int32
  437. case reflect.Uint32:
  438. p.enc = (*Buffer).enc_uint32
  439. p.dec = (*Buffer).dec_int32 // can reuse
  440. p.size = size_uint32
  441. case reflect.Int64, reflect.Uint64:
  442. p.enc = (*Buffer).enc_int64
  443. p.dec = (*Buffer).dec_int64
  444. p.size = size_int64
  445. case reflect.Float32:
  446. p.enc = (*Buffer).enc_uint32 // can just treat them as bits
  447. p.dec = (*Buffer).dec_int32
  448. p.size = size_uint32
  449. case reflect.Float64:
  450. p.enc = (*Buffer).enc_int64 // can just treat them as bits
  451. p.dec = (*Buffer).dec_int64
  452. p.size = size_int64
  453. case reflect.String:
  454. p.enc = (*Buffer).enc_string
  455. p.dec = (*Buffer).dec_string
  456. p.size = size_string
  457. case reflect.Struct:
  458. p.stype = t1.Elem()
  459. p.isMarshaler = isMarshaler(t1)
  460. p.isUnmarshaler = isUnmarshaler(t1)
  461. if p.Wire == "bytes" {
  462. p.enc = (*Buffer).enc_struct_message
  463. p.dec = (*Buffer).dec_struct_message
  464. p.size = size_struct_message
  465. } else {
  466. p.enc = (*Buffer).enc_struct_group
  467. p.dec = (*Buffer).dec_struct_group
  468. p.size = size_struct_group
  469. }
  470. }
  471. case reflect.Slice:
  472. switch t2 := t1.Elem(); t2.Kind() {
  473. default:
  474. logNoSliceEnc(t1, t2)
  475. break
  476. case reflect.Bool:
  477. if p.Packed {
  478. p.enc = (*Buffer).enc_slice_packed_bool
  479. p.size = size_slice_packed_bool
  480. } else {
  481. p.enc = (*Buffer).enc_slice_bool
  482. p.size = size_slice_bool
  483. }
  484. p.dec = (*Buffer).dec_slice_bool
  485. p.packedDec = (*Buffer).dec_slice_packed_bool
  486. case reflect.Int32:
  487. if p.Packed {
  488. p.enc = (*Buffer).enc_slice_packed_int32
  489. p.size = size_slice_packed_int32
  490. } else {
  491. p.enc = (*Buffer).enc_slice_int32
  492. p.size = size_slice_int32
  493. }
  494. p.dec = (*Buffer).dec_slice_int32
  495. p.packedDec = (*Buffer).dec_slice_packed_int32
  496. case reflect.Uint32:
  497. if p.Packed {
  498. p.enc = (*Buffer).enc_slice_packed_uint32
  499. p.size = size_slice_packed_uint32
  500. } else {
  501. p.enc = (*Buffer).enc_slice_uint32
  502. p.size = size_slice_uint32
  503. }
  504. p.dec = (*Buffer).dec_slice_int32
  505. p.packedDec = (*Buffer).dec_slice_packed_int32
  506. case reflect.Int64, reflect.Uint64:
  507. if p.Packed {
  508. p.enc = (*Buffer).enc_slice_packed_int64
  509. p.size = size_slice_packed_int64
  510. } else {
  511. p.enc = (*Buffer).enc_slice_int64
  512. p.size = size_slice_int64
  513. }
  514. p.dec = (*Buffer).dec_slice_int64
  515. p.packedDec = (*Buffer).dec_slice_packed_int64
  516. case reflect.Uint8:
  517. p.dec = (*Buffer).dec_slice_byte
  518. if p.proto3 {
  519. p.enc = (*Buffer).enc_proto3_slice_byte
  520. p.size = size_proto3_slice_byte
  521. } else {
  522. p.enc = (*Buffer).enc_slice_byte
  523. p.size = size_slice_byte
  524. }
  525. case reflect.Float32, reflect.Float64:
  526. switch t2.Bits() {
  527. case 32:
  528. // can just treat them as bits
  529. if p.Packed {
  530. p.enc = (*Buffer).enc_slice_packed_uint32
  531. p.size = size_slice_packed_uint32
  532. } else {
  533. p.enc = (*Buffer).enc_slice_uint32
  534. p.size = size_slice_uint32
  535. }
  536. p.dec = (*Buffer).dec_slice_int32
  537. p.packedDec = (*Buffer).dec_slice_packed_int32
  538. case 64:
  539. // can just treat them as bits
  540. if p.Packed {
  541. p.enc = (*Buffer).enc_slice_packed_int64
  542. p.size = size_slice_packed_int64
  543. } else {
  544. p.enc = (*Buffer).enc_slice_int64
  545. p.size = size_slice_int64
  546. }
  547. p.dec = (*Buffer).dec_slice_int64
  548. p.packedDec = (*Buffer).dec_slice_packed_int64
  549. default:
  550. logNoSliceEnc(t1, t2)
  551. break
  552. }
  553. case reflect.String:
  554. p.enc = (*Buffer).enc_slice_string
  555. p.dec = (*Buffer).dec_slice_string
  556. p.size = size_slice_string
  557. case reflect.Ptr:
  558. switch t3 := t2.Elem(); t3.Kind() {
  559. default:
  560. fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3)
  561. break
  562. case reflect.Struct:
  563. p.stype = t2.Elem()
  564. p.isMarshaler = isMarshaler(t2)
  565. p.isUnmarshaler = isUnmarshaler(t2)
  566. if p.Wire == "bytes" {
  567. p.enc = (*Buffer).enc_slice_struct_message
  568. p.dec = (*Buffer).dec_slice_struct_message
  569. p.size = size_slice_struct_message
  570. } else {
  571. p.enc = (*Buffer).enc_slice_struct_group
  572. p.dec = (*Buffer).dec_slice_struct_group
  573. p.size = size_slice_struct_group
  574. }
  575. }
  576. case reflect.Slice:
  577. switch t2.Elem().Kind() {
  578. default:
  579. fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem())
  580. break
  581. case reflect.Uint8:
  582. p.enc = (*Buffer).enc_slice_slice_byte
  583. p.dec = (*Buffer).dec_slice_slice_byte
  584. p.size = size_slice_slice_byte
  585. }
  586. case reflect.Struct:
  587. p.setSliceOfNonPointerStructs(t1)
  588. }
  589. case reflect.Map:
  590. p.enc = (*Buffer).enc_new_map
  591. p.dec = (*Buffer).dec_new_map
  592. p.size = size_new_map
  593. p.mtype = t1
  594. p.mkeyprop = &Properties{}
  595. p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
  596. p.mvalprop = &Properties{}
  597. vtype := p.mtype.Elem()
  598. if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice {
  599. // The value type is not a message (*T) or bytes ([]byte),
  600. // so we need encoders for the pointer to this type.
  601. vtype = reflect.PtrTo(vtype)
  602. }
  603. p.mvalprop.CustomType = p.CustomType
  604. p.mvalprop.StdDuration = p.StdDuration
  605. p.mvalprop.StdTime = p.StdTime
  606. p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
  607. }
  608. p.setTag(lockGetProp)
  609. }
  610. func (p *Properties) setTag(lockGetProp bool) {
  611. // precalculate tag code
  612. wire := p.WireType
  613. if p.Packed {
  614. wire = WireBytes
  615. }
  616. x := uint32(p.Tag)<<3 | uint32(wire)
  617. i := 0
  618. for i = 0; x > 127; i++ {
  619. p.tagbuf[i] = 0x80 | uint8(x&0x7F)
  620. x >>= 7
  621. }
  622. p.tagbuf[i] = uint8(x)
  623. p.tagcode = p.tagbuf[0 : i+1]
  624. if p.stype != nil {
  625. if lockGetProp {
  626. p.sprop = GetProperties(p.stype)
  627. } else {
  628. p.sprop = getPropertiesLocked(p.stype)
  629. }
  630. }
  631. }
  632. var (
  633. marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
  634. unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
  635. )
  636. // isMarshaler reports whether type t implements Marshaler.
  637. func isMarshaler(t reflect.Type) bool {
  638. return t.Implements(marshalerType)
  639. }
  640. // isUnmarshaler reports whether type t implements Unmarshaler.
  641. func isUnmarshaler(t reflect.Type) bool {
  642. return t.Implements(unmarshalerType)
  643. }
  644. // Init populates the properties from a protocol buffer struct tag.
  645. func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
  646. p.init(typ, name, tag, f, true)
  647. }
  648. func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
  649. // "bytes,49,opt,def=hello!"
  650. p.Name = name
  651. p.OrigName = name
  652. if f != nil {
  653. p.field = toField(f)
  654. }
  655. if tag == "" {
  656. return
  657. }
  658. p.Parse(tag)
  659. p.setEncAndDec(typ, f, lockGetProp)
  660. }
  661. var (
  662. propertiesMu sync.RWMutex
  663. propertiesMap = make(map[reflect.Type]*StructProperties)
  664. )
  665. // GetProperties returns the list of properties for the type represented by t.
  666. // t must represent a generated struct type of a protocol message.
  667. func GetProperties(t reflect.Type) *StructProperties {
  668. if t.Kind() != reflect.Struct {
  669. panic("proto: type must have kind struct")
  670. }
  671. // Most calls to GetProperties in a long-running program will be
  672. // retrieving details for types we have seen before.
  673. propertiesMu.RLock()
  674. sprop, ok := propertiesMap[t]
  675. propertiesMu.RUnlock()
  676. if ok {
  677. if collectStats {
  678. stats.Chit++
  679. }
  680. return sprop
  681. }
  682. propertiesMu.Lock()
  683. sprop = getPropertiesLocked(t)
  684. propertiesMu.Unlock()
  685. return sprop
  686. }
  687. // getPropertiesLocked requires that propertiesMu is held.
  688. func getPropertiesLocked(t reflect.Type) *StructProperties {
  689. if prop, ok := propertiesMap[t]; ok {
  690. if collectStats {
  691. stats.Chit++
  692. }
  693. return prop
  694. }
  695. if collectStats {
  696. stats.Cmiss++
  697. }
  698. prop := new(StructProperties)
  699. // in case of recursive protos, fill this in now.
  700. propertiesMap[t] = prop
  701. // build properties
  702. prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) ||
  703. reflect.PtrTo(t).Implements(extendableProtoV1Type) ||
  704. reflect.PtrTo(t).Implements(extendableBytesType)
  705. prop.unrecField = invalidField
  706. prop.Prop = make([]*Properties, t.NumField())
  707. prop.order = make([]int, t.NumField())
  708. isOneofMessage := false
  709. for i := 0; i < t.NumField(); i++ {
  710. f := t.Field(i)
  711. p := new(Properties)
  712. name := f.Name
  713. p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
  714. if f.Name == "XXX_InternalExtensions" { // special case
  715. p.enc = (*Buffer).enc_exts
  716. p.dec = nil // not needed
  717. p.size = size_exts
  718. } else if f.Name == "XXX_extensions" { // special case
  719. if len(f.Tag.Get("protobuf")) > 0 {
  720. p.enc = (*Buffer).enc_ext_slice_byte
  721. p.dec = nil // not needed
  722. p.size = size_ext_slice_byte
  723. } else {
  724. p.enc = (*Buffer).enc_map
  725. p.dec = nil // not needed
  726. p.size = size_map
  727. }
  728. } else if f.Name == "XXX_unrecognized" { // special case
  729. prop.unrecField = toField(&f)
  730. }
  731. oneof := f.Tag.Get("protobuf_oneof") // special case
  732. if oneof != "" {
  733. isOneofMessage = true
  734. // Oneof fields don't use the traditional protobuf tag.
  735. p.OrigName = oneof
  736. }
  737. prop.Prop[i] = p
  738. prop.order[i] = i
  739. if debug {
  740. print(i, " ", f.Name, " ", t.String(), " ")
  741. if p.Tag > 0 {
  742. print(p.String())
  743. }
  744. print("\n")
  745. }
  746. if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && oneof == "" {
  747. fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]")
  748. }
  749. }
  750. // Re-order prop.order.
  751. sort.Sort(prop)
  752. type oneofMessage interface {
  753. XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
  754. }
  755. if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); isOneofMessage && ok {
  756. var oots []interface{}
  757. prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs()
  758. prop.stype = t
  759. // Interpret oneof metadata.
  760. prop.OneofTypes = make(map[string]*OneofProperties)
  761. for _, oot := range oots {
  762. oop := &OneofProperties{
  763. Type: reflect.ValueOf(oot).Type(), // *T
  764. Prop: new(Properties),
  765. }
  766. sft := oop.Type.Elem().Field(0)
  767. oop.Prop.Name = sft.Name
  768. oop.Prop.Parse(sft.Tag.Get("protobuf"))
  769. // There will be exactly one interface field that
  770. // this new value is assignable to.
  771. for i := 0; i < t.NumField(); i++ {
  772. f := t.Field(i)
  773. if f.Type.Kind() != reflect.Interface {
  774. continue
  775. }
  776. if !oop.Type.AssignableTo(f.Type) {
  777. continue
  778. }
  779. oop.Field = i
  780. break
  781. }
  782. prop.OneofTypes[oop.Prop.OrigName] = oop
  783. }
  784. }
  785. // build required counts
  786. // build tags
  787. reqCount := 0
  788. prop.decoderOrigNames = make(map[string]int)
  789. for i, p := range prop.Prop {
  790. if strings.HasPrefix(p.Name, "XXX_") {
  791. // Internal fields should not appear in tags/origNames maps.
  792. // They are handled specially when encoding and decoding.
  793. continue
  794. }
  795. if p.Required {
  796. reqCount++
  797. }
  798. prop.decoderTags.put(p.Tag, i)
  799. prop.decoderOrigNames[p.OrigName] = i
  800. }
  801. prop.reqCount = reqCount
  802. return prop
  803. }
  804. // Return the Properties object for the x[0]'th field of the structure.
  805. func propByIndex(t reflect.Type, x []int) *Properties {
  806. if len(x) != 1 {
  807. fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t)
  808. return nil
  809. }
  810. prop := GetProperties(t)
  811. return prop.Prop[x[0]]
  812. }
  813. // Get the address and type of a pointer to a struct from an interface.
  814. func getbase(pb Message) (t reflect.Type, b structPointer, err error) {
  815. if pb == nil {
  816. err = ErrNil
  817. return
  818. }
  819. // get the reflect type of the pointer to the struct.
  820. t = reflect.TypeOf(pb)
  821. // get the address of the struct.
  822. value := reflect.ValueOf(pb)
  823. b = toStructPointer(value)
  824. return
  825. }
  826. // A global registry of enum types.
  827. // The generated code will register the generated maps by calling RegisterEnum.
  828. var enumValueMaps = make(map[string]map[string]int32)
  829. var enumStringMaps = make(map[string]map[int32]string)
  830. // RegisterEnum is called from the generated code to install the enum descriptor
  831. // maps into the global table to aid parsing text format protocol buffers.
  832. func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
  833. if _, ok := enumValueMaps[typeName]; ok {
  834. panic("proto: duplicate enum registered: " + typeName)
  835. }
  836. enumValueMaps[typeName] = valueMap
  837. if _, ok := enumStringMaps[typeName]; ok {
  838. panic("proto: duplicate enum registered: " + typeName)
  839. }
  840. enumStringMaps[typeName] = unusedNameMap
  841. }
  842. // EnumValueMap returns the mapping from names to integers of the
  843. // enum type enumType, or a nil if not found.
  844. func EnumValueMap(enumType string) map[string]int32 {
  845. return enumValueMaps[enumType]
  846. }
  847. // A registry of all linked message types.
  848. // The string is a fully-qualified proto name ("pkg.Message").
  849. var (
  850. protoTypes = make(map[string]reflect.Type)
  851. revProtoTypes = make(map[reflect.Type]string)
  852. )
  853. // RegisterType is called from generated code and maps from the fully qualified
  854. // proto name to the type (pointer to struct) of the protocol buffer.
  855. func RegisterType(x Message, name string) {
  856. if _, ok := protoTypes[name]; ok {
  857. // TODO: Some day, make this a panic.
  858. log.Printf("proto: duplicate proto type registered: %s", name)
  859. return
  860. }
  861. t := reflect.TypeOf(x)
  862. protoTypes[name] = t
  863. revProtoTypes[t] = name
  864. }
  865. // MessageName returns the fully-qualified proto name for the given message type.
  866. func MessageName(x Message) string {
  867. type xname interface {
  868. XXX_MessageName() string
  869. }
  870. if m, ok := x.(xname); ok {
  871. return m.XXX_MessageName()
  872. }
  873. return revProtoTypes[reflect.TypeOf(x)]
  874. }
  875. // MessageType returns the message type (pointer to struct) for a named message.
  876. func MessageType(name string) reflect.Type { return protoTypes[name] }
  877. // A registry of all linked proto files.
  878. var (
  879. protoFiles = make(map[string][]byte) // file name => fileDescriptor
  880. )
  881. // RegisterFile is called from generated code and maps from the
  882. // full file name of a .proto file to its compressed FileDescriptorProto.
  883. func RegisterFile(filename string, fileDescriptor []byte) {
  884. protoFiles[filename] = fileDescriptor
  885. }
  886. // FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
  887. func FileDescriptor(filename string) []byte { return protoFiles[filename] }