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