Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame^] | 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 | "errors" |
| 269 | "fmt" |
| 270 | "log" |
| 271 | "reflect" |
| 272 | "sort" |
| 273 | "strconv" |
| 274 | "sync" |
| 275 | ) |
| 276 | |
| 277 | var errInvalidUTF8 = errors.New("proto: invalid UTF-8 string") |
| 278 | |
| 279 | // Message is implemented by generated protocol buffer messages. |
| 280 | type Message interface { |
| 281 | Reset() |
| 282 | String() string |
| 283 | ProtoMessage() |
| 284 | } |
| 285 | |
| 286 | // Stats records allocation details about the protocol buffer encoders |
| 287 | // and decoders. Useful for tuning the library itself. |
| 288 | type Stats struct { |
| 289 | Emalloc uint64 // mallocs in encode |
| 290 | Dmalloc uint64 // mallocs in decode |
| 291 | Encode uint64 // number of encodes |
| 292 | Decode uint64 // number of decodes |
| 293 | Chit uint64 // number of cache hits |
| 294 | Cmiss uint64 // number of cache misses |
| 295 | Size uint64 // number of sizes |
| 296 | } |
| 297 | |
| 298 | // Set to true to enable stats collection. |
| 299 | const collectStats = false |
| 300 | |
| 301 | var stats Stats |
| 302 | |
| 303 | // GetStats returns a copy of the global Stats structure. |
| 304 | func GetStats() Stats { return stats } |
| 305 | |
| 306 | // A Buffer is a buffer manager for marshaling and unmarshaling |
| 307 | // protocol buffers. It may be reused between invocations to |
| 308 | // reduce memory usage. It is not necessary to use a Buffer; |
| 309 | // the global functions Marshal and Unmarshal create a |
| 310 | // temporary Buffer and are fine for most applications. |
| 311 | type Buffer struct { |
| 312 | buf []byte // encode/decode byte stream |
| 313 | index int // read point |
| 314 | |
| 315 | deterministic bool |
| 316 | } |
| 317 | |
| 318 | // NewBuffer allocates a new Buffer and initializes its internal data to |
| 319 | // the contents of the argument slice. |
| 320 | func NewBuffer(e []byte) *Buffer { |
| 321 | return &Buffer{buf: e} |
| 322 | } |
| 323 | |
| 324 | // Reset resets the Buffer, ready for marshaling a new protocol buffer. |
| 325 | func (p *Buffer) Reset() { |
| 326 | p.buf = p.buf[0:0] // for reading/writing |
| 327 | p.index = 0 // for reading |
| 328 | } |
| 329 | |
| 330 | // SetBuf replaces the internal buffer with the slice, |
| 331 | // ready for unmarshaling the contents of the slice. |
| 332 | func (p *Buffer) SetBuf(s []byte) { |
| 333 | p.buf = s |
| 334 | p.index = 0 |
| 335 | } |
| 336 | |
| 337 | // Bytes returns the contents of the Buffer. |
| 338 | func (p *Buffer) Bytes() []byte { return p.buf } |
| 339 | |
| 340 | // SetDeterministic sets whether to use deterministic serialization. |
| 341 | // |
| 342 | // Deterministic serialization guarantees that for a given binary, equal |
| 343 | // messages will always be serialized to the same bytes. This implies: |
| 344 | // |
| 345 | // - Repeated serialization of a message will return the same bytes. |
| 346 | // - Different processes of the same binary (which may be executing on |
| 347 | // different machines) will serialize equal messages to the same bytes. |
| 348 | // |
| 349 | // Note that the deterministic serialization is NOT canonical across |
| 350 | // languages. It is not guaranteed to remain stable over time. It is unstable |
| 351 | // across different builds with schema changes due to unknown fields. |
| 352 | // Users who need canonical serialization (e.g., persistent storage in a |
| 353 | // canonical form, fingerprinting, etc.) should define their own |
| 354 | // canonicalization specification and implement their own serializer rather |
| 355 | // than relying on this API. |
| 356 | // |
| 357 | // If deterministic serialization is requested, map entries will be sorted |
| 358 | // by keys in lexographical order. This is an implementation detail and |
| 359 | // subject to change. |
| 360 | func (p *Buffer) SetDeterministic(deterministic bool) { |
| 361 | p.deterministic = deterministic |
| 362 | } |
| 363 | |
| 364 | /* |
| 365 | * Helper routines for simplifying the creation of optional fields of basic type. |
| 366 | */ |
| 367 | |
| 368 | // Bool is a helper routine that allocates a new bool value |
| 369 | // to store v and returns a pointer to it. |
| 370 | func Bool(v bool) *bool { |
| 371 | return &v |
| 372 | } |
| 373 | |
| 374 | // Int32 is a helper routine that allocates a new int32 value |
| 375 | // to store v and returns a pointer to it. |
| 376 | func Int32(v int32) *int32 { |
| 377 | return &v |
| 378 | } |
| 379 | |
| 380 | // Int is a helper routine that allocates a new int32 value |
| 381 | // to store v and returns a pointer to it, but unlike Int32 |
| 382 | // its argument value is an int. |
| 383 | func Int(v int) *int32 { |
| 384 | p := new(int32) |
| 385 | *p = int32(v) |
| 386 | return p |
| 387 | } |
| 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 | |
| 395 | // Float32 is a helper routine that allocates a new float32 value |
| 396 | // to store v and returns a pointer to it. |
| 397 | func Float32(v float32) *float32 { |
| 398 | return &v |
| 399 | } |
| 400 | |
| 401 | // Float64 is a helper routine that allocates a new float64 value |
| 402 | // to store v and returns a pointer to it. |
| 403 | func Float64(v float64) *float64 { |
| 404 | return &v |
| 405 | } |
| 406 | |
| 407 | // Uint32 is a helper routine that allocates a new uint32 value |
| 408 | // to store v and returns a pointer to it. |
| 409 | func Uint32(v uint32) *uint32 { |
| 410 | return &v |
| 411 | } |
| 412 | |
| 413 | // Uint64 is a helper routine that allocates a new uint64 value |
| 414 | // to store v and returns a pointer to it. |
| 415 | func Uint64(v uint64) *uint64 { |
| 416 | return &v |
| 417 | } |
| 418 | |
| 419 | // String is a helper routine that allocates a new string value |
| 420 | // to store v and returns a pointer to it. |
| 421 | func String(v string) *string { |
| 422 | return &v |
| 423 | } |
| 424 | |
| 425 | // EnumName is a helper function to simplify printing protocol buffer enums |
| 426 | // by name. Given an enum map and a value, it returns a useful string. |
| 427 | func EnumName(m map[int32]string, v int32) string { |
| 428 | s, ok := m[v] |
| 429 | if ok { |
| 430 | return s |
| 431 | } |
| 432 | return strconv.Itoa(int(v)) |
| 433 | } |
| 434 | |
| 435 | // UnmarshalJSONEnum is a helper function to simplify recovering enum int values |
| 436 | // from their JSON-encoded representation. Given a map from the enum's symbolic |
| 437 | // names to its int values, and a byte buffer containing the JSON-encoded |
| 438 | // value, it returns an int32 that can be cast to the enum type by the caller. |
| 439 | // |
| 440 | // The function can deal with both JSON representations, numeric and symbolic. |
| 441 | func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { |
| 442 | if data[0] == '"' { |
| 443 | // New style: enums are strings. |
| 444 | var repr string |
| 445 | if err := json.Unmarshal(data, &repr); err != nil { |
| 446 | return -1, err |
| 447 | } |
| 448 | val, ok := m[repr] |
| 449 | if !ok { |
| 450 | return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) |
| 451 | } |
| 452 | return val, nil |
| 453 | } |
| 454 | // Old style: enums are ints. |
| 455 | var val int32 |
| 456 | if err := json.Unmarshal(data, &val); err != nil { |
| 457 | return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) |
| 458 | } |
| 459 | return val, nil |
| 460 | } |
| 461 | |
| 462 | // DebugPrint dumps the encoded data in b in a debugging format with a header |
| 463 | // including the string s. Used in testing but made available for general debugging. |
| 464 | func (p *Buffer) DebugPrint(s string, b []byte) { |
| 465 | var u uint64 |
| 466 | |
| 467 | obuf := p.buf |
| 468 | index := p.index |
| 469 | p.buf = b |
| 470 | p.index = 0 |
| 471 | depth := 0 |
| 472 | |
| 473 | fmt.Printf("\n--- %s ---\n", s) |
| 474 | |
| 475 | out: |
| 476 | for { |
| 477 | for i := 0; i < depth; i++ { |
| 478 | fmt.Print(" ") |
| 479 | } |
| 480 | |
| 481 | index := p.index |
| 482 | if index == len(p.buf) { |
| 483 | break |
| 484 | } |
| 485 | |
| 486 | op, err := p.DecodeVarint() |
| 487 | if err != nil { |
| 488 | fmt.Printf("%3d: fetching op err %v\n", index, err) |
| 489 | break out |
| 490 | } |
| 491 | tag := op >> 3 |
| 492 | wire := op & 7 |
| 493 | |
| 494 | switch wire { |
| 495 | default: |
| 496 | fmt.Printf("%3d: t=%3d unknown wire=%d\n", |
| 497 | index, tag, wire) |
| 498 | break out |
| 499 | |
| 500 | case WireBytes: |
| 501 | var r []byte |
| 502 | |
| 503 | r, err = p.DecodeRawBytes(false) |
| 504 | if err != nil { |
| 505 | break out |
| 506 | } |
| 507 | fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) |
| 508 | if len(r) <= 6 { |
| 509 | for i := 0; i < len(r); i++ { |
| 510 | fmt.Printf(" %.2x", r[i]) |
| 511 | } |
| 512 | } else { |
| 513 | for i := 0; i < 3; i++ { |
| 514 | fmt.Printf(" %.2x", r[i]) |
| 515 | } |
| 516 | fmt.Printf(" ..") |
| 517 | for i := len(r) - 3; i < len(r); i++ { |
| 518 | fmt.Printf(" %.2x", r[i]) |
| 519 | } |
| 520 | } |
| 521 | fmt.Printf("\n") |
| 522 | |
| 523 | case WireFixed32: |
| 524 | u, err = p.DecodeFixed32() |
| 525 | if err != nil { |
| 526 | fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) |
| 527 | break out |
| 528 | } |
| 529 | fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) |
| 530 | |
| 531 | case WireFixed64: |
| 532 | u, err = p.DecodeFixed64() |
| 533 | if err != nil { |
| 534 | fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) |
| 535 | break out |
| 536 | } |
| 537 | fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) |
| 538 | |
| 539 | case WireVarint: |
| 540 | u, err = p.DecodeVarint() |
| 541 | if err != nil { |
| 542 | fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) |
| 543 | break out |
| 544 | } |
| 545 | fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) |
| 546 | |
| 547 | case WireStartGroup: |
| 548 | fmt.Printf("%3d: t=%3d start\n", index, tag) |
| 549 | depth++ |
| 550 | |
| 551 | case WireEndGroup: |
| 552 | depth-- |
| 553 | fmt.Printf("%3d: t=%3d end\n", index, tag) |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | if depth != 0 { |
| 558 | fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) |
| 559 | } |
| 560 | fmt.Printf("\n") |
| 561 | |
| 562 | p.buf = obuf |
| 563 | p.index = index |
| 564 | } |
| 565 | |
| 566 | // SetDefaults sets unset protocol buffer fields to their default values. |
| 567 | // It only modifies fields that are both unset and have defined defaults. |
| 568 | // It recursively sets default values in any non-nil sub-messages. |
| 569 | func SetDefaults(pb Message) { |
| 570 | setDefaults(reflect.ValueOf(pb), true, false) |
| 571 | } |
| 572 | |
| 573 | // v is a pointer to a struct. |
| 574 | func setDefaults(v reflect.Value, recur, zeros bool) { |
| 575 | v = v.Elem() |
| 576 | |
| 577 | defaultMu.RLock() |
| 578 | dm, ok := defaults[v.Type()] |
| 579 | defaultMu.RUnlock() |
| 580 | if !ok { |
| 581 | dm = buildDefaultMessage(v.Type()) |
| 582 | defaultMu.Lock() |
| 583 | defaults[v.Type()] = dm |
| 584 | defaultMu.Unlock() |
| 585 | } |
| 586 | |
| 587 | for _, sf := range dm.scalars { |
| 588 | f := v.Field(sf.index) |
| 589 | if !f.IsNil() { |
| 590 | // field already set |
| 591 | continue |
| 592 | } |
| 593 | dv := sf.value |
| 594 | if dv == nil && !zeros { |
| 595 | // no explicit default, and don't want to set zeros |
| 596 | continue |
| 597 | } |
| 598 | fptr := f.Addr().Interface() // **T |
| 599 | // TODO: Consider batching the allocations we do here. |
| 600 | switch sf.kind { |
| 601 | case reflect.Bool: |
| 602 | b := new(bool) |
| 603 | if dv != nil { |
| 604 | *b = dv.(bool) |
| 605 | } |
| 606 | *(fptr.(**bool)) = b |
| 607 | case reflect.Float32: |
| 608 | f := new(float32) |
| 609 | if dv != nil { |
| 610 | *f = dv.(float32) |
| 611 | } |
| 612 | *(fptr.(**float32)) = f |
| 613 | case reflect.Float64: |
| 614 | f := new(float64) |
| 615 | if dv != nil { |
| 616 | *f = dv.(float64) |
| 617 | } |
| 618 | *(fptr.(**float64)) = f |
| 619 | case reflect.Int32: |
| 620 | // might be an enum |
| 621 | if ft := f.Type(); ft != int32PtrType { |
| 622 | // enum |
| 623 | f.Set(reflect.New(ft.Elem())) |
| 624 | if dv != nil { |
| 625 | f.Elem().SetInt(int64(dv.(int32))) |
| 626 | } |
| 627 | } else { |
| 628 | // int32 field |
| 629 | i := new(int32) |
| 630 | if dv != nil { |
| 631 | *i = dv.(int32) |
| 632 | } |
| 633 | *(fptr.(**int32)) = i |
| 634 | } |
| 635 | case reflect.Int64: |
| 636 | i := new(int64) |
| 637 | if dv != nil { |
| 638 | *i = dv.(int64) |
| 639 | } |
| 640 | *(fptr.(**int64)) = i |
| 641 | case reflect.String: |
| 642 | s := new(string) |
| 643 | if dv != nil { |
| 644 | *s = dv.(string) |
| 645 | } |
| 646 | *(fptr.(**string)) = s |
| 647 | case reflect.Uint8: |
| 648 | // exceptional case: []byte |
| 649 | var b []byte |
| 650 | if dv != nil { |
| 651 | db := dv.([]byte) |
| 652 | b = make([]byte, len(db)) |
| 653 | copy(b, db) |
| 654 | } else { |
| 655 | b = []byte{} |
| 656 | } |
| 657 | *(fptr.(*[]byte)) = b |
| 658 | case reflect.Uint32: |
| 659 | u := new(uint32) |
| 660 | if dv != nil { |
| 661 | *u = dv.(uint32) |
| 662 | } |
| 663 | *(fptr.(**uint32)) = u |
| 664 | case reflect.Uint64: |
| 665 | u := new(uint64) |
| 666 | if dv != nil { |
| 667 | *u = dv.(uint64) |
| 668 | } |
| 669 | *(fptr.(**uint64)) = u |
| 670 | default: |
| 671 | log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | for _, ni := range dm.nested { |
| 676 | f := v.Field(ni) |
| 677 | // f is *T or []*T or map[T]*T |
| 678 | switch f.Kind() { |
| 679 | case reflect.Ptr: |
| 680 | if f.IsNil() { |
| 681 | continue |
| 682 | } |
| 683 | setDefaults(f, recur, zeros) |
| 684 | |
| 685 | case reflect.Slice: |
| 686 | for i := 0; i < f.Len(); i++ { |
| 687 | e := f.Index(i) |
| 688 | if e.IsNil() { |
| 689 | continue |
| 690 | } |
| 691 | setDefaults(e, recur, zeros) |
| 692 | } |
| 693 | |
| 694 | case reflect.Map: |
| 695 | for _, k := range f.MapKeys() { |
| 696 | e := f.MapIndex(k) |
| 697 | if e.IsNil() { |
| 698 | continue |
| 699 | } |
| 700 | setDefaults(e, recur, zeros) |
| 701 | } |
| 702 | } |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | var ( |
| 707 | // defaults maps a protocol buffer struct type to a slice of the fields, |
| 708 | // with its scalar fields set to their proto-declared non-zero default values. |
| 709 | defaultMu sync.RWMutex |
| 710 | defaults = make(map[reflect.Type]defaultMessage) |
| 711 | |
| 712 | int32PtrType = reflect.TypeOf((*int32)(nil)) |
| 713 | ) |
| 714 | |
| 715 | // defaultMessage represents information about the default values of a message. |
| 716 | type defaultMessage struct { |
| 717 | scalars []scalarField |
| 718 | nested []int // struct field index of nested messages |
| 719 | } |
| 720 | |
| 721 | type scalarField struct { |
| 722 | index int // struct field index |
| 723 | kind reflect.Kind // element type (the T in *T or []T) |
| 724 | value interface{} // the proto-declared default value, or nil |
| 725 | } |
| 726 | |
| 727 | // t is a struct type. |
| 728 | func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { |
| 729 | sprop := GetProperties(t) |
| 730 | for _, prop := range sprop.Prop { |
| 731 | fi, ok := sprop.decoderTags.get(prop.Tag) |
| 732 | if !ok { |
| 733 | // XXX_unrecognized |
| 734 | continue |
| 735 | } |
| 736 | ft := t.Field(fi).Type |
| 737 | |
| 738 | sf, nested, err := fieldDefault(ft, prop) |
| 739 | switch { |
| 740 | case err != nil: |
| 741 | log.Print(err) |
| 742 | case nested: |
| 743 | dm.nested = append(dm.nested, fi) |
| 744 | case sf != nil: |
| 745 | sf.index = fi |
| 746 | dm.scalars = append(dm.scalars, *sf) |
| 747 | } |
| 748 | } |
| 749 | |
| 750 | return dm |
| 751 | } |
| 752 | |
| 753 | // fieldDefault returns the scalarField for field type ft. |
| 754 | // sf will be nil if the field can not have a default. |
| 755 | // nestedMessage will be true if this is a nested message. |
| 756 | // Note that sf.index is not set on return. |
| 757 | func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { |
| 758 | var canHaveDefault bool |
| 759 | switch ft.Kind() { |
| 760 | case reflect.Ptr: |
| 761 | if ft.Elem().Kind() == reflect.Struct { |
| 762 | nestedMessage = true |
| 763 | } else { |
| 764 | canHaveDefault = true // proto2 scalar field |
| 765 | } |
| 766 | |
| 767 | case reflect.Slice: |
| 768 | switch ft.Elem().Kind() { |
| 769 | case reflect.Ptr: |
| 770 | nestedMessage = true // repeated message |
| 771 | case reflect.Uint8: |
| 772 | canHaveDefault = true // bytes field |
| 773 | } |
| 774 | |
| 775 | case reflect.Map: |
| 776 | if ft.Elem().Kind() == reflect.Ptr { |
| 777 | nestedMessage = true // map with message values |
| 778 | } |
| 779 | } |
| 780 | |
| 781 | if !canHaveDefault { |
| 782 | if nestedMessage { |
| 783 | return nil, true, nil |
| 784 | } |
| 785 | return nil, false, nil |
| 786 | } |
| 787 | |
| 788 | // We now know that ft is a pointer or slice. |
| 789 | sf = &scalarField{kind: ft.Elem().Kind()} |
| 790 | |
| 791 | // scalar fields without defaults |
| 792 | if !prop.HasDefault { |
| 793 | return sf, false, nil |
| 794 | } |
| 795 | |
| 796 | // a scalar field: either *T or []byte |
| 797 | switch ft.Elem().Kind() { |
| 798 | case reflect.Bool: |
| 799 | x, err := strconv.ParseBool(prop.Default) |
| 800 | if err != nil { |
| 801 | return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) |
| 802 | } |
| 803 | sf.value = x |
| 804 | case reflect.Float32: |
| 805 | x, err := strconv.ParseFloat(prop.Default, 32) |
| 806 | if err != nil { |
| 807 | return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) |
| 808 | } |
| 809 | sf.value = float32(x) |
| 810 | case reflect.Float64: |
| 811 | x, err := strconv.ParseFloat(prop.Default, 64) |
| 812 | if err != nil { |
| 813 | return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) |
| 814 | } |
| 815 | sf.value = x |
| 816 | case reflect.Int32: |
| 817 | x, err := strconv.ParseInt(prop.Default, 10, 32) |
| 818 | if err != nil { |
| 819 | return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) |
| 820 | } |
| 821 | sf.value = int32(x) |
| 822 | case reflect.Int64: |
| 823 | x, err := strconv.ParseInt(prop.Default, 10, 64) |
| 824 | if err != nil { |
| 825 | return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) |
| 826 | } |
| 827 | sf.value = x |
| 828 | case reflect.String: |
| 829 | sf.value = prop.Default |
| 830 | case reflect.Uint8: |
| 831 | // []byte (not *uint8) |
| 832 | sf.value = []byte(prop.Default) |
| 833 | case reflect.Uint32: |
| 834 | x, err := strconv.ParseUint(prop.Default, 10, 32) |
| 835 | if err != nil { |
| 836 | return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) |
| 837 | } |
| 838 | sf.value = uint32(x) |
| 839 | case reflect.Uint64: |
| 840 | x, err := strconv.ParseUint(prop.Default, 10, 64) |
| 841 | if err != nil { |
| 842 | return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) |
| 843 | } |
| 844 | sf.value = x |
| 845 | default: |
| 846 | return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) |
| 847 | } |
| 848 | |
| 849 | return sf, false, nil |
| 850 | } |
| 851 | |
| 852 | // mapKeys returns a sort.Interface to be used for sorting the map keys. |
| 853 | // Map fields may have key types of non-float scalars, strings and enums. |
| 854 | func mapKeys(vs []reflect.Value) sort.Interface { |
| 855 | s := mapKeySorter{vs: vs} |
| 856 | |
| 857 | // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps. |
| 858 | if len(vs) == 0 { |
| 859 | return s |
| 860 | } |
| 861 | switch vs[0].Kind() { |
| 862 | case reflect.Int32, reflect.Int64: |
| 863 | s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } |
| 864 | case reflect.Uint32, reflect.Uint64: |
| 865 | s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } |
| 866 | case reflect.Bool: |
| 867 | s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true |
| 868 | case reflect.String: |
| 869 | s.less = func(a, b reflect.Value) bool { return a.String() < b.String() } |
| 870 | default: |
| 871 | panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind())) |
| 872 | } |
| 873 | |
| 874 | return s |
| 875 | } |
| 876 | |
| 877 | type mapKeySorter struct { |
| 878 | vs []reflect.Value |
| 879 | less func(a, b reflect.Value) bool |
| 880 | } |
| 881 | |
| 882 | func (s mapKeySorter) Len() int { return len(s.vs) } |
| 883 | func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } |
| 884 | func (s mapKeySorter) Less(i, j int) bool { |
| 885 | return s.less(s.vs[i], s.vs[j]) |
| 886 | } |
| 887 | |
| 888 | // isProto3Zero reports whether v is a zero proto3 value. |
| 889 | func isProto3Zero(v reflect.Value) bool { |
| 890 | switch v.Kind() { |
| 891 | case reflect.Bool: |
| 892 | return !v.Bool() |
| 893 | case reflect.Int32, reflect.Int64: |
| 894 | return v.Int() == 0 |
| 895 | case reflect.Uint32, reflect.Uint64: |
| 896 | return v.Uint() == 0 |
| 897 | case reflect.Float32, reflect.Float64: |
| 898 | return v.Float() == 0 |
| 899 | case reflect.String: |
| 900 | return v.String() == "" |
| 901 | } |
| 902 | return false |
| 903 | } |
| 904 | |
| 905 | // ProtoPackageIsVersion2 is referenced from generated protocol buffer files |
| 906 | // to assert that that code is compatible with this version of the proto package. |
| 907 | const ProtoPackageIsVersion2 = true |
| 908 | |
| 909 | // ProtoPackageIsVersion1 is referenced from generated protocol buffer files |
| 910 | // to assert that that code is compatible with this version of the proto package. |
| 911 | const ProtoPackageIsVersion1 = true |
| 912 | |
| 913 | // InternalMessageInfo is a type used internally by generated .pb.go files. |
| 914 | // This type is not intended to be used by non-generated code. |
| 915 | // This type is not subject to any compatibility guarantee. |
| 916 | type InternalMessageInfo struct { |
| 917 | marshal *marshalInfo |
| 918 | unmarshal *unmarshalInfo |
| 919 | merge *mergeInfo |
| 920 | discard *discardInfo |
| 921 | } |