properties.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. // Extensions for Protocol Buffers to create more go like structures.
  2. //
  3. // Copyright (c) 2013, Vastech SA (PTY) LTD. All rights reserved.
  4. // http://github.com/gogo/protobuf/gogoproto
  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.enc = (*Buffer).enc_slice_byte
  502. p.dec = (*Buffer).dec_slice_byte
  503. p.size = size_slice_byte
  504. // This is a []byte, which is either a bytes field,
  505. // or the value of a map field. In the latter case,
  506. // we always encode an empty []byte, so we should not
  507. // use the proto3 enc/size funcs.
  508. // f == nil iff this is the key/value of a map field.
  509. if p.proto3 && f != nil {
  510. p.enc = (*Buffer).enc_proto3_slice_byte
  511. p.size = size_proto3_slice_byte
  512. }
  513. case reflect.Float32, reflect.Float64:
  514. switch t2.Bits() {
  515. case 32:
  516. // can just treat them as bits
  517. if p.Packed {
  518. p.enc = (*Buffer).enc_slice_packed_uint32
  519. p.size = size_slice_packed_uint32
  520. } else {
  521. p.enc = (*Buffer).enc_slice_uint32
  522. p.size = size_slice_uint32
  523. }
  524. p.dec = (*Buffer).dec_slice_int32
  525. p.packedDec = (*Buffer).dec_slice_packed_int32
  526. case 64:
  527. // can just treat them as bits
  528. if p.Packed {
  529. p.enc = (*Buffer).enc_slice_packed_int64
  530. p.size = size_slice_packed_int64
  531. } else {
  532. p.enc = (*Buffer).enc_slice_int64
  533. p.size = size_slice_int64
  534. }
  535. p.dec = (*Buffer).dec_slice_int64
  536. p.packedDec = (*Buffer).dec_slice_packed_int64
  537. default:
  538. logNoSliceEnc(t1, t2)
  539. break
  540. }
  541. case reflect.String:
  542. p.enc = (*Buffer).enc_slice_string
  543. p.dec = (*Buffer).dec_slice_string
  544. p.size = size_slice_string
  545. case reflect.Ptr:
  546. switch t3 := t2.Elem(); t3.Kind() {
  547. default:
  548. fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3)
  549. break
  550. case reflect.Struct:
  551. p.stype = t2.Elem()
  552. p.isMarshaler = isMarshaler(t2)
  553. p.isUnmarshaler = isUnmarshaler(t2)
  554. if p.Wire == "bytes" {
  555. p.enc = (*Buffer).enc_slice_struct_message
  556. p.dec = (*Buffer).dec_slice_struct_message
  557. p.size = size_slice_struct_message
  558. } else {
  559. p.enc = (*Buffer).enc_slice_struct_group
  560. p.dec = (*Buffer).dec_slice_struct_group
  561. p.size = size_slice_struct_group
  562. }
  563. }
  564. case reflect.Slice:
  565. switch t2.Elem().Kind() {
  566. default:
  567. fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem())
  568. break
  569. case reflect.Uint8:
  570. p.enc = (*Buffer).enc_slice_slice_byte
  571. p.dec = (*Buffer).dec_slice_slice_byte
  572. p.size = size_slice_slice_byte
  573. }
  574. case reflect.Struct:
  575. p.setSliceOfNonPointerStructs(t1)
  576. }
  577. case reflect.Map:
  578. p.enc = (*Buffer).enc_new_map
  579. p.dec = (*Buffer).dec_new_map
  580. p.size = size_new_map
  581. p.mtype = t1
  582. p.mkeyprop = &Properties{}
  583. p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
  584. p.mvalprop = &Properties{}
  585. vtype := p.mtype.Elem()
  586. if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice {
  587. // The value type is not a message (*T) or bytes ([]byte),
  588. // so we need encoders for the pointer to this type.
  589. vtype = reflect.PtrTo(vtype)
  590. }
  591. p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
  592. }
  593. p.setTag(lockGetProp)
  594. }
  595. func (p *Properties) setTag(lockGetProp bool) {
  596. // precalculate tag code
  597. wire := p.WireType
  598. if p.Packed {
  599. wire = WireBytes
  600. }
  601. x := uint32(p.Tag)<<3 | uint32(wire)
  602. i := 0
  603. for i = 0; x > 127; i++ {
  604. p.tagbuf[i] = 0x80 | uint8(x&0x7F)
  605. x >>= 7
  606. }
  607. p.tagbuf[i] = uint8(x)
  608. p.tagcode = p.tagbuf[0 : i+1]
  609. if p.stype != nil {
  610. if lockGetProp {
  611. p.sprop = GetProperties(p.stype)
  612. } else {
  613. p.sprop = getPropertiesLocked(p.stype)
  614. }
  615. }
  616. }
  617. var (
  618. marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
  619. unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
  620. )
  621. // isMarshaler reports whether type t implements Marshaler.
  622. func isMarshaler(t reflect.Type) bool {
  623. return t.Implements(marshalerType)
  624. }
  625. // isUnmarshaler reports whether type t implements Unmarshaler.
  626. func isUnmarshaler(t reflect.Type) bool {
  627. return t.Implements(unmarshalerType)
  628. }
  629. // Init populates the properties from a protocol buffer struct tag.
  630. func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
  631. p.init(typ, name, tag, f, true)
  632. }
  633. func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
  634. // "bytes,49,opt,def=hello!"
  635. p.Name = name
  636. p.OrigName = name
  637. if f != nil {
  638. p.field = toField(f)
  639. }
  640. if tag == "" {
  641. return
  642. }
  643. p.Parse(tag)
  644. p.setEncAndDec(typ, f, lockGetProp)
  645. }
  646. var (
  647. propertiesMu sync.RWMutex
  648. propertiesMap = make(map[reflect.Type]*StructProperties)
  649. )
  650. // GetProperties returns the list of properties for the type represented by t.
  651. // t must represent a generated struct type of a protocol message.
  652. func GetProperties(t reflect.Type) *StructProperties {
  653. if t.Kind() != reflect.Struct {
  654. panic("proto: type must have kind struct")
  655. }
  656. // Most calls to GetProperties in a long-running program will be
  657. // retrieving details for types we have seen before.
  658. propertiesMu.RLock()
  659. sprop, ok := propertiesMap[t]
  660. propertiesMu.RUnlock()
  661. if ok {
  662. if collectStats {
  663. stats.Chit++
  664. }
  665. return sprop
  666. }
  667. propertiesMu.Lock()
  668. sprop = getPropertiesLocked(t)
  669. propertiesMu.Unlock()
  670. return sprop
  671. }
  672. // getPropertiesLocked requires that propertiesMu is held.
  673. func getPropertiesLocked(t reflect.Type) *StructProperties {
  674. if prop, ok := propertiesMap[t]; ok {
  675. if collectStats {
  676. stats.Chit++
  677. }
  678. return prop
  679. }
  680. if collectStats {
  681. stats.Cmiss++
  682. }
  683. prop := new(StructProperties)
  684. // in case of recursive protos, fill this in now.
  685. propertiesMap[t] = prop
  686. // build properties
  687. prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType)
  688. prop.unrecField = invalidField
  689. prop.Prop = make([]*Properties, t.NumField())
  690. prop.order = make([]int, t.NumField())
  691. isOneofMessage := false
  692. for i := 0; i < t.NumField(); i++ {
  693. f := t.Field(i)
  694. p := new(Properties)
  695. name := f.Name
  696. p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
  697. if f.Name == "XXX_extensions" { // special case
  698. if len(f.Tag.Get("protobuf")) > 0 {
  699. p.enc = (*Buffer).enc_ext_slice_byte
  700. p.dec = nil // not needed
  701. p.size = size_ext_slice_byte
  702. } else {
  703. p.enc = (*Buffer).enc_map
  704. p.dec = nil // not needed
  705. p.size = size_map
  706. }
  707. }
  708. if f.Name == "XXX_unrecognized" { // special case
  709. prop.unrecField = toField(&f)
  710. }
  711. oneof := f.Tag.Get("protobuf_oneof") != "" // special case
  712. if oneof {
  713. isOneofMessage = true
  714. }
  715. prop.Prop[i] = p
  716. prop.order[i] = i
  717. if debug {
  718. print(i, " ", f.Name, " ", t.String(), " ")
  719. if p.Tag > 0 {
  720. print(p.String())
  721. }
  722. print("\n")
  723. }
  724. if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && !oneof {
  725. fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]")
  726. }
  727. }
  728. // Re-order prop.order.
  729. sort.Sort(prop)
  730. type oneofMessage interface {
  731. XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
  732. }
  733. if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); isOneofMessage && ok {
  734. var oots []interface{}
  735. prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs()
  736. prop.stype = t
  737. // Interpret oneof metadata.
  738. prop.OneofTypes = make(map[string]*OneofProperties)
  739. for _, oot := range oots {
  740. oop := &OneofProperties{
  741. Type: reflect.ValueOf(oot).Type(), // *T
  742. Prop: new(Properties),
  743. }
  744. sft := oop.Type.Elem().Field(0)
  745. oop.Prop.Name = sft.Name
  746. oop.Prop.Parse(sft.Tag.Get("protobuf"))
  747. // There will be exactly one interface field that
  748. // this new value is assignable to.
  749. for i := 0; i < t.NumField(); i++ {
  750. f := t.Field(i)
  751. if f.Type.Kind() != reflect.Interface {
  752. continue
  753. }
  754. if !oop.Type.AssignableTo(f.Type) {
  755. continue
  756. }
  757. oop.Field = i
  758. break
  759. }
  760. prop.OneofTypes[oop.Prop.OrigName] = oop
  761. }
  762. }
  763. // build required counts
  764. // build tags
  765. reqCount := 0
  766. prop.decoderOrigNames = make(map[string]int)
  767. for i, p := range prop.Prop {
  768. if strings.HasPrefix(p.Name, "XXX_") {
  769. // Internal fields should not appear in tags/origNames maps.
  770. // They are handled specially when encoding and decoding.
  771. continue
  772. }
  773. if p.Required {
  774. reqCount++
  775. }
  776. prop.decoderTags.put(p.Tag, i)
  777. prop.decoderOrigNames[p.OrigName] = i
  778. }
  779. prop.reqCount = reqCount
  780. return prop
  781. }
  782. // Return the Properties object for the x[0]'th field of the structure.
  783. func propByIndex(t reflect.Type, x []int) *Properties {
  784. if len(x) != 1 {
  785. fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t)
  786. return nil
  787. }
  788. prop := GetProperties(t)
  789. return prop.Prop[x[0]]
  790. }
  791. // Get the address and type of a pointer to a struct from an interface.
  792. func getbase(pb Message) (t reflect.Type, b structPointer, err error) {
  793. if pb == nil {
  794. err = ErrNil
  795. return
  796. }
  797. // get the reflect type of the pointer to the struct.
  798. t = reflect.TypeOf(pb)
  799. // get the address of the struct.
  800. value := reflect.ValueOf(pb)
  801. b = toStructPointer(value)
  802. return
  803. }
  804. // A global registry of enum types.
  805. // The generated code will register the generated maps by calling RegisterEnum.
  806. var enumValueMaps = make(map[string]map[string]int32)
  807. var enumStringMaps = make(map[string]map[int32]string)
  808. // RegisterEnum is called from the generated code to install the enum descriptor
  809. // maps into the global table to aid parsing text format protocol buffers.
  810. func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
  811. if _, ok := enumValueMaps[typeName]; ok {
  812. panic("proto: duplicate enum registered: " + typeName)
  813. }
  814. enumValueMaps[typeName] = valueMap
  815. if _, ok := enumStringMaps[typeName]; ok {
  816. panic("proto: duplicate enum registered: " + typeName)
  817. }
  818. enumStringMaps[typeName] = unusedNameMap
  819. }
  820. // EnumValueMap returns the mapping from names to integers of the
  821. // enum type enumType, or a nil if not found.
  822. func EnumValueMap(enumType string) map[string]int32 {
  823. return enumValueMaps[enumType]
  824. }
  825. // A registry of all linked message types.
  826. // The string is a fully-qualified proto name ("pkg.Message").
  827. var (
  828. protoTypes = make(map[string]reflect.Type)
  829. revProtoTypes = make(map[reflect.Type]string)
  830. )
  831. // RegisterType is called from generated code and maps from the fully qualified
  832. // proto name to the type (pointer to struct) of the protocol buffer.
  833. func RegisterType(x Message, name string) {
  834. if _, ok := protoTypes[name]; ok {
  835. // TODO: Some day, make this a panic.
  836. log.Printf("proto: duplicate proto type registered: %s", name)
  837. return
  838. }
  839. t := reflect.TypeOf(x)
  840. protoTypes[name] = t
  841. revProtoTypes[t] = name
  842. }
  843. // MessageName returns the fully-qualified proto name for the given message type.
  844. func MessageName(x Message) string { return revProtoTypes[reflect.TypeOf(x)] }
  845. // MessageType returns the message type (pointer to struct) for a named message.
  846. func MessageType(name string) reflect.Type { return protoTypes[name] }