properties.go 24 KB

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