http urls monitor.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2010 The Go Authors. All rights reserved.
  4. // https://github.com/golang/protobuf
  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. msg.Foo = proto.String("hello") // set field
  51. - Constants are defined to hold the default values of all fields that
  52. have them. They have the form Default_StructName_FieldName.
  53. Because the getter methods handle defaulted values,
  54. direct use of these constants should be rare.
  55. - Enums are given type names and maps from names to values.
  56. Enum values are prefixed by the enclosing message's name, or by the
  57. enum's type name if it is a top-level enum. Enum types have a String
  58. method, and a Enum method to assist in message construction.
  59. - Nested messages, groups and enums have type names prefixed with the name of
  60. the surrounding message type.
  61. - Extensions are given descriptor names that start with E_,
  62. followed by an underscore-delimited list of the nested messages
  63. that contain it (if any) followed by the CamelCased name of the
  64. extension field itself. HasExtension, ClearExtension, GetExtension
  65. and SetExtension are functions for manipulating extensions.
  66. - Oneof field sets are given a single field in their message,
  67. with distinguished wrapper types for each possible field value.
  68. - Marshal and Unmarshal are functions to encode and decode the wire format.
  69. When the .proto file specifies `syntax="proto3"`, there are some differences:
  70. - Non-repeated fields of non-message type are values instead of pointers.
  71. - Enum types do not get an Enum method.
  72. The simplest way to describe this is to see an example.
  73. Given file test.proto, containing
  74. package example;
  75. enum FOO { X = 17; }
  76. message Test {
  77. required string label = 1;
  78. optional int32 type = 2 [default=77];
  79. repeated int64 reps = 3;
  80. optional group OptionalGroup = 4 {
  81. required string RequiredField = 5;
  82. }
  83. oneof union {
  84. int32 number = 6;
  85. string name = 7;
  86. }
  87. }
  88. The resulting file, test.pb.go, is:
  89. package example
  90. import proto "github.com/golang/protobuf/proto"
  91. import math "math"
  92. type FOO int32
  93. const (
  94. FOO_X FOO = 17
  95. )
  96. var FOO_name = map[int32]string{
  97. 17: "X",
  98. }
  99. var FOO_value = map[string]int32{
  100. "X": 17,
  101. }
  102. func (x FOO) Enum() *FOO {
  103. p := new(FOO)
  104. *p = x
  105. return p
  106. }
  107. func (x FOO) String() string {
  108. return proto.EnumName(FOO_name, int32(x))
  109. }
  110. func (x *FOO) UnmarshalJSON(data []byte) error {
  111. value, err := proto.UnmarshalJSONEnum(FOO_value, data)
  112. if err != nil {
  113. return err
  114. }
  115. *x = FOO(value)
  116. return nil
  117. }
  118. type Test struct {
  119. Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
  120. Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
  121. Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
  122. Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
  123. // Types that are valid to be assigned to Union:
  124. // *Test_Number
  125. // *Test_Name
  126. Union isTest_Union `protobuf_oneof:"union"`
  127. XXX_unrecognized []byte `json:"-"`
  128. }
  129. func (m *Test) Reset() { *m = Test{} }
  130. func (m *Test) String() string { return proto.CompactTextString(m) }
  131. func (*Test) ProtoMessage() {}
  132. type isTest_Union interface {
  133. isTest_Union()
  134. }
  135. type Test_Number struct {
  136. Number int32 `protobuf:"varint,6,opt,name=number"`
  137. }
  138. type Test_Name struct {
  139. Name string `protobuf:"bytes,7,opt,name=name"`
  140. }
  141. func (*Test_Number) isTest_Union() {}
  142. func (*Test_Name) isTest_Union() {}
  143. func (m *Test) GetUnion() isTest_Union {
  144. if m != nil {
  145. return m.Union
  146. }
  147. return nil
  148. }
  149. const Default_Test_Type int32 = 77
  150. func (m *Test) GetLabel() string {
  151. if m != nil && m.Label != nil {
  152. return *m.Label
  153. }
  154. return ""
  155. }
  156. func (m *Test) GetType() int32 {
  157. if m != nil && m.Type != nil {
  158. return *m.Type
  159. }
  160. return Default_Test_Type
  161. }
  162. func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
  163. if m != nil {
  164. return m.Optionalgroup
  165. }
  166. return nil
  167. }
  168. type Test_OptionalGroup struct {
  169. RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
  170. }
  171. func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }
  172. func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
  173. func (m *Test_OptionalGroup) GetRequiredField() string {
  174. if m != nil && m.RequiredField != nil {
  175. return *m.RequiredField
  176. }
  177. return ""
  178. }
  179. func (m *Test) GetNumber() int32 {
  180. if x, ok := m.GetUnion().(*Test_Number); ok {
  181. return x.Number
  182. }
  183. return 0
  184. }
  185. func (m *Test) GetName() string {
  186. if x, ok := m.GetUnion().(*Test_Name); ok {
  187. return x.Name
  188. }
  189. return ""
  190. }
  191. func init() {
  192. proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
  193. }
  194. To create and play with a Test object:
  195. package main
  196. import (
  197. "log"
  198. "github.com/golang/protobuf/proto"
  199. pb "./example.pb"
  200. )
  201. func main() {
  202. test := &pb.Test{
  203. Label: proto.String("hello"),
  204. Type: proto.Int32(17),
  205. Reps: []int64{1, 2, 3},
  206. Optionalgroup: &pb.Test_OptionalGroup{
  207. RequiredField: proto.String("good bye"),
  208. },
  209. Union: &pb.Test_Name{"fred"},
  210. }
  211. data, err := proto.Marshal(test)
  212. if err != nil {
  213. log.Fatal("marshaling error: ", err)
  214. }
  215. newTest := &pb.Test{}
  216. err = proto.Unmarshal(data, newTest)
  217. if err != nil {
  218. log.Fatal("unmarshaling error: ", err)
  219. }
  220. // Now test and newTest contain the same data.
  221. if test.GetLabel() != newTest.GetLabel() {
  222. log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
  223. }
  224. // Use a type switch to determine which oneof was set.
  225. switch u := test.Union.(type) {
  226. case *pb.Test_Number: // u.Number contains the number.
  227. case *pb.Test_Name: // u.Name contains the string.
  228. }
  229. // etc.
  230. }
  231. */
  232. package proto
  233. import (
  234. "encoding/json"
  235. "fmt"
  236. "log"
  237. "reflect"
  238. "sort"
  239. "strconv"
  240. "sync"
  241. )
  242. // RequiredNotSetError is an error type returned by either Marshal or Unmarshal.
  243. // Marshal reports this when a required field is not initialized.
  244. // Unmarshal reports this when a required field is missing from the wire data.
  245. type RequiredNotSetError struct{ field string }
  246. func (e *RequiredNotSetError) Error() string {
  247. if e.field == "" {
  248. return fmt.Sprintf("proto: required field not set")
  249. }
  250. return fmt.Sprintf("proto: required field %q not set", e.field)
  251. }
  252. func (e *RequiredNotSetError) RequiredNotSet() bool {
  253. return true
  254. }
  255. type invalidUTF8Error struct{ field string }
  256. func (e *invalidUTF8Error) Error() string {
  257. if e.field == "" {
  258. return "proto: invalid UTF-8 detected"
  259. }
  260. return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field)
  261. }
  262. func (e *invalidUTF8Error) InvalidUTF8() bool {
  263. return true
  264. }
  265. // errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8.
  266. // This error should not be exposed to the external API as such errors should
  267. // be recreated with the field information.
  268. var errInvalidUTF8 = &invalidUTF8Error{}
  269. // isNonFatal reports whether the error is either a RequiredNotSet error
  270. // or a InvalidUTF8 error.
  271. func isNonFatal(err error) bool {
  272. if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() {
  273. return true
  274. }
  275. if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() {
  276. return true
  277. }
  278. return false
  279. }
  280. type nonFatal struct{ E error }
  281. // Merge merges err into nf and reports whether it was successful.
  282. // Otherwise it returns false for any fatal non-nil errors.
  283. func (nf *nonFatal) Merge(err error) (ok bool) {
  284. if err == nil {
  285. return true // not an error
  286. }
  287. if !isNonFatal(err) {
  288. return false // fatal error
  289. }
  290. if nf.E == nil {
  291. nf.E = err // store first instance of non-fatal error
  292. }
  293. return true
  294. }
  295. // Message is implemented by generated protocol buffer messages.
  296. type Message interface {
  297. Reset()
  298. String() string
  299. ProtoMessage()
  300. }
  301. // Stats records allocation details about the protocol buffer encoders
  302. // and decoders. Useful for tuning the library itself.
  303. type Stats struct {
  304. Emalloc uint64 // mallocs in encode
  305. Dmalloc uint64 // mallocs in decode
  306. Encode uint64 // number of encodes
  307. Decode uint64 // number of decodes
  308. Chit uint64 // number of cache hits
  309. Cmiss uint64 // number of cache misses
  310. Size uint64 // number of sizes
  311. }
  312. // Set to true to enable stats collection.
  313. const collectStats = false
  314. var stats Stats
  315. // GetStats returns a copy of the global Stats structure.
  316. func GetStats() Stats { return stats }
  317. // A Buffer is a buffer manager for marshaling and unmarshaling
  318. // protocol buffers. It may be reused between invocations to
  319. // reduce memory usage. It is not necessary to use a Buffer;
  320. // the global functions Marshal and Unmarshal create a
  321. // temporary Buffer and are fine for most applications.
  322. type Buffer struct {
  323. buf []byte // encode/decode byte stream
  324. index int // read point
  325. deterministic bool
  326. }
  327. // NewBuffer allocates a new Buffer and initializes its internal data to
  328. // the contents of the argument slice.
  329. func NewBuffer(e []byte) *Buffer {
  330. return &Buffer{buf: e}
  331. }
  332. // Reset resets the Buffer, ready for marshaling a new protocol buffer.
  333. func (p *Buffer) Reset() {
  334. p.buf = p.buf[0:0] // for reading/writing
  335. p.index = 0 // for reading
  336. }
  337. // SetBuf replaces the internal buffer with the slice,
  338. // ready for unmarshaling the contents of the slice.
  339. func (p *Buffer) SetBuf(s []byte) {
  340. p.buf = s
  341. p.index = 0
  342. }
  343. // Bytes returns the contents of the Buffer.
  344. func (p *Buffer) Bytes() []byte { return p.buf }
  345. // SetDeterministic sets whether to use deterministic serialization.
  346. //
  347. // Deterministic serialization guarantees that for a given binary, equal
  348. // messages will always be serialized to the same bytes. This implies:
  349. //
  350. // - Repeated serialization of a message will return the same bytes.
  351. // - Different processes of the same binary (which may be executing on
  352. // different machines) will serialize equal messages to the same bytes.
  353. //
  354. // Note that the deterministic serialization is NOT canonical across
  355. // languages. It is not guaranteed to remain stable over time. It is unstable
  356. // across different builds with schema changes due to unknown fields.
  357. // Users who need canonical serialization (e.g., persistent storage in a
  358. // canonical form, fingerprinting, etc.) should define their own
  359. // canonicalization specification and implement their own serializer rather
  360. // than relying on this API.
  361. //
  362. // If deterministic serialization is requested, map entries will be sorted
  363. // by keys in lexographical order. This is an implementation detail and
  364. // subject to change.
  365. func (p *Buffer) SetDeterministic(deterministic bool) {
  366. p.deterministic = deterministic
  367. }
  368. /*
  369. * Helper routines for simplifying the creation of optional fields of basic type.
  370. */
  371. // Bool is a helper routine that allocates a new bool value
  372. // to store v and returns a pointer to it.
  373. func Bool(v bool) *bool {
  374. return &v
  375. }
  376. // Int32 is a helper routine that allocates a new int32 value
  377. // to store v and returns a pointer to it.
  378. func Int32(v int32) *int32 {
  379. return &v
  380. }
  381. // Int is a helper routine that allocates a new int32 value
  382. // to store v and returns a pointer to it, but unlike Int32
  383. // its argument value is an int.
  384. func Int(v int) *int32 {
  385. p := new(int32)
  386. *p = int32(v)
  387. return p
  388. }
  389. // Int64 is a helper routine that allocates a new int64 value
  390. // to store v and returns a pointer to it.
  391. func Int64(v int64) *int64 {
  392. return &v
  393. }
  394. // Float32 is a helper routine that allocates a new float32 value
  395. // to store v and returns a pointer to it.
  396. func Float32(v float32) *float32 {
  397. return &v
  398. }
  399. // Float64 is a helper routine that allocates a new float64 value
  400. // to store v and returns a pointer to it.
  401. func Float64(v float64) *float64 {
  402. return &v
  403. }
  404. // Uint32 is a helper routine that allocates a new uint32 value
  405. // to store v and returns a pointer to it.
  406. func Uint32(v uint32) *uint32 {
  407. return &v
  408. }
  409. // Uint64 is a helper routine that allocates a new uint64 value
  410. // to store v and returns a pointer to it.
  411. func Uint64(v uint64) *uint64 {
  412. return &v
  413. }
  414. // String is a helper routine that allocates a new string value
  415. // to store v and returns a pointer to it.
  416. func String(v string) *string {
  417. return &v
  418. }
  419. // EnumName is a helper function to simplify printing protocol buffer enums
  420. // by name. Given an enum map and a value, it returns a useful string.
  421. func EnumName(m map[int32]string, v int32) string {
  422. s, ok := m[v]
  423. if ok {
  424. return s
  425. }
  426. return strconv.Itoa(int(v))
  427. }
  428. // UnmarshalJSONEnum is a helper function to simplify recovering enum int values
  429. // from their JSON-encoded representation. Given a map from the enum's symbolic
  430. // names to its int values, and a byte buffer containing the JSON-encoded
  431. // value, it returns an int32 that can be cast to the enum type by the caller.
  432. //
  433. // The function can deal with both JSON representations, numeric and symbolic.
  434. func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
  435. if data[0] == '"' {
  436. // New style: enums are strings.
  437. var repr string
  438. if err := json.Unmarshal(data, &repr); err != nil {
  439. return -1, err
  440. }
  441. val, ok := m[repr]
  442. if !ok {
  443. return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
  444. }
  445. return val, nil
  446. }
  447. // Old style: enums are ints.
  448. var val int32
  449. if err := json.Unmarshal(data, &val); err != nil {
  450. return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
  451. }
  452. return val, nil
  453. }
  454. // DebugPrint dumps the encoded data in b in a debugging format with a header
  455. // including the string s. Used in testing but made available for general debugging.
  456. func (p *Buffer) DebugPrint(s string, b []byte) {
  457. var u uint64
  458. obuf := p.buf
  459. index := p.index
  460. p.buf = b
  461. p.index = 0
  462. depth := 0
  463. fmt.Printf("\n--- %s ---\n", s)
  464. out:
  465. for {
  466. for i := 0; i < depth; i++ {
  467. fmt.Print(" ")
  468. }
  469. index := p.index
  470. if index == len(p.buf) {
  471. break
  472. }
  473. op, err := p.DecodeVarint()
  474. if err != nil {
  475. fmt.Printf("%3d: fetching op err %v\n", index, err)
  476. break out
  477. }
  478. tag := op >> 3
  479. wire := op & 7
  480. switch wire {
  481. default:
  482. fmt.Printf("%3d: t=%3d unknown wire=%d\n",
  483. index, tag, wire)
  484. break out
  485. case WireBytes:
  486. var r []byte
  487. r, err = p.DecodeRawBytes(false)
  488. if err != nil {
  489. break out
  490. }
  491. fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
  492. if len(r) <= 6 {
  493. for i := 0; i < len(r); i++ {
  494. fmt.Printf(" %.2x", r[i])
  495. }
  496. } else {
  497. for i := 0; i < 3; i++ {
  498. fmt.Printf(" %.2x", r[i])
  499. }
  500. fmt.Printf(" ..")
  501. for i := len(r) - 3; i < len(r); i++ {
  502. fmt.Printf(" %.2x", r[i])
  503. }
  504. }
  505. fmt.Printf("\n")
  506. case WireFixed32:
  507. u, err = p.DecodeFixed32()
  508. if err != nil {
  509. fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
  510. break out
  511. }
  512. fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
  513. case WireFixed64:
  514. u, err = p.DecodeFixed64()
  515. if err != nil {
  516. fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
  517. break out
  518. }
  519. fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
  520. case WireVarint:
  521. u, err = p.DecodeVarint()
  522. if err != nil {
  523. fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
  524. break out
  525. }
  526. fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
  527. case WireStartGroup:
  528. fmt.Printf("%3d: t=%3d start\n", index, tag)
  529. depth++
  530. case WireEndGroup:
  531. depth--
  532. fmt.Printf("%3d: t=%3d end\n", index, tag)
  533. }
  534. }
  535. if depth != 0 {
  536. fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
  537. }
  538. fmt.Printf("\n")
  539. p.buf = obuf
  540. p.index = index
  541. }
  542. // SetDefaults sets unset protocol buffer fields to their default values.
  543. // It only modifies fields that are both unset and have defined defaults.
  544. // It recursively sets default values in any non-nil sub-messages.
  545. func SetDefaults(pb Message) {
  546. setDefaults(reflect.ValueOf(pb), true, false)
  547. }
  548. // v is a pointer to a struct.
  549. func setDefaults(v reflect.Value, recur, zeros bool) {
  550. v = v.Elem()
  551. defaultMu.RLock()
  552. dm, ok := defaults[v.Type()]
  553. defaultMu.RUnlock()
  554. if !ok {
  555. dm = buildDefaultMessage(v.Type())
  556. defaultMu.Lock()
  557. defaults[v.Type()] = dm
  558. defaultMu.Unlock()
  559. }
  560. for _, sf := range dm.scalars {
  561. f := v.Field(sf.index)
  562. if !f.IsNil() {
  563. // field already set
  564. continue
  565. }
  566. dv := sf.value
  567. if dv == nil && !zeros {
  568. // no explicit default, and don't want to set zeros
  569. continue
  570. }
  571. fptr := f.Addr().Interface() // **T
  572. // TODO: Consider batching the allocations we do here.
  573. switch sf.kind {
  574. case reflect.Bool:
  575. b := new(bool)
  576. if dv != nil {
  577. *b = dv.(bool)
  578. }
  579. *(fptr.(**bool)) = b
  580. case reflect.Float32:
  581. f := new(float32)
  582. if dv != nil {
  583. *f = dv.(float32)
  584. }
  585. *(fptr.(**float32)) = f
  586. case reflect.Float64:
  587. f := new(float64)
  588. if dv != nil {
  589. *f = dv.(float64)
  590. }
  591. *(fptr.(**float64)) = f
  592. case reflect.Int32:
  593. // might be an enum
  594. if ft := f.Type(); ft != int32PtrType {
  595. // enum
  596. f.Set(reflect.New(ft.Elem()))
  597. if dv != nil {
  598. f.Elem().SetInt(int64(dv.(int32)))
  599. }
  600. } else {
  601. // int32 field
  602. i := new(int32)
  603. if dv != nil {
  604. *i = dv.(int32)
  605. }
  606. *(fptr.(**int32)) = i
  607. }
  608. case reflect.Int64:
  609. i := new(int64)
  610. if dv != nil {
  611. *i = dv.(int64)
  612. }
  613. *(fptr.(**int64)) = i
  614. case reflect.String:
  615. s := new(string)
  616. if dv != nil {
  617. *s = dv.(string)
  618. }
  619. *(fptr.(**string)) = s
  620. case reflect.Uint8:
  621. // exceptional case: []byte
  622. var b []byte
  623. if dv != nil {
  624. db := dv.([]byte)
  625. b = make([]byte, len(db))
  626. copy(b, db)
  627. } else {
  628. b = []byte{}
  629. }
  630. *(fptr.(*[]byte)) = b
  631. case reflect.Uint32:
  632. u := new(uint32)
  633. if dv != nil {
  634. *u = dv.(uint32)
  635. }
  636. *(fptr.(**uint32)) = u
  637. case reflect.Uint64:
  638. u := new(uint64)
  639. if dv != nil {
  640. *u = dv.(uint64)
  641. }
  642. *(fptr.(**uint64)) = u
  643. default:
  644. log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
  645. }
  646. }
  647. for _, ni := range dm.nested {
  648. f := v.Field(ni)
  649. // f is *T or []*T or map[T]*T
  650. switch f.Kind() {
  651. case reflect.Ptr:
  652. if f.IsNil() {
  653. continue
  654. }
  655. setDefaults(f, recur, zeros)
  656. case reflect.Slice:
  657. for i := 0; i < f.Len(); i++ {
  658. e := f.Index(i)
  659. if e.IsNil() {
  660. continue
  661. }
  662. setDefaults(e, recur, zeros)
  663. }
  664. case reflect.Map:
  665. for _, k := range f.MapKeys() {
  666. e := f.MapIndex(k)
  667. if e.IsNil() {
  668. continue
  669. }
  670. setDefaults(e, recur, zeros)
  671. }
  672. }
  673. }
  674. }
  675. var (
  676. // defaults maps a protocol buffer struct type to a slice of the fields,
  677. // with its scalar fields set to their proto-declared non-zero default values.
  678. defaultMu sync.RWMutex
  679. defaults = make(map[reflect.Type]defaultMessage)
  680. int32PtrType = reflect.TypeOf((*int32)(nil))
  681. )
  682. // defaultMessage represents information about the default values of a message.
  683. type defaultMessage struct {
  684. scalars []scalarField
  685. nested []int // struct field index of nested messages
  686. }
  687. type scalarField struct {
  688. index int // struct field index
  689. kind reflect.Kind // element type (the T in *T or []T)
  690. value interface{} // the proto-declared default value, or nil
  691. }
  692. // t is a struct type.
  693. func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
  694. sprop := GetProperties(t)
  695. for _, prop := range sprop.Prop {
  696. fi, ok := sprop.decoderTags.get(prop.Tag)
  697. if !ok {
  698. // XXX_unrecognized
  699. continue
  700. }
  701. ft := t.Field(fi).Type
  702. sf, nested, err := fieldDefault(ft, prop)
  703. switch {
  704. case err != nil:
  705. log.Print(err)
  706. case nested:
  707. dm.nested = append(dm.nested, fi)
  708. case sf != nil:
  709. sf.index = fi
  710. dm.scalars = append(dm.scalars, *sf)
  711. }
  712. }
  713. return dm
  714. }
  715. // fieldDefault returns the scalarField for field type ft.
  716. // sf will be nil if the field can not have a default.
  717. // nestedMessage will be true if this is a nested message.
  718. // Note that sf.index is not set on return.
  719. func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
  720. var canHaveDefault bool
  721. switch ft.Kind() {
  722. case reflect.Ptr:
  723. if ft.Elem().Kind() == reflect.Struct {
  724. nestedMessage = true
  725. } else {
  726. canHaveDefault = true // proto2 scalar field
  727. }
  728. case reflect.Slice:
  729. switch ft.Elem().Kind() {
  730. case reflect.Ptr:
  731. nestedMessage = true // repeated message
  732. case reflect.Uint8:
  733. canHaveDefault = true // bytes field
  734. }
  735. case reflect.Map:
  736. if ft.Elem().Kind() == reflect.Ptr {
  737. nestedMessage = true // map with message values
  738. }
  739. }
  740. if !canHaveDefault {
  741. if nestedMessage {
  742. return nil, true, nil
  743. }
  744. return nil, false, nil
  745. }
  746. // We now know that ft is a pointer or slice.
  747. sf = &scalarField{kind: ft.Elem().Kind()}
  748. // scalar fields without defaults
  749. if !prop.HasDefault {
  750. return sf, false, nil
  751. }
  752. // a scalar field: either *T or []byte
  753. switch ft.Elem().Kind() {
  754. case reflect.Bool:
  755. x, err := strconv.ParseBool(prop.Default)
  756. if err != nil {
  757. return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
  758. }
  759. sf.value = x
  760. case reflect.Float32:
  761. x, err := strconv.ParseFloat(prop.Default, 32)
  762. if err != nil {
  763. return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
  764. }
  765. sf.value = float32(x)
  766. case reflect.Float64:
  767. x, err := strconv.ParseFloat(prop.Default, 64)
  768. if err != nil {
  769. return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
  770. }
  771. sf.value = x
  772. case reflect.Int32:
  773. x, err := strconv.ParseInt(prop.Default, 10, 32)
  774. if err != nil {
  775. return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
  776. }
  777. sf.value = int32(x)
  778. case reflect.Int64:
  779. x, err := strconv.ParseInt(prop.Default, 10, 64)
  780. if err != nil {
  781. return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
  782. }
  783. sf.value = x
  784. case reflect.String:
  785. sf.value = prop.Default
  786. case reflect.Uint8:
  787. // []byte (not *uint8)
  788. sf.value = []byte(prop.Default)
  789. case reflect.Uint32:
  790. x, err := strconv.ParseUint(prop.Default, 10, 32)
  791. if err != nil {
  792. return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
  793. }
  794. sf.value = uint32(x)
  795. case reflect.Uint64:
  796. x, err := strconv.ParseUint(prop.Default, 10, 64)
  797. if err != nil {
  798. return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
  799. }
  800. sf.value = x
  801. default:
  802. return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
  803. }
  804. return sf, false, nil
  805. }
  806. // mapKeys returns a sort.Interface to be used for sorting the map keys.
  807. // Map fields may have key types of non-float scalars, strings and enums.
  808. func mapKeys(vs []reflect.Value) sort.Interface {
  809. s := mapKeySorter{vs: vs}
  810. // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps.
  811. if len(vs) == 0 {
  812. return s
  813. }
  814. switch vs[0].Kind() {
  815. case reflect.Int32, reflect.Int64:
  816. s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
  817. case reflect.Uint32, reflect.Uint64:
  818. s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
  819. case reflect.Bool:
  820. s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true
  821. case reflect.String:
  822. s.less = func(a, b reflect.Value) bool { return a.String() < b.String() }
  823. default:
  824. panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind()))
  825. }
  826. return s
  827. }
  828. type mapKeySorter struct {
  829. vs []reflect.Value
  830. less func(a, b reflect.Value) bool
  831. }
  832. func (s mapKeySorter) Len() int { return len(s.vs) }
  833. func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
  834. func (s mapKeySorter) Less(i, j int) bool {
  835. return s.less(s.vs[i], s.vs[j])
  836. }
  837. // isProto3Zero reports whether v is a zero proto3 value.
  838. func isProto3Zero(v reflect.Value) bool {
  839. switch v.Kind() {
  840. case reflect.Bool:
  841. return !v.Bool()
  842. case reflect.Int32, reflect.Int64:
  843. return v.Int() == 0
  844. case reflect.Uint32, reflect.Uint64:
  845. return v.Uint() == 0
  846. case reflect.Float32, reflect.Float64:
  847. return v.Float() == 0
  848. case reflect.String:
  849. return v.String() == ""
  850. }
  851. return false
  852. }
  853. // ProtoPackageIsVersion2 is referenced from generated protocol buffer files
  854. // to assert that that code is compatible with this version of the proto package.
  855. const ProtoPackageIsVersion2 = true
  856. // ProtoPackageIsVersion1 is referenced from generated protocol buffer files
  857. // to assert that that code is compatible with this version of the proto package.
  858. const ProtoPackageIsVersion1 = true
  859. // InternalMessageInfo is a type used internally by generated .pb.go files.
  860. // This type is not intended to be used by non-generated code.
  861. // This type is not subject to any compatibility guarantee.
  862. type InternalMessageInfo struct {
  863. marshal *marshalInfo
  864. unmarshal *unmarshalInfo
  865. merge *mergeInfo
  866. discard *discardInfo
  867. }