properties.go 25 KB

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