lib.go 23 KB

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