lib.go 21 KB

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