blob: 89d0caa8268f5bcc106d542e4eeb35dbd5df7302 [file] [log] [blame]
Rob Pikeaaa3a622010-03-20 22:32:34 -07001// Go support for Protocol Buffers - Google's data interchange format
2//
David Symondsee6e9c52012-11-29 08:51:07 +11003// Copyright 2010 The Go Authors. All rights reserved.
David Symonds558f13f2014-11-24 10:28:53 +11004// https://github.com/golang/protobuf
Rob Pikeaaa3a622010-03-20 22:32:34 -07005//
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
32package proto
33
34/*
35 * Routines for encoding data into the wire format for protocol buffers.
36 */
37
38import (
Rob Pikea17fdd92011-11-02 12:43:05 -070039 "errors"
David Symonds4646c372013-09-09 13:18:58 +100040 "fmt"
Rob Pikeaaa3a622010-03-20 22:32:34 -070041 "reflect"
David Symondsdf583ae2012-12-06 14:06:53 +110042 "sort"
Rob Pikeaaa3a622010-03-20 22:32:34 -070043)
44
David Symondse583a5f2013-09-27 10:02:37 +100045// RequiredNotSetError is the error returned if Marshal is called with
Rob Pikeaaa3a622010-03-20 22:32:34 -070046// a protocol buffer struct whose required fields have not
Rob Pikec6d8e4a2010-07-28 15:34:32 -070047// 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
49// required fields.
David Symonds4646c372013-09-09 13:18:58 +100050//
David Symondse583a5f2013-09-27 10:02:37 +100051// When printed, RequiredNotSetError reports the first unset required field in a
David Symonds4646c372013-09-09 13:18:58 +100052// message. If the field cannot be precisely determined, it is reported as
53// "{Unknown}".
David Symondse583a5f2013-09-27 10:02:37 +100054type RequiredNotSetError struct {
David Symonds4646c372013-09-09 13:18:58 +100055 field string
David Symonds5b7775e2010-12-01 10:09:04 +110056}
57
David Symondse583a5f2013-09-27 10:02:37 +100058func (e *RequiredNotSetError) Error() string {
David Symonds4646c372013-09-09 13:18:58 +100059 return fmt.Sprintf("proto: required field %q not set", e.field)
David Symonds5b7775e2010-12-01 10:09:04 +110060}
Rob Pikeaaa3a622010-03-20 22:32:34 -070061
David Symonds7656e742011-07-22 14:54:17 +100062var (
David Symondsf62db482015-02-23 12:37:00 +110063 // errRepeatedHasNil is the error returned if Marshal is called with
David Symonds7656e742011-07-22 14:54:17 +100064 // a struct with a repeated field containing a nil element.
David Symondsf62db482015-02-23 12:37:00 +110065 errRepeatedHasNil = errors.New("proto: repeated field has nil element")
Rob Pikeaaa3a622010-03-20 22:32:34 -070066
David Symonds7656e742011-07-22 14:54:17 +100067 // ErrNil is the error returned if Marshal is called with nil.
Rob Pikea17fdd92011-11-02 12:43:05 -070068 ErrNil = errors.New("proto: Marshal called with nil")
David Symonds7656e742011-07-22 14:54:17 +100069)
Rob Pikeaaa3a622010-03-20 22:32:34 -070070
71// The fundamental encoders that put bytes on the wire.
72// Those that take integer types all accept uint64 and are
73// therefore of type valueEncoder.
74
David Symonds4fee3b12010-11-11 10:00:13 +110075const maxVarintBytes = 10 // maximum length of a varint
76
Rob Pikeaaa3a622010-03-20 22:32:34 -070077// EncodeVarint returns the varint encoding of x.
78// This is the format for the
79// int32, int64, uint32, uint64, bool, and enum
80// protocol buffer types.
81// Not used by the package itself, but helpful to clients
82// wishing to use the same encoding.
83func EncodeVarint(x uint64) []byte {
David Symonds4fee3b12010-11-11 10:00:13 +110084 var buf [maxVarintBytes]byte
Rob Pikeaaa3a622010-03-20 22:32:34 -070085 var n int
86 for n = 0; x > 127; n++ {
87 buf[n] = 0x80 | uint8(x&0x7F)
88 x >>= 7
89 }
90 buf[n] = uint8(x)
91 n++
92 return buf[0:n]
93}
94
95// EncodeVarint writes a varint-encoded integer to the Buffer.
96// This is the format for the
97// int32, int64, uint32, uint64, bool, and enum
98// protocol buffer types.
Rob Pikea17fdd92011-11-02 12:43:05 -070099func (p *Buffer) EncodeVarint(x uint64) error {
David Symonds4fee3b12010-11-11 10:00:13 +1100100 for x >= 1<<7 {
David Symondsd9da6ba2011-08-30 14:41:30 +1000101 p.buf = append(p.buf, uint8(x&0x7f|0x80))
Rob Pikeaaa3a622010-03-20 22:32:34 -0700102 x >>= 7
103 }
David Symondsd9da6ba2011-08-30 14:41:30 +1000104 p.buf = append(p.buf, uint8(x))
Rob Pikeaaa3a622010-03-20 22:32:34 -0700105 return nil
106}
107
David Symonds0bf1ad52013-10-11 09:07:50 +1100108func sizeVarint(x uint64) (n int) {
109 for {
110 n++
111 x >>= 7
112 if x == 0 {
113 break
114 }
115 }
116 return n
117}
118
Rob Pikeaaa3a622010-03-20 22:32:34 -0700119// EncodeFixed64 writes a 64-bit integer to the Buffer.
120// This is the format for the
121// fixed64, sfixed64, and double protocol buffer types.
Rob Pikea17fdd92011-11-02 12:43:05 -0700122func (p *Buffer) EncodeFixed64(x uint64) error {
David Symondsd9da6ba2011-08-30 14:41:30 +1000123 p.buf = append(p.buf,
124 uint8(x),
125 uint8(x>>8),
126 uint8(x>>16),
127 uint8(x>>24),
128 uint8(x>>32),
129 uint8(x>>40),
130 uint8(x>>48),
131 uint8(x>>56))
Rob Pikeaaa3a622010-03-20 22:32:34 -0700132 return nil
133}
134
David Symonds0bf1ad52013-10-11 09:07:50 +1100135func sizeFixed64(x uint64) int {
136 return 8
137}
138
Rob Pikeaaa3a622010-03-20 22:32:34 -0700139// EncodeFixed32 writes a 32-bit integer to the Buffer.
140// This is the format for the
141// fixed32, sfixed32, and float protocol buffer types.
Rob Pikea17fdd92011-11-02 12:43:05 -0700142func (p *Buffer) EncodeFixed32(x uint64) error {
David Symondsd9da6ba2011-08-30 14:41:30 +1000143 p.buf = append(p.buf,
144 uint8(x),
145 uint8(x>>8),
146 uint8(x>>16),
147 uint8(x>>24))
Rob Pikeaaa3a622010-03-20 22:32:34 -0700148 return nil
149}
150
David Symonds0bf1ad52013-10-11 09:07:50 +1100151func sizeFixed32(x uint64) int {
152 return 4
153}
154
Rob Pikeaaa3a622010-03-20 22:32:34 -0700155// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
156// to the Buffer.
157// This is the format used for the sint64 protocol buffer type.
Rob Pikea17fdd92011-11-02 12:43:05 -0700158func (p *Buffer) EncodeZigzag64(x uint64) error {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700159 // use signed number to get arithmetic right shift.
160 return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
161}
162
David Symonds0bf1ad52013-10-11 09:07:50 +1100163func sizeZigzag64(x uint64) int {
164 return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
165}
166
Rob Pikeaaa3a622010-03-20 22:32:34 -0700167// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
168// to the Buffer.
169// This is the format used for the sint32 protocol buffer type.
Rob Pikea17fdd92011-11-02 12:43:05 -0700170func (p *Buffer) EncodeZigzag32(x uint64) error {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700171 // use signed number to get arithmetic right shift.
172 return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
173}
174
David Symonds0bf1ad52013-10-11 09:07:50 +1100175func sizeZigzag32(x uint64) int {
176 return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
177}
178
Rob Pikeaaa3a622010-03-20 22:32:34 -0700179// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
180// This is the format used for the bytes protocol buffer
181// type and for embedded messages.
Rob Pikea17fdd92011-11-02 12:43:05 -0700182func (p *Buffer) EncodeRawBytes(b []byte) error {
Rob Pike76f6ee52011-10-20 12:58:28 -0700183 p.EncodeVarint(uint64(len(b)))
Rob Pike99fa2b62010-12-02 10:39:42 -0800184 p.buf = append(p.buf, b...)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700185 return nil
186}
187
David Symonds0bf1ad52013-10-11 09:07:50 +1100188func sizeRawBytes(b []byte) int {
189 return sizeVarint(uint64(len(b))) +
190 len(b)
191}
192
Rob Pikeaaa3a622010-03-20 22:32:34 -0700193// EncodeStringBytes writes an encoded string to the Buffer.
194// This is the format used for the proto2 string type.
Rob Pikea17fdd92011-11-02 12:43:05 -0700195func (p *Buffer) EncodeStringBytes(s string) error {
Rob Pike76f6ee52011-10-20 12:58:28 -0700196 p.EncodeVarint(uint64(len(s)))
197 p.buf = append(p.buf, s...)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700198 return nil
199}
200
David Symonds0bf1ad52013-10-11 09:07:50 +1100201func sizeStringBytes(s string) int {
202 return sizeVarint(uint64(len(s))) +
203 len(s)
204}
205
Rob Pikeaaa3a622010-03-20 22:32:34 -0700206// Marshaler is the interface representing objects that can marshal themselves.
207type Marshaler interface {
Rob Pikea17fdd92011-11-02 12:43:05 -0700208 Marshal() ([]byte, error)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700209}
210
David Symonds9f60f432012-06-14 09:45:25 +1000211// Marshal takes the protocol buffer
Rob Pikeaaa3a622010-03-20 22:32:34 -0700212// and encodes it into the wire format, returning the data.
David Symonds9f60f432012-06-14 09:45:25 +1000213func Marshal(pb Message) ([]byte, error) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700214 // Can the object marshal itself?
215 if m, ok := pb.(Marshaler); ok {
216 return m.Marshal()
217 }
218 p := NewBuffer(nil)
219 err := p.Marshal(pb)
David Symonds4646c372013-09-09 13:18:58 +1000220 var state errorState
221 if err != nil && !state.shouldContinue(err, nil) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700222 return nil, err
223 }
David Symonds8b253302014-01-14 16:24:19 +1100224 if p.buf == nil && err == nil {
225 // Return a non-nil slice on success.
226 return []byte{}, nil
227 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700228 return p.buf, err
229}
230
David Symonds59b73b32015-08-24 13:22:02 +1000231// EncodeMessage writes the protocol buffer to the Buffer,
232// prefixed by a varint-encoded length.
233func (p *Buffer) EncodeMessage(pb Message) error {
234 t, base, err := getbase(pb)
235 if structPointer_IsNil(base) {
236 return ErrNil
237 }
238 if err == nil {
239 var state errorState
240 err = p.enc_len_struct(GetProperties(t.Elem()), base, &state)
241 }
242 return err
243}
244
David Symonds9f60f432012-06-14 09:45:25 +1000245// Marshal takes the protocol buffer
Rob Pikeaaa3a622010-03-20 22:32:34 -0700246// and encodes it into the wire format, writing the result to the
247// Buffer.
David Symonds9f60f432012-06-14 09:45:25 +1000248func (p *Buffer) Marshal(pb Message) error {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700249 // Can the object marshal itself?
250 if m, ok := pb.(Marshaler); ok {
251 data, err := m.Marshal()
252 if err != nil {
253 return err
254 }
Rob Pike99fa2b62010-12-02 10:39:42 -0800255 p.buf = append(p.buf, data...)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700256 return nil
257 }
258
Russ Coxd4ce3f12012-09-12 10:36:26 +1000259 t, base, err := getbase(pb)
260 if structPointer_IsNil(base) {
David Symondsd4661c52012-08-30 15:17:53 +1000261 return ErrNil
262 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700263 if err == nil {
David Symondsba7896c2014-11-20 15:29:05 +1100264 err = p.enc_struct(GetProperties(t.Elem()), base)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700265 }
266
David Symonds9f60f432012-06-14 09:45:25 +1000267 if collectStats {
268 stats.Encode++
269 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700270
271 return err
272}
273
David Symonds0bf1ad52013-10-11 09:07:50 +1100274// Size returns the encoded size of a protocol buffer.
275func Size(pb Message) (n int) {
276 // Can the object marshal itself? If so, Size is slow.
277 // TODO: add Size to Marshaler, or add a Sizer interface.
278 if m, ok := pb.(Marshaler); ok {
279 b, _ := m.Marshal()
280 return len(b)
281 }
282
283 t, base, err := getbase(pb)
284 if structPointer_IsNil(base) {
285 return 0
286 }
287 if err == nil {
David Symondsba7896c2014-11-20 15:29:05 +1100288 n = size_struct(GetProperties(t.Elem()), base)
David Symonds0bf1ad52013-10-11 09:07:50 +1100289 }
290
291 if collectStats {
292 stats.Size++
293 }
294
295 return
296}
297
Rob Pikeaaa3a622010-03-20 22:32:34 -0700298// Individual type encoders.
299
300// Encode a bool.
Russ Coxd4ce3f12012-09-12 10:36:26 +1000301func (o *Buffer) enc_bool(p *Properties, base structPointer) error {
302 v := *structPointer_Bool(base, p.field)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700303 if v == nil {
304 return ErrNil
305 }
Rob Pike0f42a272011-10-20 16:03:11 -0700306 x := 0
307 if *v {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700308 x = 1
309 }
Rob Pike99fa2b62010-12-02 10:39:42 -0800310 o.buf = append(o.buf, p.tagcode...)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700311 p.valEnc(o, uint64(x))
312 return nil
313}
314
David Symondsabd3b412014-11-28 11:43:44 +1100315func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error {
316 v := *structPointer_BoolVal(base, p.field)
317 if !v {
318 return ErrNil
319 }
320 o.buf = append(o.buf, p.tagcode...)
321 p.valEnc(o, 1)
322 return nil
323}
324
David Symonds0bf1ad52013-10-11 09:07:50 +1100325func size_bool(p *Properties, base structPointer) int {
326 v := *structPointer_Bool(base, p.field)
327 if v == nil {
328 return 0
329 }
330 return len(p.tagcode) + 1 // each bool takes exactly one byte
331}
332
David Symondsabd3b412014-11-28 11:43:44 +1100333func size_proto3_bool(p *Properties, base structPointer) int {
334 v := *structPointer_BoolVal(base, p.field)
David Symonds535a1042015-09-11 08:27:00 +1000335 if !v && !p.oneof {
David Symondsabd3b412014-11-28 11:43:44 +1100336 return 0
337 }
338 return len(p.tagcode) + 1 // each bool takes exactly one byte
339}
340
Rob Pikeaaa3a622010-03-20 22:32:34 -0700341// Encode an int32.
Russ Coxd4ce3f12012-09-12 10:36:26 +1000342func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
343 v := structPointer_Word32(base, p.field)
344 if word32_IsNil(v) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700345 return ErrNil
346 }
David Symondsf054e842014-07-22 14:06:27 +1000347 x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
Rob Pike99fa2b62010-12-02 10:39:42 -0800348 o.buf = append(o.buf, p.tagcode...)
David Symondsc31645c2013-06-22 17:57:36 +1000349 p.valEnc(o, uint64(x))
Rob Pikeaaa3a622010-03-20 22:32:34 -0700350 return nil
351}
352
David Symondsabd3b412014-11-28 11:43:44 +1100353func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error {
354 v := structPointer_Word32Val(base, p.field)
355 x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
356 if x == 0 {
357 return ErrNil
358 }
359 o.buf = append(o.buf, p.tagcode...)
360 p.valEnc(o, uint64(x))
361 return nil
362}
363
David Symonds0bf1ad52013-10-11 09:07:50 +1100364func size_int32(p *Properties, base structPointer) (n int) {
365 v := structPointer_Word32(base, p.field)
366 if word32_IsNil(v) {
367 return 0
368 }
David Symondsf054e842014-07-22 14:06:27 +1000369 x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
370 n += len(p.tagcode)
371 n += p.valSize(uint64(x))
372 return
373}
374
David Symondsabd3b412014-11-28 11:43:44 +1100375func size_proto3_int32(p *Properties, base structPointer) (n int) {
376 v := structPointer_Word32Val(base, p.field)
377 x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
David Symonds535a1042015-09-11 08:27:00 +1000378 if x == 0 && !p.oneof {
David Symondsabd3b412014-11-28 11:43:44 +1100379 return 0
380 }
381 n += len(p.tagcode)
382 n += p.valSize(uint64(x))
383 return
384}
385
David Symondsf054e842014-07-22 14:06:27 +1000386// Encode a uint32.
387// Exactly the same as int32, except for no sign extension.
388func (o *Buffer) enc_uint32(p *Properties, base structPointer) error {
389 v := structPointer_Word32(base, p.field)
390 if word32_IsNil(v) {
391 return ErrNil
392 }
393 x := word32_Get(v)
394 o.buf = append(o.buf, p.tagcode...)
395 p.valEnc(o, uint64(x))
396 return nil
397}
398
David Symondsabd3b412014-11-28 11:43:44 +1100399func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error {
400 v := structPointer_Word32Val(base, p.field)
401 x := word32Val_Get(v)
402 if x == 0 {
403 return ErrNil
404 }
405 o.buf = append(o.buf, p.tagcode...)
406 p.valEnc(o, uint64(x))
407 return nil
408}
409
David Symondsf054e842014-07-22 14:06:27 +1000410func size_uint32(p *Properties, base structPointer) (n int) {
411 v := structPointer_Word32(base, p.field)
412 if word32_IsNil(v) {
413 return 0
414 }
David Symonds0bf1ad52013-10-11 09:07:50 +1100415 x := word32_Get(v)
416 n += len(p.tagcode)
417 n += p.valSize(uint64(x))
418 return
419}
420
David Symondsabd3b412014-11-28 11:43:44 +1100421func size_proto3_uint32(p *Properties, base structPointer) (n int) {
422 v := structPointer_Word32Val(base, p.field)
423 x := word32Val_Get(v)
David Symonds535a1042015-09-11 08:27:00 +1000424 if x == 0 && !p.oneof {
David Symondsabd3b412014-11-28 11:43:44 +1100425 return 0
426 }
427 n += len(p.tagcode)
428 n += p.valSize(uint64(x))
429 return
430}
431
Rob Pikeaaa3a622010-03-20 22:32:34 -0700432// Encode an int64.
Russ Coxd4ce3f12012-09-12 10:36:26 +1000433func (o *Buffer) enc_int64(p *Properties, base structPointer) error {
434 v := structPointer_Word64(base, p.field)
435 if word64_IsNil(v) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700436 return ErrNil
437 }
Russ Coxd4ce3f12012-09-12 10:36:26 +1000438 x := word64_Get(v)
Rob Pike99fa2b62010-12-02 10:39:42 -0800439 o.buf = append(o.buf, p.tagcode...)
Russ Coxd4ce3f12012-09-12 10:36:26 +1000440 p.valEnc(o, x)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700441 return nil
442}
443
David Symondsabd3b412014-11-28 11:43:44 +1100444func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error {
445 v := structPointer_Word64Val(base, p.field)
446 x := word64Val_Get(v)
447 if x == 0 {
448 return ErrNil
449 }
450 o.buf = append(o.buf, p.tagcode...)
451 p.valEnc(o, x)
452 return nil
453}
454
David Symonds0bf1ad52013-10-11 09:07:50 +1100455func size_int64(p *Properties, base structPointer) (n int) {
456 v := structPointer_Word64(base, p.field)
457 if word64_IsNil(v) {
458 return 0
459 }
460 x := word64_Get(v)
461 n += len(p.tagcode)
462 n += p.valSize(x)
463 return
464}
465
David Symondsabd3b412014-11-28 11:43:44 +1100466func size_proto3_int64(p *Properties, base structPointer) (n int) {
467 v := structPointer_Word64Val(base, p.field)
468 x := word64Val_Get(v)
David Symonds535a1042015-09-11 08:27:00 +1000469 if x == 0 && !p.oneof {
David Symondsabd3b412014-11-28 11:43:44 +1100470 return 0
471 }
472 n += len(p.tagcode)
473 n += p.valSize(x)
474 return
475}
476
Rob Pikeaaa3a622010-03-20 22:32:34 -0700477// Encode a string.
Russ Coxd4ce3f12012-09-12 10:36:26 +1000478func (o *Buffer) enc_string(p *Properties, base structPointer) error {
479 v := *structPointer_String(base, p.field)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700480 if v == nil {
481 return ErrNil
482 }
483 x := *v
Rob Pike99fa2b62010-12-02 10:39:42 -0800484 o.buf = append(o.buf, p.tagcode...)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700485 o.EncodeStringBytes(x)
486 return nil
487}
488
David Symondsabd3b412014-11-28 11:43:44 +1100489func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error {
490 v := *structPointer_StringVal(base, p.field)
491 if v == "" {
492 return ErrNil
493 }
494 o.buf = append(o.buf, p.tagcode...)
495 o.EncodeStringBytes(v)
496 return nil
497}
498
David Symonds0bf1ad52013-10-11 09:07:50 +1100499func size_string(p *Properties, base structPointer) (n int) {
500 v := *structPointer_String(base, p.field)
501 if v == nil {
502 return 0
503 }
504 x := *v
505 n += len(p.tagcode)
506 n += sizeStringBytes(x)
507 return
508}
509
David Symondsabd3b412014-11-28 11:43:44 +1100510func size_proto3_string(p *Properties, base structPointer) (n int) {
511 v := *structPointer_StringVal(base, p.field)
David Symonds535a1042015-09-11 08:27:00 +1000512 if v == "" && !p.oneof {
David Symondsabd3b412014-11-28 11:43:44 +1100513 return 0
514 }
515 n += len(p.tagcode)
516 n += sizeStringBytes(v)
517 return
518}
519
Rob Pike97e934d2011-04-11 12:52:49 -0700520// All protocol buffer fields are nillable, but be careful.
521func isNil(v reflect.Value) bool {
522 switch v.Kind() {
David Symonds007ed9d2012-07-24 10:59:36 +1000523 case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
Rob Pike97e934d2011-04-11 12:52:49 -0700524 return v.IsNil()
525 }
526 return false
527}
528
Rob Pikeaaa3a622010-03-20 22:32:34 -0700529// Encode a message struct.
Russ Coxd4ce3f12012-09-12 10:36:26 +1000530func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
David Symonds4646c372013-09-09 13:18:58 +1000531 var state errorState
Russ Coxd4ce3f12012-09-12 10:36:26 +1000532 structp := structPointer_GetStructPointer(base, p.field)
533 if structPointer_IsNil(structp) {
David Symondsa80b2822012-03-14 14:31:25 +1100534 return ErrNil
535 }
536
Rob Pikeaaa3a622010-03-20 22:32:34 -0700537 // Can the object marshal itself?
David Symondsa80b2822012-03-14 14:31:25 +1100538 if p.isMarshaler {
Russ Coxd4ce3f12012-09-12 10:36:26 +1000539 m := structPointer_Interface(structp, p.stype).(Marshaler)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700540 data, err := m.Marshal()
David Symonds4646c372013-09-09 13:18:58 +1000541 if err != nil && !state.shouldContinue(err, nil) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700542 return err
543 }
Rob Pike99fa2b62010-12-02 10:39:42 -0800544 o.buf = append(o.buf, p.tagcode...)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700545 o.EncodeRawBytes(data)
David Symonds68c687d2015-07-27 19:06:00 +1000546 return state.err
Rob Pikeaaa3a622010-03-20 22:32:34 -0700547 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700548
Rob Pike99fa2b62010-12-02 10:39:42 -0800549 o.buf = append(o.buf, p.tagcode...)
David Symondsba7896c2014-11-20 15:29:05 +1100550 return o.enc_len_struct(p.sprop, structp, &state)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700551}
552
David Symonds0bf1ad52013-10-11 09:07:50 +1100553func size_struct_message(p *Properties, base structPointer) int {
554 structp := structPointer_GetStructPointer(base, p.field)
555 if structPointer_IsNil(structp) {
556 return 0
557 }
558
559 // Can the object marshal itself?
560 if p.isMarshaler {
561 m := structPointer_Interface(structp, p.stype).(Marshaler)
562 data, _ := m.Marshal()
563 n0 := len(p.tagcode)
564 n1 := sizeRawBytes(data)
565 return n0 + n1
566 }
567
568 n0 := len(p.tagcode)
David Symondsba7896c2014-11-20 15:29:05 +1100569 n1 := size_struct(p.sprop, structp)
David Symonds0bf1ad52013-10-11 09:07:50 +1100570 n2 := sizeVarint(uint64(n1)) // size of encoded length
571 return n0 + n1 + n2
572}
573
Rob Pikeaaa3a622010-03-20 22:32:34 -0700574// Encode a group struct.
Russ Coxd4ce3f12012-09-12 10:36:26 +1000575func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error {
David Symonds4646c372013-09-09 13:18:58 +1000576 var state errorState
Russ Coxd4ce3f12012-09-12 10:36:26 +1000577 b := structPointer_GetStructPointer(base, p.field)
578 if structPointer_IsNil(b) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700579 return ErrNil
580 }
581
582 o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
David Symondsba7896c2014-11-20 15:29:05 +1100583 err := o.enc_struct(p.sprop, b)
David Symonds4646c372013-09-09 13:18:58 +1000584 if err != nil && !state.shouldContinue(err, nil) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700585 return err
586 }
587 o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
David Symonds4646c372013-09-09 13:18:58 +1000588 return state.err
Rob Pikeaaa3a622010-03-20 22:32:34 -0700589}
590
David Symonds0bf1ad52013-10-11 09:07:50 +1100591func size_struct_group(p *Properties, base structPointer) (n int) {
592 b := structPointer_GetStructPointer(base, p.field)
593 if structPointer_IsNil(b) {
594 return 0
595 }
596
597 n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup))
David Symondsba7896c2014-11-20 15:29:05 +1100598 n += size_struct(p.sprop, b)
David Symonds0bf1ad52013-10-11 09:07:50 +1100599 n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup))
600 return
601}
602
Rob Pikeaaa3a622010-03-20 22:32:34 -0700603// Encode a slice of bools ([]bool).
Russ Coxd4ce3f12012-09-12 10:36:26 +1000604func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
605 s := *structPointer_BoolSlice(base, p.field)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700606 l := len(s)
607 if l == 0 {
608 return ErrNil
609 }
610 for _, x := range s {
Rob Pike99fa2b62010-12-02 10:39:42 -0800611 o.buf = append(o.buf, p.tagcode...)
Russ Coxd4ce3f12012-09-12 10:36:26 +1000612 v := uint64(0)
613 if x {
614 v = 1
Rob Pikeaaa3a622010-03-20 22:32:34 -0700615 }
Russ Coxd4ce3f12012-09-12 10:36:26 +1000616 p.valEnc(o, v)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700617 }
618 return nil
619}
620
David Symonds0bf1ad52013-10-11 09:07:50 +1100621func size_slice_bool(p *Properties, base structPointer) int {
622 s := *structPointer_BoolSlice(base, p.field)
623 l := len(s)
624 if l == 0 {
625 return 0
626 }
627 return l * (len(p.tagcode) + 1) // each bool takes exactly one byte
628}
629
David Symonds5b7775e2010-12-01 10:09:04 +1100630// Encode a slice of bools ([]bool) in packed format.
Russ Coxd4ce3f12012-09-12 10:36:26 +1000631func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error {
632 s := *structPointer_BoolSlice(base, p.field)
David Symonds5b7775e2010-12-01 10:09:04 +1100633 l := len(s)
634 if l == 0 {
635 return ErrNil
636 }
637 o.buf = append(o.buf, p.tagcode...)
638 o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
639 for _, x := range s {
Russ Coxd4ce3f12012-09-12 10:36:26 +1000640 v := uint64(0)
641 if x {
642 v = 1
David Symonds5b7775e2010-12-01 10:09:04 +1100643 }
Russ Coxd4ce3f12012-09-12 10:36:26 +1000644 p.valEnc(o, v)
David Symonds5b7775e2010-12-01 10:09:04 +1100645 }
646 return nil
647}
648
David Symonds0bf1ad52013-10-11 09:07:50 +1100649func size_slice_packed_bool(p *Properties, base structPointer) (n int) {
650 s := *structPointer_BoolSlice(base, p.field)
651 l := len(s)
652 if l == 0 {
653 return 0
654 }
655 n += len(p.tagcode)
656 n += sizeVarint(uint64(l))
657 n += l // each bool takes exactly one byte
658 return
659}
660
Rob Pikeaaa3a622010-03-20 22:32:34 -0700661// Encode a slice of bytes ([]byte).
Russ Coxd4ce3f12012-09-12 10:36:26 +1000662func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
663 s := *structPointer_Bytes(base, p.field)
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800664 if s == nil {
665 return ErrNil
666 }
Rob Pike99fa2b62010-12-02 10:39:42 -0800667 o.buf = append(o.buf, p.tagcode...)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700668 o.EncodeRawBytes(s)
669 return nil
670}
671
David Symondsabd3b412014-11-28 11:43:44 +1100672func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error {
673 s := *structPointer_Bytes(base, p.field)
674 if len(s) == 0 {
675 return ErrNil
676 }
677 o.buf = append(o.buf, p.tagcode...)
678 o.EncodeRawBytes(s)
679 return nil
680}
681
David Symonds0bf1ad52013-10-11 09:07:50 +1100682func size_slice_byte(p *Properties, base structPointer) (n int) {
683 s := *structPointer_Bytes(base, p.field)
David Symonds535a1042015-09-11 08:27:00 +1000684 if s == nil && !p.oneof {
David Symonds0bf1ad52013-10-11 09:07:50 +1100685 return 0
686 }
687 n += len(p.tagcode)
688 n += sizeRawBytes(s)
689 return
690}
691
David Symondsabd3b412014-11-28 11:43:44 +1100692func size_proto3_slice_byte(p *Properties, base structPointer) (n int) {
693 s := *structPointer_Bytes(base, p.field)
David Symonds535a1042015-09-11 08:27:00 +1000694 if len(s) == 0 && !p.oneof {
David Symondsabd3b412014-11-28 11:43:44 +1100695 return 0
696 }
697 n += len(p.tagcode)
698 n += sizeRawBytes(s)
699 return
700}
701
Rob Pikeaaa3a622010-03-20 22:32:34 -0700702// Encode a slice of int32s ([]int32).
Russ Coxd4ce3f12012-09-12 10:36:26 +1000703func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error {
704 s := structPointer_Word32Slice(base, p.field)
705 l := s.Len()
Rob Pikeaaa3a622010-03-20 22:32:34 -0700706 if l == 0 {
707 return ErrNil
708 }
709 for i := 0; i < l; i++ {
Rob Pike99fa2b62010-12-02 10:39:42 -0800710 o.buf = append(o.buf, p.tagcode...)
David Symonds0ec36a22014-08-12 13:21:46 +1000711 x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
Rob Pikeaaa3a622010-03-20 22:32:34 -0700712 p.valEnc(o, uint64(x))
713 }
714 return nil
715}
716
David Symonds0bf1ad52013-10-11 09:07:50 +1100717func size_slice_int32(p *Properties, base structPointer) (n int) {
718 s := structPointer_Word32Slice(base, p.field)
719 l := s.Len()
720 if l == 0 {
721 return 0
722 }
723 for i := 0; i < l; i++ {
724 n += len(p.tagcode)
David Symonds0ec36a22014-08-12 13:21:46 +1000725 x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
David Symonds0bf1ad52013-10-11 09:07:50 +1100726 n += p.valSize(uint64(x))
727 }
728 return
729}
730
David Symonds5b7775e2010-12-01 10:09:04 +1100731// Encode a slice of int32s ([]int32) in packed format.
Russ Coxd4ce3f12012-09-12 10:36:26 +1000732func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error {
733 s := structPointer_Word32Slice(base, p.field)
734 l := s.Len()
David Symonds5b7775e2010-12-01 10:09:04 +1100735 if l == 0 {
736 return ErrNil
737 }
738 // TODO: Reuse a Buffer.
739 buf := NewBuffer(nil)
740 for i := 0; i < l; i++ {
David Symonds0ec36a22014-08-12 13:21:46 +1000741 x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
742 p.valEnc(buf, uint64(x))
743 }
744
745 o.buf = append(o.buf, p.tagcode...)
746 o.EncodeVarint(uint64(len(buf.buf)))
747 o.buf = append(o.buf, buf.buf...)
748 return nil
749}
750
751func size_slice_packed_int32(p *Properties, base structPointer) (n int) {
752 s := structPointer_Word32Slice(base, p.field)
753 l := s.Len()
754 if l == 0 {
755 return 0
756 }
757 var bufSize int
758 for i := 0; i < l; i++ {
759 x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
760 bufSize += p.valSize(uint64(x))
761 }
762
763 n += len(p.tagcode)
764 n += sizeVarint(uint64(bufSize))
765 n += bufSize
766 return
767}
768
769// Encode a slice of uint32s ([]uint32).
770// Exactly the same as int32, except for no sign extension.
771func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error {
772 s := structPointer_Word32Slice(base, p.field)
773 l := s.Len()
774 if l == 0 {
775 return ErrNil
776 }
777 for i := 0; i < l; i++ {
778 o.buf = append(o.buf, p.tagcode...)
779 x := s.Index(i)
780 p.valEnc(o, uint64(x))
781 }
782 return nil
783}
784
785func size_slice_uint32(p *Properties, base structPointer) (n int) {
786 s := structPointer_Word32Slice(base, p.field)
787 l := s.Len()
788 if l == 0 {
789 return 0
790 }
791 for i := 0; i < l; i++ {
792 n += len(p.tagcode)
793 x := s.Index(i)
794 n += p.valSize(uint64(x))
795 }
796 return
797}
798
799// Encode a slice of uint32s ([]uint32) in packed format.
800// Exactly the same as int32, except for no sign extension.
801func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error {
802 s := structPointer_Word32Slice(base, p.field)
803 l := s.Len()
804 if l == 0 {
805 return ErrNil
806 }
807 // TODO: Reuse a Buffer.
808 buf := NewBuffer(nil)
809 for i := 0; i < l; i++ {
Russ Coxd4ce3f12012-09-12 10:36:26 +1000810 p.valEnc(buf, uint64(s.Index(i)))
David Symonds5b7775e2010-12-01 10:09:04 +1100811 }
812
813 o.buf = append(o.buf, p.tagcode...)
814 o.EncodeVarint(uint64(len(buf.buf)))
815 o.buf = append(o.buf, buf.buf...)
816 return nil
817}
818
David Symonds0ec36a22014-08-12 13:21:46 +1000819func size_slice_packed_uint32(p *Properties, base structPointer) (n int) {
David Symonds0bf1ad52013-10-11 09:07:50 +1100820 s := structPointer_Word32Slice(base, p.field)
821 l := s.Len()
822 if l == 0 {
823 return 0
824 }
825 var bufSize int
826 for i := 0; i < l; i++ {
827 bufSize += p.valSize(uint64(s.Index(i)))
828 }
829
830 n += len(p.tagcode)
831 n += sizeVarint(uint64(bufSize))
832 n += bufSize
833 return
834}
835
Rob Pikeaaa3a622010-03-20 22:32:34 -0700836// Encode a slice of int64s ([]int64).
Russ Coxd4ce3f12012-09-12 10:36:26 +1000837func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error {
838 s := structPointer_Word64Slice(base, p.field)
839 l := s.Len()
Rob Pikeaaa3a622010-03-20 22:32:34 -0700840 if l == 0 {
841 return ErrNil
842 }
843 for i := 0; i < l; i++ {
Rob Pike99fa2b62010-12-02 10:39:42 -0800844 o.buf = append(o.buf, p.tagcode...)
Russ Coxd4ce3f12012-09-12 10:36:26 +1000845 p.valEnc(o, s.Index(i))
Rob Pikeaaa3a622010-03-20 22:32:34 -0700846 }
847 return nil
848}
849
David Symonds0bf1ad52013-10-11 09:07:50 +1100850func size_slice_int64(p *Properties, base structPointer) (n int) {
851 s := structPointer_Word64Slice(base, p.field)
852 l := s.Len()
853 if l == 0 {
854 return 0
855 }
856 for i := 0; i < l; i++ {
857 n += len(p.tagcode)
858 n += p.valSize(s.Index(i))
859 }
860 return
861}
862
David Symonds5b7775e2010-12-01 10:09:04 +1100863// Encode a slice of int64s ([]int64) in packed format.
Russ Coxd4ce3f12012-09-12 10:36:26 +1000864func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error {
865 s := structPointer_Word64Slice(base, p.field)
866 l := s.Len()
David Symonds5b7775e2010-12-01 10:09:04 +1100867 if l == 0 {
868 return ErrNil
869 }
870 // TODO: Reuse a Buffer.
871 buf := NewBuffer(nil)
872 for i := 0; i < l; i++ {
Russ Coxd4ce3f12012-09-12 10:36:26 +1000873 p.valEnc(buf, s.Index(i))
David Symonds5b7775e2010-12-01 10:09:04 +1100874 }
875
876 o.buf = append(o.buf, p.tagcode...)
877 o.EncodeVarint(uint64(len(buf.buf)))
878 o.buf = append(o.buf, buf.buf...)
879 return nil
880}
881
David Symonds0bf1ad52013-10-11 09:07:50 +1100882func size_slice_packed_int64(p *Properties, base structPointer) (n int) {
883 s := structPointer_Word64Slice(base, p.field)
884 l := s.Len()
885 if l == 0 {
886 return 0
887 }
888 var bufSize int
889 for i := 0; i < l; i++ {
890 bufSize += p.valSize(s.Index(i))
891 }
892
893 n += len(p.tagcode)
894 n += sizeVarint(uint64(bufSize))
895 n += bufSize
896 return
897}
898
Rob Pikeaaa3a622010-03-20 22:32:34 -0700899// Encode a slice of slice of bytes ([][]byte).
Russ Coxd4ce3f12012-09-12 10:36:26 +1000900func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
901 ss := *structPointer_BytesSlice(base, p.field)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700902 l := len(ss)
903 if l == 0 {
904 return ErrNil
905 }
906 for i := 0; i < l; i++ {
Rob Pike99fa2b62010-12-02 10:39:42 -0800907 o.buf = append(o.buf, p.tagcode...)
David Symonds0bf1ad52013-10-11 09:07:50 +1100908 o.EncodeRawBytes(ss[i])
Rob Pikeaaa3a622010-03-20 22:32:34 -0700909 }
910 return nil
911}
912
David Symonds0bf1ad52013-10-11 09:07:50 +1100913func size_slice_slice_byte(p *Properties, base structPointer) (n int) {
914 ss := *structPointer_BytesSlice(base, p.field)
915 l := len(ss)
916 if l == 0 {
917 return 0
918 }
919 n += l * len(p.tagcode)
920 for i := 0; i < l; i++ {
921 n += sizeRawBytes(ss[i])
922 }
923 return
924}
925
Rob Pikeaaa3a622010-03-20 22:32:34 -0700926// Encode a slice of strings ([]string).
Russ Coxd4ce3f12012-09-12 10:36:26 +1000927func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
928 ss := *structPointer_StringSlice(base, p.field)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700929 l := len(ss)
930 for i := 0; i < l; i++ {
Rob Pike99fa2b62010-12-02 10:39:42 -0800931 o.buf = append(o.buf, p.tagcode...)
David Symonds0bf1ad52013-10-11 09:07:50 +1100932 o.EncodeStringBytes(ss[i])
Rob Pikeaaa3a622010-03-20 22:32:34 -0700933 }
934 return nil
935}
936
David Symonds0bf1ad52013-10-11 09:07:50 +1100937func size_slice_string(p *Properties, base structPointer) (n int) {
938 ss := *structPointer_StringSlice(base, p.field)
939 l := len(ss)
940 n += l * len(p.tagcode)
941 for i := 0; i < l; i++ {
942 n += sizeStringBytes(ss[i])
943 }
944 return
945}
946
Rob Pikeaaa3a622010-03-20 22:32:34 -0700947// Encode a slice of message structs ([]*struct).
Russ Coxd4ce3f12012-09-12 10:36:26 +1000948func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error {
David Symonds4646c372013-09-09 13:18:58 +1000949 var state errorState
Russ Coxd4ce3f12012-09-12 10:36:26 +1000950 s := structPointer_StructPointerSlice(base, p.field)
951 l := s.Len()
Rob Pikeaaa3a622010-03-20 22:32:34 -0700952
953 for i := 0; i < l; i++ {
Russ Coxd4ce3f12012-09-12 10:36:26 +1000954 structp := s.Index(i)
955 if structPointer_IsNil(structp) {
David Symondsf62db482015-02-23 12:37:00 +1100956 return errRepeatedHasNil
Rob Pikeaaa3a622010-03-20 22:32:34 -0700957 }
958
959 // Can the object marshal itself?
David Symondsa80b2822012-03-14 14:31:25 +1100960 if p.isMarshaler {
Russ Coxd4ce3f12012-09-12 10:36:26 +1000961 m := structPointer_Interface(structp, p.stype).(Marshaler)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700962 data, err := m.Marshal()
David Symonds4646c372013-09-09 13:18:58 +1000963 if err != nil && !state.shouldContinue(err, nil) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700964 return err
965 }
Rob Pike99fa2b62010-12-02 10:39:42 -0800966 o.buf = append(o.buf, p.tagcode...)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700967 o.EncodeRawBytes(data)
968 continue
969 }
970
David Symonds1d8ba132014-01-13 16:01:15 +1100971 o.buf = append(o.buf, p.tagcode...)
David Symondsba7896c2014-11-20 15:29:05 +1100972 err := o.enc_len_struct(p.sprop, structp, &state)
David Symonds4646c372013-09-09 13:18:58 +1000973 if err != nil && !state.shouldContinue(err, nil) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700974 if err == ErrNil {
David Symondsf62db482015-02-23 12:37:00 +1100975 return errRepeatedHasNil
Rob Pikeaaa3a622010-03-20 22:32:34 -0700976 }
977 return err
978 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700979 }
David Symonds4646c372013-09-09 13:18:58 +1000980 return state.err
Rob Pikeaaa3a622010-03-20 22:32:34 -0700981}
982
David Symonds0bf1ad52013-10-11 09:07:50 +1100983func size_slice_struct_message(p *Properties, base structPointer) (n int) {
984 s := structPointer_StructPointerSlice(base, p.field)
985 l := s.Len()
986 n += l * len(p.tagcode)
987 for i := 0; i < l; i++ {
988 structp := s.Index(i)
989 if structPointer_IsNil(structp) {
990 return // return the size up to this point
991 }
992
993 // Can the object marshal itself?
994 if p.isMarshaler {
995 m := structPointer_Interface(structp, p.stype).(Marshaler)
996 data, _ := m.Marshal()
997 n += len(p.tagcode)
998 n += sizeRawBytes(data)
999 continue
1000 }
1001
David Symondsba7896c2014-11-20 15:29:05 +11001002 n0 := size_struct(p.sprop, structp)
David Symonds0bf1ad52013-10-11 09:07:50 +11001003 n1 := sizeVarint(uint64(n0)) // size of encoded length
1004 n += n0 + n1
1005 }
1006 return
1007}
1008
Rob Pikeaaa3a622010-03-20 22:32:34 -07001009// Encode a slice of group structs ([]*struct).
Russ Coxd4ce3f12012-09-12 10:36:26 +10001010func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error {
David Symonds4646c372013-09-09 13:18:58 +10001011 var state errorState
Russ Coxd4ce3f12012-09-12 10:36:26 +10001012 s := structPointer_StructPointerSlice(base, p.field)
1013 l := s.Len()
Rob Pikeaaa3a622010-03-20 22:32:34 -07001014
1015 for i := 0; i < l; i++ {
Russ Coxd4ce3f12012-09-12 10:36:26 +10001016 b := s.Index(i)
1017 if structPointer_IsNil(b) {
David Symondsf62db482015-02-23 12:37:00 +11001018 return errRepeatedHasNil
Rob Pikeaaa3a622010-03-20 22:32:34 -07001019 }
1020
1021 o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
1022
David Symondsba7896c2014-11-20 15:29:05 +11001023 err := o.enc_struct(p.sprop, b)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001024
David Symonds4646c372013-09-09 13:18:58 +10001025 if err != nil && !state.shouldContinue(err, nil) {
Rob Pikeaaa3a622010-03-20 22:32:34 -07001026 if err == ErrNil {
David Symondsf62db482015-02-23 12:37:00 +11001027 return errRepeatedHasNil
Rob Pikeaaa3a622010-03-20 22:32:34 -07001028 }
1029 return err
1030 }
1031
1032 o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
1033 }
David Symonds4646c372013-09-09 13:18:58 +10001034 return state.err
Rob Pikeaaa3a622010-03-20 22:32:34 -07001035}
1036
David Symonds0bf1ad52013-10-11 09:07:50 +11001037func size_slice_struct_group(p *Properties, base structPointer) (n int) {
1038 s := structPointer_StructPointerSlice(base, p.field)
1039 l := s.Len()
1040
1041 n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup))
1042 n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup))
1043 for i := 0; i < l; i++ {
1044 b := s.Index(i)
1045 if structPointer_IsNil(b) {
1046 return // return size up to this point
1047 }
1048
David Symondsba7896c2014-11-20 15:29:05 +11001049 n += size_struct(p.sprop, b)
David Symonds0bf1ad52013-10-11 09:07:50 +11001050 }
1051 return
1052}
1053
Rob Pikeaaa3a622010-03-20 22:32:34 -07001054// Encode an extension map.
Russ Coxd4ce3f12012-09-12 10:36:26 +10001055func (o *Buffer) enc_map(p *Properties, base structPointer) error {
1056 v := *structPointer_ExtMap(base, p.field)
David Symonds1d72f7a2011-08-19 18:28:52 +10001057 if err := encodeExtensionMap(v); err != nil {
1058 return err
1059 }
David Symondsdf583ae2012-12-06 14:06:53 +11001060 // Fast-path for common cases: zero or one extensions.
1061 if len(v) <= 1 {
1062 for _, e := range v {
1063 o.buf = append(o.buf, e.enc...)
1064 }
1065 return nil
1066 }
1067
1068 // Sort keys to provide a deterministic encoding.
1069 keys := make([]int, 0, len(v))
1070 for k := range v {
1071 keys = append(keys, int(k))
1072 }
1073 sort.Ints(keys)
1074
1075 for _, k := range keys {
1076 o.buf = append(o.buf, v[int32(k)].enc...)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001077 }
1078 return nil
1079}
1080
David Symonds0bf1ad52013-10-11 09:07:50 +11001081func size_map(p *Properties, base structPointer) int {
1082 v := *structPointer_ExtMap(base, p.field)
1083 return sizeExtensionMap(v)
1084}
1085
David Symonds3ea3e052014-12-22 16:15:28 +11001086// Encode a map field.
1087func (o *Buffer) enc_new_map(p *Properties, base structPointer) error {
1088 var state errorState // XXX: or do we need to plumb this through?
1089
1090 /*
1091 A map defined as
1092 map<key_type, value_type> map_field = N;
1093 is encoded in the same way as
1094 message MapFieldEntry {
1095 key_type key = 1;
1096 value_type value = 2;
1097 }
1098 repeated MapFieldEntry map_field = N;
1099 */
1100
David Symonds0f7a9ca2015-07-20 16:00:00 +10001101 v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
David Symonds3ea3e052014-12-22 16:15:28 +11001102 if v.Len() == 0 {
1103 return nil
1104 }
1105
1106 keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
1107
1108 enc := func() error {
1109 if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil {
1110 return err
1111 }
1112 if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil {
1113 return err
1114 }
1115 return nil
1116 }
1117
David Symonds7f079252015-01-09 11:09:00 +11001118 keys := v.MapKeys()
1119 sort.Sort(mapKeys(keys))
1120 for _, key := range keys {
David Symonds3ea3e052014-12-22 16:15:28 +11001121 val := v.MapIndex(key)
1122
David Symondscab84a32015-05-19 09:29:00 +10001123 // The only illegal map entry values are nil message pointers.
1124 if val.Kind() == reflect.Ptr && val.IsNil() {
1125 return errors.New("proto: map has nil element")
1126 }
1127
David Symonds3ea3e052014-12-22 16:15:28 +11001128 keycopy.Set(key)
1129 valcopy.Set(val)
1130
1131 o.buf = append(o.buf, p.tagcode...)
1132 if err := o.enc_len_thing(enc, &state); err != nil {
1133 return err
1134 }
1135 }
1136 return nil
1137}
1138
1139func size_new_map(p *Properties, base structPointer) int {
David Symonds0f7a9ca2015-07-20 16:00:00 +10001140 v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
David Symonds3ea3e052014-12-22 16:15:28 +11001141
1142 keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
1143
1144 n := 0
1145 for _, key := range v.MapKeys() {
1146 val := v.MapIndex(key)
1147 keycopy.Set(key)
1148 valcopy.Set(val)
1149
David Symondsa8323e22015-03-24 10:18:00 +11001150 // Tag codes for key and val are the responsibility of the sub-sizer.
1151 keysize := p.mkeyprop.size(p.mkeyprop, keybase)
1152 valsize := p.mvalprop.size(p.mvalprop, valbase)
1153 entry := keysize + valsize
1154 // Add on tag code and length of map entry itself.
1155 n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry
David Symonds3ea3e052014-12-22 16:15:28 +11001156 }
1157 return n
1158}
1159
1160// mapEncodeScratch returns a new reflect.Value matching the map's value type,
1161// and a structPointer suitable for passing to an encoder or sizer.
1162func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) {
1163 // Prepare addressable doubly-indirect placeholders for the key and value types.
1164 // This is needed because the element-type encoders expect **T, but the map iteration produces T.
1165
1166 keycopy = reflect.New(mapType.Key()).Elem() // addressable K
1167 keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K
1168 keyptr.Set(keycopy.Addr()) //
1169 keybase = toStructPointer(keyptr.Addr()) // **K
1170
1171 // Value types are more varied and require special handling.
1172 switch mapType.Elem().Kind() {
1173 case reflect.Slice:
1174 // []byte
1175 var dummy []byte
1176 valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte
1177 valbase = toStructPointer(valcopy.Addr())
1178 case reflect.Ptr:
1179 // message; the generated field type is map[K]*Msg (so V is *Msg),
1180 // so we only need one level of indirection.
1181 valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
1182 valbase = toStructPointer(valcopy.Addr())
1183 default:
1184 // everything else
1185 valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
1186 valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V
1187 valptr.Set(valcopy.Addr()) //
1188 valbase = toStructPointer(valptr.Addr()) // **V
1189 }
1190 return
1191}
1192
Rob Pikeaaa3a622010-03-20 22:32:34 -07001193// Encode a struct.
David Symondsba7896c2014-11-20 15:29:05 +11001194func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error {
David Symonds4646c372013-09-09 13:18:58 +10001195 var state errorState
David Symondsd15e81b2011-10-03 14:31:12 -07001196 // Encode fields in tag order so that decoders may use optimizations
1197 // that depend on the ordering.
David Symonds380d2d02014-11-24 10:50:43 +11001198 // https://developers.google.com/protocol-buffers/docs/encoding#order
David Symondsd15e81b2011-10-03 14:31:12 -07001199 for _, i := range prop.order {
1200 p := prop.Prop[i]
Rob Pikeaaa3a622010-03-20 22:32:34 -07001201 if p.enc != nil {
1202 err := p.enc(o, p, base)
David Symonds4a2eeb52013-09-25 11:54:08 +10001203 if err != nil {
1204 if err == ErrNil {
1205 if p.Required && state.err == nil {
David Symondse583a5f2013-09-27 10:02:37 +10001206 state.err = &RequiredNotSetError{p.Name}
David Symonds4a2eeb52013-09-25 11:54:08 +10001207 }
David Symondsf62db482015-02-23 12:37:00 +11001208 } else if err == errRepeatedHasNil {
1209 // Give more context to nil values in repeated fields.
1210 return errors.New("repeated field " + p.OrigName + " has nil element")
David Symonds4a2eeb52013-09-25 11:54:08 +10001211 } else if !state.shouldContinue(err, p) {
Rob Pikeaaa3a622010-03-20 22:32:34 -07001212 return err
1213 }
Rob Pikeaaa3a622010-03-20 22:32:34 -07001214 }
1215 }
1216 }
Rob Pikeaaa3a622010-03-20 22:32:34 -07001217
David Symonds59b73b32015-08-24 13:22:02 +10001218 // Do oneof fields.
1219 if prop.oneofMarshaler != nil {
1220 m := structPointer_Interface(base, prop.stype).(Message)
1221 if err := prop.oneofMarshaler(m, o); err != nil {
1222 return err
1223 }
1224 }
1225
David Symonds10c93ba2012-08-04 16:38:08 +10001226 // Add unrecognized fields at the end.
Russ Coxd4ce3f12012-09-12 10:36:26 +10001227 if prop.unrecField.IsValid() {
1228 v := *structPointer_Bytes(base, prop.unrecField)
1229 if len(v) > 0 {
1230 o.buf = append(o.buf, v...)
1231 }
David Symonds10c93ba2012-08-04 16:38:08 +10001232 }
1233
David Symonds4646c372013-09-09 13:18:58 +10001234 return state.err
1235}
1236
David Symondsba7896c2014-11-20 15:29:05 +11001237func size_struct(prop *StructProperties, base structPointer) (n int) {
David Symonds0bf1ad52013-10-11 09:07:50 +11001238 for _, i := range prop.order {
1239 p := prop.Prop[i]
1240 if p.size != nil {
1241 n += p.size(p, base)
1242 }
1243 }
1244
1245 // Add unrecognized fields at the end.
1246 if prop.unrecField.IsValid() {
1247 v := *structPointer_Bytes(base, prop.unrecField)
1248 n += len(v)
1249 }
1250
David Symonds59b73b32015-08-24 13:22:02 +10001251 // Factor in any oneof fields.
1252 // TODO: This could be faster and use less reflection.
1253 if prop.oneofMarshaler != nil {
1254 sv := reflect.ValueOf(structPointer_Interface(base, prop.stype)).Elem()
1255 for i := 0; i < prop.stype.NumField(); i++ {
1256 fv := sv.Field(i)
1257 if fv.Kind() != reflect.Interface || fv.IsNil() {
1258 continue
1259 }
1260 if prop.stype.Field(i).Tag.Get("protobuf_oneof") == "" {
1261 continue
1262 }
1263 spv := fv.Elem() // interface -> *T
1264 sv := spv.Elem() // *T -> T
1265 sf := sv.Type().Field(0) // StructField inside T
1266 var prop Properties
1267 prop.Init(sf.Type, "whatever", sf.Tag.Get("protobuf"), &sf)
1268 n += prop.size(&prop, toStructPointer(spv))
1269 }
1270 }
1271
David Symonds0bf1ad52013-10-11 09:07:50 +11001272 return
1273}
1274
David Symonds1d8ba132014-01-13 16:01:15 +11001275var zeroes [20]byte // longer than any conceivable sizeVarint
1276
1277// Encode a struct, preceded by its encoded length (as a varint).
David Symondsba7896c2014-11-20 15:29:05 +11001278func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error {
David Symonds3ea3e052014-12-22 16:15:28 +11001279 return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state)
1280}
1281
1282// Encode something, preceded by its encoded length (as a varint).
1283func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error {
David Symonds1d8ba132014-01-13 16:01:15 +11001284 iLen := len(o.buf)
1285 o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length
1286 iMsg := len(o.buf)
David Symonds3ea3e052014-12-22 16:15:28 +11001287 err := enc()
David Symonds1d8ba132014-01-13 16:01:15 +11001288 if err != nil && !state.shouldContinue(err, nil) {
1289 return err
1290 }
1291 lMsg := len(o.buf) - iMsg
1292 lLen := sizeVarint(uint64(lMsg))
1293 switch x := lLen - (iMsg - iLen); {
1294 case x > 0: // actual length is x bytes larger than the space we reserved
1295 // Move msg x bytes right.
1296 o.buf = append(o.buf, zeroes[:x]...)
1297 copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
1298 case x < 0: // actual length is x bytes smaller than the space we reserved
1299 // Move msg x bytes left.
1300 copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
1301 o.buf = o.buf[:len(o.buf)+x] // x is negative
1302 }
1303 // Encode the length in the reserved space.
1304 o.buf = o.buf[:iLen]
1305 o.EncodeVarint(uint64(lMsg))
1306 o.buf = o.buf[:len(o.buf)+lMsg]
1307 return state.err
1308}
1309
David Symonds4646c372013-09-09 13:18:58 +10001310// errorState maintains the first error that occurs and updates that error
1311// with additional context.
1312type errorState struct {
1313 err error
1314}
1315
1316// shouldContinue reports whether encoding should continue upon encountering the
David Symondse583a5f2013-09-27 10:02:37 +10001317// given error. If the error is RequiredNotSetError, shouldContinue returns true
David Symonds4646c372013-09-09 13:18:58 +10001318// and, if this is the first appearance of that error, remembers it for future
1319// reporting.
1320//
1321// If prop is not nil, it may update any error with additional context about the
1322// field with the error.
1323func (s *errorState) shouldContinue(err error, prop *Properties) bool {
1324 // Ignore unset required fields.
David Symondse583a5f2013-09-27 10:02:37 +10001325 reqNotSet, ok := err.(*RequiredNotSetError)
David Symonds4646c372013-09-09 13:18:58 +10001326 if !ok {
1327 return false
1328 }
1329 if s.err == nil {
1330 if prop != nil {
David Symondse583a5f2013-09-27 10:02:37 +10001331 err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field}
David Symonds4646c372013-09-09 13:18:58 +10001332 }
1333 s.err = err
1334 }
1335 return true
Rob Pikeaaa3a622010-03-20 22:32:34 -07001336}