lib.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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. /*
  32. Package proto converts data structures to and from the wire format of
  33. protocol buffers. It works in concert with the Go source code generated
  34. for .proto files by the protocol compiler.
  35. A summary of the properties of the protocol buffer interface
  36. for a protocol buffer variable v:
  37. - Names are turned from camel_case to CamelCase for export.
  38. - There are no methods on v to set fields; just treat
  39. them as structure fields.
  40. - There are getters that return a field's value if set,
  41. and return the field's default value if unset.
  42. The getters work even if the receiver is a nil message.
  43. - The zero value for a struct is its correct initialization state.
  44. All desired fields must be set before marshaling.
  45. - A Reset() method will restore a protobuf struct to its zero state.
  46. - Non-repeated fields are pointers to the values; nil means unset.
  47. That is, optional or required field int32 f becomes F *int32.
  48. - Repeated fields are slices.
  49. - Helper functions are available to aid the setting of fields.
  50. msg.Foo = proto.String("hello") // set field
  51. - Constants are defined to hold the default values of all fields that
  52. have them. They have the form Default_StructName_FieldName.
  53. Because the getter methods handle defaulted values,
  54. direct use of these constants should be rare.
  55. - Enums are given type names and maps from names to values.
  56. Enum values are prefixed by the enclosing message's name, or by the
  57. enum's type name if it is a top-level enum. Enum types have a String
  58. method, and a Enum method to assist in message construction.
  59. - Nested messages, groups and enums have type names prefixed with the name of
  60. the surrounding message type.
  61. - Extensions are given descriptor names that start with E_,
  62. followed by an underscore-delimited list of the nested messages
  63. that contain it (if any) followed by the CamelCased name of the
  64. extension field itself. HasExtension, ClearExtension, GetExtension
  65. and SetExtension are functions for manipulating extensions.
  66. - Oneof field sets are given a single field in their message,
  67. with distinguished wrapper types for each possible field value.
  68. - Marshal and Unmarshal are functions to encode and decode the wire format.
  69. The simplest way to describe this is to see an example.
  70. Given file test.proto, containing
  71. package example;
  72. enum FOO { X = 17; }
  73. message Test {
  74. required string label = 1;
  75. optional int32 type = 2 [default=77];
  76. repeated int64 reps = 3;
  77. optional group OptionalGroup = 4 {
  78. required string RequiredField = 5;
  79. }
  80. oneof union {
  81. int32 number = 6;
  82. string name = 7;
  83. }
  84. }
  85. The resulting file, test.pb.go, is:
  86. package example
  87. import proto "github.com/gogo/protobuf/proto"
  88. import math "math"
  89. type FOO int32
  90. const (
  91. FOO_X FOO = 17
  92. )
  93. var FOO_name = map[int32]string{
  94. 17: "X",
  95. }
  96. var FOO_value = map[string]int32{
  97. "X": 17,
  98. }
  99. func (x FOO) Enum() *FOO {
  100. p := new(FOO)
  101. *p = x
  102. return p
  103. }
  104. func (x FOO) String() string {
  105. return proto.EnumName(FOO_name, int32(x))
  106. }
  107. func (x *FOO) UnmarshalJSON(data []byte) error {
  108. value, err := proto.UnmarshalJSONEnum(FOO_value, data)
  109. if err != nil {
  110. return err
  111. }
  112. *x = FOO(value)
  113. return nil
  114. }
  115. type Test struct {
  116. Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
  117. Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
  118. Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
  119. Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
  120. // Types that are valid to be assigned to Union:
  121. // *Test_Number
  122. // *Test_Name
  123. Union isTest_Union `protobuf_oneof:"union"`
  124. XXX_unrecognized []byte `json:"-"`
  125. }
  126. func (m *Test) Reset() { *m = Test{} }
  127. func (m *Test) String() string { return proto.CompactTextString(m) }
  128. func (*Test) ProtoMessage() {}
  129. type isTest_Union interface {
  130. isTest_Union()
  131. }
  132. type Test_Number struct {
  133. Number int32 `protobuf:"varint,6,opt,name=number"`
  134. }
  135. type Test_Name struct {
  136. Name string `protobuf:"bytes,7,opt,name=name"`
  137. }
  138. func (*Test_Number) isTest_Union() {}
  139. func (*Test_Name) isTest_Union() {}
  140. func (m *Test) GetUnion() isTest_Union {
  141. if m != nil {
  142. return m.Union
  143. }
  144. return nil
  145. }
  146. const Default_Test_Type int32 = 77
  147. func (m *Test) GetLabel() string {
  148. if m != nil && m.Label != nil {
  149. return *m.Label
  150. }
  151. return ""
  152. }
  153. func (m *Test) GetType() int32 {
  154. if m != nil && m.Type != nil {
  155. return *m.Type
  156. }
  157. return Default_Test_Type
  158. }
  159. func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
  160. if m != nil {
  161. return m.Optionalgroup
  162. }
  163. return nil
  164. }
  165. type Test_OptionalGroup struct {
  166. RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
  167. }
  168. func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }
  169. func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
  170. func (m *Test_OptionalGroup) GetRequiredField() string {
  171. if m != nil && m.RequiredField != nil {
  172. return *m.RequiredField
  173. }
  174. return ""
  175. }
  176. func (m *Test) GetNumber() int32 {
  177. if x, ok := m.GetUnion().(*Test_Number); ok {
  178. return x.Number
  179. }
  180. return 0
  181. }
  182. func (m *Test) GetName() string {
  183. if x, ok := m.GetUnion().(*Test_Name); ok {
  184. return x.Name
  185. }
  186. return ""
  187. }
  188. func init() {
  189. proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
  190. }
  191. To create and play with a Test object:
  192. package main
  193. import (
  194. "log"
  195. "github.com/gogo/protobuf/proto"
  196. pb "./example.pb"
  197. )
  198. func main() {
  199. test := &pb.Test{
  200. Label: proto.String("hello"),
  201. Type: proto.Int32(17),
  202. Optionalgroup: &pb.Test_OptionalGroup{
  203. RequiredField: proto.String("good bye"),
  204. },
  205. Union: &pb.Test_Name{"fred"},
  206. }
  207. data, err := proto.Marshal(test)
  208. if err != nil {
  209. log.Fatal("marshaling error: ", err)
  210. }
  211. newTest := &pb.Test{}
  212. err = proto.Unmarshal(data, newTest)
  213. if err != nil {
  214. log.Fatal("unmarshaling error: ", err)
  215. }
  216. // Now test and newTest contain the same data.
  217. if test.GetLabel() != newTest.GetLabel() {
  218. log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
  219. }
  220. // Use a type switch to determine which oneof was set.
  221. switch u := test.Union.(type) {
  222. case *pb.Test_Number: // u.Number contains the number.
  223. case *pb.Test_Name: // u.Name contains the string.
  224. }
  225. // etc.
  226. }
  227. */
  228. package proto
  229. import (
  230. "encoding/json"
  231. "fmt"
  232. "log"
  233. "reflect"
  234. "sort"
  235. "strconv"
  236. "sync"
  237. )
  238. // Message is implemented by generated protocol buffer messages.
  239. type Message interface {
  240. Reset()
  241. String() string
  242. ProtoMessage()
  243. }
  244. // Stats records allocation details about the protocol buffer encoders
  245. // and decoders. Useful for tuning the library itself.
  246. type Stats struct {
  247. Emalloc uint64 // mallocs in encode
  248. Dmalloc uint64 // mallocs in decode
  249. Encode uint64 // number of encodes
  250. Decode uint64 // number of decodes
  251. Chit uint64 // number of cache hits
  252. Cmiss uint64 // number of cache misses
  253. Size uint64 // number of sizes
  254. }
  255. // Set to true to enable stats collection.
  256. const collectStats = false
  257. var stats Stats
  258. // GetStats returns a copy of the global Stats structure.
  259. func GetStats() Stats { return stats }
  260. // A Buffer is a buffer manager for marshaling and unmarshaling
  261. // protocol buffers. It may be reused between invocations to
  262. // reduce memory usage. It is not necessary to use a Buffer;
  263. // the global functions Marshal and Unmarshal create a
  264. // temporary Buffer and are fine for most applications.
  265. type Buffer struct {
  266. buf []byte // encode/decode byte stream
  267. index int // write point
  268. // pools of basic types to amortize allocation.
  269. bools []bool
  270. uint32s []uint32
  271. uint64s []uint64
  272. // extra pools, only used with pointer_reflect.go
  273. int32s []int32
  274. int64s []int64
  275. float32s []float32
  276. float64s []float64
  277. }
  278. // NewBuffer allocates a new Buffer and initializes its internal data to
  279. // the contents of the argument slice.
  280. func NewBuffer(e []byte) *Buffer {
  281. return &Buffer{buf: e}
  282. }
  283. // Reset resets the Buffer, ready for marshaling a new protocol buffer.
  284. func (p *Buffer) Reset() {
  285. p.buf = p.buf[0:0] // for reading/writing
  286. p.index = 0 // for reading
  287. }
  288. // SetBuf replaces the internal buffer with the slice,
  289. // ready for unmarshaling the contents of the slice.
  290. func (p *Buffer) SetBuf(s []byte) {
  291. p.buf = s
  292. p.index = 0
  293. }
  294. // Bytes returns the contents of the Buffer.
  295. func (p *Buffer) Bytes() []byte { return p.buf }
  296. /*
  297. * Helper routines for simplifying the creation of optional fields of basic type.
  298. */
  299. // Bool is a helper routine that allocates a new bool value
  300. // to store v and returns a pointer to it.
  301. func Bool(v bool) *bool {
  302. return &v
  303. }
  304. // Int32 is a helper routine that allocates a new int32 value
  305. // to store v and returns a pointer to it.
  306. func Int32(v int32) *int32 {
  307. return &v
  308. }
  309. // Int is a helper routine that allocates a new int32 value
  310. // to store v and returns a pointer to it, but unlike Int32
  311. // its argument value is an int.
  312. func Int(v int) *int32 {
  313. p := new(int32)
  314. *p = int32(v)
  315. return p
  316. }
  317. // Int64 is a helper routine that allocates a new int64 value
  318. // to store v and returns a pointer to it.
  319. func Int64(v int64) *int64 {
  320. return &v
  321. }
  322. // Float32 is a helper routine that allocates a new float32 value
  323. // to store v and returns a pointer to it.
  324. func Float32(v float32) *float32 {
  325. return &v
  326. }
  327. // Float64 is a helper routine that allocates a new float64 value
  328. // to store v and returns a pointer to it.
  329. func Float64(v float64) *float64 {
  330. return &v
  331. }
  332. // Uint32 is a helper routine that allocates a new uint32 value
  333. // to store v and returns a pointer to it.
  334. func Uint32(v uint32) *uint32 {
  335. return &v
  336. }
  337. // Uint64 is a helper routine that allocates a new uint64 value
  338. // to store v and returns a pointer to it.
  339. func Uint64(v uint64) *uint64 {
  340. return &v
  341. }
  342. // String is a helper routine that allocates a new string value
  343. // to store v and returns a pointer to it.
  344. func String(v string) *string {
  345. return &v
  346. }
  347. // EnumName is a helper function to simplify printing protocol buffer enums
  348. // by name. Given an enum map and a value, it returns a useful string.
  349. func EnumName(m map[int32]string, v int32) string {
  350. s, ok := m[v]
  351. if ok {
  352. return s
  353. }
  354. return strconv.Itoa(int(v))
  355. }
  356. // UnmarshalJSONEnum is a helper function to simplify recovering enum int values
  357. // from their JSON-encoded representation. Given a map from the enum's symbolic
  358. // names to its int values, and a byte buffer containing the JSON-encoded
  359. // value, it returns an int32 that can be cast to the enum type by the caller.
  360. //
  361. // The function can deal with both JSON representations, numeric and symbolic.
  362. func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
  363. if data[0] == '"' {
  364. // New style: enums are strings.
  365. var repr string
  366. if err := json.Unmarshal(data, &repr); err != nil {
  367. return -1, err
  368. }
  369. val, ok := m[repr]
  370. if !ok {
  371. return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
  372. }
  373. return val, nil
  374. }
  375. // Old style: enums are ints.
  376. var val int32
  377. if err := json.Unmarshal(data, &val); err != nil {
  378. return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
  379. }
  380. return val, nil
  381. }
  382. // DebugPrint dumps the encoded data in b in a debugging format with a header
  383. // including the string s. Used in testing but made available for general debugging.
  384. func (p *Buffer) DebugPrint(s string, b []byte) {
  385. var u uint64
  386. obuf := p.buf
  387. index := p.index
  388. p.buf = b
  389. p.index = 0
  390. depth := 0
  391. fmt.Printf("\n--- %s ---\n", s)
  392. out:
  393. for {
  394. for i := 0; i < depth; i++ {
  395. fmt.Print(" ")
  396. }
  397. index := p.index
  398. if index == len(p.buf) {
  399. break
  400. }
  401. op, err := p.DecodeVarint()
  402. if err != nil {
  403. fmt.Printf("%3d: fetching op err %v\n", index, err)
  404. break out
  405. }
  406. tag := op >> 3
  407. wire := op & 7
  408. switch wire {
  409. default:
  410. fmt.Printf("%3d: t=%3d unknown wire=%d\n",
  411. index, tag, wire)
  412. break out
  413. case WireBytes:
  414. var r []byte
  415. r, err = p.DecodeRawBytes(false)
  416. if err != nil {
  417. break out
  418. }
  419. fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
  420. if len(r) <= 6 {
  421. for i := 0; i < len(r); i++ {
  422. fmt.Printf(" %.2x", r[i])
  423. }
  424. } else {
  425. for i := 0; i < 3; i++ {
  426. fmt.Printf(" %.2x", r[i])
  427. }
  428. fmt.Printf(" ..")
  429. for i := len(r) - 3; i < len(r); i++ {
  430. fmt.Printf(" %.2x", r[i])
  431. }
  432. }
  433. fmt.Printf("\n")
  434. case WireFixed32:
  435. u, err = p.DecodeFixed32()
  436. if err != nil {
  437. fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
  438. break out
  439. }
  440. fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
  441. case WireFixed64:
  442. u, err = p.DecodeFixed64()
  443. if err != nil {
  444. fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
  445. break out
  446. }
  447. fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
  448. case WireVarint:
  449. u, err = p.DecodeVarint()
  450. if err != nil {
  451. fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
  452. break out
  453. }
  454. fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
  455. case WireStartGroup:
  456. fmt.Printf("%3d: t=%3d start\n", index, tag)
  457. depth++
  458. case WireEndGroup:
  459. depth--
  460. fmt.Printf("%3d: t=%3d end\n", index, tag)
  461. }
  462. }
  463. if depth != 0 {
  464. fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
  465. }
  466. fmt.Printf("\n")
  467. p.buf = obuf
  468. p.index = index
  469. }
  470. // SetDefaults sets unset protocol buffer fields to their default values.
  471. // It only modifies fields that are both unset and have defined defaults.
  472. // It recursively sets default values in any non-nil sub-messages.
  473. func SetDefaults(pb Message) {
  474. setDefaults(reflect.ValueOf(pb), true, false)
  475. }
  476. // v is a pointer to a struct.
  477. func setDefaults(v reflect.Value, recur, zeros bool) {
  478. v = v.Elem()
  479. defaultMu.RLock()
  480. dm, ok := defaults[v.Type()]
  481. defaultMu.RUnlock()
  482. if !ok {
  483. dm = buildDefaultMessage(v.Type())
  484. defaultMu.Lock()
  485. defaults[v.Type()] = dm
  486. defaultMu.Unlock()
  487. }
  488. for _, sf := range dm.scalars {
  489. f := v.Field(sf.index)
  490. if !f.IsNil() {
  491. // field already set
  492. continue
  493. }
  494. dv := sf.value
  495. if dv == nil && !zeros {
  496. // no explicit default, and don't want to set zeros
  497. continue
  498. }
  499. fptr := f.Addr().Interface() // **T
  500. // TODO: Consider batching the allocations we do here.
  501. switch sf.kind {
  502. case reflect.Bool:
  503. b := new(bool)
  504. if dv != nil {
  505. *b = dv.(bool)
  506. }
  507. *(fptr.(**bool)) = b
  508. case reflect.Float32:
  509. f := new(float32)
  510. if dv != nil {
  511. *f = dv.(float32)
  512. }
  513. *(fptr.(**float32)) = f
  514. case reflect.Float64:
  515. f := new(float64)
  516. if dv != nil {
  517. *f = dv.(float64)
  518. }
  519. *(fptr.(**float64)) = f
  520. case reflect.Int32:
  521. // might be an enum
  522. if ft := f.Type(); ft != int32PtrType {
  523. // enum
  524. f.Set(reflect.New(ft.Elem()))
  525. if dv != nil {
  526. f.Elem().SetInt(int64(dv.(int32)))
  527. }
  528. } else {
  529. // int32 field
  530. i := new(int32)
  531. if dv != nil {
  532. *i = dv.(int32)
  533. }
  534. *(fptr.(**int32)) = i
  535. }
  536. case reflect.Int64:
  537. i := new(int64)
  538. if dv != nil {
  539. *i = dv.(int64)
  540. }
  541. *(fptr.(**int64)) = i
  542. case reflect.String:
  543. s := new(string)
  544. if dv != nil {
  545. *s = dv.(string)
  546. }
  547. *(fptr.(**string)) = s
  548. case reflect.Uint8:
  549. // exceptional case: []byte
  550. var b []byte
  551. if dv != nil {
  552. db := dv.([]byte)
  553. b = make([]byte, len(db))
  554. copy(b, db)
  555. } else {
  556. b = []byte{}
  557. }
  558. *(fptr.(*[]byte)) = b
  559. case reflect.Uint32:
  560. u := new(uint32)
  561. if dv != nil {
  562. *u = dv.(uint32)
  563. }
  564. *(fptr.(**uint32)) = u
  565. case reflect.Uint64:
  566. u := new(uint64)
  567. if dv != nil {
  568. *u = dv.(uint64)
  569. }
  570. *(fptr.(**uint64)) = u
  571. default:
  572. log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
  573. }
  574. }
  575. for _, ni := range dm.nested {
  576. f := v.Field(ni)
  577. // f is *T or []*T or map[T]*T
  578. switch f.Kind() {
  579. case reflect.Ptr:
  580. if f.IsNil() {
  581. continue
  582. }
  583. setDefaults(f, recur, zeros)
  584. case reflect.Slice:
  585. for i := 0; i < f.Len(); i++ {
  586. e := f.Index(i)
  587. if e.IsNil() {
  588. continue
  589. }
  590. setDefaults(e, recur, zeros)
  591. }
  592. case reflect.Map:
  593. for _, k := range f.MapKeys() {
  594. e := f.MapIndex(k)
  595. if e.IsNil() {
  596. continue
  597. }
  598. setDefaults(e, recur, zeros)
  599. }
  600. }
  601. }
  602. }
  603. var (
  604. // defaults maps a protocol buffer struct type to a slice of the fields,
  605. // with its scalar fields set to their proto-declared non-zero default values.
  606. defaultMu sync.RWMutex
  607. defaults = make(map[reflect.Type]defaultMessage)
  608. int32PtrType = reflect.TypeOf((*int32)(nil))
  609. )
  610. // defaultMessage represents information about the default values of a message.
  611. type defaultMessage struct {
  612. scalars []scalarField
  613. nested []int // struct field index of nested messages
  614. }
  615. type scalarField struct {
  616. index int // struct field index
  617. kind reflect.Kind // element type (the T in *T or []T)
  618. value interface{} // the proto-declared default value, or nil
  619. }
  620. // t is a struct type.
  621. func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
  622. sprop := GetProperties(t)
  623. for _, prop := range sprop.Prop {
  624. fi, ok := sprop.decoderTags.get(prop.Tag)
  625. if !ok {
  626. // XXX_unrecognized
  627. continue
  628. }
  629. ft := t.Field(fi).Type
  630. sf, nested, err := fieldDefault(ft, prop)
  631. switch {
  632. case err != nil:
  633. log.Print(err)
  634. case nested:
  635. dm.nested = append(dm.nested, fi)
  636. case sf != nil:
  637. sf.index = fi
  638. dm.scalars = append(dm.scalars, *sf)
  639. }
  640. }
  641. return dm
  642. }
  643. // fieldDefault returns the scalarField for field type ft.
  644. // sf will be nil if the field can not have a default.
  645. // nestedMessage will be true if this is a nested message.
  646. // Note that sf.index is not set on return.
  647. func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
  648. var canHaveDefault bool
  649. switch ft.Kind() {
  650. case reflect.Ptr:
  651. if ft.Elem().Kind() == reflect.Struct {
  652. nestedMessage = true
  653. } else {
  654. canHaveDefault = true // proto2 scalar field
  655. }
  656. case reflect.Slice:
  657. switch ft.Elem().Kind() {
  658. case reflect.Ptr:
  659. nestedMessage = true // repeated message
  660. case reflect.Uint8:
  661. canHaveDefault = true // bytes field
  662. }
  663. case reflect.Map:
  664. if ft.Elem().Kind() == reflect.Ptr {
  665. nestedMessage = true // map with message values
  666. }
  667. }
  668. if !canHaveDefault {
  669. if nestedMessage {
  670. return nil, true, nil
  671. }
  672. return nil, false, nil
  673. }
  674. // We now know that ft is a pointer or slice.
  675. sf = &scalarField{kind: ft.Elem().Kind()}
  676. // scalar fields without defaults
  677. if !prop.HasDefault {
  678. return sf, false, nil
  679. }
  680. // a scalar field: either *T or []byte
  681. switch ft.Elem().Kind() {
  682. case reflect.Bool:
  683. x, err := strconv.ParseBool(prop.Default)
  684. if err != nil {
  685. return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
  686. }
  687. sf.value = x
  688. case reflect.Float32:
  689. x, err := strconv.ParseFloat(prop.Default, 32)
  690. if err != nil {
  691. return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
  692. }
  693. sf.value = float32(x)
  694. case reflect.Float64:
  695. x, err := strconv.ParseFloat(prop.Default, 64)
  696. if err != nil {
  697. return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
  698. }
  699. sf.value = x
  700. case reflect.Int32:
  701. x, err := strconv.ParseInt(prop.Default, 10, 32)
  702. if err != nil {
  703. return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
  704. }
  705. sf.value = int32(x)
  706. case reflect.Int64:
  707. x, err := strconv.ParseInt(prop.Default, 10, 64)
  708. if err != nil {
  709. return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
  710. }
  711. sf.value = x
  712. case reflect.String:
  713. sf.value = prop.Default
  714. case reflect.Uint8:
  715. // []byte (not *uint8)
  716. sf.value = []byte(prop.Default)
  717. case reflect.Uint32:
  718. x, err := strconv.ParseUint(prop.Default, 10, 32)
  719. if err != nil {
  720. return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
  721. }
  722. sf.value = uint32(x)
  723. case reflect.Uint64:
  724. x, err := strconv.ParseUint(prop.Default, 10, 64)
  725. if err != nil {
  726. return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
  727. }
  728. sf.value = x
  729. default:
  730. return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
  731. }
  732. return sf, false, nil
  733. }
  734. // Map fields may have key types of non-float scalars, strings and enums.
  735. // The easiest way to sort them in some deterministic order is to use fmt.
  736. // If this turns out to be inefficient we can always consider other options,
  737. // such as doing a Schwartzian transform.
  738. func mapKeys(vs []reflect.Value) sort.Interface {
  739. s := mapKeySorter{
  740. vs: vs,
  741. // default Less function: textual comparison
  742. less: func(a, b reflect.Value) bool {
  743. return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface())
  744. },
  745. }
  746. // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps;
  747. // numeric keys are sorted numerically.
  748. if len(vs) == 0 {
  749. return s
  750. }
  751. switch vs[0].Kind() {
  752. case reflect.Int32, reflect.Int64:
  753. s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
  754. case reflect.Uint32, reflect.Uint64:
  755. s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
  756. }
  757. return s
  758. }
  759. type mapKeySorter struct {
  760. vs []reflect.Value
  761. less func(a, b reflect.Value) bool
  762. }
  763. func (s mapKeySorter) Len() int { return len(s.vs) }
  764. func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
  765. func (s mapKeySorter) Less(i, j int) bool {
  766. return s.less(s.vs[i], s.vs[j])
  767. }
  768. // isProto3Zero reports whether v is a zero proto3 value.
  769. func isProto3Zero(v reflect.Value) bool {
  770. switch v.Kind() {
  771. case reflect.Bool:
  772. return !v.Bool()
  773. case reflect.Int32, reflect.Int64:
  774. return v.Int() == 0
  775. case reflect.Uint32, reflect.Uint64:
  776. return v.Uint() == 0
  777. case reflect.Float32, reflect.Float64:
  778. return v.Float() == 0
  779. case reflect.String:
  780. return v.String() == ""
  781. }
  782. return false
  783. }