lib.go 24 KB

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