lib.go 20 KB

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