• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Go support for Protocol Buffers - Google's data interchange format
2//
3// Copyright 2016 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
32package proto
33
34import (
35	"errors"
36	"fmt"
37	"math"
38	"reflect"
39	"sort"
40	"strconv"
41	"strings"
42	"sync"
43	"sync/atomic"
44	"unicode/utf8"
45)
46
47// a sizer takes a pointer to a field and the size of its tag, computes the size of
48// the encoded data.
49type sizer func(pointer, int) int
50
51// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format),
52// marshals the field to the end of the slice, returns the slice and error (if any).
53type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error)
54
55// marshalInfo is the information used for marshaling a message.
56type marshalInfo struct {
57	typ          reflect.Type
58	fields       []*marshalFieldInfo
59	unrecognized field                      // offset of XXX_unrecognized
60	extensions   field                      // offset of XXX_InternalExtensions
61	v1extensions field                      // offset of XXX_extensions
62	sizecache    field                      // offset of XXX_sizecache
63	initialized  int32                      // 0 -- only typ is set, 1 -- fully initialized
64	messageset   bool                       // uses message set wire format
65	hasmarshaler bool                       // has custom marshaler
66	sync.RWMutex                            // protect extElems map, also for initialization
67	extElems     map[int32]*marshalElemInfo // info of extension elements
68}
69
70// marshalFieldInfo is the information used for marshaling a field of a message.
71type marshalFieldInfo struct {
72	field      field
73	wiretag    uint64 // tag in wire format
74	tagsize    int    // size of tag in wire format
75	sizer      sizer
76	marshaler  marshaler
77	isPointer  bool
78	required   bool                              // field is required
79	name       string                            // name of the field, for error reporting
80	oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements
81}
82
83// marshalElemInfo is the information used for marshaling an extension or oneof element.
84type marshalElemInfo struct {
85	wiretag   uint64 // tag in wire format
86	tagsize   int    // size of tag in wire format
87	sizer     sizer
88	marshaler marshaler
89	isptr     bool // elem is pointer typed, thus interface of this type is a direct interface (extension only)
90}
91
92var (
93	marshalInfoMap  = map[reflect.Type]*marshalInfo{}
94	marshalInfoLock sync.Mutex
95)
96
97// getMarshalInfo returns the information to marshal a given type of message.
98// The info it returns may not necessarily initialized.
99// t is the type of the message (NOT the pointer to it).
100func getMarshalInfo(t reflect.Type) *marshalInfo {
101	marshalInfoLock.Lock()
102	u, ok := marshalInfoMap[t]
103	if !ok {
104		u = &marshalInfo{typ: t}
105		marshalInfoMap[t] = u
106	}
107	marshalInfoLock.Unlock()
108	return u
109}
110
111// Size is the entry point from generated code,
112// and should be ONLY called by generated code.
113// It computes the size of encoded data of msg.
114// a is a pointer to a place to store cached marshal info.
115func (a *InternalMessageInfo) Size(msg Message) int {
116	u := getMessageMarshalInfo(msg, a)
117	ptr := toPointer(&msg)
118	if ptr.isNil() {
119		// We get here if msg is a typed nil ((*SomeMessage)(nil)),
120		// so it satisfies the interface, and msg == nil wouldn't
121		// catch it. We don't want crash in this case.
122		return 0
123	}
124	return u.size(ptr)
125}
126
127// Marshal is the entry point from generated code,
128// and should be ONLY called by generated code.
129// It marshals msg to the end of b.
130// a is a pointer to a place to store cached marshal info.
131func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) {
132	u := getMessageMarshalInfo(msg, a)
133	ptr := toPointer(&msg)
134	if ptr.isNil() {
135		// We get here if msg is a typed nil ((*SomeMessage)(nil)),
136		// so it satisfies the interface, and msg == nil wouldn't
137		// catch it. We don't want crash in this case.
138		return b, ErrNil
139	}
140	return u.marshal(b, ptr, deterministic)
141}
142
143func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo {
144	// u := a.marshal, but atomically.
145	// We use an atomic here to ensure memory consistency.
146	u := atomicLoadMarshalInfo(&a.marshal)
147	if u == nil {
148		// Get marshal information from type of message.
149		t := reflect.ValueOf(msg).Type()
150		if t.Kind() != reflect.Ptr {
151			panic(fmt.Sprintf("cannot handle non-pointer message type %v", t))
152		}
153		u = getMarshalInfo(t.Elem())
154		// Store it in the cache for later users.
155		// a.marshal = u, but atomically.
156		atomicStoreMarshalInfo(&a.marshal, u)
157	}
158	return u
159}
160
161// size is the main function to compute the size of the encoded data of a message.
162// ptr is the pointer to the message.
163func (u *marshalInfo) size(ptr pointer) int {
164	if atomic.LoadInt32(&u.initialized) == 0 {
165		u.computeMarshalInfo()
166	}
167
168	// If the message can marshal itself, let it do it, for compatibility.
169	// NOTE: This is not efficient.
170	if u.hasmarshaler {
171		m := ptr.asPointerTo(u.typ).Interface().(Marshaler)
172		b, _ := m.Marshal()
173		return len(b)
174	}
175
176	n := 0
177	for _, f := range u.fields {
178		if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
179			// nil pointer always marshals to nothing
180			continue
181		}
182		n += f.sizer(ptr.offset(f.field), f.tagsize)
183	}
184	if u.extensions.IsValid() {
185		e := ptr.offset(u.extensions).toExtensions()
186		if u.messageset {
187			n += u.sizeMessageSet(e)
188		} else {
189			n += u.sizeExtensions(e)
190		}
191	}
192	if u.v1extensions.IsValid() {
193		m := *ptr.offset(u.v1extensions).toOldExtensions()
194		n += u.sizeV1Extensions(m)
195	}
196	if u.unrecognized.IsValid() {
197		s := *ptr.offset(u.unrecognized).toBytes()
198		n += len(s)
199	}
200	// cache the result for use in marshal
201	if u.sizecache.IsValid() {
202		atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n))
203	}
204	return n
205}
206
207// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated),
208// fall back to compute the size.
209func (u *marshalInfo) cachedsize(ptr pointer) int {
210	if u.sizecache.IsValid() {
211		return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32()))
212	}
213	return u.size(ptr)
214}
215
216// marshal is the main function to marshal a message. It takes a byte slice and appends
217// the encoded data to the end of the slice, returns the slice and error (if any).
218// ptr is the pointer to the message.
219// If deterministic is true, map is marshaled in deterministic order.
220func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) {
221	if atomic.LoadInt32(&u.initialized) == 0 {
222		u.computeMarshalInfo()
223	}
224
225	// If the message can marshal itself, let it do it, for compatibility.
226	// NOTE: This is not efficient.
227	if u.hasmarshaler {
228		m := ptr.asPointerTo(u.typ).Interface().(Marshaler)
229		b1, err := m.Marshal()
230		b = append(b, b1...)
231		return b, err
232	}
233
234	var err, errreq error
235	// The old marshaler encodes extensions at beginning.
236	if u.extensions.IsValid() {
237		e := ptr.offset(u.extensions).toExtensions()
238		if u.messageset {
239			b, err = u.appendMessageSet(b, e, deterministic)
240		} else {
241			b, err = u.appendExtensions(b, e, deterministic)
242		}
243		if err != nil {
244			return b, err
245		}
246	}
247	if u.v1extensions.IsValid() {
248		m := *ptr.offset(u.v1extensions).toOldExtensions()
249		b, err = u.appendV1Extensions(b, m, deterministic)
250		if err != nil {
251			return b, err
252		}
253	}
254	for _, f := range u.fields {
255		if f.required && errreq == nil {
256			if ptr.offset(f.field).getPointer().isNil() {
257				// Required field is not set.
258				// We record the error but keep going, to give a complete marshaling.
259				errreq = &RequiredNotSetError{f.name}
260				continue
261			}
262		}
263		if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
264			// nil pointer always marshals to nothing
265			continue
266		}
267		b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic)
268		if err != nil {
269			if err1, ok := err.(*RequiredNotSetError); ok {
270				// Required field in submessage is not set.
271				// We record the error but keep going, to give a complete marshaling.
272				if errreq == nil {
273					errreq = &RequiredNotSetError{f.name + "." + err1.field}
274				}
275				continue
276			}
277			if err == errRepeatedHasNil {
278				err = errors.New("proto: repeated field " + f.name + " has nil element")
279			}
280			if err == errInvalidUTF8 {
281				fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name
282				err = fmt.Errorf("proto: string field %q contains invalid UTF-8", fullName)
283			}
284			return b, err
285		}
286	}
287	if u.unrecognized.IsValid() {
288		s := *ptr.offset(u.unrecognized).toBytes()
289		b = append(b, s...)
290	}
291	return b, errreq
292}
293
294// computeMarshalInfo initializes the marshal info.
295func (u *marshalInfo) computeMarshalInfo() {
296	u.Lock()
297	defer u.Unlock()
298	if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock
299		return
300	}
301
302	t := u.typ
303	u.unrecognized = invalidField
304	u.extensions = invalidField
305	u.v1extensions = invalidField
306	u.sizecache = invalidField
307
308	// If the message can marshal itself, let it do it, for compatibility.
309	// NOTE: This is not efficient.
310	if reflect.PtrTo(t).Implements(marshalerType) {
311		u.hasmarshaler = true
312		atomic.StoreInt32(&u.initialized, 1)
313		return
314	}
315
316	// get oneof implementers
317	var oneofImplementers []interface{}
318	if m, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok {
319		_, _, _, oneofImplementers = m.XXX_OneofFuncs()
320	}
321
322	n := t.NumField()
323
324	// deal with XXX fields first
325	for i := 0; i < t.NumField(); i++ {
326		f := t.Field(i)
327		if !strings.HasPrefix(f.Name, "XXX_") {
328			continue
329		}
330		switch f.Name {
331		case "XXX_sizecache":
332			u.sizecache = toField(&f)
333		case "XXX_unrecognized":
334			u.unrecognized = toField(&f)
335		case "XXX_InternalExtensions":
336			u.extensions = toField(&f)
337			u.messageset = f.Tag.Get("protobuf_messageset") == "1"
338		case "XXX_extensions":
339			u.v1extensions = toField(&f)
340		case "XXX_NoUnkeyedLiteral":
341			// nothing to do
342		default:
343			panic("unknown XXX field: " + f.Name)
344		}
345		n--
346	}
347
348	// normal fields
349	fields := make([]marshalFieldInfo, n) // batch allocation
350	u.fields = make([]*marshalFieldInfo, 0, n)
351	for i, j := 0, 0; i < t.NumField(); i++ {
352		f := t.Field(i)
353
354		if strings.HasPrefix(f.Name, "XXX_") {
355			continue
356		}
357		field := &fields[j]
358		j++
359		field.name = f.Name
360		u.fields = append(u.fields, field)
361		if f.Tag.Get("protobuf_oneof") != "" {
362			field.computeOneofFieldInfo(&f, oneofImplementers)
363			continue
364		}
365		if f.Tag.Get("protobuf") == "" {
366			// field has no tag (not in generated message), ignore it
367			u.fields = u.fields[:len(u.fields)-1]
368			j--
369			continue
370		}
371		field.computeMarshalFieldInfo(&f)
372	}
373
374	// fields are marshaled in tag order on the wire.
375	sort.Sort(byTag(u.fields))
376
377	atomic.StoreInt32(&u.initialized, 1)
378}
379
380// helper for sorting fields by tag
381type byTag []*marshalFieldInfo
382
383func (a byTag) Len() int           { return len(a) }
384func (a byTag) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
385func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag }
386
387// getExtElemInfo returns the information to marshal an extension element.
388// The info it returns is initialized.
389func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo {
390	// get from cache first
391	u.RLock()
392	e, ok := u.extElems[desc.Field]
393	u.RUnlock()
394	if ok {
395		return e
396	}
397
398	t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct
399	tags := strings.Split(desc.Tag, ",")
400	tag, err := strconv.Atoi(tags[1])
401	if err != nil {
402		panic("tag is not an integer")
403	}
404	wt := wiretype(tags[0])
405	sizer, marshaler := typeMarshaler(t, tags, false, false)
406	e = &marshalElemInfo{
407		wiretag:   uint64(tag)<<3 | wt,
408		tagsize:   SizeVarint(uint64(tag) << 3),
409		sizer:     sizer,
410		marshaler: marshaler,
411		isptr:     t.Kind() == reflect.Ptr,
412	}
413
414	// update cache
415	u.Lock()
416	if u.extElems == nil {
417		u.extElems = make(map[int32]*marshalElemInfo)
418	}
419	u.extElems[desc.Field] = e
420	u.Unlock()
421	return e
422}
423
424// computeMarshalFieldInfo fills up the information to marshal a field.
425func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) {
426	// parse protobuf tag of the field.
427	// tag has format of "bytes,49,opt,name=foo,def=hello!"
428	tags := strings.Split(f.Tag.Get("protobuf"), ",")
429	if tags[0] == "" {
430		return
431	}
432	tag, err := strconv.Atoi(tags[1])
433	if err != nil {
434		panic("tag is not an integer")
435	}
436	wt := wiretype(tags[0])
437	if tags[2] == "req" {
438		fi.required = true
439	}
440	fi.setTag(f, tag, wt)
441	fi.setMarshaler(f, tags)
442}
443
444func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) {
445	fi.field = toField(f)
446	fi.wiretag = 1<<31 - 1 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire.
447	fi.isPointer = true
448	fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f)
449	fi.oneofElems = make(map[reflect.Type]*marshalElemInfo)
450
451	ityp := f.Type // interface type
452	for _, o := range oneofImplementers {
453		t := reflect.TypeOf(o)
454		if !t.Implements(ityp) {
455			continue
456		}
457		sf := t.Elem().Field(0) // oneof implementer is a struct with a single field
458		tags := strings.Split(sf.Tag.Get("protobuf"), ",")
459		tag, err := strconv.Atoi(tags[1])
460		if err != nil {
461			panic("tag is not an integer")
462		}
463		wt := wiretype(tags[0])
464		sizer, marshaler := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value
465		fi.oneofElems[t.Elem()] = &marshalElemInfo{
466			wiretag:   uint64(tag)<<3 | wt,
467			tagsize:   SizeVarint(uint64(tag) << 3),
468			sizer:     sizer,
469			marshaler: marshaler,
470		}
471	}
472}
473
474type oneofMessage interface {
475	XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
476}
477
478// wiretype returns the wire encoding of the type.
479func wiretype(encoding string) uint64 {
480	switch encoding {
481	case "fixed32":
482		return WireFixed32
483	case "fixed64":
484		return WireFixed64
485	case "varint", "zigzag32", "zigzag64":
486		return WireVarint
487	case "bytes":
488		return WireBytes
489	case "group":
490		return WireStartGroup
491	}
492	panic("unknown wire type " + encoding)
493}
494
495// setTag fills up the tag (in wire format) and its size in the info of a field.
496func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) {
497	fi.field = toField(f)
498	fi.wiretag = uint64(tag)<<3 | wt
499	fi.tagsize = SizeVarint(uint64(tag) << 3)
500}
501
502// setMarshaler fills up the sizer and marshaler in the info of a field.
503func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) {
504	switch f.Type.Kind() {
505	case reflect.Map:
506		// map field
507		fi.isPointer = true
508		fi.sizer, fi.marshaler = makeMapMarshaler(f)
509		return
510	case reflect.Ptr, reflect.Slice:
511		fi.isPointer = true
512	}
513	fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false)
514}
515
516// typeMarshaler returns the sizer and marshaler of a given field.
517// t is the type of the field.
518// tags is the generated "protobuf" tag of the field.
519// If nozero is true, zero value is not marshaled to the wire.
520// If oneof is true, it is a oneof field.
521func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) {
522	encoding := tags[0]
523
524	pointer := false
525	slice := false
526	if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 {
527		slice = true
528		t = t.Elem()
529	}
530	if t.Kind() == reflect.Ptr {
531		pointer = true
532		t = t.Elem()
533	}
534
535	packed := false
536	proto3 := false
537	validateUTF8 := true
538	for i := 2; i < len(tags); i++ {
539		if tags[i] == "packed" {
540			packed = true
541		}
542		if tags[i] == "proto3" {
543			proto3 = true
544		}
545	}
546	validateUTF8 = validateUTF8 && proto3
547
548	switch t.Kind() {
549	case reflect.Bool:
550		if pointer {
551			return sizeBoolPtr, appendBoolPtr
552		}
553		if slice {
554			if packed {
555				return sizeBoolPackedSlice, appendBoolPackedSlice
556			}
557			return sizeBoolSlice, appendBoolSlice
558		}
559		if nozero {
560			return sizeBoolValueNoZero, appendBoolValueNoZero
561		}
562		return sizeBoolValue, appendBoolValue
563	case reflect.Uint32:
564		switch encoding {
565		case "fixed32":
566			if pointer {
567				return sizeFixed32Ptr, appendFixed32Ptr
568			}
569			if slice {
570				if packed {
571					return sizeFixed32PackedSlice, appendFixed32PackedSlice
572				}
573				return sizeFixed32Slice, appendFixed32Slice
574			}
575			if nozero {
576				return sizeFixed32ValueNoZero, appendFixed32ValueNoZero
577			}
578			return sizeFixed32Value, appendFixed32Value
579		case "varint":
580			if pointer {
581				return sizeVarint32Ptr, appendVarint32Ptr
582			}
583			if slice {
584				if packed {
585					return sizeVarint32PackedSlice, appendVarint32PackedSlice
586				}
587				return sizeVarint32Slice, appendVarint32Slice
588			}
589			if nozero {
590				return sizeVarint32ValueNoZero, appendVarint32ValueNoZero
591			}
592			return sizeVarint32Value, appendVarint32Value
593		}
594	case reflect.Int32:
595		switch encoding {
596		case "fixed32":
597			if pointer {
598				return sizeFixedS32Ptr, appendFixedS32Ptr
599			}
600			if slice {
601				if packed {
602					return sizeFixedS32PackedSlice, appendFixedS32PackedSlice
603				}
604				return sizeFixedS32Slice, appendFixedS32Slice
605			}
606			if nozero {
607				return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero
608			}
609			return sizeFixedS32Value, appendFixedS32Value
610		case "varint":
611			if pointer {
612				return sizeVarintS32Ptr, appendVarintS32Ptr
613			}
614			if slice {
615				if packed {
616					return sizeVarintS32PackedSlice, appendVarintS32PackedSlice
617				}
618				return sizeVarintS32Slice, appendVarintS32Slice
619			}
620			if nozero {
621				return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero
622			}
623			return sizeVarintS32Value, appendVarintS32Value
624		case "zigzag32":
625			if pointer {
626				return sizeZigzag32Ptr, appendZigzag32Ptr
627			}
628			if slice {
629				if packed {
630					return sizeZigzag32PackedSlice, appendZigzag32PackedSlice
631				}
632				return sizeZigzag32Slice, appendZigzag32Slice
633			}
634			if nozero {
635				return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero
636			}
637			return sizeZigzag32Value, appendZigzag32Value
638		}
639	case reflect.Uint64:
640		switch encoding {
641		case "fixed64":
642			if pointer {
643				return sizeFixed64Ptr, appendFixed64Ptr
644			}
645			if slice {
646				if packed {
647					return sizeFixed64PackedSlice, appendFixed64PackedSlice
648				}
649				return sizeFixed64Slice, appendFixed64Slice
650			}
651			if nozero {
652				return sizeFixed64ValueNoZero, appendFixed64ValueNoZero
653			}
654			return sizeFixed64Value, appendFixed64Value
655		case "varint":
656			if pointer {
657				return sizeVarint64Ptr, appendVarint64Ptr
658			}
659			if slice {
660				if packed {
661					return sizeVarint64PackedSlice, appendVarint64PackedSlice
662				}
663				return sizeVarint64Slice, appendVarint64Slice
664			}
665			if nozero {
666				return sizeVarint64ValueNoZero, appendVarint64ValueNoZero
667			}
668			return sizeVarint64Value, appendVarint64Value
669		}
670	case reflect.Int64:
671		switch encoding {
672		case "fixed64":
673			if pointer {
674				return sizeFixedS64Ptr, appendFixedS64Ptr
675			}
676			if slice {
677				if packed {
678					return sizeFixedS64PackedSlice, appendFixedS64PackedSlice
679				}
680				return sizeFixedS64Slice, appendFixedS64Slice
681			}
682			if nozero {
683				return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero
684			}
685			return sizeFixedS64Value, appendFixedS64Value
686		case "varint":
687			if pointer {
688				return sizeVarintS64Ptr, appendVarintS64Ptr
689			}
690			if slice {
691				if packed {
692					return sizeVarintS64PackedSlice, appendVarintS64PackedSlice
693				}
694				return sizeVarintS64Slice, appendVarintS64Slice
695			}
696			if nozero {
697				return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero
698			}
699			return sizeVarintS64Value, appendVarintS64Value
700		case "zigzag64":
701			if pointer {
702				return sizeZigzag64Ptr, appendZigzag64Ptr
703			}
704			if slice {
705				if packed {
706					return sizeZigzag64PackedSlice, appendZigzag64PackedSlice
707				}
708				return sizeZigzag64Slice, appendZigzag64Slice
709			}
710			if nozero {
711				return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero
712			}
713			return sizeZigzag64Value, appendZigzag64Value
714		}
715	case reflect.Float32:
716		if pointer {
717			return sizeFloat32Ptr, appendFloat32Ptr
718		}
719		if slice {
720			if packed {
721				return sizeFloat32PackedSlice, appendFloat32PackedSlice
722			}
723			return sizeFloat32Slice, appendFloat32Slice
724		}
725		if nozero {
726			return sizeFloat32ValueNoZero, appendFloat32ValueNoZero
727		}
728		return sizeFloat32Value, appendFloat32Value
729	case reflect.Float64:
730		if pointer {
731			return sizeFloat64Ptr, appendFloat64Ptr
732		}
733		if slice {
734			if packed {
735				return sizeFloat64PackedSlice, appendFloat64PackedSlice
736			}
737			return sizeFloat64Slice, appendFloat64Slice
738		}
739		if nozero {
740			return sizeFloat64ValueNoZero, appendFloat64ValueNoZero
741		}
742		return sizeFloat64Value, appendFloat64Value
743	case reflect.String:
744		if validateUTF8 {
745			if pointer {
746				return sizeStringPtr, appendUTF8StringPtr
747			}
748			if slice {
749				return sizeStringSlice, appendUTF8StringSlice
750			}
751			if nozero {
752				return sizeStringValueNoZero, appendUTF8StringValueNoZero
753			}
754			return sizeStringValue, appendUTF8StringValue
755		}
756		if pointer {
757			return sizeStringPtr, appendStringPtr
758		}
759		if slice {
760			return sizeStringSlice, appendStringSlice
761		}
762		if nozero {
763			return sizeStringValueNoZero, appendStringValueNoZero
764		}
765		return sizeStringValue, appendStringValue
766	case reflect.Slice:
767		if slice {
768			return sizeBytesSlice, appendBytesSlice
769		}
770		if oneof {
771			// Oneof bytes field may also have "proto3" tag.
772			// We want to marshal it as a oneof field. Do this
773			// check before the proto3 check.
774			return sizeBytesOneof, appendBytesOneof
775		}
776		if proto3 {
777			return sizeBytes3, appendBytes3
778		}
779		return sizeBytes, appendBytes
780	case reflect.Struct:
781		switch encoding {
782		case "group":
783			if slice {
784				return makeGroupSliceMarshaler(getMarshalInfo(t))
785			}
786			return makeGroupMarshaler(getMarshalInfo(t))
787		case "bytes":
788			if slice {
789				return makeMessageSliceMarshaler(getMarshalInfo(t))
790			}
791			return makeMessageMarshaler(getMarshalInfo(t))
792		}
793	}
794	panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding))
795}
796
797// Below are functions to size/marshal a specific type of a field.
798// They are stored in the field's info, and called by function pointers.
799// They have type sizer or marshaler.
800
801func sizeFixed32Value(_ pointer, tagsize int) int {
802	return 4 + tagsize
803}
804func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int {
805	v := *ptr.toUint32()
806	if v == 0 {
807		return 0
808	}
809	return 4 + tagsize
810}
811func sizeFixed32Ptr(ptr pointer, tagsize int) int {
812	p := *ptr.toUint32Ptr()
813	if p == nil {
814		return 0
815	}
816	return 4 + tagsize
817}
818func sizeFixed32Slice(ptr pointer, tagsize int) int {
819	s := *ptr.toUint32Slice()
820	return (4 + tagsize) * len(s)
821}
822func sizeFixed32PackedSlice(ptr pointer, tagsize int) int {
823	s := *ptr.toUint32Slice()
824	if len(s) == 0 {
825		return 0
826	}
827	return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
828}
829func sizeFixedS32Value(_ pointer, tagsize int) int {
830	return 4 + tagsize
831}
832func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int {
833	v := *ptr.toInt32()
834	if v == 0 {
835		return 0
836	}
837	return 4 + tagsize
838}
839func sizeFixedS32Ptr(ptr pointer, tagsize int) int {
840	p := ptr.getInt32Ptr()
841	if p == nil {
842		return 0
843	}
844	return 4 + tagsize
845}
846func sizeFixedS32Slice(ptr pointer, tagsize int) int {
847	s := ptr.getInt32Slice()
848	return (4 + tagsize) * len(s)
849}
850func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int {
851	s := ptr.getInt32Slice()
852	if len(s) == 0 {
853		return 0
854	}
855	return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
856}
857func sizeFloat32Value(_ pointer, tagsize int) int {
858	return 4 + tagsize
859}
860func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int {
861	v := math.Float32bits(*ptr.toFloat32())
862	if v == 0 {
863		return 0
864	}
865	return 4 + tagsize
866}
867func sizeFloat32Ptr(ptr pointer, tagsize int) int {
868	p := *ptr.toFloat32Ptr()
869	if p == nil {
870		return 0
871	}
872	return 4 + tagsize
873}
874func sizeFloat32Slice(ptr pointer, tagsize int) int {
875	s := *ptr.toFloat32Slice()
876	return (4 + tagsize) * len(s)
877}
878func sizeFloat32PackedSlice(ptr pointer, tagsize int) int {
879	s := *ptr.toFloat32Slice()
880	if len(s) == 0 {
881		return 0
882	}
883	return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
884}
885func sizeFixed64Value(_ pointer, tagsize int) int {
886	return 8 + tagsize
887}
888func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int {
889	v := *ptr.toUint64()
890	if v == 0 {
891		return 0
892	}
893	return 8 + tagsize
894}
895func sizeFixed64Ptr(ptr pointer, tagsize int) int {
896	p := *ptr.toUint64Ptr()
897	if p == nil {
898		return 0
899	}
900	return 8 + tagsize
901}
902func sizeFixed64Slice(ptr pointer, tagsize int) int {
903	s := *ptr.toUint64Slice()
904	return (8 + tagsize) * len(s)
905}
906func sizeFixed64PackedSlice(ptr pointer, tagsize int) int {
907	s := *ptr.toUint64Slice()
908	if len(s) == 0 {
909		return 0
910	}
911	return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
912}
913func sizeFixedS64Value(_ pointer, tagsize int) int {
914	return 8 + tagsize
915}
916func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int {
917	v := *ptr.toInt64()
918	if v == 0 {
919		return 0
920	}
921	return 8 + tagsize
922}
923func sizeFixedS64Ptr(ptr pointer, tagsize int) int {
924	p := *ptr.toInt64Ptr()
925	if p == nil {
926		return 0
927	}
928	return 8 + tagsize
929}
930func sizeFixedS64Slice(ptr pointer, tagsize int) int {
931	s := *ptr.toInt64Slice()
932	return (8 + tagsize) * len(s)
933}
934func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int {
935	s := *ptr.toInt64Slice()
936	if len(s) == 0 {
937		return 0
938	}
939	return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
940}
941func sizeFloat64Value(_ pointer, tagsize int) int {
942	return 8 + tagsize
943}
944func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int {
945	v := math.Float64bits(*ptr.toFloat64())
946	if v == 0 {
947		return 0
948	}
949	return 8 + tagsize
950}
951func sizeFloat64Ptr(ptr pointer, tagsize int) int {
952	p := *ptr.toFloat64Ptr()
953	if p == nil {
954		return 0
955	}
956	return 8 + tagsize
957}
958func sizeFloat64Slice(ptr pointer, tagsize int) int {
959	s := *ptr.toFloat64Slice()
960	return (8 + tagsize) * len(s)
961}
962func sizeFloat64PackedSlice(ptr pointer, tagsize int) int {
963	s := *ptr.toFloat64Slice()
964	if len(s) == 0 {
965		return 0
966	}
967	return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
968}
969func sizeVarint32Value(ptr pointer, tagsize int) int {
970	v := *ptr.toUint32()
971	return SizeVarint(uint64(v)) + tagsize
972}
973func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int {
974	v := *ptr.toUint32()
975	if v == 0 {
976		return 0
977	}
978	return SizeVarint(uint64(v)) + tagsize
979}
980func sizeVarint32Ptr(ptr pointer, tagsize int) int {
981	p := *ptr.toUint32Ptr()
982	if p == nil {
983		return 0
984	}
985	return SizeVarint(uint64(*p)) + tagsize
986}
987func sizeVarint32Slice(ptr pointer, tagsize int) int {
988	s := *ptr.toUint32Slice()
989	n := 0
990	for _, v := range s {
991		n += SizeVarint(uint64(v)) + tagsize
992	}
993	return n
994}
995func sizeVarint32PackedSlice(ptr pointer, tagsize int) int {
996	s := *ptr.toUint32Slice()
997	if len(s) == 0 {
998		return 0
999	}
1000	n := 0
1001	for _, v := range s {
1002		n += SizeVarint(uint64(v))
1003	}
1004	return n + SizeVarint(uint64(n)) + tagsize
1005}
1006func sizeVarintS32Value(ptr pointer, tagsize int) int {
1007	v := *ptr.toInt32()
1008	return SizeVarint(uint64(v)) + tagsize
1009}
1010func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int {
1011	v := *ptr.toInt32()
1012	if v == 0 {
1013		return 0
1014	}
1015	return SizeVarint(uint64(v)) + tagsize
1016}
1017func sizeVarintS32Ptr(ptr pointer, tagsize int) int {
1018	p := ptr.getInt32Ptr()
1019	if p == nil {
1020		return 0
1021	}
1022	return SizeVarint(uint64(*p)) + tagsize
1023}
1024func sizeVarintS32Slice(ptr pointer, tagsize int) int {
1025	s := ptr.getInt32Slice()
1026	n := 0
1027	for _, v := range s {
1028		n += SizeVarint(uint64(v)) + tagsize
1029	}
1030	return n
1031}
1032func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int {
1033	s := ptr.getInt32Slice()
1034	if len(s) == 0 {
1035		return 0
1036	}
1037	n := 0
1038	for _, v := range s {
1039		n += SizeVarint(uint64(v))
1040	}
1041	return n + SizeVarint(uint64(n)) + tagsize
1042}
1043func sizeVarint64Value(ptr pointer, tagsize int) int {
1044	v := *ptr.toUint64()
1045	return SizeVarint(v) + tagsize
1046}
1047func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int {
1048	v := *ptr.toUint64()
1049	if v == 0 {
1050		return 0
1051	}
1052	return SizeVarint(v) + tagsize
1053}
1054func sizeVarint64Ptr(ptr pointer, tagsize int) int {
1055	p := *ptr.toUint64Ptr()
1056	if p == nil {
1057		return 0
1058	}
1059	return SizeVarint(*p) + tagsize
1060}
1061func sizeVarint64Slice(ptr pointer, tagsize int) int {
1062	s := *ptr.toUint64Slice()
1063	n := 0
1064	for _, v := range s {
1065		n += SizeVarint(v) + tagsize
1066	}
1067	return n
1068}
1069func sizeVarint64PackedSlice(ptr pointer, tagsize int) int {
1070	s := *ptr.toUint64Slice()
1071	if len(s) == 0 {
1072		return 0
1073	}
1074	n := 0
1075	for _, v := range s {
1076		n += SizeVarint(v)
1077	}
1078	return n + SizeVarint(uint64(n)) + tagsize
1079}
1080func sizeVarintS64Value(ptr pointer, tagsize int) int {
1081	v := *ptr.toInt64()
1082	return SizeVarint(uint64(v)) + tagsize
1083}
1084func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int {
1085	v := *ptr.toInt64()
1086	if v == 0 {
1087		return 0
1088	}
1089	return SizeVarint(uint64(v)) + tagsize
1090}
1091func sizeVarintS64Ptr(ptr pointer, tagsize int) int {
1092	p := *ptr.toInt64Ptr()
1093	if p == nil {
1094		return 0
1095	}
1096	return SizeVarint(uint64(*p)) + tagsize
1097}
1098func sizeVarintS64Slice(ptr pointer, tagsize int) int {
1099	s := *ptr.toInt64Slice()
1100	n := 0
1101	for _, v := range s {
1102		n += SizeVarint(uint64(v)) + tagsize
1103	}
1104	return n
1105}
1106func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int {
1107	s := *ptr.toInt64Slice()
1108	if len(s) == 0 {
1109		return 0
1110	}
1111	n := 0
1112	for _, v := range s {
1113		n += SizeVarint(uint64(v))
1114	}
1115	return n + SizeVarint(uint64(n)) + tagsize
1116}
1117func sizeZigzag32Value(ptr pointer, tagsize int) int {
1118	v := *ptr.toInt32()
1119	return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
1120}
1121func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int {
1122	v := *ptr.toInt32()
1123	if v == 0 {
1124		return 0
1125	}
1126	return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
1127}
1128func sizeZigzag32Ptr(ptr pointer, tagsize int) int {
1129	p := ptr.getInt32Ptr()
1130	if p == nil {
1131		return 0
1132	}
1133	v := *p
1134	return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
1135}
1136func sizeZigzag32Slice(ptr pointer, tagsize int) int {
1137	s := ptr.getInt32Slice()
1138	n := 0
1139	for _, v := range s {
1140		n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
1141	}
1142	return n
1143}
1144func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int {
1145	s := ptr.getInt32Slice()
1146	if len(s) == 0 {
1147		return 0
1148	}
1149	n := 0
1150	for _, v := range s {
1151		n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31))))
1152	}
1153	return n + SizeVarint(uint64(n)) + tagsize
1154}
1155func sizeZigzag64Value(ptr pointer, tagsize int) int {
1156	v := *ptr.toInt64()
1157	return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
1158}
1159func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int {
1160	v := *ptr.toInt64()
1161	if v == 0 {
1162		return 0
1163	}
1164	return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
1165}
1166func sizeZigzag64Ptr(ptr pointer, tagsize int) int {
1167	p := *ptr.toInt64Ptr()
1168	if p == nil {
1169		return 0
1170	}
1171	v := *p
1172	return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
1173}
1174func sizeZigzag64Slice(ptr pointer, tagsize int) int {
1175	s := *ptr.toInt64Slice()
1176	n := 0
1177	for _, v := range s {
1178		n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
1179	}
1180	return n
1181}
1182func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int {
1183	s := *ptr.toInt64Slice()
1184	if len(s) == 0 {
1185		return 0
1186	}
1187	n := 0
1188	for _, v := range s {
1189		n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63)))
1190	}
1191	return n + SizeVarint(uint64(n)) + tagsize
1192}
1193func sizeBoolValue(_ pointer, tagsize int) int {
1194	return 1 + tagsize
1195}
1196func sizeBoolValueNoZero(ptr pointer, tagsize int) int {
1197	v := *ptr.toBool()
1198	if !v {
1199		return 0
1200	}
1201	return 1 + tagsize
1202}
1203func sizeBoolPtr(ptr pointer, tagsize int) int {
1204	p := *ptr.toBoolPtr()
1205	if p == nil {
1206		return 0
1207	}
1208	return 1 + tagsize
1209}
1210func sizeBoolSlice(ptr pointer, tagsize int) int {
1211	s := *ptr.toBoolSlice()
1212	return (1 + tagsize) * len(s)
1213}
1214func sizeBoolPackedSlice(ptr pointer, tagsize int) int {
1215	s := *ptr.toBoolSlice()
1216	if len(s) == 0 {
1217		return 0
1218	}
1219	return len(s) + SizeVarint(uint64(len(s))) + tagsize
1220}
1221func sizeStringValue(ptr pointer, tagsize int) int {
1222	v := *ptr.toString()
1223	return len(v) + SizeVarint(uint64(len(v))) + tagsize
1224}
1225func sizeStringValueNoZero(ptr pointer, tagsize int) int {
1226	v := *ptr.toString()
1227	if v == "" {
1228		return 0
1229	}
1230	return len(v) + SizeVarint(uint64(len(v))) + tagsize
1231}
1232func sizeStringPtr(ptr pointer, tagsize int) int {
1233	p := *ptr.toStringPtr()
1234	if p == nil {
1235		return 0
1236	}
1237	v := *p
1238	return len(v) + SizeVarint(uint64(len(v))) + tagsize
1239}
1240func sizeStringSlice(ptr pointer, tagsize int) int {
1241	s := *ptr.toStringSlice()
1242	n := 0
1243	for _, v := range s {
1244		n += len(v) + SizeVarint(uint64(len(v))) + tagsize
1245	}
1246	return n
1247}
1248func sizeBytes(ptr pointer, tagsize int) int {
1249	v := *ptr.toBytes()
1250	if v == nil {
1251		return 0
1252	}
1253	return len(v) + SizeVarint(uint64(len(v))) + tagsize
1254}
1255func sizeBytes3(ptr pointer, tagsize int) int {
1256	v := *ptr.toBytes()
1257	if len(v) == 0 {
1258		return 0
1259	}
1260	return len(v) + SizeVarint(uint64(len(v))) + tagsize
1261}
1262func sizeBytesOneof(ptr pointer, tagsize int) int {
1263	v := *ptr.toBytes()
1264	return len(v) + SizeVarint(uint64(len(v))) + tagsize
1265}
1266func sizeBytesSlice(ptr pointer, tagsize int) int {
1267	s := *ptr.toBytesSlice()
1268	n := 0
1269	for _, v := range s {
1270		n += len(v) + SizeVarint(uint64(len(v))) + tagsize
1271	}
1272	return n
1273}
1274
1275// appendFixed32 appends an encoded fixed32 to b.
1276func appendFixed32(b []byte, v uint32) []byte {
1277	b = append(b,
1278		byte(v),
1279		byte(v>>8),
1280		byte(v>>16),
1281		byte(v>>24))
1282	return b
1283}
1284
1285// appendFixed64 appends an encoded fixed64 to b.
1286func appendFixed64(b []byte, v uint64) []byte {
1287	b = append(b,
1288		byte(v),
1289		byte(v>>8),
1290		byte(v>>16),
1291		byte(v>>24),
1292		byte(v>>32),
1293		byte(v>>40),
1294		byte(v>>48),
1295		byte(v>>56))
1296	return b
1297}
1298
1299// appendVarint appends an encoded varint to b.
1300func appendVarint(b []byte, v uint64) []byte {
1301	// TODO: make 1-byte (maybe 2-byte) case inline-able, once we
1302	// have non-leaf inliner.
1303	switch {
1304	case v < 1<<7:
1305		b = append(b, byte(v))
1306	case v < 1<<14:
1307		b = append(b,
1308			byte(v&0x7f|0x80),
1309			byte(v>>7))
1310	case v < 1<<21:
1311		b = append(b,
1312			byte(v&0x7f|0x80),
1313			byte((v>>7)&0x7f|0x80),
1314			byte(v>>14))
1315	case v < 1<<28:
1316		b = append(b,
1317			byte(v&0x7f|0x80),
1318			byte((v>>7)&0x7f|0x80),
1319			byte((v>>14)&0x7f|0x80),
1320			byte(v>>21))
1321	case v < 1<<35:
1322		b = append(b,
1323			byte(v&0x7f|0x80),
1324			byte((v>>7)&0x7f|0x80),
1325			byte((v>>14)&0x7f|0x80),
1326			byte((v>>21)&0x7f|0x80),
1327			byte(v>>28))
1328	case v < 1<<42:
1329		b = append(b,
1330			byte(v&0x7f|0x80),
1331			byte((v>>7)&0x7f|0x80),
1332			byte((v>>14)&0x7f|0x80),
1333			byte((v>>21)&0x7f|0x80),
1334			byte((v>>28)&0x7f|0x80),
1335			byte(v>>35))
1336	case v < 1<<49:
1337		b = append(b,
1338			byte(v&0x7f|0x80),
1339			byte((v>>7)&0x7f|0x80),
1340			byte((v>>14)&0x7f|0x80),
1341			byte((v>>21)&0x7f|0x80),
1342			byte((v>>28)&0x7f|0x80),
1343			byte((v>>35)&0x7f|0x80),
1344			byte(v>>42))
1345	case v < 1<<56:
1346		b = append(b,
1347			byte(v&0x7f|0x80),
1348			byte((v>>7)&0x7f|0x80),
1349			byte((v>>14)&0x7f|0x80),
1350			byte((v>>21)&0x7f|0x80),
1351			byte((v>>28)&0x7f|0x80),
1352			byte((v>>35)&0x7f|0x80),
1353			byte((v>>42)&0x7f|0x80),
1354			byte(v>>49))
1355	case v < 1<<63:
1356		b = append(b,
1357			byte(v&0x7f|0x80),
1358			byte((v>>7)&0x7f|0x80),
1359			byte((v>>14)&0x7f|0x80),
1360			byte((v>>21)&0x7f|0x80),
1361			byte((v>>28)&0x7f|0x80),
1362			byte((v>>35)&0x7f|0x80),
1363			byte((v>>42)&0x7f|0x80),
1364			byte((v>>49)&0x7f|0x80),
1365			byte(v>>56))
1366	default:
1367		b = append(b,
1368			byte(v&0x7f|0x80),
1369			byte((v>>7)&0x7f|0x80),
1370			byte((v>>14)&0x7f|0x80),
1371			byte((v>>21)&0x7f|0x80),
1372			byte((v>>28)&0x7f|0x80),
1373			byte((v>>35)&0x7f|0x80),
1374			byte((v>>42)&0x7f|0x80),
1375			byte((v>>49)&0x7f|0x80),
1376			byte((v>>56)&0x7f|0x80),
1377			1)
1378	}
1379	return b
1380}
1381
1382func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1383	v := *ptr.toUint32()
1384	b = appendVarint(b, wiretag)
1385	b = appendFixed32(b, v)
1386	return b, nil
1387}
1388func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1389	v := *ptr.toUint32()
1390	if v == 0 {
1391		return b, nil
1392	}
1393	b = appendVarint(b, wiretag)
1394	b = appendFixed32(b, v)
1395	return b, nil
1396}
1397func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1398	p := *ptr.toUint32Ptr()
1399	if p == nil {
1400		return b, nil
1401	}
1402	b = appendVarint(b, wiretag)
1403	b = appendFixed32(b, *p)
1404	return b, nil
1405}
1406func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1407	s := *ptr.toUint32Slice()
1408	for _, v := range s {
1409		b = appendVarint(b, wiretag)
1410		b = appendFixed32(b, v)
1411	}
1412	return b, nil
1413}
1414func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1415	s := *ptr.toUint32Slice()
1416	if len(s) == 0 {
1417		return b, nil
1418	}
1419	b = appendVarint(b, wiretag&^7|WireBytes)
1420	b = appendVarint(b, uint64(4*len(s)))
1421	for _, v := range s {
1422		b = appendFixed32(b, v)
1423	}
1424	return b, nil
1425}
1426func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1427	v := *ptr.toInt32()
1428	b = appendVarint(b, wiretag)
1429	b = appendFixed32(b, uint32(v))
1430	return b, nil
1431}
1432func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1433	v := *ptr.toInt32()
1434	if v == 0 {
1435		return b, nil
1436	}
1437	b = appendVarint(b, wiretag)
1438	b = appendFixed32(b, uint32(v))
1439	return b, nil
1440}
1441func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1442	p := ptr.getInt32Ptr()
1443	if p == nil {
1444		return b, nil
1445	}
1446	b = appendVarint(b, wiretag)
1447	b = appendFixed32(b, uint32(*p))
1448	return b, nil
1449}
1450func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1451	s := ptr.getInt32Slice()
1452	for _, v := range s {
1453		b = appendVarint(b, wiretag)
1454		b = appendFixed32(b, uint32(v))
1455	}
1456	return b, nil
1457}
1458func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1459	s := ptr.getInt32Slice()
1460	if len(s) == 0 {
1461		return b, nil
1462	}
1463	b = appendVarint(b, wiretag&^7|WireBytes)
1464	b = appendVarint(b, uint64(4*len(s)))
1465	for _, v := range s {
1466		b = appendFixed32(b, uint32(v))
1467	}
1468	return b, nil
1469}
1470func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1471	v := math.Float32bits(*ptr.toFloat32())
1472	b = appendVarint(b, wiretag)
1473	b = appendFixed32(b, v)
1474	return b, nil
1475}
1476func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1477	v := math.Float32bits(*ptr.toFloat32())
1478	if v == 0 {
1479		return b, nil
1480	}
1481	b = appendVarint(b, wiretag)
1482	b = appendFixed32(b, v)
1483	return b, nil
1484}
1485func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1486	p := *ptr.toFloat32Ptr()
1487	if p == nil {
1488		return b, nil
1489	}
1490	b = appendVarint(b, wiretag)
1491	b = appendFixed32(b, math.Float32bits(*p))
1492	return b, nil
1493}
1494func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1495	s := *ptr.toFloat32Slice()
1496	for _, v := range s {
1497		b = appendVarint(b, wiretag)
1498		b = appendFixed32(b, math.Float32bits(v))
1499	}
1500	return b, nil
1501}
1502func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1503	s := *ptr.toFloat32Slice()
1504	if len(s) == 0 {
1505		return b, nil
1506	}
1507	b = appendVarint(b, wiretag&^7|WireBytes)
1508	b = appendVarint(b, uint64(4*len(s)))
1509	for _, v := range s {
1510		b = appendFixed32(b, math.Float32bits(v))
1511	}
1512	return b, nil
1513}
1514func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1515	v := *ptr.toUint64()
1516	b = appendVarint(b, wiretag)
1517	b = appendFixed64(b, v)
1518	return b, nil
1519}
1520func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1521	v := *ptr.toUint64()
1522	if v == 0 {
1523		return b, nil
1524	}
1525	b = appendVarint(b, wiretag)
1526	b = appendFixed64(b, v)
1527	return b, nil
1528}
1529func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1530	p := *ptr.toUint64Ptr()
1531	if p == nil {
1532		return b, nil
1533	}
1534	b = appendVarint(b, wiretag)
1535	b = appendFixed64(b, *p)
1536	return b, nil
1537}
1538func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1539	s := *ptr.toUint64Slice()
1540	for _, v := range s {
1541		b = appendVarint(b, wiretag)
1542		b = appendFixed64(b, v)
1543	}
1544	return b, nil
1545}
1546func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1547	s := *ptr.toUint64Slice()
1548	if len(s) == 0 {
1549		return b, nil
1550	}
1551	b = appendVarint(b, wiretag&^7|WireBytes)
1552	b = appendVarint(b, uint64(8*len(s)))
1553	for _, v := range s {
1554		b = appendFixed64(b, v)
1555	}
1556	return b, nil
1557}
1558func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1559	v := *ptr.toInt64()
1560	b = appendVarint(b, wiretag)
1561	b = appendFixed64(b, uint64(v))
1562	return b, nil
1563}
1564func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1565	v := *ptr.toInt64()
1566	if v == 0 {
1567		return b, nil
1568	}
1569	b = appendVarint(b, wiretag)
1570	b = appendFixed64(b, uint64(v))
1571	return b, nil
1572}
1573func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1574	p := *ptr.toInt64Ptr()
1575	if p == nil {
1576		return b, nil
1577	}
1578	b = appendVarint(b, wiretag)
1579	b = appendFixed64(b, uint64(*p))
1580	return b, nil
1581}
1582func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1583	s := *ptr.toInt64Slice()
1584	for _, v := range s {
1585		b = appendVarint(b, wiretag)
1586		b = appendFixed64(b, uint64(v))
1587	}
1588	return b, nil
1589}
1590func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1591	s := *ptr.toInt64Slice()
1592	if len(s) == 0 {
1593		return b, nil
1594	}
1595	b = appendVarint(b, wiretag&^7|WireBytes)
1596	b = appendVarint(b, uint64(8*len(s)))
1597	for _, v := range s {
1598		b = appendFixed64(b, uint64(v))
1599	}
1600	return b, nil
1601}
1602func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1603	v := math.Float64bits(*ptr.toFloat64())
1604	b = appendVarint(b, wiretag)
1605	b = appendFixed64(b, v)
1606	return b, nil
1607}
1608func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1609	v := math.Float64bits(*ptr.toFloat64())
1610	if v == 0 {
1611		return b, nil
1612	}
1613	b = appendVarint(b, wiretag)
1614	b = appendFixed64(b, v)
1615	return b, nil
1616}
1617func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1618	p := *ptr.toFloat64Ptr()
1619	if p == nil {
1620		return b, nil
1621	}
1622	b = appendVarint(b, wiretag)
1623	b = appendFixed64(b, math.Float64bits(*p))
1624	return b, nil
1625}
1626func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1627	s := *ptr.toFloat64Slice()
1628	for _, v := range s {
1629		b = appendVarint(b, wiretag)
1630		b = appendFixed64(b, math.Float64bits(v))
1631	}
1632	return b, nil
1633}
1634func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1635	s := *ptr.toFloat64Slice()
1636	if len(s) == 0 {
1637		return b, nil
1638	}
1639	b = appendVarint(b, wiretag&^7|WireBytes)
1640	b = appendVarint(b, uint64(8*len(s)))
1641	for _, v := range s {
1642		b = appendFixed64(b, math.Float64bits(v))
1643	}
1644	return b, nil
1645}
1646func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1647	v := *ptr.toUint32()
1648	b = appendVarint(b, wiretag)
1649	b = appendVarint(b, uint64(v))
1650	return b, nil
1651}
1652func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1653	v := *ptr.toUint32()
1654	if v == 0 {
1655		return b, nil
1656	}
1657	b = appendVarint(b, wiretag)
1658	b = appendVarint(b, uint64(v))
1659	return b, nil
1660}
1661func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1662	p := *ptr.toUint32Ptr()
1663	if p == nil {
1664		return b, nil
1665	}
1666	b = appendVarint(b, wiretag)
1667	b = appendVarint(b, uint64(*p))
1668	return b, nil
1669}
1670func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1671	s := *ptr.toUint32Slice()
1672	for _, v := range s {
1673		b = appendVarint(b, wiretag)
1674		b = appendVarint(b, uint64(v))
1675	}
1676	return b, nil
1677}
1678func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1679	s := *ptr.toUint32Slice()
1680	if len(s) == 0 {
1681		return b, nil
1682	}
1683	b = appendVarint(b, wiretag&^7|WireBytes)
1684	// compute size
1685	n := 0
1686	for _, v := range s {
1687		n += SizeVarint(uint64(v))
1688	}
1689	b = appendVarint(b, uint64(n))
1690	for _, v := range s {
1691		b = appendVarint(b, uint64(v))
1692	}
1693	return b, nil
1694}
1695func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1696	v := *ptr.toInt32()
1697	b = appendVarint(b, wiretag)
1698	b = appendVarint(b, uint64(v))
1699	return b, nil
1700}
1701func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1702	v := *ptr.toInt32()
1703	if v == 0 {
1704		return b, nil
1705	}
1706	b = appendVarint(b, wiretag)
1707	b = appendVarint(b, uint64(v))
1708	return b, nil
1709}
1710func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1711	p := ptr.getInt32Ptr()
1712	if p == nil {
1713		return b, nil
1714	}
1715	b = appendVarint(b, wiretag)
1716	b = appendVarint(b, uint64(*p))
1717	return b, nil
1718}
1719func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1720	s := ptr.getInt32Slice()
1721	for _, v := range s {
1722		b = appendVarint(b, wiretag)
1723		b = appendVarint(b, uint64(v))
1724	}
1725	return b, nil
1726}
1727func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1728	s := ptr.getInt32Slice()
1729	if len(s) == 0 {
1730		return b, nil
1731	}
1732	b = appendVarint(b, wiretag&^7|WireBytes)
1733	// compute size
1734	n := 0
1735	for _, v := range s {
1736		n += SizeVarint(uint64(v))
1737	}
1738	b = appendVarint(b, uint64(n))
1739	for _, v := range s {
1740		b = appendVarint(b, uint64(v))
1741	}
1742	return b, nil
1743}
1744func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1745	v := *ptr.toUint64()
1746	b = appendVarint(b, wiretag)
1747	b = appendVarint(b, v)
1748	return b, nil
1749}
1750func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1751	v := *ptr.toUint64()
1752	if v == 0 {
1753		return b, nil
1754	}
1755	b = appendVarint(b, wiretag)
1756	b = appendVarint(b, v)
1757	return b, nil
1758}
1759func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1760	p := *ptr.toUint64Ptr()
1761	if p == nil {
1762		return b, nil
1763	}
1764	b = appendVarint(b, wiretag)
1765	b = appendVarint(b, *p)
1766	return b, nil
1767}
1768func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1769	s := *ptr.toUint64Slice()
1770	for _, v := range s {
1771		b = appendVarint(b, wiretag)
1772		b = appendVarint(b, v)
1773	}
1774	return b, nil
1775}
1776func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1777	s := *ptr.toUint64Slice()
1778	if len(s) == 0 {
1779		return b, nil
1780	}
1781	b = appendVarint(b, wiretag&^7|WireBytes)
1782	// compute size
1783	n := 0
1784	for _, v := range s {
1785		n += SizeVarint(v)
1786	}
1787	b = appendVarint(b, uint64(n))
1788	for _, v := range s {
1789		b = appendVarint(b, v)
1790	}
1791	return b, nil
1792}
1793func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1794	v := *ptr.toInt64()
1795	b = appendVarint(b, wiretag)
1796	b = appendVarint(b, uint64(v))
1797	return b, nil
1798}
1799func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1800	v := *ptr.toInt64()
1801	if v == 0 {
1802		return b, nil
1803	}
1804	b = appendVarint(b, wiretag)
1805	b = appendVarint(b, uint64(v))
1806	return b, nil
1807}
1808func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1809	p := *ptr.toInt64Ptr()
1810	if p == nil {
1811		return b, nil
1812	}
1813	b = appendVarint(b, wiretag)
1814	b = appendVarint(b, uint64(*p))
1815	return b, nil
1816}
1817func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1818	s := *ptr.toInt64Slice()
1819	for _, v := range s {
1820		b = appendVarint(b, wiretag)
1821		b = appendVarint(b, uint64(v))
1822	}
1823	return b, nil
1824}
1825func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1826	s := *ptr.toInt64Slice()
1827	if len(s) == 0 {
1828		return b, nil
1829	}
1830	b = appendVarint(b, wiretag&^7|WireBytes)
1831	// compute size
1832	n := 0
1833	for _, v := range s {
1834		n += SizeVarint(uint64(v))
1835	}
1836	b = appendVarint(b, uint64(n))
1837	for _, v := range s {
1838		b = appendVarint(b, uint64(v))
1839	}
1840	return b, nil
1841}
1842func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1843	v := *ptr.toInt32()
1844	b = appendVarint(b, wiretag)
1845	b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
1846	return b, nil
1847}
1848func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1849	v := *ptr.toInt32()
1850	if v == 0 {
1851		return b, nil
1852	}
1853	b = appendVarint(b, wiretag)
1854	b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
1855	return b, nil
1856}
1857func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1858	p := ptr.getInt32Ptr()
1859	if p == nil {
1860		return b, nil
1861	}
1862	b = appendVarint(b, wiretag)
1863	v := *p
1864	b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
1865	return b, nil
1866}
1867func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1868	s := ptr.getInt32Slice()
1869	for _, v := range s {
1870		b = appendVarint(b, wiretag)
1871		b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
1872	}
1873	return b, nil
1874}
1875func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1876	s := ptr.getInt32Slice()
1877	if len(s) == 0 {
1878		return b, nil
1879	}
1880	b = appendVarint(b, wiretag&^7|WireBytes)
1881	// compute size
1882	n := 0
1883	for _, v := range s {
1884		n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31))))
1885	}
1886	b = appendVarint(b, uint64(n))
1887	for _, v := range s {
1888		b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
1889	}
1890	return b, nil
1891}
1892func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1893	v := *ptr.toInt64()
1894	b = appendVarint(b, wiretag)
1895	b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
1896	return b, nil
1897}
1898func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1899	v := *ptr.toInt64()
1900	if v == 0 {
1901		return b, nil
1902	}
1903	b = appendVarint(b, wiretag)
1904	b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
1905	return b, nil
1906}
1907func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1908	p := *ptr.toInt64Ptr()
1909	if p == nil {
1910		return b, nil
1911	}
1912	b = appendVarint(b, wiretag)
1913	v := *p
1914	b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
1915	return b, nil
1916}
1917func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1918	s := *ptr.toInt64Slice()
1919	for _, v := range s {
1920		b = appendVarint(b, wiretag)
1921		b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
1922	}
1923	return b, nil
1924}
1925func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1926	s := *ptr.toInt64Slice()
1927	if len(s) == 0 {
1928		return b, nil
1929	}
1930	b = appendVarint(b, wiretag&^7|WireBytes)
1931	// compute size
1932	n := 0
1933	for _, v := range s {
1934		n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63)))
1935	}
1936	b = appendVarint(b, uint64(n))
1937	for _, v := range s {
1938		b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
1939	}
1940	return b, nil
1941}
1942func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1943	v := *ptr.toBool()
1944	b = appendVarint(b, wiretag)
1945	if v {
1946		b = append(b, 1)
1947	} else {
1948		b = append(b, 0)
1949	}
1950	return b, nil
1951}
1952func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1953	v := *ptr.toBool()
1954	if !v {
1955		return b, nil
1956	}
1957	b = appendVarint(b, wiretag)
1958	b = append(b, 1)
1959	return b, nil
1960}
1961
1962func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1963	p := *ptr.toBoolPtr()
1964	if p == nil {
1965		return b, nil
1966	}
1967	b = appendVarint(b, wiretag)
1968	if *p {
1969		b = append(b, 1)
1970	} else {
1971		b = append(b, 0)
1972	}
1973	return b, nil
1974}
1975func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1976	s := *ptr.toBoolSlice()
1977	for _, v := range s {
1978		b = appendVarint(b, wiretag)
1979		if v {
1980			b = append(b, 1)
1981		} else {
1982			b = append(b, 0)
1983		}
1984	}
1985	return b, nil
1986}
1987func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
1988	s := *ptr.toBoolSlice()
1989	if len(s) == 0 {
1990		return b, nil
1991	}
1992	b = appendVarint(b, wiretag&^7|WireBytes)
1993	b = appendVarint(b, uint64(len(s)))
1994	for _, v := range s {
1995		if v {
1996			b = append(b, 1)
1997		} else {
1998			b = append(b, 0)
1999		}
2000	}
2001	return b, nil
2002}
2003func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
2004	v := *ptr.toString()
2005	b = appendVarint(b, wiretag)
2006	b = appendVarint(b, uint64(len(v)))
2007	b = append(b, v...)
2008	return b, nil
2009}
2010func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
2011	v := *ptr.toString()
2012	if v == "" {
2013		return b, nil
2014	}
2015	b = appendVarint(b, wiretag)
2016	b = appendVarint(b, uint64(len(v)))
2017	b = append(b, v...)
2018	return b, nil
2019}
2020func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
2021	p := *ptr.toStringPtr()
2022	if p == nil {
2023		return b, nil
2024	}
2025	v := *p
2026	b = appendVarint(b, wiretag)
2027	b = appendVarint(b, uint64(len(v)))
2028	b = append(b, v...)
2029	return b, nil
2030}
2031func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
2032	s := *ptr.toStringSlice()
2033	for _, v := range s {
2034		b = appendVarint(b, wiretag)
2035		b = appendVarint(b, uint64(len(v)))
2036		b = append(b, v...)
2037	}
2038	return b, nil
2039}
2040func appendUTF8StringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
2041	v := *ptr.toString()
2042	if !utf8.ValidString(v) {
2043		return nil, errInvalidUTF8
2044	}
2045	b = appendVarint(b, wiretag)
2046	b = appendVarint(b, uint64(len(v)))
2047	b = append(b, v...)
2048	return b, nil
2049}
2050func appendUTF8StringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
2051	v := *ptr.toString()
2052	if v == "" {
2053		return b, nil
2054	}
2055	if !utf8.ValidString(v) {
2056		return nil, errInvalidUTF8
2057	}
2058	b = appendVarint(b, wiretag)
2059	b = appendVarint(b, uint64(len(v)))
2060	b = append(b, v...)
2061	return b, nil
2062}
2063func appendUTF8StringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
2064	p := *ptr.toStringPtr()
2065	if p == nil {
2066		return b, nil
2067	}
2068	v := *p
2069	if !utf8.ValidString(v) {
2070		return nil, errInvalidUTF8
2071	}
2072	b = appendVarint(b, wiretag)
2073	b = appendVarint(b, uint64(len(v)))
2074	b = append(b, v...)
2075	return b, nil
2076}
2077func appendUTF8StringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
2078	s := *ptr.toStringSlice()
2079	for _, v := range s {
2080		if !utf8.ValidString(v) {
2081			return nil, errInvalidUTF8
2082		}
2083		b = appendVarint(b, wiretag)
2084		b = appendVarint(b, uint64(len(v)))
2085		b = append(b, v...)
2086	}
2087	return b, nil
2088}
2089func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
2090	v := *ptr.toBytes()
2091	if v == nil {
2092		return b, nil
2093	}
2094	b = appendVarint(b, wiretag)
2095	b = appendVarint(b, uint64(len(v)))
2096	b = append(b, v...)
2097	return b, nil
2098}
2099func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
2100	v := *ptr.toBytes()
2101	if len(v) == 0 {
2102		return b, nil
2103	}
2104	b = appendVarint(b, wiretag)
2105	b = appendVarint(b, uint64(len(v)))
2106	b = append(b, v...)
2107	return b, nil
2108}
2109func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
2110	v := *ptr.toBytes()
2111	b = appendVarint(b, wiretag)
2112	b = appendVarint(b, uint64(len(v)))
2113	b = append(b, v...)
2114	return b, nil
2115}
2116func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
2117	s := *ptr.toBytesSlice()
2118	for _, v := range s {
2119		b = appendVarint(b, wiretag)
2120		b = appendVarint(b, uint64(len(v)))
2121		b = append(b, v...)
2122	}
2123	return b, nil
2124}
2125
2126// makeGroupMarshaler returns the sizer and marshaler for a group.
2127// u is the marshal info of the underlying message.
2128func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) {
2129	return func(ptr pointer, tagsize int) int {
2130			p := ptr.getPointer()
2131			if p.isNil() {
2132				return 0
2133			}
2134			return u.size(p) + 2*tagsize
2135		},
2136		func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
2137			p := ptr.getPointer()
2138			if p.isNil() {
2139				return b, nil
2140			}
2141			var err error
2142			b = appendVarint(b, wiretag) // start group
2143			b, err = u.marshal(b, p, deterministic)
2144			b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group
2145			return b, err
2146		}
2147}
2148
2149// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice.
2150// u is the marshal info of the underlying message.
2151func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
2152	return func(ptr pointer, tagsize int) int {
2153			s := ptr.getPointerSlice()
2154			n := 0
2155			for _, v := range s {
2156				if v.isNil() {
2157					continue
2158				}
2159				n += u.size(v) + 2*tagsize
2160			}
2161			return n
2162		},
2163		func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
2164			s := ptr.getPointerSlice()
2165			var err, errreq error
2166			for _, v := range s {
2167				if v.isNil() {
2168					return b, errRepeatedHasNil
2169				}
2170				b = appendVarint(b, wiretag) // start group
2171				b, err = u.marshal(b, v, deterministic)
2172				b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group
2173				if err != nil {
2174					if _, ok := err.(*RequiredNotSetError); ok {
2175						// Required field in submessage is not set.
2176						// We record the error but keep going, to give a complete marshaling.
2177						if errreq == nil {
2178							errreq = err
2179						}
2180						continue
2181					}
2182					if err == ErrNil {
2183						err = errRepeatedHasNil
2184					}
2185					return b, err
2186				}
2187			}
2188			return b, errreq
2189		}
2190}
2191
2192// makeMessageMarshaler returns the sizer and marshaler for a message field.
2193// u is the marshal info of the message.
2194func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) {
2195	return func(ptr pointer, tagsize int) int {
2196			p := ptr.getPointer()
2197			if p.isNil() {
2198				return 0
2199			}
2200			siz := u.size(p)
2201			return siz + SizeVarint(uint64(siz)) + tagsize
2202		},
2203		func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
2204			p := ptr.getPointer()
2205			if p.isNil() {
2206				return b, nil
2207			}
2208			b = appendVarint(b, wiretag)
2209			siz := u.cachedsize(p)
2210			b = appendVarint(b, uint64(siz))
2211			return u.marshal(b, p, deterministic)
2212		}
2213}
2214
2215// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice.
2216// u is the marshal info of the message.
2217func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
2218	return func(ptr pointer, tagsize int) int {
2219			s := ptr.getPointerSlice()
2220			n := 0
2221			for _, v := range s {
2222				if v.isNil() {
2223					continue
2224				}
2225				siz := u.size(v)
2226				n += siz + SizeVarint(uint64(siz)) + tagsize
2227			}
2228			return n
2229		},
2230		func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
2231			s := ptr.getPointerSlice()
2232			var err, errreq error
2233			for _, v := range s {
2234				if v.isNil() {
2235					return b, errRepeatedHasNil
2236				}
2237				b = appendVarint(b, wiretag)
2238				siz := u.cachedsize(v)
2239				b = appendVarint(b, uint64(siz))
2240				b, err = u.marshal(b, v, deterministic)
2241
2242				if err != nil {
2243					if _, ok := err.(*RequiredNotSetError); ok {
2244						// Required field in submessage is not set.
2245						// We record the error but keep going, to give a complete marshaling.
2246						if errreq == nil {
2247							errreq = err
2248						}
2249						continue
2250					}
2251					if err == ErrNil {
2252						err = errRepeatedHasNil
2253					}
2254					return b, err
2255				}
2256			}
2257			return b, errreq
2258		}
2259}
2260
2261// makeMapMarshaler returns the sizer and marshaler for a map field.
2262// f is the pointer to the reflect data structure of the field.
2263func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) {
2264	// figure out key and value type
2265	t := f.Type
2266	keyType := t.Key()
2267	valType := t.Elem()
2268	keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",")
2269	valTags := strings.Split(f.Tag.Get("protobuf_val"), ",")
2270	keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map
2271	valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map
2272	keyWireTag := 1<<3 | wiretype(keyTags[0])
2273	valWireTag := 2<<3 | wiretype(valTags[0])
2274
2275	// We create an interface to get the addresses of the map key and value.
2276	// If value is pointer-typed, the interface is a direct interface, the
2277	// idata itself is the value. Otherwise, the idata is the pointer to the
2278	// value.
2279	// Key cannot be pointer-typed.
2280	valIsPtr := valType.Kind() == reflect.Ptr
2281	return func(ptr pointer, tagsize int) int {
2282			m := ptr.asPointerTo(t).Elem() // the map
2283			n := 0
2284			for _, k := range m.MapKeys() {
2285				ki := k.Interface()
2286				vi := m.MapIndex(k).Interface()
2287				kaddr := toAddrPointer(&ki, false)             // pointer to key
2288				vaddr := toAddrPointer(&vi, valIsPtr)          // pointer to value
2289				siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1)
2290				n += siz + SizeVarint(uint64(siz)) + tagsize
2291			}
2292			return n
2293		},
2294		func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) {
2295			m := ptr.asPointerTo(t).Elem() // the map
2296			var err error
2297			keys := m.MapKeys()
2298			if len(keys) > 1 && deterministic {
2299				sort.Sort(mapKeys(keys))
2300			}
2301			for _, k := range keys {
2302				ki := k.Interface()
2303				vi := m.MapIndex(k).Interface()
2304				kaddr := toAddrPointer(&ki, false)    // pointer to key
2305				vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value
2306				b = appendVarint(b, tag)
2307				siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1)
2308				b = appendVarint(b, uint64(siz))
2309				b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic)
2310				if err != nil {
2311					return b, err
2312				}
2313				b, err = valMarshaler(b, vaddr, valWireTag, deterministic)
2314				if err != nil && err != ErrNil { // allow nil value in map
2315					return b, err
2316				}
2317			}
2318			return b, nil
2319		}
2320}
2321
2322// makeOneOfMarshaler returns the sizer and marshaler for a oneof field.
2323// fi is the marshal info of the field.
2324// f is the pointer to the reflect data structure of the field.
2325func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) {
2326	// Oneof field is an interface. We need to get the actual data type on the fly.
2327	t := f.Type
2328	return func(ptr pointer, _ int) int {
2329			p := ptr.getInterfacePointer()
2330			if p.isNil() {
2331				return 0
2332			}
2333			v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct
2334			telem := v.Type()
2335			e := fi.oneofElems[telem]
2336			return e.sizer(p, e.tagsize)
2337		},
2338		func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) {
2339			p := ptr.getInterfacePointer()
2340			if p.isNil() {
2341				return b, nil
2342			}
2343			v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct
2344			telem := v.Type()
2345			if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() {
2346				return b, errOneofHasNil
2347			}
2348			e := fi.oneofElems[telem]
2349			return e.marshaler(b, p, e.wiretag, deterministic)
2350		}
2351}
2352
2353// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field.
2354func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int {
2355	m, mu := ext.extensionsRead()
2356	if m == nil {
2357		return 0
2358	}
2359	mu.Lock()
2360
2361	n := 0
2362	for _, e := range m {
2363		if e.value == nil || e.desc == nil {
2364			// Extension is only in its encoded form.
2365			n += len(e.enc)
2366			continue
2367		}
2368
2369		// We don't skip extensions that have an encoded form set,
2370		// because the extension value may have been mutated after
2371		// the last time this function was called.
2372		ei := u.getExtElemInfo(e.desc)
2373		v := e.value
2374		p := toAddrPointer(&v, ei.isptr)
2375		n += ei.sizer(p, ei.tagsize)
2376	}
2377	mu.Unlock()
2378	return n
2379}
2380
2381// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b.
2382func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) {
2383	m, mu := ext.extensionsRead()
2384	if m == nil {
2385		return b, nil
2386	}
2387	mu.Lock()
2388	defer mu.Unlock()
2389
2390	var err error
2391
2392	// Fast-path for common cases: zero or one extensions.
2393	// Don't bother sorting the keys.
2394	if len(m) <= 1 {
2395		for _, e := range m {
2396			if e.value == nil || e.desc == nil {
2397				// Extension is only in its encoded form.
2398				b = append(b, e.enc...)
2399				continue
2400			}
2401
2402			// We don't skip extensions that have an encoded form set,
2403			// because the extension value may have been mutated after
2404			// the last time this function was called.
2405
2406			ei := u.getExtElemInfo(e.desc)
2407			v := e.value
2408			p := toAddrPointer(&v, ei.isptr)
2409			b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
2410			if err != nil {
2411				return b, err
2412			}
2413		}
2414		return b, nil
2415	}
2416
2417	// Sort the keys to provide a deterministic encoding.
2418	// Not sure this is required, but the old code does it.
2419	keys := make([]int, 0, len(m))
2420	for k := range m {
2421		keys = append(keys, int(k))
2422	}
2423	sort.Ints(keys)
2424
2425	for _, k := range keys {
2426		e := m[int32(k)]
2427		if e.value == nil || e.desc == nil {
2428			// Extension is only in its encoded form.
2429			b = append(b, e.enc...)
2430			continue
2431		}
2432
2433		// We don't skip extensions that have an encoded form set,
2434		// because the extension value may have been mutated after
2435		// the last time this function was called.
2436
2437		ei := u.getExtElemInfo(e.desc)
2438		v := e.value
2439		p := toAddrPointer(&v, ei.isptr)
2440		b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
2441		if err != nil {
2442			return b, err
2443		}
2444	}
2445	return b, nil
2446}
2447
2448// message set format is:
2449//   message MessageSet {
2450//     repeated group Item = 1 {
2451//       required int32 type_id = 2;
2452//       required string message = 3;
2453//     };
2454//   }
2455
2456// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field
2457// in message set format (above).
2458func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int {
2459	m, mu := ext.extensionsRead()
2460	if m == nil {
2461		return 0
2462	}
2463	mu.Lock()
2464
2465	n := 0
2466	for id, e := range m {
2467		n += 2                          // start group, end group. tag = 1 (size=1)
2468		n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1)
2469
2470		if e.value == nil || e.desc == nil {
2471			// Extension is only in its encoded form.
2472			msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
2473			siz := len(msgWithLen)
2474			n += siz + 1 // message, tag = 3 (size=1)
2475			continue
2476		}
2477
2478		// We don't skip extensions that have an encoded form set,
2479		// because the extension value may have been mutated after
2480		// the last time this function was called.
2481
2482		ei := u.getExtElemInfo(e.desc)
2483		v := e.value
2484		p := toAddrPointer(&v, ei.isptr)
2485		n += ei.sizer(p, 1) // message, tag = 3 (size=1)
2486	}
2487	mu.Unlock()
2488	return n
2489}
2490
2491// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above)
2492// to the end of byte slice b.
2493func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) {
2494	m, mu := ext.extensionsRead()
2495	if m == nil {
2496		return b, nil
2497	}
2498	mu.Lock()
2499	defer mu.Unlock()
2500
2501	var err error
2502
2503	// Fast-path for common cases: zero or one extensions.
2504	// Don't bother sorting the keys.
2505	if len(m) <= 1 {
2506		for id, e := range m {
2507			b = append(b, 1<<3|WireStartGroup)
2508			b = append(b, 2<<3|WireVarint)
2509			b = appendVarint(b, uint64(id))
2510
2511			if e.value == nil || e.desc == nil {
2512				// Extension is only in its encoded form.
2513				msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
2514				b = append(b, 3<<3|WireBytes)
2515				b = append(b, msgWithLen...)
2516				b = append(b, 1<<3|WireEndGroup)
2517				continue
2518			}
2519
2520			// We don't skip extensions that have an encoded form set,
2521			// because the extension value may have been mutated after
2522			// the last time this function was called.
2523
2524			ei := u.getExtElemInfo(e.desc)
2525			v := e.value
2526			p := toAddrPointer(&v, ei.isptr)
2527			b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic)
2528			if err != nil {
2529				return b, err
2530			}
2531			b = append(b, 1<<3|WireEndGroup)
2532		}
2533		return b, nil
2534	}
2535
2536	// Sort the keys to provide a deterministic encoding.
2537	keys := make([]int, 0, len(m))
2538	for k := range m {
2539		keys = append(keys, int(k))
2540	}
2541	sort.Ints(keys)
2542
2543	for _, id := range keys {
2544		e := m[int32(id)]
2545		b = append(b, 1<<3|WireStartGroup)
2546		b = append(b, 2<<3|WireVarint)
2547		b = appendVarint(b, uint64(id))
2548
2549		if e.value == nil || e.desc == nil {
2550			// Extension is only in its encoded form.
2551			msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
2552			b = append(b, 3<<3|WireBytes)
2553			b = append(b, msgWithLen...)
2554			b = append(b, 1<<3|WireEndGroup)
2555			continue
2556		}
2557
2558		// We don't skip extensions that have an encoded form set,
2559		// because the extension value may have been mutated after
2560		// the last time this function was called.
2561
2562		ei := u.getExtElemInfo(e.desc)
2563		v := e.value
2564		p := toAddrPointer(&v, ei.isptr)
2565		b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic)
2566		b = append(b, 1<<3|WireEndGroup)
2567		if err != nil {
2568			return b, err
2569		}
2570	}
2571	return b, nil
2572}
2573
2574// sizeV1Extensions computes the size of encoded data for a V1-API extension field.
2575func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int {
2576	if m == nil {
2577		return 0
2578	}
2579
2580	n := 0
2581	for _, e := range m {
2582		if e.value == nil || e.desc == nil {
2583			// Extension is only in its encoded form.
2584			n += len(e.enc)
2585			continue
2586		}
2587
2588		// We don't skip extensions that have an encoded form set,
2589		// because the extension value may have been mutated after
2590		// the last time this function was called.
2591
2592		ei := u.getExtElemInfo(e.desc)
2593		v := e.value
2594		p := toAddrPointer(&v, ei.isptr)
2595		n += ei.sizer(p, ei.tagsize)
2596	}
2597	return n
2598}
2599
2600// appendV1Extensions marshals a V1-API extension field to the end of byte slice b.
2601func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) {
2602	if m == nil {
2603		return b, nil
2604	}
2605
2606	// Sort the keys to provide a deterministic encoding.
2607	keys := make([]int, 0, len(m))
2608	for k := range m {
2609		keys = append(keys, int(k))
2610	}
2611	sort.Ints(keys)
2612
2613	var err error
2614	for _, k := range keys {
2615		e := m[int32(k)]
2616		if e.value == nil || e.desc == nil {
2617			// Extension is only in its encoded form.
2618			b = append(b, e.enc...)
2619			continue
2620		}
2621
2622		// We don't skip extensions that have an encoded form set,
2623		// because the extension value may have been mutated after
2624		// the last time this function was called.
2625
2626		ei := u.getExtElemInfo(e.desc)
2627		v := e.value
2628		p := toAddrPointer(&v, ei.isptr)
2629		b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
2630		if err != nil {
2631			return b, err
2632		}
2633	}
2634	return b, nil
2635}
2636
2637// newMarshaler is the interface representing objects that can marshal themselves.
2638//
2639// This exists to support protoc-gen-go generated messages.
2640// The proto package will stop type-asserting to this interface in the future.
2641//
2642// DO NOT DEPEND ON THIS.
2643type newMarshaler interface {
2644	XXX_Size() int
2645	XXX_Marshal(b []byte, deterministic bool) ([]byte, error)
2646}
2647
2648// Size returns the encoded size of a protocol buffer message.
2649// This is the main entry point.
2650func Size(pb Message) int {
2651	if m, ok := pb.(newMarshaler); ok {
2652		return m.XXX_Size()
2653	}
2654	if m, ok := pb.(Marshaler); ok {
2655		// If the message can marshal itself, let it do it, for compatibility.
2656		// NOTE: This is not efficient.
2657		b, _ := m.Marshal()
2658		return len(b)
2659	}
2660	// in case somehow we didn't generate the wrapper
2661	if pb == nil {
2662		return 0
2663	}
2664	var info InternalMessageInfo
2665	return info.Size(pb)
2666}
2667
2668// Marshal takes a protocol buffer message
2669// and encodes it into the wire format, returning the data.
2670// This is the main entry point.
2671func Marshal(pb Message) ([]byte, error) {
2672	if m, ok := pb.(newMarshaler); ok {
2673		siz := m.XXX_Size()
2674		b := make([]byte, 0, siz)
2675		return m.XXX_Marshal(b, false)
2676	}
2677	if m, ok := pb.(Marshaler); ok {
2678		// If the message can marshal itself, let it do it, for compatibility.
2679		// NOTE: This is not efficient.
2680		return m.Marshal()
2681	}
2682	// in case somehow we didn't generate the wrapper
2683	if pb == nil {
2684		return nil, ErrNil
2685	}
2686	var info InternalMessageInfo
2687	siz := info.Size(pb)
2688	b := make([]byte, 0, siz)
2689	return info.Marshal(b, pb, false)
2690}
2691
2692// Marshal takes a protocol buffer message
2693// and encodes it into the wire format, writing the result to the
2694// Buffer.
2695// This is an alternative entry point. It is not necessary to use
2696// a Buffer for most applications.
2697func (p *Buffer) Marshal(pb Message) error {
2698	var err error
2699	if m, ok := pb.(newMarshaler); ok {
2700		siz := m.XXX_Size()
2701		p.grow(siz) // make sure buf has enough capacity
2702		p.buf, err = m.XXX_Marshal(p.buf, p.deterministic)
2703		return err
2704	}
2705	if m, ok := pb.(Marshaler); ok {
2706		// If the message can marshal itself, let it do it, for compatibility.
2707		// NOTE: This is not efficient.
2708		b, err := m.Marshal()
2709		p.buf = append(p.buf, b...)
2710		return err
2711	}
2712	// in case somehow we didn't generate the wrapper
2713	if pb == nil {
2714		return ErrNil
2715	}
2716	var info InternalMessageInfo
2717	siz := info.Size(pb)
2718	p.grow(siz) // make sure buf has enough capacity
2719	p.buf, err = info.Marshal(p.buf, pb, p.deterministic)
2720	return err
2721}
2722
2723// grow grows the buffer's capacity, if necessary, to guarantee space for
2724// another n bytes. After grow(n), at least n bytes can be written to the
2725// buffer without another allocation.
2726func (p *Buffer) grow(n int) {
2727	need := len(p.buf) + n
2728	if need <= cap(p.buf) {
2729		return
2730	}
2731	newCap := len(p.buf) * 2
2732	if newCap < need {
2733		newCap = need
2734	}
2735	p.buf = append(make([]byte, 0, newCap), p.buf...)
2736}
2737