blob: a4e72bd9c0b0c5c18a47d72db411f39612fadd93 [file] [log] [blame]
Scott Baker105df152020-04-13 15:55:14 -07001// Copyright 2019 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package proto
6
7import (
8 "google.golang.org/protobuf/encoding/protowire"
9 "google.golang.org/protobuf/internal/encoding/messageset"
10 "google.golang.org/protobuf/reflect/protoreflect"
11 "google.golang.org/protobuf/runtime/protoiface"
12)
13
14// Size returns the size in bytes of the wire-format encoding of m.
15func Size(m Message) int {
16 return MarshalOptions{}.Size(m)
17}
18
19// Size returns the size in bytes of the wire-format encoding of m.
20func (o MarshalOptions) Size(m Message) int {
21 return sizeMessage(m.ProtoReflect())
22}
23
24func sizeMessage(m protoreflect.Message) (size int) {
25 methods := protoMethods(m)
26 if methods != nil && methods.Size != nil {
27 out := methods.Size(protoiface.SizeInput{
28 Message: m,
29 })
30 return out.Size
31 }
32 if methods != nil && methods.Marshal != nil {
33 // This is not efficient, but we don't have any choice.
34 // This case is mainly used for legacy types with a Marshal method.
35 out, _ := methods.Marshal(protoiface.MarshalInput{
36 Message: m,
37 })
38 return len(out.Buf)
39 }
40 return sizeMessageSlow(m)
41}
42
43func sizeMessageSlow(m protoreflect.Message) (size int) {
44 if messageset.IsMessageSet(m.Descriptor()) {
45 return sizeMessageSet(m)
46 }
47 m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
48 size += sizeField(fd, v)
49 return true
50 })
51 size += len(m.GetUnknown())
52 return size
53}
54
55func sizeField(fd protoreflect.FieldDescriptor, value protoreflect.Value) (size int) {
56 num := fd.Number()
57 switch {
58 case fd.IsList():
59 return sizeList(num, fd, value.List())
60 case fd.IsMap():
61 return sizeMap(num, fd, value.Map())
62 default:
63 return protowire.SizeTag(num) + sizeSingular(num, fd.Kind(), value)
64 }
65}
66
67func sizeList(num protowire.Number, fd protoreflect.FieldDescriptor, list protoreflect.List) (size int) {
68 if fd.IsPacked() && list.Len() > 0 {
69 content := 0
70 for i, llen := 0, list.Len(); i < llen; i++ {
71 content += sizeSingular(num, fd.Kind(), list.Get(i))
72 }
73 return protowire.SizeTag(num) + protowire.SizeBytes(content)
74 }
75
76 for i, llen := 0, list.Len(); i < llen; i++ {
77 size += protowire.SizeTag(num) + sizeSingular(num, fd.Kind(), list.Get(i))
78 }
79 return size
80}
81
82func sizeMap(num protowire.Number, fd protoreflect.FieldDescriptor, mapv protoreflect.Map) (size int) {
83 mapv.Range(func(key protoreflect.MapKey, value protoreflect.Value) bool {
84 size += protowire.SizeTag(num)
85 size += protowire.SizeBytes(sizeField(fd.MapKey(), key.Value()) + sizeField(fd.MapValue(), value))
86 return true
87 })
88 return size
89}