lib.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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. p := new(bool)
  293. *p = v
  294. return p
  295. }
  296. // Int32 is a helper routine that allocates a new int32 value
  297. // to store v and returns a pointer to it.
  298. func Int32(v int32) *int32 {
  299. p := new(int32)
  300. *p = v
  301. return p
  302. }
  303. // Int is a helper routine that allocates a new int32 value
  304. // to store v and returns a pointer to it, but unlike Int32
  305. // its argument value is an int.
  306. func Int(v int) *int32 {
  307. p := new(int32)
  308. *p = int32(v)
  309. return p
  310. }
  311. // Int64 is a helper routine that allocates a new int64 value
  312. // to store v and returns a pointer to it.
  313. func Int64(v int64) *int64 {
  314. p := new(int64)
  315. *p = v
  316. return p
  317. }
  318. // Float32 is a helper routine that allocates a new float32 value
  319. // to store v and returns a pointer to it.
  320. func Float32(v float32) *float32 {
  321. p := new(float32)
  322. *p = v
  323. return p
  324. }
  325. // Float64 is a helper routine that allocates a new float64 value
  326. // to store v and returns a pointer to it.
  327. func Float64(v float64) *float64 {
  328. p := new(float64)
  329. *p = v
  330. return p
  331. }
  332. // Uint32 is a helper routine that allocates a new uint32 value
  333. // to store v and returns a pointer to it.
  334. func Uint32(v uint32) *uint32 {
  335. p := new(uint32)
  336. *p = v
  337. return p
  338. }
  339. // Uint64 is a helper routine that allocates a new uint64 value
  340. // to store v and returns a pointer to it.
  341. func Uint64(v uint64) *uint64 {
  342. p := new(uint64)
  343. *p = v
  344. return p
  345. }
  346. // String is a helper routine that allocates a new string value
  347. // to store v and returns a pointer to it.
  348. func String(v string) *string {
  349. p := new(string)
  350. *p = v
  351. return p
  352. }
  353. // EnumName is a helper function to simplify printing protocol buffer enums
  354. // by name. Given an enum map and a value, it returns a useful string.
  355. func EnumName(m map[int32]string, v int32) string {
  356. s, ok := m[v]
  357. if ok {
  358. return s
  359. }
  360. return strconv.Itoa(int(v))
  361. }
  362. // UnmarshalJSONEnum is a helper function to simplify recovering enum int values
  363. // from their JSON-encoded representation. Given a map from the enum's symbolic
  364. // names to its int values, and a byte buffer containing the JSON-encoded
  365. // value, it returns an int32 that can be cast to the enum type by the caller.
  366. //
  367. // The function can deal with older JSON representations, which represented
  368. // enums directly by their int32 values, or with newer representations, which
  369. // use the symbolic name as a string.
  370. func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
  371. if data[0] == '"' {
  372. // New style: enums are strings.
  373. var repr string
  374. if err := json.Unmarshal(data, &repr); err != nil {
  375. return -1, err
  376. }
  377. val, ok := m[repr]
  378. if !ok {
  379. return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
  380. }
  381. return val, nil
  382. }
  383. // Old style: enums are ints.
  384. var val int32
  385. if err := json.Unmarshal(data, &val); err != nil {
  386. return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
  387. }
  388. return val, nil
  389. }
  390. // DebugPrint dumps the encoded data in b in a debugging format with a header
  391. // including the string s. Used in testing but made available for general debugging.
  392. func (o *Buffer) DebugPrint(s string, b []byte) {
  393. var u uint64
  394. obuf := o.buf
  395. index := o.index
  396. o.buf = b
  397. o.index = 0
  398. depth := 0
  399. fmt.Printf("\n--- %s ---\n", s)
  400. out:
  401. for {
  402. for i := 0; i < depth; i++ {
  403. fmt.Print(" ")
  404. }
  405. index := o.index
  406. if index == len(o.buf) {
  407. break
  408. }
  409. op, err := o.DecodeVarint()
  410. if err != nil {
  411. fmt.Printf("%3d: fetching op err %v\n", index, err)
  412. break out
  413. }
  414. tag := op >> 3
  415. wire := op & 7
  416. switch wire {
  417. default:
  418. fmt.Printf("%3d: t=%3d unknown wire=%d\n",
  419. index, tag, wire)
  420. break out
  421. case WireBytes:
  422. var r []byte
  423. r, err = o.DecodeRawBytes(false)
  424. if err != nil {
  425. break out
  426. }
  427. fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
  428. if len(r) <= 6 {
  429. for i := 0; i < len(r); i++ {
  430. fmt.Printf(" %.2x", r[i])
  431. }
  432. } else {
  433. for i := 0; i < 3; i++ {
  434. fmt.Printf(" %.2x", r[i])
  435. }
  436. fmt.Printf(" ..")
  437. for i := len(r) - 3; i < len(r); i++ {
  438. fmt.Printf(" %.2x", r[i])
  439. }
  440. }
  441. fmt.Printf("\n")
  442. case WireFixed32:
  443. u, err = o.DecodeFixed32()
  444. if err != nil {
  445. fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
  446. break out
  447. }
  448. fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
  449. case WireFixed64:
  450. u, err = o.DecodeFixed64()
  451. if err != nil {
  452. fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
  453. break out
  454. }
  455. fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
  456. break
  457. case WireVarint:
  458. u, err = o.DecodeVarint()
  459. if err != nil {
  460. fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
  461. break out
  462. }
  463. fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
  464. case WireStartGroup:
  465. if err != nil {
  466. fmt.Printf("%3d: t=%3d start err %v\n", index, tag, err)
  467. break out
  468. }
  469. fmt.Printf("%3d: t=%3d start\n", index, tag)
  470. depth++
  471. case WireEndGroup:
  472. depth--
  473. if err != nil {
  474. fmt.Printf("%3d: t=%3d end err %v\n", index, tag, err)
  475. break out
  476. }
  477. fmt.Printf("%3d: t=%3d end\n", index, tag)
  478. }
  479. }
  480. if depth != 0 {
  481. fmt.Printf("%3d: start-end not balanced %d\n", o.index, depth)
  482. }
  483. fmt.Printf("\n")
  484. o.buf = obuf
  485. o.index = index
  486. }
  487. // SetDefaults sets unset protocol buffer fields to their default values.
  488. // It only modifies fields that are both unset and have defined defaults.
  489. // It recursively sets default values in any non-nil sub-messages.
  490. func SetDefaults(pb Message) {
  491. setDefaults(reflect.ValueOf(pb), true, false)
  492. }
  493. // v is a pointer to a struct.
  494. func setDefaults(v reflect.Value, recur, zeros bool) {
  495. v = v.Elem()
  496. defaultMu.RLock()
  497. dm, ok := defaults[v.Type()]
  498. defaultMu.RUnlock()
  499. if !ok {
  500. dm = buildDefaultMessage(v.Type())
  501. defaultMu.Lock()
  502. defaults[v.Type()] = dm
  503. defaultMu.Unlock()
  504. }
  505. for _, sf := range dm.scalars {
  506. f := v.Field(sf.index)
  507. if !f.IsNil() {
  508. // field already set
  509. continue
  510. }
  511. dv := sf.value
  512. if dv == nil && !zeros {
  513. // no explicit default, and don't want to set zeros
  514. continue
  515. }
  516. fptr := f.Addr().Interface() // **T
  517. // TODO: Consider batching the allocations we do here.
  518. switch sf.kind {
  519. case reflect.Bool:
  520. b := new(bool)
  521. if dv != nil {
  522. *b = dv.(bool)
  523. }
  524. *(fptr.(**bool)) = b
  525. case reflect.Float32:
  526. f := new(float32)
  527. if dv != nil {
  528. *f = dv.(float32)
  529. }
  530. *(fptr.(**float32)) = f
  531. case reflect.Float64:
  532. f := new(float64)
  533. if dv != nil {
  534. *f = dv.(float64)
  535. }
  536. *(fptr.(**float64)) = f
  537. case reflect.Int32:
  538. // might be an enum
  539. if ft := f.Type(); ft != int32PtrType {
  540. // enum
  541. f.Set(reflect.New(ft.Elem()))
  542. if dv != nil {
  543. f.Elem().SetInt(int64(dv.(int32)))
  544. }
  545. } else {
  546. // int32 field
  547. i := new(int32)
  548. if dv != nil {
  549. *i = dv.(int32)
  550. }
  551. *(fptr.(**int32)) = i
  552. }
  553. case reflect.Int64:
  554. i := new(int64)
  555. if dv != nil {
  556. *i = dv.(int64)
  557. }
  558. *(fptr.(**int64)) = i
  559. case reflect.String:
  560. s := new(string)
  561. if dv != nil {
  562. *s = dv.(string)
  563. }
  564. *(fptr.(**string)) = s
  565. case reflect.Uint8:
  566. // exceptional case: []byte
  567. var b []byte
  568. if dv != nil {
  569. db := dv.([]byte)
  570. b = make([]byte, len(db))
  571. copy(b, db)
  572. } else {
  573. b = []byte{}
  574. }
  575. *(fptr.(*[]byte)) = b
  576. case reflect.Uint32:
  577. u := new(uint32)
  578. if dv != nil {
  579. *u = dv.(uint32)
  580. }
  581. *(fptr.(**uint32)) = u
  582. case reflect.Uint64:
  583. u := new(uint64)
  584. if dv != nil {
  585. *u = dv.(uint64)
  586. }
  587. *(fptr.(**uint64)) = u
  588. default:
  589. log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
  590. }
  591. }
  592. for _, ni := range dm.nested {
  593. f := v.Field(ni)
  594. if f.IsNil() {
  595. continue
  596. }
  597. // f is *T or []*T
  598. if f.Kind() == reflect.Ptr {
  599. setDefaults(f, recur, zeros)
  600. } else {
  601. for i := 0; i < f.Len(); i++ {
  602. e := f.Index(i)
  603. if e.IsNil() {
  604. continue
  605. }
  606. setDefaults(e, recur, zeros)
  607. }
  608. }
  609. }
  610. }
  611. var (
  612. // defaults maps a protocol buffer struct type to a slice of the fields,
  613. // with its scalar fields set to their proto-declared non-zero default values.
  614. defaultMu sync.RWMutex
  615. defaults = make(map[reflect.Type]defaultMessage)
  616. int32PtrType = reflect.TypeOf((*int32)(nil))
  617. )
  618. // defaultMessage represents information about the default values of a message.
  619. type defaultMessage struct {
  620. scalars []scalarField
  621. nested []int // struct field index of nested messages
  622. }
  623. type scalarField struct {
  624. index int // struct field index
  625. kind reflect.Kind // element type (the T in *T or []T)
  626. value interface{} // the proto-declared default value, or nil
  627. }
  628. func ptrToStruct(t reflect.Type) bool {
  629. return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
  630. }
  631. // t is a struct type.
  632. func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
  633. sprop := GetProperties(t)
  634. for _, prop := range sprop.Prop {
  635. fi, ok := sprop.decoderTags.get(prop.Tag)
  636. if !ok {
  637. // XXX_unrecognized
  638. continue
  639. }
  640. ft := t.Field(fi).Type
  641. // nested messages
  642. if ptrToStruct(ft) || (ft.Kind() == reflect.Slice && ptrToStruct(ft.Elem())) {
  643. dm.nested = append(dm.nested, fi)
  644. continue
  645. }
  646. sf := scalarField{
  647. index: fi,
  648. kind: ft.Elem().Kind(),
  649. }
  650. // scalar fields without defaults
  651. if prop.Default == "" {
  652. dm.scalars = append(dm.scalars, sf)
  653. continue
  654. }
  655. // a scalar field: either *T or []byte
  656. switch ft.Elem().Kind() {
  657. case reflect.Bool:
  658. x, err := strconv.ParseBool(prop.Default)
  659. if err != nil {
  660. log.Printf("proto: bad default bool %q: %v", prop.Default, err)
  661. continue
  662. }
  663. sf.value = x
  664. case reflect.Float32:
  665. x, err := strconv.ParseFloat(prop.Default, 32)
  666. if err != nil {
  667. log.Printf("proto: bad default float32 %q: %v", prop.Default, err)
  668. continue
  669. }
  670. sf.value = float32(x)
  671. case reflect.Float64:
  672. x, err := strconv.ParseFloat(prop.Default, 64)
  673. if err != nil {
  674. log.Printf("proto: bad default float64 %q: %v", prop.Default, err)
  675. continue
  676. }
  677. sf.value = x
  678. case reflect.Int32:
  679. x, err := strconv.ParseInt(prop.Default, 10, 32)
  680. if err != nil {
  681. log.Printf("proto: bad default int32 %q: %v", prop.Default, err)
  682. continue
  683. }
  684. sf.value = int32(x)
  685. case reflect.Int64:
  686. x, err := strconv.ParseInt(prop.Default, 10, 64)
  687. if err != nil {
  688. log.Printf("proto: bad default int64 %q: %v", prop.Default, err)
  689. continue
  690. }
  691. sf.value = x
  692. case reflect.String:
  693. sf.value = prop.Default
  694. case reflect.Uint8:
  695. // []byte (not *uint8)
  696. sf.value = []byte(prop.Default)
  697. case reflect.Uint32:
  698. x, err := strconv.ParseUint(prop.Default, 10, 32)
  699. if err != nil {
  700. log.Printf("proto: bad default uint32 %q: %v", prop.Default, err)
  701. continue
  702. }
  703. sf.value = uint32(x)
  704. case reflect.Uint64:
  705. x, err := strconv.ParseUint(prop.Default, 10, 64)
  706. if err != nil {
  707. log.Printf("proto: bad default uint64 %q: %v", prop.Default, err)
  708. continue
  709. }
  710. sf.value = x
  711. default:
  712. log.Printf("proto: unhandled def kind %v", ft.Elem().Kind())
  713. continue
  714. }
  715. dm.scalars = append(dm.scalars, sf)
  716. }
  717. return dm
  718. }