1 // Go support for Protocol Buffers - Google's data interchange format
3 // Copyright 2010 The Go Authors. All rights reserved.
4 // https://github.com/golang/protobuf
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are
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
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.
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.
35 * Routines for encoding data into the wire format for protocol buffers.
45 // RequiredNotSetError is the error returned if Marshal is called with
46 // a protocol buffer struct whose required fields have not
47 // all been initialized. It is also the error returned if Unmarshal is
48 // called with an encoded protocol buffer that does not include all the
51 // When printed, RequiredNotSetError reports the first unset required field in a
52 // message. If the field cannot be precisely determined, it is reported as
54 type RequiredNotSetError struct {
58 func (e *RequiredNotSetError) Error() string {
59 return fmt.Sprintf("proto: required field %q not set", e.field)
63 // errRepeatedHasNil is the error returned if Marshal is called with
64 // a struct with a repeated field containing a nil element.
65 errRepeatedHasNil = errors.New("proto: repeated field has nil element")
67 // errOneofHasNil is the error returned if Marshal is called with
68 // a struct with a oneof field containing a nil element.
69 errOneofHasNil = errors.New("proto: oneof field has nil value")
71 // ErrNil is the error returned if Marshal is called with nil.
72 ErrNil = errors.New("proto: Marshal called with nil")
74 // ErrTooLarge is the error returned if Marshal is called with a
75 // message that encodes to >2GB.
76 ErrTooLarge = errors.New("proto: message encodes to over 2 GB")
79 // The fundamental encoders that put bytes on the wire.
80 // Those that take integer types all accept uint64 and are
81 // therefore of type valueEncoder.
83 const maxVarintBytes = 10 // maximum length of a varint
85 // maxMarshalSize is the largest allowed size of an encoded protobuf,
86 // since C++ and Java use signed int32s for the size.
87 const maxMarshalSize = 1<<31 - 1
89 // EncodeVarint returns the varint encoding of x.
90 // This is the format for the
91 // int32, int64, uint32, uint64, bool, and enum
92 // protocol buffer types.
93 // Not used by the package itself, but helpful to clients
94 // wishing to use the same encoding.
95 func EncodeVarint(x uint64) []byte {
96 var buf [maxVarintBytes]byte
98 for n = 0; x > 127; n++ {
99 buf[n] = 0x80 | uint8(x&0x7F)
107 // EncodeVarint writes a varint-encoded integer to the Buffer.
108 // This is the format for the
109 // int32, int64, uint32, uint64, bool, and enum
110 // protocol buffer types.
111 func (p *Buffer) EncodeVarint(x uint64) error {
113 p.buf = append(p.buf, uint8(x&0x7f|0x80))
116 p.buf = append(p.buf, uint8(x))
120 // SizeVarint returns the varint encoding size of an integer.
121 func SizeVarint(x uint64) int {
125 func sizeVarint(x uint64) (n int) {
136 // EncodeFixed64 writes a 64-bit integer to the Buffer.
137 // This is the format for the
138 // fixed64, sfixed64, and double protocol buffer types.
139 func (p *Buffer) EncodeFixed64(x uint64) error {
140 p.buf = append(p.buf,
152 func sizeFixed64(x uint64) int {
156 // EncodeFixed32 writes a 32-bit integer to the Buffer.
157 // This is the format for the
158 // fixed32, sfixed32, and float protocol buffer types.
159 func (p *Buffer) EncodeFixed32(x uint64) error {
160 p.buf = append(p.buf,
168 func sizeFixed32(x uint64) int {
172 // EncodeZigzag64 writes a zigzag-encoded 64-bit integer
174 // This is the format used for the sint64 protocol buffer type.
175 func (p *Buffer) EncodeZigzag64(x uint64) error {
176 // use signed number to get arithmetic right shift.
177 return p.EncodeVarint((x << 1) ^ uint64((int64(x) >> 63)))
180 func sizeZigzag64(x uint64) int {
181 return sizeVarint((x << 1) ^ uint64((int64(x) >> 63)))
184 // EncodeZigzag32 writes a zigzag-encoded 32-bit integer
186 // This is the format used for the sint32 protocol buffer type.
187 func (p *Buffer) EncodeZigzag32(x uint64) error {
188 // use signed number to get arithmetic right shift.
189 return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
192 func sizeZigzag32(x uint64) int {
193 return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
196 // EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
197 // This is the format used for the bytes protocol buffer
198 // type and for embedded messages.
199 func (p *Buffer) EncodeRawBytes(b []byte) error {
200 p.EncodeVarint(uint64(len(b)))
201 p.buf = append(p.buf, b...)
205 func sizeRawBytes(b []byte) int {
206 return sizeVarint(uint64(len(b))) +
210 // EncodeStringBytes writes an encoded string to the Buffer.
211 // This is the format used for the proto2 string type.
212 func (p *Buffer) EncodeStringBytes(s string) error {
213 p.EncodeVarint(uint64(len(s)))
214 p.buf = append(p.buf, s...)
218 func sizeStringBytes(s string) int {
219 return sizeVarint(uint64(len(s))) +
223 // Marshaler is the interface representing objects that can marshal themselves.
224 type Marshaler interface {
225 Marshal() ([]byte, error)
228 // Marshal takes the protocol buffer
229 // and encodes it into the wire format, returning the data.
230 func Marshal(pb Message) ([]byte, error) {
231 // Can the object marshal itself?
232 if m, ok := pb.(Marshaler); ok {
237 if p.buf == nil && err == nil {
238 // Return a non-nil slice on success.
244 // EncodeMessage writes the protocol buffer to the Buffer,
245 // prefixed by a varint-encoded length.
246 func (p *Buffer) EncodeMessage(pb Message) error {
247 t, base, err := getbase(pb)
248 if structPointer_IsNil(base) {
253 err = p.enc_len_struct(GetProperties(t.Elem()), base, &state)
258 // Marshal takes the protocol buffer
259 // and encodes it into the wire format, writing the result to the
261 func (p *Buffer) Marshal(pb Message) error {
262 // Can the object marshal itself?
263 if m, ok := pb.(Marshaler); ok {
264 data, err := m.Marshal()
265 p.buf = append(p.buf, data...)
269 t, base, err := getbase(pb)
270 if structPointer_IsNil(base) {
274 err = p.enc_struct(GetProperties(t.Elem()), base)
278 (stats).Encode++ // Parens are to work around a goimports bug.
281 if len(p.buf) > maxMarshalSize {
287 // Size returns the encoded size of a protocol buffer.
288 func Size(pb Message) (n int) {
289 // Can the object marshal itself? If so, Size is slow.
290 // TODO: add Size to Marshaler, or add a Sizer interface.
291 if m, ok := pb.(Marshaler); ok {
296 t, base, err := getbase(pb)
297 if structPointer_IsNil(base) {
301 n = size_struct(GetProperties(t.Elem()), base)
305 (stats).Size++ // Parens are to work around a goimports bug.
311 // Individual type encoders.
314 func (o *Buffer) enc_bool(p *Properties, base structPointer) error {
315 v := *structPointer_Bool(base, p.field)
323 o.buf = append(o.buf, p.tagcode...)
324 p.valEnc(o, uint64(x))
328 func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error {
329 v := *structPointer_BoolVal(base, p.field)
333 o.buf = append(o.buf, p.tagcode...)
338 func size_bool(p *Properties, base structPointer) int {
339 v := *structPointer_Bool(base, p.field)
343 return len(p.tagcode) + 1 // each bool takes exactly one byte
346 func size_proto3_bool(p *Properties, base structPointer) int {
347 v := *structPointer_BoolVal(base, p.field)
351 return len(p.tagcode) + 1 // each bool takes exactly one byte
355 func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
356 v := structPointer_Word32(base, p.field)
360 x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
361 o.buf = append(o.buf, p.tagcode...)
362 p.valEnc(o, uint64(x))
366 func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error {
367 v := structPointer_Word32Val(base, p.field)
368 x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
372 o.buf = append(o.buf, p.tagcode...)
373 p.valEnc(o, uint64(x))
377 func size_int32(p *Properties, base structPointer) (n int) {
378 v := structPointer_Word32(base, p.field)
382 x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
384 n += p.valSize(uint64(x))
388 func size_proto3_int32(p *Properties, base structPointer) (n int) {
389 v := structPointer_Word32Val(base, p.field)
390 x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
391 if x == 0 && !p.oneof {
395 n += p.valSize(uint64(x))
400 // Exactly the same as int32, except for no sign extension.
401 func (o *Buffer) enc_uint32(p *Properties, base structPointer) error {
402 v := structPointer_Word32(base, p.field)
407 o.buf = append(o.buf, p.tagcode...)
408 p.valEnc(o, uint64(x))
412 func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error {
413 v := structPointer_Word32Val(base, p.field)
414 x := word32Val_Get(v)
418 o.buf = append(o.buf, p.tagcode...)
419 p.valEnc(o, uint64(x))
423 func size_uint32(p *Properties, base structPointer) (n int) {
424 v := structPointer_Word32(base, p.field)
430 n += p.valSize(uint64(x))
434 func size_proto3_uint32(p *Properties, base structPointer) (n int) {
435 v := structPointer_Word32Val(base, p.field)
436 x := word32Val_Get(v)
437 if x == 0 && !p.oneof {
441 n += p.valSize(uint64(x))
446 func (o *Buffer) enc_int64(p *Properties, base structPointer) error {
447 v := structPointer_Word64(base, p.field)
452 o.buf = append(o.buf, p.tagcode...)
457 func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error {
458 v := structPointer_Word64Val(base, p.field)
459 x := word64Val_Get(v)
463 o.buf = append(o.buf, p.tagcode...)
468 func size_int64(p *Properties, base structPointer) (n int) {
469 v := structPointer_Word64(base, p.field)
479 func size_proto3_int64(p *Properties, base structPointer) (n int) {
480 v := structPointer_Word64Val(base, p.field)
481 x := word64Val_Get(v)
482 if x == 0 && !p.oneof {
491 func (o *Buffer) enc_string(p *Properties, base structPointer) error {
492 v := *structPointer_String(base, p.field)
497 o.buf = append(o.buf, p.tagcode...)
498 o.EncodeStringBytes(x)
502 func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error {
503 v := *structPointer_StringVal(base, p.field)
507 o.buf = append(o.buf, p.tagcode...)
508 o.EncodeStringBytes(v)
512 func size_string(p *Properties, base structPointer) (n int) {
513 v := *structPointer_String(base, p.field)
519 n += sizeStringBytes(x)
523 func size_proto3_string(p *Properties, base structPointer) (n int) {
524 v := *structPointer_StringVal(base, p.field)
525 if v == "" && !p.oneof {
529 n += sizeStringBytes(v)
533 // All protocol buffer fields are nillable, but be careful.
534 func isNil(v reflect.Value) bool {
536 case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
542 // Encode a message struct.
543 func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
545 structp := structPointer_GetStructPointer(base, p.field)
546 if structPointer_IsNil(structp) {
550 // Can the object marshal itself?
552 m := structPointer_Interface(structp, p.stype).(Marshaler)
553 data, err := m.Marshal()
554 if err != nil && !state.shouldContinue(err, nil) {
557 o.buf = append(o.buf, p.tagcode...)
558 o.EncodeRawBytes(data)
562 o.buf = append(o.buf, p.tagcode...)
563 return o.enc_len_struct(p.sprop, structp, &state)
566 func size_struct_message(p *Properties, base structPointer) int {
567 structp := structPointer_GetStructPointer(base, p.field)
568 if structPointer_IsNil(structp) {
572 // Can the object marshal itself?
574 m := structPointer_Interface(structp, p.stype).(Marshaler)
575 data, _ := m.Marshal()
577 n1 := sizeRawBytes(data)
582 n1 := size_struct(p.sprop, structp)
583 n2 := sizeVarint(uint64(n1)) // size of encoded length
587 // Encode a group struct.
588 func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error {
590 b := structPointer_GetStructPointer(base, p.field)
591 if structPointer_IsNil(b) {
595 o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
596 err := o.enc_struct(p.sprop, b)
597 if err != nil && !state.shouldContinue(err, nil) {
600 o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
604 func size_struct_group(p *Properties, base structPointer) (n int) {
605 b := structPointer_GetStructPointer(base, p.field)
606 if structPointer_IsNil(b) {
610 n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup))
611 n += size_struct(p.sprop, b)
612 n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup))
616 // Encode a slice of bools ([]bool).
617 func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
618 s := *structPointer_BoolSlice(base, p.field)
623 for _, x := range s {
624 o.buf = append(o.buf, p.tagcode...)
634 func size_slice_bool(p *Properties, base structPointer) int {
635 s := *structPointer_BoolSlice(base, p.field)
640 return l * (len(p.tagcode) + 1) // each bool takes exactly one byte
643 // Encode a slice of bools ([]bool) in packed format.
644 func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error {
645 s := *structPointer_BoolSlice(base, p.field)
650 o.buf = append(o.buf, p.tagcode...)
651 o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
652 for _, x := range s {
662 func size_slice_packed_bool(p *Properties, base structPointer) (n int) {
663 s := *structPointer_BoolSlice(base, p.field)
669 n += sizeVarint(uint64(l))
670 n += l // each bool takes exactly one byte
674 // Encode a slice of bytes ([]byte).
675 func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
676 s := *structPointer_Bytes(base, p.field)
680 o.buf = append(o.buf, p.tagcode...)
685 func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error {
686 s := *structPointer_Bytes(base, p.field)
690 o.buf = append(o.buf, p.tagcode...)
695 func size_slice_byte(p *Properties, base structPointer) (n int) {
696 s := *structPointer_Bytes(base, p.field)
697 if s == nil && !p.oneof {
705 func size_proto3_slice_byte(p *Properties, base structPointer) (n int) {
706 s := *structPointer_Bytes(base, p.field)
707 if len(s) == 0 && !p.oneof {
715 // Encode a slice of int32s ([]int32).
716 func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error {
717 s := structPointer_Word32Slice(base, p.field)
722 for i := 0; i < l; i++ {
723 o.buf = append(o.buf, p.tagcode...)
724 x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
725 p.valEnc(o, uint64(x))
730 func size_slice_int32(p *Properties, base structPointer) (n int) {
731 s := structPointer_Word32Slice(base, p.field)
736 for i := 0; i < l; i++ {
738 x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
739 n += p.valSize(uint64(x))
744 // Encode a slice of int32s ([]int32) in packed format.
745 func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error {
746 s := structPointer_Word32Slice(base, p.field)
751 // TODO: Reuse a Buffer.
752 buf := NewBuffer(nil)
753 for i := 0; i < l; i++ {
754 x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
755 p.valEnc(buf, uint64(x))
758 o.buf = append(o.buf, p.tagcode...)
759 o.EncodeVarint(uint64(len(buf.buf)))
760 o.buf = append(o.buf, buf.buf...)
764 func size_slice_packed_int32(p *Properties, base structPointer) (n int) {
765 s := structPointer_Word32Slice(base, p.field)
771 for i := 0; i < l; i++ {
772 x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
773 bufSize += p.valSize(uint64(x))
777 n += sizeVarint(uint64(bufSize))
782 // Encode a slice of uint32s ([]uint32).
783 // Exactly the same as int32, except for no sign extension.
784 func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error {
785 s := structPointer_Word32Slice(base, p.field)
790 for i := 0; i < l; i++ {
791 o.buf = append(o.buf, p.tagcode...)
793 p.valEnc(o, uint64(x))
798 func size_slice_uint32(p *Properties, base structPointer) (n int) {
799 s := structPointer_Word32Slice(base, p.field)
804 for i := 0; i < l; i++ {
807 n += p.valSize(uint64(x))
812 // Encode a slice of uint32s ([]uint32) in packed format.
813 // Exactly the same as int32, except for no sign extension.
814 func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error {
815 s := structPointer_Word32Slice(base, p.field)
820 // TODO: Reuse a Buffer.
821 buf := NewBuffer(nil)
822 for i := 0; i < l; i++ {
823 p.valEnc(buf, uint64(s.Index(i)))
826 o.buf = append(o.buf, p.tagcode...)
827 o.EncodeVarint(uint64(len(buf.buf)))
828 o.buf = append(o.buf, buf.buf...)
832 func size_slice_packed_uint32(p *Properties, base structPointer) (n int) {
833 s := structPointer_Word32Slice(base, p.field)
839 for i := 0; i < l; i++ {
840 bufSize += p.valSize(uint64(s.Index(i)))
844 n += sizeVarint(uint64(bufSize))
849 // Encode a slice of int64s ([]int64).
850 func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error {
851 s := structPointer_Word64Slice(base, p.field)
856 for i := 0; i < l; i++ {
857 o.buf = append(o.buf, p.tagcode...)
858 p.valEnc(o, s.Index(i))
863 func size_slice_int64(p *Properties, base structPointer) (n int) {
864 s := structPointer_Word64Slice(base, p.field)
869 for i := 0; i < l; i++ {
871 n += p.valSize(s.Index(i))
876 // Encode a slice of int64s ([]int64) in packed format.
877 func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error {
878 s := structPointer_Word64Slice(base, p.field)
883 // TODO: Reuse a Buffer.
884 buf := NewBuffer(nil)
885 for i := 0; i < l; i++ {
886 p.valEnc(buf, s.Index(i))
889 o.buf = append(o.buf, p.tagcode...)
890 o.EncodeVarint(uint64(len(buf.buf)))
891 o.buf = append(o.buf, buf.buf...)
895 func size_slice_packed_int64(p *Properties, base structPointer) (n int) {
896 s := structPointer_Word64Slice(base, p.field)
902 for i := 0; i < l; i++ {
903 bufSize += p.valSize(s.Index(i))
907 n += sizeVarint(uint64(bufSize))
912 // Encode a slice of slice of bytes ([][]byte).
913 func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
914 ss := *structPointer_BytesSlice(base, p.field)
919 for i := 0; i < l; i++ {
920 o.buf = append(o.buf, p.tagcode...)
921 o.EncodeRawBytes(ss[i])
926 func size_slice_slice_byte(p *Properties, base structPointer) (n int) {
927 ss := *structPointer_BytesSlice(base, p.field)
932 n += l * len(p.tagcode)
933 for i := 0; i < l; i++ {
934 n += sizeRawBytes(ss[i])
939 // Encode a slice of strings ([]string).
940 func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
941 ss := *structPointer_StringSlice(base, p.field)
943 for i := 0; i < l; i++ {
944 o.buf = append(o.buf, p.tagcode...)
945 o.EncodeStringBytes(ss[i])
950 func size_slice_string(p *Properties, base structPointer) (n int) {
951 ss := *structPointer_StringSlice(base, p.field)
953 n += l * len(p.tagcode)
954 for i := 0; i < l; i++ {
955 n += sizeStringBytes(ss[i])
960 // Encode a slice of message structs ([]*struct).
961 func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error {
963 s := structPointer_StructPointerSlice(base, p.field)
966 for i := 0; i < l; i++ {
967 structp := s.Index(i)
968 if structPointer_IsNil(structp) {
969 return errRepeatedHasNil
972 // Can the object marshal itself?
974 m := structPointer_Interface(structp, p.stype).(Marshaler)
975 data, err := m.Marshal()
976 if err != nil && !state.shouldContinue(err, nil) {
979 o.buf = append(o.buf, p.tagcode...)
980 o.EncodeRawBytes(data)
984 o.buf = append(o.buf, p.tagcode...)
985 err := o.enc_len_struct(p.sprop, structp, &state)
986 if err != nil && !state.shouldContinue(err, nil) {
988 return errRepeatedHasNil
996 func size_slice_struct_message(p *Properties, base structPointer) (n int) {
997 s := structPointer_StructPointerSlice(base, p.field)
999 n += l * len(p.tagcode)
1000 for i := 0; i < l; i++ {
1001 structp := s.Index(i)
1002 if structPointer_IsNil(structp) {
1003 return // return the size up to this point
1006 // Can the object marshal itself?
1008 m := structPointer_Interface(structp, p.stype).(Marshaler)
1009 data, _ := m.Marshal()
1010 n += sizeRawBytes(data)
1014 n0 := size_struct(p.sprop, structp)
1015 n1 := sizeVarint(uint64(n0)) // size of encoded length
1021 // Encode a slice of group structs ([]*struct).
1022 func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error {
1023 var state errorState
1024 s := structPointer_StructPointerSlice(base, p.field)
1027 for i := 0; i < l; i++ {
1029 if structPointer_IsNil(b) {
1030 return errRepeatedHasNil
1033 o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
1035 err := o.enc_struct(p.sprop, b)
1037 if err != nil && !state.shouldContinue(err, nil) {
1039 return errRepeatedHasNil
1044 o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
1049 func size_slice_struct_group(p *Properties, base structPointer) (n int) {
1050 s := structPointer_StructPointerSlice(base, p.field)
1053 n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup))
1054 n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup))
1055 for i := 0; i < l; i++ {
1057 if structPointer_IsNil(b) {
1058 return // return size up to this point
1061 n += size_struct(p.sprop, b)
1066 // Encode an extension map.
1067 func (o *Buffer) enc_map(p *Properties, base structPointer) error {
1068 exts := structPointer_ExtMap(base, p.field)
1069 if err := encodeExtensionsMap(*exts); err != nil {
1073 return o.enc_map_body(*exts)
1076 func (o *Buffer) enc_exts(p *Properties, base structPointer) error {
1077 exts := structPointer_Extensions(base, p.field)
1079 v, mu := exts.extensionsRead()
1086 if err := encodeExtensionsMap(v); err != nil {
1090 return o.enc_map_body(v)
1093 func (o *Buffer) enc_map_body(v map[int32]Extension) error {
1094 // Fast-path for common cases: zero or one extensions.
1096 for _, e := range v {
1097 o.buf = append(o.buf, e.enc...)
1102 // Sort keys to provide a deterministic encoding.
1103 keys := make([]int, 0, len(v))
1105 keys = append(keys, int(k))
1109 for _, k := range keys {
1110 o.buf = append(o.buf, v[int32(k)].enc...)
1115 func size_map(p *Properties, base structPointer) int {
1116 v := structPointer_ExtMap(base, p.field)
1117 return extensionsMapSize(*v)
1120 func size_exts(p *Properties, base structPointer) int {
1121 v := structPointer_Extensions(base, p.field)
1122 return extensionsSize(v)
1125 // Encode a map field.
1126 func (o *Buffer) enc_new_map(p *Properties, base structPointer) error {
1127 var state errorState // XXX: or do we need to plumb this through?
1131 map<key_type, value_type> map_field = N;
1132 is encoded in the same way as
1133 message MapFieldEntry {
1135 value_type value = 2;
1137 repeated MapFieldEntry map_field = N;
1140 v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
1145 keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
1147 enc := func() error {
1148 if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil {
1151 if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil && err != ErrNil {
1157 // Don't sort map keys. It is not required by the spec, and C++ doesn't do it.
1158 for _, key := range v.MapKeys() {
1159 val := v.MapIndex(key)
1164 o.buf = append(o.buf, p.tagcode...)
1165 if err := o.enc_len_thing(enc, &state); err != nil {
1172 func size_new_map(p *Properties, base structPointer) int {
1173 v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
1175 keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
1178 for _, key := range v.MapKeys() {
1179 val := v.MapIndex(key)
1183 // Tag codes for key and val are the responsibility of the sub-sizer.
1184 keysize := p.mkeyprop.size(p.mkeyprop, keybase)
1185 valsize := p.mvalprop.size(p.mvalprop, valbase)
1186 entry := keysize + valsize
1187 // Add on tag code and length of map entry itself.
1188 n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry
1193 // mapEncodeScratch returns a new reflect.Value matching the map's value type,
1194 // and a structPointer suitable for passing to an encoder or sizer.
1195 func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) {
1196 // Prepare addressable doubly-indirect placeholders for the key and value types.
1197 // This is needed because the element-type encoders expect **T, but the map iteration produces T.
1199 keycopy = reflect.New(mapType.Key()).Elem() // addressable K
1200 keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K
1201 keyptr.Set(keycopy.Addr()) //
1202 keybase = toStructPointer(keyptr.Addr()) // **K
1204 // Value types are more varied and require special handling.
1205 switch mapType.Elem().Kind() {
1209 valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte
1210 valbase = toStructPointer(valcopy.Addr())
1212 // message; the generated field type is map[K]*Msg (so V is *Msg),
1213 // so we only need one level of indirection.
1214 valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
1215 valbase = toStructPointer(valcopy.Addr())
1218 valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
1219 valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V
1220 valptr.Set(valcopy.Addr()) //
1221 valbase = toStructPointer(valptr.Addr()) // **V
1227 func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error {
1228 var state errorState
1229 // Encode fields in tag order so that decoders may use optimizations
1230 // that depend on the ordering.
1231 // https://developers.google.com/protocol-buffers/docs/encoding#order
1232 for _, i := range prop.order {
1235 err := p.enc(o, p, base)
1238 if p.Required && state.err == nil {
1239 state.err = &RequiredNotSetError{p.Name}
1241 } else if err == errRepeatedHasNil {
1242 // Give more context to nil values in repeated fields.
1243 return errors.New("repeated field " + p.OrigName + " has nil element")
1244 } else if !state.shouldContinue(err, p) {
1248 if len(o.buf) > maxMarshalSize {
1255 if prop.oneofMarshaler != nil {
1256 m := structPointer_Interface(base, prop.stype).(Message)
1257 if err := prop.oneofMarshaler(m, o); err == ErrNil {
1258 return errOneofHasNil
1259 } else if err != nil {
1264 // Add unrecognized fields at the end.
1265 if prop.unrecField.IsValid() {
1266 v := *structPointer_Bytes(base, prop.unrecField)
1267 if len(o.buf)+len(v) > maxMarshalSize {
1271 o.buf = append(o.buf, v...)
1278 func size_struct(prop *StructProperties, base structPointer) (n int) {
1279 for _, i := range prop.order {
1282 n += p.size(p, base)
1286 // Add unrecognized fields at the end.
1287 if prop.unrecField.IsValid() {
1288 v := *structPointer_Bytes(base, prop.unrecField)
1292 // Factor in any oneof fields.
1293 if prop.oneofSizer != nil {
1294 m := structPointer_Interface(base, prop.stype).(Message)
1295 n += prop.oneofSizer(m)
1301 var zeroes [20]byte // longer than any conceivable sizeVarint
1303 // Encode a struct, preceded by its encoded length (as a varint).
1304 func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error {
1305 return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state)
1308 // Encode something, preceded by its encoded length (as a varint).
1309 func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error {
1311 o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length
1314 if err != nil && !state.shouldContinue(err, nil) {
1317 lMsg := len(o.buf) - iMsg
1318 lLen := sizeVarint(uint64(lMsg))
1319 switch x := lLen - (iMsg - iLen); {
1320 case x > 0: // actual length is x bytes larger than the space we reserved
1321 // Move msg x bytes right.
1322 o.buf = append(o.buf, zeroes[:x]...)
1323 copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
1324 case x < 0: // actual length is x bytes smaller than the space we reserved
1325 // Move msg x bytes left.
1326 copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
1327 o.buf = o.buf[:len(o.buf)+x] // x is negative
1329 // Encode the length in the reserved space.
1330 o.buf = o.buf[:iLen]
1331 o.EncodeVarint(uint64(lMsg))
1332 o.buf = o.buf[:len(o.buf)+lMsg]
1336 // errorState maintains the first error that occurs and updates that error
1337 // with additional context.
1338 type errorState struct {
1342 // shouldContinue reports whether encoding should continue upon encountering the
1343 // given error. If the error is RequiredNotSetError, shouldContinue returns true
1344 // and, if this is the first appearance of that error, remembers it for future
1347 // If prop is not nil, it may update any error with additional context about the
1348 // field with the error.
1349 func (s *errorState) shouldContinue(err error, prop *Properties) bool {
1350 // Ignore unset required fields.
1351 reqNotSet, ok := err.(*RequiredNotSetError)
1357 err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field}