lib.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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 "code.google.com/p/goprotobuf/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. "code.google.com/p/goprotobuf/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. }
  200. // Set to true to enable stats collection.
  201. const collectStats = false
  202. var stats Stats
  203. // GetStats returns a copy of the global Stats structure.
  204. func GetStats() Stats { return stats }
  205. // A Buffer is a buffer manager for marshaling and unmarshaling
  206. // protocol buffers. It may be reused between invocations to
  207. // reduce memory usage. It is not necessary to use a Buffer;
  208. // the global functions Marshal and Unmarshal create a
  209. // temporary Buffer and are fine for most applications.
  210. type Buffer struct {
  211. buf []byte // encode/decode byte stream
  212. index int // write point
  213. freelist [10][]byte // list of available buffers
  214. nfreelist int // number of free buffers
  215. // pools of basic types to amortize allocation.
  216. bools []bool
  217. uint32s []uint32
  218. uint64s []uint64
  219. // extra pools, only used with pointer_reflect.go
  220. int32s []int32
  221. int64s []int64
  222. float32s []float32
  223. float64s []float64
  224. }
  225. // NewBuffer allocates a new Buffer and initializes its internal data to
  226. // the contents of the argument slice.
  227. func NewBuffer(e []byte) *Buffer {
  228. p := new(Buffer)
  229. if e == nil {
  230. e = p.bufalloc()
  231. }
  232. p.buf = e
  233. p.index = 0
  234. return p
  235. }
  236. // Reset resets the Buffer, ready for marshaling a new protocol buffer.
  237. func (p *Buffer) Reset() {
  238. if p.buf == nil {
  239. p.buf = p.bufalloc()
  240. }
  241. p.buf = p.buf[0:0] // for reading/writing
  242. p.index = 0 // for reading
  243. }
  244. // SetBuf replaces the internal buffer with the slice,
  245. // ready for unmarshaling the contents of the slice.
  246. func (p *Buffer) SetBuf(s []byte) {
  247. p.buf = s
  248. p.index = 0
  249. }
  250. // Bytes returns the contents of the Buffer.
  251. func (p *Buffer) Bytes() []byte { return p.buf }
  252. // Allocate a buffer for the Buffer.
  253. func (p *Buffer) bufalloc() []byte {
  254. if p.nfreelist > 0 {
  255. // reuse an old one
  256. p.nfreelist--
  257. s := p.freelist[p.nfreelist]
  258. return s[0:0]
  259. }
  260. // make a new one
  261. s := make([]byte, 0, 16)
  262. return s
  263. }
  264. // Free (and remember in freelist) a byte buffer for the Buffer.
  265. func (p *Buffer) buffree(s []byte) {
  266. if p.nfreelist < len(p.freelist) {
  267. // Take next slot.
  268. p.freelist[p.nfreelist] = s
  269. p.nfreelist++
  270. return
  271. }
  272. // Find the smallest.
  273. besti := -1
  274. bestl := len(s)
  275. for i, b := range p.freelist {
  276. if len(b) < bestl {
  277. besti = i
  278. bestl = len(b)
  279. }
  280. }
  281. // Overwrite the smallest.
  282. if besti >= 0 {
  283. p.freelist[besti] = s
  284. }
  285. }
  286. /*
  287. * Helper routines for simplifying the creation of optional fields of basic type.
  288. */
  289. // Bool is a helper routine that allocates a new bool value
  290. // to store v and returns a pointer to it.
  291. func Bool(v bool) *bool {
  292. return &v
  293. }
  294. // Int32 is a helper routine that allocates a new int32 value
  295. // to store v and returns a pointer to it.
  296. func Int32(v int32) *int32 {
  297. return &v
  298. }
  299. // Int is a helper routine that allocates a new int32 value
  300. // to store v and returns a pointer to it, but unlike Int32
  301. // its argument value is an int.
  302. func Int(v int) *int32 {
  303. p := new(int32)
  304. *p = int32(v)
  305. return p
  306. }
  307. // Int64 is a helper routine that allocates a new int64 value
  308. // to store v and returns a pointer to it.
  309. func Int64(v int64) *int64 {
  310. return &v
  311. }
  312. // Float32 is a helper routine that allocates a new float32 value
  313. // to store v and returns a pointer to it.
  314. func Float32(v float32) *float32 {
  315. return &v
  316. }
  317. // Float64 is a helper routine that allocates a new float64 value
  318. // to store v and returns a pointer to it.
  319. func Float64(v float64) *float64 {
  320. return &v
  321. }
  322. // Uint32 is a helper routine that allocates a new uint32 value
  323. // to store v and returns a pointer to it.
  324. func Uint32(v uint32) *uint32 {
  325. p := new(uint32)
  326. *p = v
  327. return p
  328. }
  329. // Uint64 is a helper routine that allocates a new uint64 value
  330. // to store v and returns a pointer to it.
  331. func Uint64(v uint64) *uint64 {
  332. return &v
  333. }
  334. // String is a helper routine that allocates a new string value
  335. // to store v and returns a pointer to it.
  336. func String(v string) *string {
  337. return &v
  338. }
  339. // EnumName is a helper function to simplify printing protocol buffer enums
  340. // by name. Given an enum map and a value, it returns a useful string.
  341. func EnumName(m map[int32]string, v int32) string {
  342. s, ok := m[v]
  343. if ok {
  344. return s
  345. }
  346. return strconv.Itoa(int(v))
  347. }
  348. // UnmarshalJSONEnum is a helper function to simplify recovering enum int values
  349. // from their JSON-encoded representation. Given a map from the enum's symbolic
  350. // names to its int values, and a byte buffer containing the JSON-encoded
  351. // value, it returns an int32 that can be cast to the enum type by the caller.
  352. //
  353. // The function can deal with older JSON representations, which represented
  354. // enums directly by their int32 values, or with newer representations, which
  355. // use the symbolic name as a string.
  356. func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
  357. if data[0] == '"' {
  358. // New style: enums are strings.
  359. var repr string
  360. if err := json.Unmarshal(data, &repr); err != nil {
  361. return -1, err
  362. }
  363. val, ok := m[repr]
  364. if !ok {
  365. return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
  366. }
  367. return val, nil
  368. }
  369. // Old style: enums are ints.
  370. var val int32
  371. if err := json.Unmarshal(data, &val); err != nil {
  372. return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
  373. }
  374. return val, nil
  375. }
  376. // DebugPrint dumps the encoded data in b in a debugging format with a header
  377. // including the string s. Used in testing but made available for general debugging.
  378. func (o *Buffer) DebugPrint(s string, b []byte) {
  379. var u uint64
  380. obuf := o.buf
  381. index := o.index
  382. o.buf = b
  383. o.index = 0
  384. depth := 0
  385. fmt.Printf("\n--- %s ---\n", s)
  386. out:
  387. for {
  388. for i := 0; i < depth; i++ {
  389. fmt.Print(" ")
  390. }
  391. index := o.index
  392. if index == len(o.buf) {
  393. break
  394. }
  395. op, err := o.DecodeVarint()
  396. if err != nil {
  397. fmt.Printf("%3d: fetching op err %v\n", index, err)
  398. break out
  399. }
  400. tag := op >> 3
  401. wire := op & 7
  402. switch wire {
  403. default:
  404. fmt.Printf("%3d: t=%3d unknown wire=%d\n",
  405. index, tag, wire)
  406. break out
  407. case WireBytes:
  408. var r []byte
  409. r, err = o.DecodeRawBytes(false)
  410. if err != nil {
  411. break out
  412. }
  413. fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
  414. if len(r) <= 6 {
  415. for i := 0; i < len(r); i++ {
  416. fmt.Printf(" %.2x", r[i])
  417. }
  418. } else {
  419. for i := 0; i < 3; i++ {
  420. fmt.Printf(" %.2x", r[i])
  421. }
  422. fmt.Printf(" ..")
  423. for i := len(r) - 3; i < len(r); i++ {
  424. fmt.Printf(" %.2x", r[i])
  425. }
  426. }
  427. fmt.Printf("\n")
  428. case WireFixed32:
  429. u, err = o.DecodeFixed32()
  430. if err != nil {
  431. fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
  432. break out
  433. }
  434. fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
  435. case WireFixed64:
  436. u, err = o.DecodeFixed64()
  437. if err != nil {
  438. fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
  439. break out
  440. }
  441. fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
  442. break
  443. case WireVarint:
  444. u, err = o.DecodeVarint()
  445. if err != nil {
  446. fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
  447. break out
  448. }
  449. fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
  450. case WireStartGroup:
  451. if err != nil {
  452. fmt.Printf("%3d: t=%3d start err %v\n", index, tag, err)
  453. break out
  454. }
  455. fmt.Printf("%3d: t=%3d start\n", index, tag)
  456. depth++
  457. case WireEndGroup:
  458. depth--
  459. if err != nil {
  460. fmt.Printf("%3d: t=%3d end err %v\n", index, tag, err)
  461. break out
  462. }
  463. fmt.Printf("%3d: t=%3d end\n", index, tag)
  464. }
  465. }
  466. if depth != 0 {
  467. fmt.Printf("%3d: start-end not balanced %d\n", o.index, depth)
  468. }
  469. fmt.Printf("\n")
  470. o.buf = obuf
  471. o.index = index
  472. }
  473. // SetDefaults sets unset protocol buffer fields to their default values.
  474. // It only modifies fields that are both unset and have defined defaults.
  475. // It recursively sets default values in any non-nil sub-messages.
  476. func SetDefaults(pb Message) {
  477. setDefaults(reflect.ValueOf(pb), true, false)
  478. }
  479. // v is a pointer to a struct.
  480. func setDefaults(v reflect.Value, recur, zeros bool) {
  481. v = v.Elem()
  482. defaultMu.RLock()
  483. dm, ok := defaults[v.Type()]
  484. defaultMu.RUnlock()
  485. if !ok {
  486. dm = buildDefaultMessage(v.Type())
  487. defaultMu.Lock()
  488. defaults[v.Type()] = dm
  489. defaultMu.Unlock()
  490. }
  491. for _, sf := range dm.scalars {
  492. f := v.Field(sf.index)
  493. if !f.IsNil() {
  494. // field already set
  495. continue
  496. }
  497. dv := sf.value
  498. if dv == nil && !zeros {
  499. // no explicit default, and don't want to set zeros
  500. continue
  501. }
  502. fptr := f.Addr().Interface() // **T
  503. // TODO: Consider batching the allocations we do here.
  504. switch sf.kind {
  505. case reflect.Bool:
  506. b := new(bool)
  507. if dv != nil {
  508. *b = dv.(bool)
  509. }
  510. *(fptr.(**bool)) = b
  511. case reflect.Float32:
  512. f := new(float32)
  513. if dv != nil {
  514. *f = dv.(float32)
  515. }
  516. *(fptr.(**float32)) = f
  517. case reflect.Float64:
  518. f := new(float64)
  519. if dv != nil {
  520. *f = dv.(float64)
  521. }
  522. *(fptr.(**float64)) = f
  523. case reflect.Int32:
  524. // might be an enum
  525. if ft := f.Type(); ft != int32PtrType {
  526. // enum
  527. f.Set(reflect.New(ft.Elem()))
  528. if dv != nil {
  529. f.Elem().SetInt(int64(dv.(int32)))
  530. }
  531. } else {
  532. // int32 field
  533. i := new(int32)
  534. if dv != nil {
  535. *i = dv.(int32)
  536. }
  537. *(fptr.(**int32)) = i
  538. }
  539. case reflect.Int64:
  540. i := new(int64)
  541. if dv != nil {
  542. *i = dv.(int64)
  543. }
  544. *(fptr.(**int64)) = i
  545. case reflect.String:
  546. s := new(string)
  547. if dv != nil {
  548. *s = dv.(string)
  549. }
  550. *(fptr.(**string)) = s
  551. case reflect.Uint8:
  552. // exceptional case: []byte
  553. var b []byte
  554. if dv != nil {
  555. db := dv.([]byte)
  556. b = make([]byte, len(db))
  557. copy(b, db)
  558. } else {
  559. b = []byte{}
  560. }
  561. *(fptr.(*[]byte)) = b
  562. case reflect.Uint32:
  563. u := new(uint32)
  564. if dv != nil {
  565. *u = dv.(uint32)
  566. }
  567. *(fptr.(**uint32)) = u
  568. case reflect.Uint64:
  569. u := new(uint64)
  570. if dv != nil {
  571. *u = dv.(uint64)
  572. }
  573. *(fptr.(**uint64)) = u
  574. default:
  575. log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
  576. }
  577. }
  578. for _, ni := range dm.nested {
  579. f := v.Field(ni)
  580. if f.IsNil() {
  581. continue
  582. }
  583. // f is *T or []*T
  584. if f.Kind() == reflect.Ptr {
  585. setDefaults(f, recur, zeros)
  586. } else {
  587. for i := 0; i < f.Len(); i++ {
  588. e := f.Index(i)
  589. if e.IsNil() {
  590. continue
  591. }
  592. setDefaults(e, recur, zeros)
  593. }
  594. }
  595. }
  596. }
  597. var (
  598. // defaults maps a protocol buffer struct type to a slice of the fields,
  599. // with its scalar fields set to their proto-declared non-zero default values.
  600. defaultMu sync.RWMutex
  601. defaults = make(map[reflect.Type]defaultMessage)
  602. int32PtrType = reflect.TypeOf((*int32)(nil))
  603. )
  604. // defaultMessage represents information about the default values of a message.
  605. type defaultMessage struct {
  606. scalars []scalarField
  607. nested []int // struct field index of nested messages
  608. }
  609. type scalarField struct {
  610. index int // struct field index
  611. kind reflect.Kind // element type (the T in *T or []T)
  612. value interface{} // the proto-declared default value, or nil
  613. }
  614. func ptrToStruct(t reflect.Type) bool {
  615. return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
  616. }
  617. // t is a struct type.
  618. func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
  619. sprop := GetProperties(t)
  620. for _, prop := range sprop.Prop {
  621. fi, ok := sprop.decoderTags.get(prop.Tag)
  622. if !ok {
  623. // XXX_unrecognized
  624. continue
  625. }
  626. ft := t.Field(fi).Type
  627. // nested messages
  628. if ptrToStruct(ft) || (ft.Kind() == reflect.Slice && ptrToStruct(ft.Elem())) {
  629. dm.nested = append(dm.nested, fi)
  630. continue
  631. }
  632. sf := scalarField{
  633. index: fi,
  634. kind: ft.Elem().Kind(),
  635. }
  636. // scalar fields without defaults
  637. if prop.Default == "" {
  638. dm.scalars = append(dm.scalars, sf)
  639. continue
  640. }
  641. // a scalar field: either *T or []byte
  642. switch ft.Elem().Kind() {
  643. case reflect.Bool:
  644. x, err := strconv.ParseBool(prop.Default)
  645. if err != nil {
  646. log.Printf("proto: bad default bool %q: %v", prop.Default, err)
  647. continue
  648. }
  649. sf.value = x
  650. case reflect.Float32:
  651. x, err := strconv.ParseFloat(prop.Default, 32)
  652. if err != nil {
  653. log.Printf("proto: bad default float32 %q: %v", prop.Default, err)
  654. continue
  655. }
  656. sf.value = float32(x)
  657. case reflect.Float64:
  658. x, err := strconv.ParseFloat(prop.Default, 64)
  659. if err != nil {
  660. log.Printf("proto: bad default float64 %q: %v", prop.Default, err)
  661. continue
  662. }
  663. sf.value = x
  664. case reflect.Int32:
  665. x, err := strconv.ParseInt(prop.Default, 10, 32)
  666. if err != nil {
  667. log.Printf("proto: bad default int32 %q: %v", prop.Default, err)
  668. continue
  669. }
  670. sf.value = int32(x)
  671. case reflect.Int64:
  672. x, err := strconv.ParseInt(prop.Default, 10, 64)
  673. if err != nil {
  674. log.Printf("proto: bad default int64 %q: %v", prop.Default, err)
  675. continue
  676. }
  677. sf.value = x
  678. case reflect.String:
  679. sf.value = prop.Default
  680. case reflect.Uint8:
  681. // []byte (not *uint8)
  682. sf.value = []byte(prop.Default)
  683. case reflect.Uint32:
  684. x, err := strconv.ParseUint(prop.Default, 10, 32)
  685. if err != nil {
  686. log.Printf("proto: bad default uint32 %q: %v", prop.Default, err)
  687. continue
  688. }
  689. sf.value = uint32(x)
  690. case reflect.Uint64:
  691. x, err := strconv.ParseUint(prop.Default, 10, 64)
  692. if err != nil {
  693. log.Printf("proto: bad default uint64 %q: %v", prop.Default, err)
  694. continue
  695. }
  696. sf.value = x
  697. default:
  698. log.Printf("proto: unhandled def kind %v", ft.Elem().Kind())
  699. continue
  700. }
  701. dm.scalars = append(dm.scalars, sf)
  702. }
  703. return dm
  704. }