properties.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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. def_uint64 uint64
  170. enc encoder
  171. valEnc valueEncoder // set for bool and numeric types only
  172. field field
  173. tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType)
  174. tagbuf [8]byte
  175. stype reflect.Type // set for struct types only
  176. sstype reflect.Type // set for slices of structs types only
  177. ctype reflect.Type // set for custom types only
  178. sprop *StructProperties // set for struct types only
  179. isMarshaler bool
  180. isUnmarshaler bool
  181. mtype reflect.Type // set for map types only
  182. mkeyprop *Properties // set for map types only
  183. mvalprop *Properties // set for map types only
  184. size sizer
  185. valSize valueSizer // set for bool and numeric types only
  186. dec decoder
  187. valDec valueDecoder // set for bool and numeric types only
  188. // If this is a packable field, this will be the decoder for the packed version of the field.
  189. packedDec decoder
  190. }
  191. // String formats the properties in the protobuf struct field tag style.
  192. func (p *Properties) String() string {
  193. s := p.Wire
  194. s = ","
  195. s += strconv.Itoa(p.Tag)
  196. if p.Required {
  197. s += ",req"
  198. }
  199. if p.Optional {
  200. s += ",opt"
  201. }
  202. if p.Repeated {
  203. s += ",rep"
  204. }
  205. if p.Packed {
  206. s += ",packed"
  207. }
  208. s += ",name=" + p.OrigName
  209. if p.JSONName != p.OrigName {
  210. s += ",json=" + p.JSONName
  211. }
  212. if p.proto3 {
  213. s += ",proto3"
  214. }
  215. if p.oneof {
  216. s += ",oneof"
  217. }
  218. if len(p.Enum) > 0 {
  219. s += ",enum=" + p.Enum
  220. }
  221. if p.HasDefault {
  222. s += ",def=" + p.Default
  223. }
  224. return s
  225. }
  226. // Parse populates p by parsing a string in the protobuf struct field tag style.
  227. func (p *Properties) Parse(s string) {
  228. // "bytes,49,opt,name=foo,def=hello!"
  229. fields := strings.Split(s, ",") // breaks def=, but handled below.
  230. if len(fields) < 2 {
  231. fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s)
  232. return
  233. }
  234. p.Wire = fields[0]
  235. switch p.Wire {
  236. case "varint":
  237. p.WireType = WireVarint
  238. p.valEnc = (*Buffer).EncodeVarint
  239. p.valDec = (*Buffer).DecodeVarint
  240. p.valSize = sizeVarint
  241. case "fixed32":
  242. p.WireType = WireFixed32
  243. p.valEnc = (*Buffer).EncodeFixed32
  244. p.valDec = (*Buffer).DecodeFixed32
  245. p.valSize = sizeFixed32
  246. case "fixed64":
  247. p.WireType = WireFixed64
  248. p.valEnc = (*Buffer).EncodeFixed64
  249. p.valDec = (*Buffer).DecodeFixed64
  250. p.valSize = sizeFixed64
  251. case "zigzag32":
  252. p.WireType = WireVarint
  253. p.valEnc = (*Buffer).EncodeZigzag32
  254. p.valDec = (*Buffer).DecodeZigzag32
  255. p.valSize = sizeZigzag32
  256. case "zigzag64":
  257. p.WireType = WireVarint
  258. p.valEnc = (*Buffer).EncodeZigzag64
  259. p.valDec = (*Buffer).DecodeZigzag64
  260. p.valSize = sizeZigzag64
  261. case "bytes", "group":
  262. p.WireType = WireBytes
  263. // no numeric converter for non-numeric types
  264. default:
  265. fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s)
  266. return
  267. }
  268. var err error
  269. p.Tag, err = strconv.Atoi(fields[1])
  270. if err != nil {
  271. return
  272. }
  273. for i := 2; i < len(fields); i++ {
  274. f := fields[i]
  275. switch {
  276. case f == "req":
  277. p.Required = true
  278. case f == "opt":
  279. p.Optional = true
  280. case f == "rep":
  281. p.Repeated = true
  282. case f == "packed":
  283. p.Packed = true
  284. case strings.HasPrefix(f, "name="):
  285. p.OrigName = f[5:]
  286. case strings.HasPrefix(f, "json="):
  287. p.JSONName = f[5:]
  288. case strings.HasPrefix(f, "enum="):
  289. p.Enum = f[5:]
  290. case f == "proto3":
  291. p.proto3 = true
  292. case f == "oneof":
  293. p.oneof = true
  294. case strings.HasPrefix(f, "def="):
  295. p.HasDefault = true
  296. p.Default = f[4:] // rest of string
  297. if i+1 < len(fields) {
  298. // Commas aren't escaped, and def is always last.
  299. p.Default += "," + strings.Join(fields[i+1:], ",")
  300. break
  301. }
  302. case strings.HasPrefix(f, "embedded="):
  303. p.OrigName = strings.Split(f, "=")[1]
  304. case strings.HasPrefix(f, "customtype="):
  305. p.CustomType = strings.Split(f, "=")[1]
  306. }
  307. }
  308. }
  309. func logNoSliceEnc(t1, t2 reflect.Type) {
  310. fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2)
  311. }
  312. var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
  313. // Initialize the fields for encoding and decoding.
  314. func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) {
  315. p.enc = nil
  316. p.dec = nil
  317. p.size = nil
  318. if len(p.CustomType) > 0 {
  319. p.setCustomEncAndDec(typ)
  320. p.setTag(lockGetProp)
  321. return
  322. }
  323. switch t1 := typ; t1.Kind() {
  324. default:
  325. fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1)
  326. // proto3 scalar types
  327. case reflect.Bool:
  328. if p.proto3 {
  329. p.enc = (*Buffer).enc_proto3_bool
  330. p.dec = (*Buffer).dec_proto3_bool
  331. p.size = size_proto3_bool
  332. } else {
  333. p.enc = (*Buffer).enc_ref_bool
  334. p.dec = (*Buffer).dec_proto3_bool
  335. p.size = size_ref_bool
  336. }
  337. case reflect.Int32:
  338. if p.proto3 {
  339. p.enc = (*Buffer).enc_proto3_int32
  340. p.dec = (*Buffer).dec_proto3_int32
  341. p.size = size_proto3_int32
  342. } else {
  343. p.enc = (*Buffer).enc_ref_int32
  344. p.dec = (*Buffer).dec_proto3_int32
  345. p.size = size_ref_int32
  346. }
  347. case reflect.Uint32:
  348. if p.proto3 {
  349. p.enc = (*Buffer).enc_proto3_uint32
  350. p.dec = (*Buffer).dec_proto3_int32 // can reuse
  351. p.size = size_proto3_uint32
  352. } else {
  353. p.enc = (*Buffer).enc_ref_uint32
  354. p.dec = (*Buffer).dec_proto3_int32 // can reuse
  355. p.size = size_ref_uint32
  356. }
  357. case reflect.Int64, reflect.Uint64:
  358. if p.proto3 {
  359. p.enc = (*Buffer).enc_proto3_int64
  360. p.dec = (*Buffer).dec_proto3_int64
  361. p.size = size_proto3_int64
  362. } else {
  363. p.enc = (*Buffer).enc_ref_int64
  364. p.dec = (*Buffer).dec_proto3_int64
  365. p.size = size_ref_int64
  366. }
  367. case reflect.Float32:
  368. if p.proto3 {
  369. p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits
  370. p.dec = (*Buffer).dec_proto3_int32
  371. p.size = size_proto3_uint32
  372. } else {
  373. p.enc = (*Buffer).enc_ref_uint32 // can just treat them as bits
  374. p.dec = (*Buffer).dec_proto3_int32
  375. p.size = size_ref_uint32
  376. }
  377. case reflect.Float64:
  378. if p.proto3 {
  379. p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits
  380. p.dec = (*Buffer).dec_proto3_int64
  381. p.size = size_proto3_int64
  382. } else {
  383. p.enc = (*Buffer).enc_ref_int64 // can just treat them as bits
  384. p.dec = (*Buffer).dec_proto3_int64
  385. p.size = size_ref_int64
  386. }
  387. case reflect.String:
  388. if p.proto3 {
  389. p.enc = (*Buffer).enc_proto3_string
  390. p.dec = (*Buffer).dec_proto3_string
  391. p.size = size_proto3_string
  392. } else {
  393. p.enc = (*Buffer).enc_ref_string
  394. p.dec = (*Buffer).dec_proto3_string
  395. p.size = size_ref_string
  396. }
  397. case reflect.Struct:
  398. p.stype = typ
  399. p.isMarshaler = isMarshaler(typ)
  400. p.isUnmarshaler = isUnmarshaler(typ)
  401. if p.Wire == "bytes" {
  402. p.enc = (*Buffer).enc_ref_struct_message
  403. p.dec = (*Buffer).dec_ref_struct_message
  404. p.size = size_ref_struct_message
  405. } else {
  406. fmt.Fprintf(os.Stderr, "proto: no coders for struct %T\n", typ)
  407. }
  408. case reflect.Ptr:
  409. switch t2 := t1.Elem(); t2.Kind() {
  410. default:
  411. fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2)
  412. break
  413. case reflect.Bool:
  414. p.enc = (*Buffer).enc_bool
  415. p.dec = (*Buffer).dec_bool
  416. p.size = size_bool
  417. case reflect.Int32:
  418. p.enc = (*Buffer).enc_int32
  419. p.dec = (*Buffer).dec_int32
  420. p.size = size_int32
  421. case reflect.Uint32:
  422. p.enc = (*Buffer).enc_uint32
  423. p.dec = (*Buffer).dec_int32 // can reuse
  424. p.size = size_uint32
  425. case reflect.Int64, reflect.Uint64:
  426. p.enc = (*Buffer).enc_int64
  427. p.dec = (*Buffer).dec_int64
  428. p.size = size_int64
  429. case reflect.Float32:
  430. p.enc = (*Buffer).enc_uint32 // can just treat them as bits
  431. p.dec = (*Buffer).dec_int32
  432. p.size = size_uint32
  433. case reflect.Float64:
  434. p.enc = (*Buffer).enc_int64 // can just treat them as bits
  435. p.dec = (*Buffer).dec_int64
  436. p.size = size_int64
  437. case reflect.String:
  438. p.enc = (*Buffer).enc_string
  439. p.dec = (*Buffer).dec_string
  440. p.size = size_string
  441. case reflect.Struct:
  442. p.stype = t1.Elem()
  443. p.isMarshaler = isMarshaler(t1)
  444. p.isUnmarshaler = isUnmarshaler(t1)
  445. if p.Wire == "bytes" {
  446. p.enc = (*Buffer).enc_struct_message
  447. p.dec = (*Buffer).dec_struct_message
  448. p.size = size_struct_message
  449. } else {
  450. p.enc = (*Buffer).enc_struct_group
  451. p.dec = (*Buffer).dec_struct_group
  452. p.size = size_struct_group
  453. }
  454. }
  455. case reflect.Slice:
  456. switch t2 := t1.Elem(); t2.Kind() {
  457. default:
  458. logNoSliceEnc(t1, t2)
  459. break
  460. case reflect.Bool:
  461. if p.Packed {
  462. p.enc = (*Buffer).enc_slice_packed_bool
  463. p.size = size_slice_packed_bool
  464. } else {
  465. p.enc = (*Buffer).enc_slice_bool
  466. p.size = size_slice_bool
  467. }
  468. p.dec = (*Buffer).dec_slice_bool
  469. p.packedDec = (*Buffer).dec_slice_packed_bool
  470. case reflect.Int32:
  471. if p.Packed {
  472. p.enc = (*Buffer).enc_slice_packed_int32
  473. p.size = size_slice_packed_int32
  474. } else {
  475. p.enc = (*Buffer).enc_slice_int32
  476. p.size = size_slice_int32
  477. }
  478. p.dec = (*Buffer).dec_slice_int32
  479. p.packedDec = (*Buffer).dec_slice_packed_int32
  480. case reflect.Uint32:
  481. if p.Packed {
  482. p.enc = (*Buffer).enc_slice_packed_uint32
  483. p.size = size_slice_packed_uint32
  484. } else {
  485. p.enc = (*Buffer).enc_slice_uint32
  486. p.size = size_slice_uint32
  487. }
  488. p.dec = (*Buffer).dec_slice_int32
  489. p.packedDec = (*Buffer).dec_slice_packed_int32
  490. case reflect.Int64, reflect.Uint64:
  491. if p.Packed {
  492. p.enc = (*Buffer).enc_slice_packed_int64
  493. p.size = size_slice_packed_int64
  494. } else {
  495. p.enc = (*Buffer).enc_slice_int64
  496. p.size = size_slice_int64
  497. }
  498. p.dec = (*Buffer).dec_slice_int64
  499. p.packedDec = (*Buffer).dec_slice_packed_int64
  500. case reflect.Uint8:
  501. p.dec = (*Buffer).dec_slice_byte
  502. if p.proto3 {
  503. p.enc = (*Buffer).enc_proto3_slice_byte
  504. p.size = size_proto3_slice_byte
  505. } else {
  506. p.enc = (*Buffer).enc_slice_byte
  507. p.size = size_slice_byte
  508. }
  509. case reflect.Float32, reflect.Float64:
  510. switch t2.Bits() {
  511. case 32:
  512. // can just treat them as bits
  513. if p.Packed {
  514. p.enc = (*Buffer).enc_slice_packed_uint32
  515. p.size = size_slice_packed_uint32
  516. } else {
  517. p.enc = (*Buffer).enc_slice_uint32
  518. p.size = size_slice_uint32
  519. }
  520. p.dec = (*Buffer).dec_slice_int32
  521. p.packedDec = (*Buffer).dec_slice_packed_int32
  522. case 64:
  523. // can just treat them as bits
  524. if p.Packed {
  525. p.enc = (*Buffer).enc_slice_packed_int64
  526. p.size = size_slice_packed_int64
  527. } else {
  528. p.enc = (*Buffer).enc_slice_int64
  529. p.size = size_slice_int64
  530. }
  531. p.dec = (*Buffer).dec_slice_int64
  532. p.packedDec = (*Buffer).dec_slice_packed_int64
  533. default:
  534. logNoSliceEnc(t1, t2)
  535. break
  536. }
  537. case reflect.String:
  538. p.enc = (*Buffer).enc_slice_string
  539. p.dec = (*Buffer).dec_slice_string
  540. p.size = size_slice_string
  541. case reflect.Ptr:
  542. switch t3 := t2.Elem(); t3.Kind() {
  543. default:
  544. fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3)
  545. break
  546. case reflect.Struct:
  547. p.stype = t2.Elem()
  548. p.isMarshaler = isMarshaler(t2)
  549. p.isUnmarshaler = isUnmarshaler(t2)
  550. if p.Wire == "bytes" {
  551. p.enc = (*Buffer).enc_slice_struct_message
  552. p.dec = (*Buffer).dec_slice_struct_message
  553. p.size = size_slice_struct_message
  554. } else {
  555. p.enc = (*Buffer).enc_slice_struct_group
  556. p.dec = (*Buffer).dec_slice_struct_group
  557. p.size = size_slice_struct_group
  558. }
  559. }
  560. case reflect.Slice:
  561. switch t2.Elem().Kind() {
  562. default:
  563. fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem())
  564. break
  565. case reflect.Uint8:
  566. p.enc = (*Buffer).enc_slice_slice_byte
  567. p.dec = (*Buffer).dec_slice_slice_byte
  568. p.size = size_slice_slice_byte
  569. }
  570. case reflect.Struct:
  571. p.setSliceOfNonPointerStructs(t1)
  572. }
  573. case reflect.Map:
  574. p.enc = (*Buffer).enc_new_map
  575. p.dec = (*Buffer).dec_new_map
  576. p.size = size_new_map
  577. p.mtype = t1
  578. p.mkeyprop = &Properties{}
  579. p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
  580. p.mvalprop = &Properties{}
  581. vtype := p.mtype.Elem()
  582. if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice {
  583. // The value type is not a message (*T) or bytes ([]byte),
  584. // so we need encoders for the pointer to this type.
  585. vtype = reflect.PtrTo(vtype)
  586. }
  587. p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
  588. }
  589. p.setTag(lockGetProp)
  590. }
  591. func (p *Properties) setTag(lockGetProp bool) {
  592. // precalculate tag code
  593. wire := p.WireType
  594. if p.Packed {
  595. wire = WireBytes
  596. }
  597. x := uint32(p.Tag)<<3 | uint32(wire)
  598. i := 0
  599. for i = 0; x > 127; i++ {
  600. p.tagbuf[i] = 0x80 | uint8(x&0x7F)
  601. x >>= 7
  602. }
  603. p.tagbuf[i] = uint8(x)
  604. p.tagcode = p.tagbuf[0 : i+1]
  605. if p.stype != nil {
  606. if lockGetProp {
  607. p.sprop = GetProperties(p.stype)
  608. } else {
  609. p.sprop = getPropertiesLocked(p.stype)
  610. }
  611. }
  612. }
  613. var (
  614. marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
  615. unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
  616. )
  617. // isMarshaler reports whether type t implements Marshaler.
  618. func isMarshaler(t reflect.Type) bool {
  619. return t.Implements(marshalerType)
  620. }
  621. // isUnmarshaler reports whether type t implements Unmarshaler.
  622. func isUnmarshaler(t reflect.Type) bool {
  623. return t.Implements(unmarshalerType)
  624. }
  625. // Init populates the properties from a protocol buffer struct tag.
  626. func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
  627. p.init(typ, name, tag, f, true)
  628. }
  629. func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
  630. // "bytes,49,opt,def=hello!"
  631. p.Name = name
  632. p.OrigName = name
  633. if f != nil {
  634. p.field = toField(f)
  635. }
  636. if tag == "" {
  637. return
  638. }
  639. p.Parse(tag)
  640. p.setEncAndDec(typ, f, lockGetProp)
  641. }
  642. var (
  643. propertiesMu sync.RWMutex
  644. propertiesMap = make(map[reflect.Type]*StructProperties)
  645. )
  646. // GetProperties returns the list of properties for the type represented by t.
  647. // t must represent a generated struct type of a protocol message.
  648. func GetProperties(t reflect.Type) *StructProperties {
  649. if t.Kind() != reflect.Struct {
  650. panic("proto: type must have kind struct")
  651. }
  652. // Most calls to GetProperties in a long-running program will be
  653. // retrieving details for types we have seen before.
  654. propertiesMu.RLock()
  655. sprop, ok := propertiesMap[t]
  656. propertiesMu.RUnlock()
  657. if ok {
  658. if collectStats {
  659. stats.Chit++
  660. }
  661. return sprop
  662. }
  663. propertiesMu.Lock()
  664. sprop = getPropertiesLocked(t)
  665. propertiesMu.Unlock()
  666. return sprop
  667. }
  668. // getPropertiesLocked requires that propertiesMu is held.
  669. func getPropertiesLocked(t reflect.Type) *StructProperties {
  670. if prop, ok := propertiesMap[t]; ok {
  671. if collectStats {
  672. stats.Chit++
  673. }
  674. return prop
  675. }
  676. if collectStats {
  677. stats.Cmiss++
  678. }
  679. prop := new(StructProperties)
  680. // in case of recursive protos, fill this in now.
  681. propertiesMap[t] = prop
  682. // build properties
  683. prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) ||
  684. reflect.PtrTo(t).Implements(extendableProtoV1Type) ||
  685. reflect.PtrTo(t).Implements(extendableBytesType)
  686. prop.unrecField = invalidField
  687. prop.Prop = make([]*Properties, t.NumField())
  688. prop.order = make([]int, t.NumField())
  689. isOneofMessage := false
  690. for i := 0; i < t.NumField(); i++ {
  691. f := t.Field(i)
  692. p := new(Properties)
  693. name := f.Name
  694. p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
  695. if f.Name == "XXX_InternalExtensions" { // special case
  696. p.enc = (*Buffer).enc_exts
  697. p.dec = nil // not needed
  698. p.size = size_exts
  699. } else if f.Name == "XXX_extensions" { // special case
  700. if len(f.Tag.Get("protobuf")) > 0 {
  701. p.enc = (*Buffer).enc_ext_slice_byte
  702. p.dec = nil // not needed
  703. p.size = size_ext_slice_byte
  704. } else {
  705. p.enc = (*Buffer).enc_map
  706. p.dec = nil // not needed
  707. p.size = size_map
  708. }
  709. } else if f.Name == "XXX_unrecognized" { // special case
  710. prop.unrecField = toField(&f)
  711. }
  712. oneof := f.Tag.Get("protobuf_oneof") // special case
  713. if oneof != "" {
  714. isOneofMessage = true
  715. // Oneof fields don't use the traditional protobuf tag.
  716. p.OrigName = oneof
  717. }
  718. prop.Prop[i] = p
  719. prop.order[i] = i
  720. if debug {
  721. print(i, " ", f.Name, " ", t.String(), " ")
  722. if p.Tag > 0 {
  723. print(p.String())
  724. }
  725. print("\n")
  726. }
  727. if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && oneof == "" {
  728. fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]")
  729. }
  730. }
  731. // Re-order prop.order.
  732. sort.Sort(prop)
  733. type oneofMessage interface {
  734. XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
  735. }
  736. if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); isOneofMessage && ok {
  737. var oots []interface{}
  738. prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs()
  739. prop.stype = t
  740. // Interpret oneof metadata.
  741. prop.OneofTypes = make(map[string]*OneofProperties)
  742. for _, oot := range oots {
  743. oop := &OneofProperties{
  744. Type: reflect.ValueOf(oot).Type(), // *T
  745. Prop: new(Properties),
  746. }
  747. sft := oop.Type.Elem().Field(0)
  748. oop.Prop.Name = sft.Name
  749. oop.Prop.Parse(sft.Tag.Get("protobuf"))
  750. // There will be exactly one interface field that
  751. // this new value is assignable to.
  752. for i := 0; i < t.NumField(); i++ {
  753. f := t.Field(i)
  754. if f.Type.Kind() != reflect.Interface {
  755. continue
  756. }
  757. if !oop.Type.AssignableTo(f.Type) {
  758. continue
  759. }
  760. oop.Field = i
  761. break
  762. }
  763. prop.OneofTypes[oop.Prop.OrigName] = oop
  764. }
  765. }
  766. // build required counts
  767. // build tags
  768. reqCount := 0
  769. prop.decoderOrigNames = make(map[string]int)
  770. for i, p := range prop.Prop {
  771. if strings.HasPrefix(p.Name, "XXX_") {
  772. // Internal fields should not appear in tags/origNames maps.
  773. // They are handled specially when encoding and decoding.
  774. continue
  775. }
  776. if p.Required {
  777. reqCount++
  778. }
  779. prop.decoderTags.put(p.Tag, i)
  780. prop.decoderOrigNames[p.OrigName] = i
  781. }
  782. prop.reqCount = reqCount
  783. return prop
  784. }
  785. // Return the Properties object for the x[0]'th field of the structure.
  786. func propByIndex(t reflect.Type, x []int) *Properties {
  787. if len(x) != 1 {
  788. fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t)
  789. return nil
  790. }
  791. prop := GetProperties(t)
  792. return prop.Prop[x[0]]
  793. }
  794. // Get the address and type of a pointer to a struct from an interface.
  795. func getbase(pb Message) (t reflect.Type, b structPointer, err error) {
  796. if pb == nil {
  797. err = ErrNil
  798. return
  799. }
  800. // get the reflect type of the pointer to the struct.
  801. t = reflect.TypeOf(pb)
  802. // get the address of the struct.
  803. value := reflect.ValueOf(pb)
  804. b = toStructPointer(value)
  805. return
  806. }
  807. // A global registry of enum types.
  808. // The generated code will register the generated maps by calling RegisterEnum.
  809. var enumValueMaps = make(map[string]map[string]int32)
  810. var enumStringMaps = make(map[string]map[int32]string)
  811. // RegisterEnum is called from the generated code to install the enum descriptor
  812. // maps into the global table to aid parsing text format protocol buffers.
  813. func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
  814. if _, ok := enumValueMaps[typeName]; ok {
  815. panic("proto: duplicate enum registered: " + typeName)
  816. }
  817. enumValueMaps[typeName] = valueMap
  818. if _, ok := enumStringMaps[typeName]; ok {
  819. panic("proto: duplicate enum registered: " + typeName)
  820. }
  821. enumStringMaps[typeName] = unusedNameMap
  822. }
  823. // EnumValueMap returns the mapping from names to integers of the
  824. // enum type enumType, or a nil if not found.
  825. func EnumValueMap(enumType string) map[string]int32 {
  826. return enumValueMaps[enumType]
  827. }
  828. // A registry of all linked message types.
  829. // The string is a fully-qualified proto name ("pkg.Message").
  830. var (
  831. protoTypes = make(map[string]reflect.Type)
  832. revProtoTypes = make(map[reflect.Type]string)
  833. )
  834. // RegisterType is called from generated code and maps from the fully qualified
  835. // proto name to the type (pointer to struct) of the protocol buffer.
  836. func RegisterType(x Message, name string) {
  837. if _, ok := protoTypes[name]; ok {
  838. // TODO: Some day, make this a panic.
  839. log.Printf("proto: duplicate proto type registered: %s", name)
  840. return
  841. }
  842. t := reflect.TypeOf(x)
  843. protoTypes[name] = t
  844. revProtoTypes[t] = name
  845. }
  846. // MessageName returns the fully-qualified proto name for the given message type.
  847. func MessageName(x Message) string { return revProtoTypes[reflect.TypeOf(x)] }
  848. // MessageType returns the message type (pointer to struct) for a named message.
  849. func MessageType(name string) reflect.Type { return protoTypes[name] }
  850. // A registry of all linked proto files.
  851. var (
  852. protoFiles = make(map[string][]byte) // file name => fileDescriptor
  853. )
  854. // RegisterFile is called from generated code and maps from the
  855. // full file name of a .proto file to its compressed FileDescriptorProto.
  856. func RegisterFile(filename string, fileDescriptor []byte) {
  857. protoFiles[filename] = fileDescriptor
  858. }
  859. // FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
  860. func FileDescriptor(filename string) []byte { return protoFiles[filename] }