lib.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. // Copyright 2010 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. /*
  5. Package proto converts data structures to and from the wire format of
  6. protocol buffers. It works in concert with the Go source code generated
  7. for .proto files by the protocol compiler.
  8. A summary of the properties of the protocol buffer interface
  9. for a protocol buffer variable v:
  10. - Names are turned from camel_case to CamelCase for export.
  11. - There are no methods on v to set fields; just treat
  12. them as structure fields.
  13. - There are getters that return a field's value if set,
  14. and return the field's default value if unset.
  15. The getters work even if the receiver is a nil message.
  16. - The zero value for a struct is its correct initialization state.
  17. All desired fields must be set before marshaling.
  18. - A Reset() method will restore a protobuf struct to its zero state.
  19. - Non-repeated fields are pointers to the values; nil means unset.
  20. That is, optional or required field int32 f becomes F *int32.
  21. - Repeated fields are slices.
  22. - Helper functions are available to aid the setting of fields.
  23. msg.Foo = proto.String("hello") // set field
  24. - Constants are defined to hold the default values of all fields that
  25. have them. They have the form Default_StructName_FieldName.
  26. Because the getter methods handle defaulted values,
  27. direct use of these constants should be rare.
  28. - Enums are given type names and maps from names to values.
  29. Enum values are prefixed by the enclosing message's name, or by the
  30. enum's type name if it is a top-level enum. Enum types have a String
  31. method, and a Enum method to assist in message construction.
  32. - Nested messages, groups and enums have type names prefixed with the name of
  33. the surrounding message type.
  34. - Extensions are given descriptor names that start with E_,
  35. followed by an underscore-delimited list of the nested messages
  36. that contain it (if any) followed by the CamelCased name of the
  37. extension field itself. HasExtension, ClearExtension, GetExtension
  38. and SetExtension are functions for manipulating extensions.
  39. - Oneof field sets are given a single field in their message,
  40. with distinguished wrapper types for each possible field value.
  41. - Marshal and Unmarshal are functions to encode and decode the wire format.
  42. When the .proto file specifies `syntax="proto3"`, there are some differences:
  43. - Non-repeated fields of non-message type are values instead of pointers.
  44. - Enum types do not get an Enum method.
  45. The simplest way to describe this is to see an example.
  46. Given file test.proto, containing
  47. package example;
  48. enum FOO { X = 17; }
  49. message Test {
  50. required string label = 1;
  51. optional int32 type = 2 [default=77];
  52. repeated int64 reps = 3;
  53. optional group OptionalGroup = 4 {
  54. required string RequiredField = 5;
  55. }
  56. oneof union {
  57. int32 number = 6;
  58. string name = 7;
  59. }
  60. }
  61. The resulting file, test.pb.go, is:
  62. package example
  63. import proto "github.com/golang/protobuf/proto"
  64. import math "math"
  65. type FOO int32
  66. const (
  67. FOO_X FOO = 17
  68. )
  69. var FOO_name = map[int32]string{
  70. 17: "X",
  71. }
  72. var FOO_value = map[string]int32{
  73. "X": 17,
  74. }
  75. func (x FOO) Enum() *FOO {
  76. p := new(FOO)
  77. *p = x
  78. return p
  79. }
  80. func (x FOO) String() string {
  81. return proto.EnumName(FOO_name, int32(x))
  82. }
  83. func (x *FOO) UnmarshalJSON(data []byte) error {
  84. value, err := proto.UnmarshalJSONEnum(FOO_value, data)
  85. if err != nil {
  86. return err
  87. }
  88. *x = FOO(value)
  89. return nil
  90. }
  91. type Test struct {
  92. Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
  93. Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
  94. Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
  95. Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
  96. // Types that are valid to be assigned to Union:
  97. // *Test_Number
  98. // *Test_Name
  99. Union isTest_Union `protobuf_oneof:"union"`
  100. XXX_unrecognized []byte `json:"-"`
  101. }
  102. func (m *Test) Reset() { *m = Test{} }
  103. func (m *Test) String() string { return proto.CompactTextString(m) }
  104. func (*Test) ProtoMessage() {}
  105. type isTest_Union interface {
  106. isTest_Union()
  107. }
  108. type Test_Number struct {
  109. Number int32 `protobuf:"varint,6,opt,name=number"`
  110. }
  111. type Test_Name struct {
  112. Name string `protobuf:"bytes,7,opt,name=name"`
  113. }
  114. func (*Test_Number) isTest_Union() {}
  115. func (*Test_Name) isTest_Union() {}
  116. func (m *Test) GetUnion() isTest_Union {
  117. if m != nil {
  118. return m.Union
  119. }
  120. return nil
  121. }
  122. const Default_Test_Type int32 = 77
  123. func (m *Test) GetLabel() string {
  124. if m != nil && m.Label != nil {
  125. return *m.Label
  126. }
  127. return ""
  128. }
  129. func (m *Test) GetType() int32 {
  130. if m != nil && m.Type != nil {
  131. return *m.Type
  132. }
  133. return Default_Test_Type
  134. }
  135. func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
  136. if m != nil {
  137. return m.Optionalgroup
  138. }
  139. return nil
  140. }
  141. type Test_OptionalGroup struct {
  142. RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
  143. }
  144. func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }
  145. func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
  146. func (m *Test_OptionalGroup) GetRequiredField() string {
  147. if m != nil && m.RequiredField != nil {
  148. return *m.RequiredField
  149. }
  150. return ""
  151. }
  152. func (m *Test) GetNumber() int32 {
  153. if x, ok := m.GetUnion().(*Test_Number); ok {
  154. return x.Number
  155. }
  156. return 0
  157. }
  158. func (m *Test) GetName() string {
  159. if x, ok := m.GetUnion().(*Test_Name); ok {
  160. return x.Name
  161. }
  162. return ""
  163. }
  164. func init() {
  165. proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
  166. }
  167. To create and play with a Test object:
  168. package main
  169. import (
  170. "log"
  171. "github.com/golang/protobuf/proto"
  172. pb "./example.pb"
  173. )
  174. func main() {
  175. test := &pb.Test{
  176. Label: proto.String("hello"),
  177. Type: proto.Int32(17),
  178. Reps: []int64{1, 2, 3},
  179. Optionalgroup: &pb.Test_OptionalGroup{
  180. RequiredField: proto.String("good bye"),
  181. },
  182. Union: &pb.Test_Name{"fred"},
  183. }
  184. data, err := proto.Marshal(test)
  185. if err != nil {
  186. log.Fatal("marshaling error: ", err)
  187. }
  188. newTest := &pb.Test{}
  189. err = proto.Unmarshal(data, newTest)
  190. if err != nil {
  191. log.Fatal("unmarshaling error: ", err)
  192. }
  193. // Now test and newTest contain the same data.
  194. if test.GetLabel() != newTest.GetLabel() {
  195. log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
  196. }
  197. // Use a type switch to determine which oneof was set.
  198. switch u := test.Union.(type) {
  199. case *pb.Test_Number: // u.Number contains the number.
  200. case *pb.Test_Name: // u.Name contains the string.
  201. }
  202. // etc.
  203. }
  204. */
  205. package proto
  206. import (
  207. "fmt"
  208. "log"
  209. "reflect"
  210. "sort"
  211. "strconv"
  212. "sync"
  213. // Add a bogus dependency on the v2 API to ensure the Go toolchain does not
  214. // remove our dependency from the go.mod file.
  215. _ "github.com/golang/protobuf/v2/reflect/protoreflect"
  216. "github.com/golang/protobuf/protoapi"
  217. )
  218. // RequiredNotSetError is an error type returned by either Marshal or Unmarshal.
  219. // Marshal reports this when a required field is not initialized.
  220. // Unmarshal reports this when a required field is missing from the wire data.
  221. type RequiredNotSetError struct{ field string }
  222. func (e *RequiredNotSetError) Error() string {
  223. if e.field == "" {
  224. return fmt.Sprintf("proto: required field not set")
  225. }
  226. return fmt.Sprintf("proto: required field %q not set", e.field)
  227. }
  228. func (e *RequiredNotSetError) RequiredNotSet() bool {
  229. return true
  230. }
  231. type invalidUTF8Error struct{ field string }
  232. func (e *invalidUTF8Error) Error() string {
  233. if e.field == "" {
  234. return "proto: invalid UTF-8 detected"
  235. }
  236. return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field)
  237. }
  238. func (e *invalidUTF8Error) InvalidUTF8() bool {
  239. return true
  240. }
  241. // errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8.
  242. // This error should not be exposed to the external API as such errors should
  243. // be recreated with the field information.
  244. var errInvalidUTF8 = &invalidUTF8Error{}
  245. // isNonFatal reports whether the error is either a RequiredNotSet error
  246. // or a InvalidUTF8 error.
  247. func isNonFatal(err error) bool {
  248. if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() {
  249. return true
  250. }
  251. if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() {
  252. return true
  253. }
  254. return false
  255. }
  256. type nonFatal struct{ E error }
  257. // Merge merges err into nf and reports whether it was successful.
  258. // Otherwise it returns false for any fatal non-nil errors.
  259. func (nf *nonFatal) Merge(err error) (ok bool) {
  260. if err == nil {
  261. return true // not an error
  262. }
  263. if !isNonFatal(err) {
  264. return false // fatal error
  265. }
  266. if nf.E == nil {
  267. nf.E = err // store first instance of non-fatal error
  268. }
  269. return true
  270. }
  271. // Message is implemented by generated protocol buffer messages.
  272. type Message = protoapi.Message
  273. // A Buffer is a buffer manager for marshaling and unmarshaling
  274. // protocol buffers. It may be reused between invocations to
  275. // reduce memory usage. It is not necessary to use a Buffer;
  276. // the global functions Marshal and Unmarshal create a
  277. // temporary Buffer and are fine for most applications.
  278. type Buffer struct {
  279. buf []byte // encode/decode byte stream
  280. index int // read point
  281. deterministic bool
  282. }
  283. // NewBuffer allocates a new Buffer and initializes its internal data to
  284. // the contents of the argument slice.
  285. func NewBuffer(e []byte) *Buffer {
  286. return &Buffer{buf: e}
  287. }
  288. // Reset resets the Buffer, ready for marshaling a new protocol buffer.
  289. func (p *Buffer) Reset() {
  290. p.buf = p.buf[0:0] // for reading/writing
  291. p.index = 0 // for reading
  292. }
  293. // SetBuf replaces the internal buffer with the slice,
  294. // ready for unmarshaling the contents of the slice.
  295. func (p *Buffer) SetBuf(s []byte) {
  296. p.buf = s
  297. p.index = 0
  298. }
  299. // Bytes returns the contents of the Buffer.
  300. func (p *Buffer) Bytes() []byte { return p.buf }
  301. // SetDeterministic sets whether to use deterministic serialization.
  302. //
  303. // Deterministic serialization guarantees that for a given binary, equal
  304. // messages will always be serialized to the same bytes. This implies:
  305. //
  306. // - Repeated serialization of a message will return the same bytes.
  307. // - Different processes of the same binary (which may be executing on
  308. // different machines) will serialize equal messages to the same bytes.
  309. //
  310. // Note that the deterministic serialization is NOT canonical across
  311. // languages. It is not guaranteed to remain stable over time. It is unstable
  312. // across different builds with schema changes due to unknown fields.
  313. // Users who need canonical serialization (e.g., persistent storage in a
  314. // canonical form, fingerprinting, etc.) should define their own
  315. // canonicalization specification and implement their own serializer rather
  316. // than relying on this API.
  317. //
  318. // If deterministic serialization is requested, map entries will be sorted
  319. // by keys in lexographical order. This is an implementation detail and
  320. // subject to change.
  321. func (p *Buffer) SetDeterministic(deterministic bool) {
  322. p.deterministic = deterministic
  323. }
  324. /*
  325. * Helper routines for simplifying the creation of optional fields of basic type.
  326. */
  327. // Bool is a helper routine that allocates a new bool value
  328. // to store v and returns a pointer to it.
  329. func Bool(v bool) *bool {
  330. return &v
  331. }
  332. // Int32 is a helper routine that allocates a new int32 value
  333. // to store v and returns a pointer to it.
  334. func Int32(v int32) *int32 {
  335. return &v
  336. }
  337. // Int is a helper routine that allocates a new int32 value
  338. // to store v and returns a pointer to it, but unlike Int32
  339. // its argument value is an int.
  340. func Int(v int) *int32 {
  341. p := new(int32)
  342. *p = int32(v)
  343. return p
  344. }
  345. // Int64 is a helper routine that allocates a new int64 value
  346. // to store v and returns a pointer to it.
  347. func Int64(v int64) *int64 {
  348. return &v
  349. }
  350. // Float32 is a helper routine that allocates a new float32 value
  351. // to store v and returns a pointer to it.
  352. func Float32(v float32) *float32 {
  353. return &v
  354. }
  355. // Float64 is a helper routine that allocates a new float64 value
  356. // to store v and returns a pointer to it.
  357. func Float64(v float64) *float64 {
  358. return &v
  359. }
  360. // Uint32 is a helper routine that allocates a new uint32 value
  361. // to store v and returns a pointer to it.
  362. func Uint32(v uint32) *uint32 {
  363. return &v
  364. }
  365. // Uint64 is a helper routine that allocates a new uint64 value
  366. // to store v and returns a pointer to it.
  367. func Uint64(v uint64) *uint64 {
  368. return &v
  369. }
  370. // String is a helper routine that allocates a new string value
  371. // to store v and returns a pointer to it.
  372. func String(v string) *string {
  373. return &v
  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 (p *Buffer) DebugPrint(s string, b []byte) {
  378. var u uint64
  379. obuf := p.buf
  380. index := p.index
  381. p.buf = b
  382. p.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 := p.index
  391. if index == len(p.buf) {
  392. break
  393. }
  394. op, err := p.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 = p.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 = p.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 = p.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. case WireVarint:
  442. u, err = p.DecodeVarint()
  443. if err != nil {
  444. fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
  445. break out
  446. }
  447. fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
  448. case WireStartGroup:
  449. fmt.Printf("%3d: t=%3d start\n", index, tag)
  450. depth++
  451. case WireEndGroup:
  452. depth--
  453. fmt.Printf("%3d: t=%3d end\n", index, tag)
  454. }
  455. }
  456. if depth != 0 {
  457. fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
  458. }
  459. fmt.Printf("\n")
  460. p.buf = obuf
  461. p.index = index
  462. }
  463. // SetDefaults sets unset protocol buffer fields to their default values.
  464. // It only modifies fields that are both unset and have defined defaults.
  465. // It recursively sets default values in any non-nil sub-messages.
  466. func SetDefaults(pb Message) {
  467. setDefaults(reflect.ValueOf(pb), true, false)
  468. }
  469. // v is a pointer to a struct.
  470. func setDefaults(v reflect.Value, recur, zeros bool) {
  471. v = v.Elem()
  472. defaultMu.RLock()
  473. dm, ok := defaults[v.Type()]
  474. defaultMu.RUnlock()
  475. if !ok {
  476. dm = buildDefaultMessage(v.Type())
  477. defaultMu.Lock()
  478. defaults[v.Type()] = dm
  479. defaultMu.Unlock()
  480. }
  481. for _, sf := range dm.scalars {
  482. f := v.Field(sf.index)
  483. if !f.IsNil() {
  484. // field already set
  485. continue
  486. }
  487. dv := sf.value
  488. if dv == nil && !zeros {
  489. // no explicit default, and don't want to set zeros
  490. continue
  491. }
  492. fptr := f.Addr().Interface() // **T
  493. // TODO: Consider batching the allocations we do here.
  494. switch sf.kind {
  495. case reflect.Bool:
  496. b := new(bool)
  497. if dv != nil {
  498. *b = dv.(bool)
  499. }
  500. *(fptr.(**bool)) = b
  501. case reflect.Float32:
  502. f := new(float32)
  503. if dv != nil {
  504. *f = dv.(float32)
  505. }
  506. *(fptr.(**float32)) = f
  507. case reflect.Float64:
  508. f := new(float64)
  509. if dv != nil {
  510. *f = dv.(float64)
  511. }
  512. *(fptr.(**float64)) = f
  513. case reflect.Int32:
  514. // might be an enum
  515. if ft := f.Type(); ft != int32PtrType {
  516. // enum
  517. f.Set(reflect.New(ft.Elem()))
  518. if dv != nil {
  519. f.Elem().SetInt(int64(dv.(int32)))
  520. }
  521. } else {
  522. // int32 field
  523. i := new(int32)
  524. if dv != nil {
  525. *i = dv.(int32)
  526. }
  527. *(fptr.(**int32)) = i
  528. }
  529. case reflect.Int64:
  530. i := new(int64)
  531. if dv != nil {
  532. *i = dv.(int64)
  533. }
  534. *(fptr.(**int64)) = i
  535. case reflect.String:
  536. s := new(string)
  537. if dv != nil {
  538. *s = dv.(string)
  539. }
  540. *(fptr.(**string)) = s
  541. case reflect.Uint8:
  542. // exceptional case: []byte
  543. var b []byte
  544. if dv != nil {
  545. db := dv.([]byte)
  546. b = make([]byte, len(db))
  547. copy(b, db)
  548. } else {
  549. b = []byte{}
  550. }
  551. *(fptr.(*[]byte)) = b
  552. case reflect.Uint32:
  553. u := new(uint32)
  554. if dv != nil {
  555. *u = dv.(uint32)
  556. }
  557. *(fptr.(**uint32)) = u
  558. case reflect.Uint64:
  559. u := new(uint64)
  560. if dv != nil {
  561. *u = dv.(uint64)
  562. }
  563. *(fptr.(**uint64)) = u
  564. default:
  565. log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
  566. }
  567. }
  568. for _, ni := range dm.nested {
  569. f := v.Field(ni)
  570. // f is *T or []*T or map[T]*T
  571. switch f.Kind() {
  572. case reflect.Ptr:
  573. if f.IsNil() {
  574. continue
  575. }
  576. setDefaults(f, recur, zeros)
  577. case reflect.Slice:
  578. for i := 0; i < f.Len(); i++ {
  579. e := f.Index(i)
  580. if e.IsNil() {
  581. continue
  582. }
  583. setDefaults(e, recur, zeros)
  584. }
  585. case reflect.Map:
  586. for _, k := range f.MapKeys() {
  587. e := f.MapIndex(k)
  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. // t is a struct type.
  614. func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
  615. sprop := GetProperties(t)
  616. for _, prop := range sprop.Prop {
  617. fi, ok := sprop.decoderTags.get(prop.Tag)
  618. if !ok {
  619. // XXX_unrecognized
  620. continue
  621. }
  622. ft := t.Field(fi).Type
  623. sf, nested, err := fieldDefault(ft, prop)
  624. switch {
  625. case err != nil:
  626. log.Print(err)
  627. case nested:
  628. dm.nested = append(dm.nested, fi)
  629. case sf != nil:
  630. sf.index = fi
  631. dm.scalars = append(dm.scalars, *sf)
  632. }
  633. }
  634. return dm
  635. }
  636. // fieldDefault returns the scalarField for field type ft.
  637. // sf will be nil if the field can not have a default.
  638. // nestedMessage will be true if this is a nested message.
  639. // Note that sf.index is not set on return.
  640. func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
  641. var canHaveDefault bool
  642. switch ft.Kind() {
  643. case reflect.Ptr:
  644. if ft.Elem().Kind() == reflect.Struct {
  645. nestedMessage = true
  646. } else {
  647. canHaveDefault = true // proto2 scalar field
  648. }
  649. case reflect.Slice:
  650. switch ft.Elem().Kind() {
  651. case reflect.Ptr:
  652. nestedMessage = true // repeated message
  653. case reflect.Uint8:
  654. canHaveDefault = true // bytes field
  655. }
  656. case reflect.Map:
  657. if ft.Elem().Kind() == reflect.Ptr {
  658. nestedMessage = true // map with message values
  659. }
  660. }
  661. if !canHaveDefault {
  662. if nestedMessage {
  663. return nil, true, nil
  664. }
  665. return nil, false, nil
  666. }
  667. // We now know that ft is a pointer or slice.
  668. sf = &scalarField{kind: ft.Elem().Kind()}
  669. // scalar fields without defaults
  670. if !prop.HasDefault {
  671. return sf, false, nil
  672. }
  673. // a scalar field: either *T or []byte
  674. switch ft.Elem().Kind() {
  675. case reflect.Bool:
  676. x, err := strconv.ParseBool(prop.Default)
  677. if err != nil {
  678. return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
  679. }
  680. sf.value = x
  681. case reflect.Float32:
  682. x, err := strconv.ParseFloat(prop.Default, 32)
  683. if err != nil {
  684. return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
  685. }
  686. sf.value = float32(x)
  687. case reflect.Float64:
  688. x, err := strconv.ParseFloat(prop.Default, 64)
  689. if err != nil {
  690. return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
  691. }
  692. sf.value = x
  693. case reflect.Int32:
  694. x, err := strconv.ParseInt(prop.Default, 10, 32)
  695. if err != nil {
  696. return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
  697. }
  698. sf.value = int32(x)
  699. case reflect.Int64:
  700. x, err := strconv.ParseInt(prop.Default, 10, 64)
  701. if err != nil {
  702. return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
  703. }
  704. sf.value = x
  705. case reflect.String:
  706. sf.value = prop.Default
  707. case reflect.Uint8:
  708. // []byte (not *uint8)
  709. sf.value = []byte(prop.Default)
  710. case reflect.Uint32:
  711. x, err := strconv.ParseUint(prop.Default, 10, 32)
  712. if err != nil {
  713. return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
  714. }
  715. sf.value = uint32(x)
  716. case reflect.Uint64:
  717. x, err := strconv.ParseUint(prop.Default, 10, 64)
  718. if err != nil {
  719. return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
  720. }
  721. sf.value = x
  722. default:
  723. return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
  724. }
  725. return sf, false, nil
  726. }
  727. // mapKeys returns a sort.Interface to be used for sorting the map keys.
  728. // Map fields may have key types of non-float scalars, strings and enums.
  729. func mapKeys(vs []reflect.Value) sort.Interface {
  730. s := mapKeySorter{vs: vs}
  731. // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps.
  732. if len(vs) == 0 {
  733. return s
  734. }
  735. switch vs[0].Kind() {
  736. case reflect.Int32, reflect.Int64:
  737. s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
  738. case reflect.Uint32, reflect.Uint64:
  739. s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
  740. case reflect.Bool:
  741. s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true
  742. case reflect.String:
  743. s.less = func(a, b reflect.Value) bool { return a.String() < b.String() }
  744. default:
  745. panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind()))
  746. }
  747. return s
  748. }
  749. type mapKeySorter struct {
  750. vs []reflect.Value
  751. less func(a, b reflect.Value) bool
  752. }
  753. func (s mapKeySorter) Len() int { return len(s.vs) }
  754. func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
  755. func (s mapKeySorter) Less(i, j int) bool {
  756. return s.less(s.vs[i], s.vs[j])
  757. }
  758. // isProto3Zero reports whether v is a zero proto3 value.
  759. func isProto3Zero(v reflect.Value) bool {
  760. switch v.Kind() {
  761. case reflect.Bool:
  762. return !v.Bool()
  763. case reflect.Int32, reflect.Int64:
  764. return v.Int() == 0
  765. case reflect.Uint32, reflect.Uint64:
  766. return v.Uint() == 0
  767. case reflect.Float32, reflect.Float64:
  768. return v.Float() == 0
  769. case reflect.String:
  770. return v.String() == ""
  771. }
  772. return false
  773. }
  774. const (
  775. // ProtoPackageIsVersion3 is referenced from generated protocol buffer files
  776. // to assert that that code is compatible with this version of the proto package.
  777. ProtoPackageIsVersion3 = true
  778. // ProtoPackageIsVersion2 is referenced from generated protocol buffer files
  779. // to assert that that code is compatible with this version of the proto package.
  780. ProtoPackageIsVersion2 = true
  781. // ProtoPackageIsVersion1 is referenced from generated protocol buffer files
  782. // to assert that that code is compatible with this version of the proto package.
  783. ProtoPackageIsVersion1 = true
  784. )
  785. // InternalMessageInfo is a type used internally by generated .pb.go files.
  786. // This type is not intended to be used by non-generated code.
  787. // This type is not subject to any compatibility guarantee.
  788. type InternalMessageInfo struct {
  789. marshal *marshalInfo
  790. unmarshal *unmarshalInfo
  791. merge *mergeInfo
  792. discard *discardInfo
  793. }