Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 1 | // 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 | |
| 5 | package proto |
| 6 | |
| 7 | import ( |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 8 | "sort" |
| 9 | |
Damien Neil | 302cb32 | 2019-06-19 15:22:13 -0700 | [diff] [blame] | 10 | "google.golang.org/protobuf/internal/encoding/messageset" |
Damien Neil | e89e624 | 2019-05-13 23:55:40 -0700 | [diff] [blame] | 11 | "google.golang.org/protobuf/internal/encoding/wire" |
Damien Neil | 01c0e8d | 2019-11-12 12:33:12 -0800 | [diff] [blame] | 12 | "google.golang.org/protobuf/internal/fieldsort" |
Damien Neil | e89e624 | 2019-05-13 23:55:40 -0700 | [diff] [blame] | 13 | "google.golang.org/protobuf/internal/mapsort" |
| 14 | "google.golang.org/protobuf/internal/pragma" |
| 15 | "google.golang.org/protobuf/reflect/protoreflect" |
| 16 | "google.golang.org/protobuf/runtime/protoiface" |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 17 | ) |
| 18 | |
| 19 | // MarshalOptions configures the marshaler. |
| 20 | // |
| 21 | // Example usage: |
| 22 | // b, err := MarshalOptions{Deterministic: true}.Marshal(m) |
| 23 | type MarshalOptions struct { |
Joe Tsai | f8b855d | 2019-07-12 13:37:59 -0700 | [diff] [blame] | 24 | pragma.NoUnkeyedLiterals |
| 25 | |
Damien Neil | 96c229a | 2019-04-03 12:17:24 -0700 | [diff] [blame] | 26 | // AllowPartial allows messages that have missing required fields to marshal |
| 27 | // without returning an error. If AllowPartial is false (the default), |
| 28 | // Marshal will return an error if there are any missing required fields. |
| 29 | AllowPartial bool |
| 30 | |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 31 | // Deterministic controls whether the same message will always be |
| 32 | // serialized to the same bytes within the same binary. |
| 33 | // |
| 34 | // Setting this option guarantees that repeated serialization of |
| 35 | // the same message will return the same bytes, and that different |
| 36 | // processes of the same binary (which may be executing on different |
| 37 | // machines) will serialize equal messages to the same bytes. |
Joe Tsai | f8b855d | 2019-07-12 13:37:59 -0700 | [diff] [blame] | 38 | // It has no effect on the resulting size of the encoded message compared |
| 39 | // to a non-deterministic marshal. |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 40 | // |
| 41 | // Note that the deterministic serialization is NOT canonical across |
| 42 | // languages. It is not guaranteed to remain stable over time. It is |
| 43 | // unstable across different builds with schema changes due to unknown |
| 44 | // fields. Users who need canonical serialization (e.g., persistent |
| 45 | // storage in a canonical form, fingerprinting, etc.) must define |
| 46 | // their own canonicalization specification and implement their own |
| 47 | // serializer rather than relying on this API. |
| 48 | // |
| 49 | // If deterministic serialization is requested, map entries will be |
| 50 | // sorted by keys in lexographical order. This is an implementation |
| 51 | // detail and subject to change. |
| 52 | Deterministic bool |
| 53 | |
Damien Neil | 03e7486 | 2019-04-07 18:18:31 -0700 | [diff] [blame] | 54 | // UseCachedSize indicates that the result of a previous Size call |
| 55 | // may be reused. |
| 56 | // |
| 57 | // Setting this option asserts that: |
| 58 | // |
| 59 | // 1. Size has previously been called on this message with identical |
| 60 | // options (except for UseCachedSize itself). |
| 61 | // |
| 62 | // 2. The message and all its submessages have not changed in any |
| 63 | // way since the Size call. |
| 64 | // |
| 65 | // If either of these invariants is broken, the results are undefined |
| 66 | // but may include panics or invalid output. |
| 67 | // |
| 68 | // Implementations MAY take this option into account to provide |
| 69 | // better performance, but there is no guarantee that they will do so. |
| 70 | // There is absolutely no guarantee that Size followed by Marshal with |
| 71 | // UseCachedSize set will perform equivalently to Marshal alone. |
| 72 | UseCachedSize bool |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 73 | } |
| 74 | |
Damien Neil | 0d3e8cc | 2019-04-01 13:31:55 -0700 | [diff] [blame] | 75 | var _ = protoiface.MarshalOptions(MarshalOptions{}) |
| 76 | |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 77 | // Marshal returns the wire-format encoding of m. |
| 78 | func Marshal(m Message) ([]byte, error) { |
Damien Neil | d30e561 | 2020-01-22 10:28:16 -0800 | [diff] [blame^] | 79 | out, err := MarshalOptions{}.marshal(nil, m) |
| 80 | return out.Buf, err |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 81 | } |
| 82 | |
| 83 | // Marshal returns the wire-format encoding of m. |
| 84 | func (o MarshalOptions) Marshal(m Message) ([]byte, error) { |
Damien Neil | d30e561 | 2020-01-22 10:28:16 -0800 | [diff] [blame^] | 85 | out, err := o.marshal(nil, m) |
| 86 | return out.Buf, err |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 87 | } |
| 88 | |
| 89 | // MarshalAppend appends the wire-format encoding of m to b, |
| 90 | // returning the result. |
| 91 | func (o MarshalOptions) MarshalAppend(b []byte, m Message) ([]byte, error) { |
Damien Neil | d30e561 | 2020-01-22 10:28:16 -0800 | [diff] [blame^] | 92 | out, err := o.marshal(b, m) |
| 93 | return out.Buf, err |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 94 | } |
| 95 | |
Damien Neil | d30e561 | 2020-01-22 10:28:16 -0800 | [diff] [blame^] | 96 | // MarshalState returns the wire-format encoding of m. |
| 97 | // |
| 98 | // This method permits fine-grained control over the marshaler. |
| 99 | // Most users should use Marshal instead. |
| 100 | func (o MarshalOptions) MarshalState(m Message, in protoiface.MarshalInput) (protoiface.MarshalOutput, error) { |
| 101 | return o.marshal(in.Buf, m) |
| 102 | } |
| 103 | |
| 104 | func (o MarshalOptions) marshal(b []byte, message Message) (out protoiface.MarshalOutput, err error) { |
| 105 | allowPartial := o.AllowPartial |
| 106 | o.AllowPartial = true |
| 107 | m := message.ProtoReflect() |
Damien Neil | 61781dd | 2020-01-21 13:29:51 -0800 | [diff] [blame] | 108 | if methods := protoMethods(m); methods != nil && methods.Marshal != nil && |
Joe Tsai | f8b855d | 2019-07-12 13:37:59 -0700 | [diff] [blame] | 109 | !(o.Deterministic && methods.Flags&protoiface.SupportMarshalDeterministic == 0) { |
Damien Neil | b0d217f | 2020-01-06 11:17:07 -0800 | [diff] [blame] | 110 | if methods.Size != nil { |
| 111 | sz := methods.Size(m, protoiface.MarshalOptions(o)) |
| 112 | if cap(b) < len(b)+sz { |
| 113 | x := make([]byte, len(b), growcap(cap(b), len(b)+sz)) |
| 114 | copy(x, b) |
| 115 | b = x |
| 116 | } |
| 117 | o.UseCachedSize = true |
Damien Neil | 0d3e8cc | 2019-04-01 13:31:55 -0700 | [diff] [blame] | 118 | } |
Damien Neil | d30e561 | 2020-01-22 10:28:16 -0800 | [diff] [blame^] | 119 | out, err = methods.Marshal(m, protoiface.MarshalInput{ |
| 120 | Buf: b, |
| 121 | }, protoiface.MarshalOptions(o)) |
| 122 | } else { |
| 123 | out.Buf, err = o.marshalMessageSlow(b, m) |
Damien Neil | 0d3e8cc | 2019-04-01 13:31:55 -0700 | [diff] [blame] | 124 | } |
Damien Neil | d30e561 | 2020-01-22 10:28:16 -0800 | [diff] [blame^] | 125 | if err != nil { |
| 126 | return out, err |
| 127 | } |
| 128 | if allowPartial { |
| 129 | return out, nil |
| 130 | } |
| 131 | return out, isInitialized(m) |
| 132 | } |
| 133 | |
| 134 | func (o MarshalOptions) marshalMessage(b []byte, m protoreflect.Message) ([]byte, error) { |
| 135 | out, err := o.marshal(b, m.Interface()) |
| 136 | return out.Buf, err |
Damien Neil | 0d3e8cc | 2019-04-01 13:31:55 -0700 | [diff] [blame] | 137 | } |
| 138 | |
Damien Neil | 1e5516a | 2019-09-27 14:31:10 -0700 | [diff] [blame] | 139 | // growcap scales up the capacity of a slice. |
| 140 | // |
| 141 | // Given a slice with a current capacity of oldcap and a desired |
| 142 | // capacity of wantcap, growcap returns a new capacity >= wantcap. |
| 143 | // |
| 144 | // The algorithm is mostly identical to the one used by append as of Go 1.14. |
| 145 | func growcap(oldcap, wantcap int) (newcap int) { |
| 146 | if wantcap > oldcap*2 { |
| 147 | newcap = wantcap |
| 148 | } else if oldcap < 1024 { |
| 149 | // The Go 1.14 runtime takes this case when len(s) < 1024, |
| 150 | // not when cap(s) < 1024. The difference doesn't seem |
| 151 | // significant here. |
| 152 | newcap = oldcap * 2 |
| 153 | } else { |
| 154 | newcap = oldcap |
| 155 | for 0 < newcap && newcap < wantcap { |
| 156 | newcap += newcap / 4 |
| 157 | } |
| 158 | if newcap <= 0 { |
| 159 | newcap = wantcap |
| 160 | } |
| 161 | } |
| 162 | return newcap |
| 163 | } |
| 164 | |
Joe Tsai | 0f81b38 | 2019-07-10 23:14:31 -0700 | [diff] [blame] | 165 | func (o MarshalOptions) marshalMessageSlow(b []byte, m protoreflect.Message) ([]byte, error) { |
Damien Neil | 302cb32 | 2019-06-19 15:22:13 -0700 | [diff] [blame] | 166 | if messageset.IsMessageSet(m.Descriptor()) { |
| 167 | return marshalMessageSet(b, m, o) |
| 168 | } |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 169 | // There are many choices for what order we visit fields in. The default one here |
| 170 | // is chosen for reasonable efficiency and simplicity given the protoreflect API. |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 171 | // It is not deterministic, since Message.Range does not return fields in any |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 172 | // defined order. |
| 173 | // |
Damien Neil | 01c0e8d | 2019-11-12 12:33:12 -0800 | [diff] [blame] | 174 | // When using deterministic serialization, we sort the known fields. |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 175 | var err error |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 176 | o.rangeFields(m, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { |
| 177 | b, err = o.marshalField(b, fd, v) |
Damien Neil | 8c86fc5 | 2019-06-19 09:28:29 -0700 | [diff] [blame] | 178 | return err == nil |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 179 | }) |
| 180 | if err != nil { |
Damien Neil | 96c229a | 2019-04-03 12:17:24 -0700 | [diff] [blame] | 181 | return b, err |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 182 | } |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 183 | b = append(b, m.GetUnknown()...) |
Damien Neil | 8c86fc5 | 2019-06-19 09:28:29 -0700 | [diff] [blame] | 184 | return b, nil |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 185 | } |
| 186 | |
Damien Neil | 01c0e8d | 2019-11-12 12:33:12 -0800 | [diff] [blame] | 187 | // rangeFields visits fields in a defined order when deterministic serialization is enabled. |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 188 | func (o MarshalOptions) rangeFields(m protoreflect.Message, f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 189 | if !o.Deterministic { |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 190 | m.Range(f) |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 191 | return |
| 192 | } |
Damien Neil | a994082 | 2019-06-24 12:58:17 -0700 | [diff] [blame] | 193 | var fds []protoreflect.FieldDescriptor |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 194 | m.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { |
| 195 | fds = append(fds, fd) |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 196 | return true |
| 197 | }) |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 198 | sort.Slice(fds, func(a, b int) bool { |
Damien Neil | 01c0e8d | 2019-11-12 12:33:12 -0800 | [diff] [blame] | 199 | return fieldsort.Less(fds[a], fds[b]) |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 200 | }) |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 201 | for _, fd := range fds { |
| 202 | if !f(fd, m.Get(fd)) { |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 203 | break |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 208 | func (o MarshalOptions) marshalField(b []byte, fd protoreflect.FieldDescriptor, value protoreflect.Value) ([]byte, error) { |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 209 | switch { |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 210 | case fd.IsList(): |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 211 | return o.marshalList(b, fd, value.List()) |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 212 | case fd.IsMap(): |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 213 | return o.marshalMap(b, fd, value.Map()) |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 214 | default: |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 215 | b = wire.AppendTag(b, fd.Number(), wireTypes[fd.Kind()]) |
| 216 | return o.marshalSingular(b, fd, value) |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 217 | } |
| 218 | } |
| 219 | |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 220 | func (o MarshalOptions) marshalList(b []byte, fd protoreflect.FieldDescriptor, list protoreflect.List) ([]byte, error) { |
| 221 | if fd.IsPacked() && list.Len() > 0 { |
| 222 | b = wire.AppendTag(b, fd.Number(), wire.BytesType) |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 223 | b, pos := appendSpeculativeLength(b) |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 224 | for i, llen := 0, list.Len(); i < llen; i++ { |
| 225 | var err error |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 226 | b, err = o.marshalSingular(b, fd, list.Get(i)) |
Damien Neil | 8c86fc5 | 2019-06-19 09:28:29 -0700 | [diff] [blame] | 227 | if err != nil { |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 228 | return b, err |
| 229 | } |
| 230 | } |
| 231 | b = finishSpeculativeLength(b, pos) |
Damien Neil | 8c86fc5 | 2019-06-19 09:28:29 -0700 | [diff] [blame] | 232 | return b, nil |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 233 | } |
| 234 | |
| 235 | kind := fd.Kind() |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 236 | for i, llen := 0, list.Len(); i < llen; i++ { |
| 237 | var err error |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 238 | b = wire.AppendTag(b, fd.Number(), wireTypes[kind]) |
| 239 | b, err = o.marshalSingular(b, fd, list.Get(i)) |
Damien Neil | 8c86fc5 | 2019-06-19 09:28:29 -0700 | [diff] [blame] | 240 | if err != nil { |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 241 | return b, err |
| 242 | } |
| 243 | } |
Damien Neil | 8c86fc5 | 2019-06-19 09:28:29 -0700 | [diff] [blame] | 244 | return b, nil |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 245 | } |
| 246 | |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 247 | func (o MarshalOptions) marshalMap(b []byte, fd protoreflect.FieldDescriptor, mapv protoreflect.Map) ([]byte, error) { |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 248 | keyf := fd.MapKey() |
| 249 | valf := fd.MapValue() |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 250 | var err error |
| 251 | o.rangeMap(mapv, keyf.Kind(), func(key protoreflect.MapKey, value protoreflect.Value) bool { |
Joe Tsai | 378c132 | 2019-04-25 23:48:08 -0700 | [diff] [blame] | 252 | b = wire.AppendTag(b, fd.Number(), wire.BytesType) |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 253 | var pos int |
| 254 | b, pos = appendSpeculativeLength(b) |
| 255 | |
| 256 | b, err = o.marshalField(b, keyf, key.Value()) |
Damien Neil | 8c86fc5 | 2019-06-19 09:28:29 -0700 | [diff] [blame] | 257 | if err != nil { |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 258 | return false |
| 259 | } |
| 260 | b, err = o.marshalField(b, valf, value) |
Damien Neil | 8c86fc5 | 2019-06-19 09:28:29 -0700 | [diff] [blame] | 261 | if err != nil { |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 262 | return false |
| 263 | } |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 264 | b = finishSpeculativeLength(b, pos) |
| 265 | return true |
| 266 | }) |
Damien Neil | 8c86fc5 | 2019-06-19 09:28:29 -0700 | [diff] [blame] | 267 | return b, err |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 268 | } |
| 269 | |
| 270 | func (o MarshalOptions) rangeMap(mapv protoreflect.Map, kind protoreflect.Kind, f func(protoreflect.MapKey, protoreflect.Value) bool) { |
| 271 | if !o.Deterministic { |
| 272 | mapv.Range(f) |
| 273 | return |
| 274 | } |
| 275 | mapsort.Range(mapv, kind, f) |
| 276 | } |
| 277 | |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 278 | // When encoding length-prefixed fields, we speculatively set aside some number of bytes |
| 279 | // for the length, encode the data, and then encode the length (shifting the data if necessary |
| 280 | // to make room). |
| 281 | const speculativeLength = 1 |
| 282 | |
| 283 | func appendSpeculativeLength(b []byte) ([]byte, int) { |
| 284 | pos := len(b) |
| 285 | b = append(b, "\x00\x00\x00\x00"[:speculativeLength]...) |
| 286 | return b, pos |
| 287 | } |
| 288 | |
| 289 | func finishSpeculativeLength(b []byte, pos int) []byte { |
| 290 | mlen := len(b) - pos - speculativeLength |
| 291 | msiz := wire.SizeVarint(uint64(mlen)) |
| 292 | if msiz != speculativeLength { |
| 293 | for i := 0; i < msiz-speculativeLength; i++ { |
| 294 | b = append(b, 0) |
| 295 | } |
| 296 | copy(b[pos+msiz:], b[pos+speculativeLength:]) |
| 297 | b = b[:pos+msiz+mlen] |
| 298 | } |
| 299 | wire.AppendVarint(b[:pos], uint64(mlen)) |
| 300 | return b |
| 301 | } |