lib.go 20 KB

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