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 ( |
| 8 | "fmt" |
| 9 | "sort" |
| 10 | |
Damien Neil | e89e624 | 2019-05-13 23:55:40 -0700 | [diff] [blame] | 11 | "google.golang.org/protobuf/internal/encoding/wire" |
| 12 | "google.golang.org/protobuf/internal/errors" |
| 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 { |
Damien Neil | 96c229a | 2019-04-03 12:17:24 -0700 | [diff] [blame] | 24 | // AllowPartial allows messages that have missing required fields to marshal |
| 25 | // without returning an error. If AllowPartial is false (the default), |
| 26 | // Marshal will return an error if there are any missing required fields. |
| 27 | AllowPartial bool |
| 28 | |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 29 | // Deterministic controls whether the same message will always be |
| 30 | // serialized to the same bytes within the same binary. |
| 31 | // |
| 32 | // Setting this option guarantees that repeated serialization of |
| 33 | // the same message will return the same bytes, and that different |
| 34 | // processes of the same binary (which may be executing on different |
| 35 | // machines) will serialize equal messages to the same bytes. |
| 36 | // |
| 37 | // Note that the deterministic serialization is NOT canonical across |
| 38 | // languages. It is not guaranteed to remain stable over time. It is |
| 39 | // unstable across different builds with schema changes due to unknown |
| 40 | // fields. Users who need canonical serialization (e.g., persistent |
| 41 | // storage in a canonical form, fingerprinting, etc.) must define |
| 42 | // their own canonicalization specification and implement their own |
| 43 | // serializer rather than relying on this API. |
| 44 | // |
| 45 | // If deterministic serialization is requested, map entries will be |
| 46 | // sorted by keys in lexographical order. This is an implementation |
| 47 | // detail and subject to change. |
| 48 | Deterministic bool |
| 49 | |
Damien Neil | 03e7486 | 2019-04-07 18:18:31 -0700 | [diff] [blame] | 50 | // UseCachedSize indicates that the result of a previous Size call |
| 51 | // may be reused. |
| 52 | // |
| 53 | // Setting this option asserts that: |
| 54 | // |
| 55 | // 1. Size has previously been called on this message with identical |
| 56 | // options (except for UseCachedSize itself). |
| 57 | // |
| 58 | // 2. The message and all its submessages have not changed in any |
| 59 | // way since the Size call. |
| 60 | // |
| 61 | // If either of these invariants is broken, the results are undefined |
| 62 | // but may include panics or invalid output. |
| 63 | // |
| 64 | // Implementations MAY take this option into account to provide |
| 65 | // better performance, but there is no guarantee that they will do so. |
| 66 | // There is absolutely no guarantee that Size followed by Marshal with |
| 67 | // UseCachedSize set will perform equivalently to Marshal alone. |
| 68 | UseCachedSize bool |
| 69 | |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 70 | pragma.NoUnkeyedLiterals |
| 71 | } |
| 72 | |
Damien Neil | 0d3e8cc | 2019-04-01 13:31:55 -0700 | [diff] [blame] | 73 | var _ = protoiface.MarshalOptions(MarshalOptions{}) |
| 74 | |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 75 | // Marshal returns the wire-format encoding of m. |
| 76 | func Marshal(m Message) ([]byte, error) { |
| 77 | return MarshalOptions{}.MarshalAppend(nil, m) |
| 78 | } |
| 79 | |
| 80 | // Marshal returns the wire-format encoding of m. |
| 81 | func (o MarshalOptions) Marshal(m Message) ([]byte, error) { |
Damien Neil | 0d3e8cc | 2019-04-01 13:31:55 -0700 | [diff] [blame] | 82 | return o.MarshalAppend(nil, m) |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 83 | } |
| 84 | |
| 85 | // MarshalAppend appends the wire-format encoding of m to b, |
| 86 | // returning the result. |
| 87 | func (o MarshalOptions) MarshalAppend(b []byte, m Message) ([]byte, error) { |
Damien Neil | c37adef | 2019-04-01 13:49:56 -0700 | [diff] [blame] | 88 | // Set AllowPartial in recursive calls to marshal to avoid duplicating |
| 89 | // effort with the single initialization check below. |
| 90 | allowPartial := o.AllowPartial |
| 91 | o.AllowPartial = true |
Damien Neil | 3016b73 | 2019-04-07 12:43:10 -0700 | [diff] [blame] | 92 | out, err := o.marshalMessageFast(b, m) |
Damien Neil | 4686e23 | 2019-04-05 13:31:40 -0700 | [diff] [blame] | 93 | if err == errInternalNoFast { |
Damien Neil | 3016b73 | 2019-04-07 12:43:10 -0700 | [diff] [blame] | 94 | out, err = o.marshalMessage(b, m.ProtoReflect()) |
Damien Neil | 4686e23 | 2019-04-05 13:31:40 -0700 | [diff] [blame] | 95 | } |
| 96 | var nerr errors.NonFatal |
| 97 | if !nerr.Merge(err) { |
Damien Neil | 3016b73 | 2019-04-07 12:43:10 -0700 | [diff] [blame] | 98 | return out, err |
Damien Neil | 0d3e8cc | 2019-04-01 13:31:55 -0700 | [diff] [blame] | 99 | } |
Damien Neil | c37adef | 2019-04-01 13:49:56 -0700 | [diff] [blame] | 100 | if !allowPartial { |
Damien Neil | 4686e23 | 2019-04-05 13:31:40 -0700 | [diff] [blame] | 101 | nerr.Merge(IsInitialized(m)) |
| 102 | } |
Damien Neil | 3016b73 | 2019-04-07 12:43:10 -0700 | [diff] [blame] | 103 | return out, nerr.E |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 104 | } |
| 105 | |
Damien Neil | 0d3e8cc | 2019-04-01 13:31:55 -0700 | [diff] [blame] | 106 | func (o MarshalOptions) marshalMessageFast(b []byte, m Message) ([]byte, error) { |
Damien Neil | 0d3e8cc | 2019-04-01 13:31:55 -0700 | [diff] [blame] | 107 | methods := protoMethods(m) |
| 108 | if methods == nil || |
| 109 | methods.MarshalAppend == nil || |
| 110 | (o.Deterministic && methods.Flags&protoiface.MethodFlagDeterministicMarshal == 0) { |
| 111 | return nil, errInternalNoFast |
| 112 | } |
| 113 | if methods.Size != nil { |
| 114 | sz := methods.Size(m) |
| 115 | if cap(b) < len(b)+sz { |
| 116 | x := make([]byte, len(b), len(b)+sz) |
| 117 | copy(x, b) |
| 118 | b = x |
| 119 | } |
Damien Neil | 03e7486 | 2019-04-07 18:18:31 -0700 | [diff] [blame] | 120 | o.UseCachedSize = true |
Damien Neil | 0d3e8cc | 2019-04-01 13:31:55 -0700 | [diff] [blame] | 121 | } |
| 122 | return methods.MarshalAppend(b, m, protoiface.MarshalOptions(o)) |
| 123 | } |
| 124 | |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 125 | func (o MarshalOptions) marshalMessage(b []byte, m protoreflect.Message) ([]byte, error) { |
| 126 | // There are many choices for what order we visit fields in. The default one here |
| 127 | // is chosen for reasonable efficiency and simplicity given the protoreflect API. |
| 128 | // It is not deterministic, since KnownFields.Range does not return fields in any |
| 129 | // defined order. |
| 130 | // |
| 131 | // When using deterministic serialization, we sort the known fields by field number. |
Joe Tsai | 0fc49f8 | 2019-05-01 12:29:25 -0700 | [diff] [blame] | 132 | fieldDescs := m.Descriptor().Fields() |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 133 | knownFields := m.KnownFields() |
| 134 | var err error |
Damien Neil | 96c229a | 2019-04-03 12:17:24 -0700 | [diff] [blame] | 135 | var nerr errors.NonFatal |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 136 | o.rangeKnown(knownFields, func(num protoreflect.FieldNumber, value protoreflect.Value) bool { |
Joe Tsai | 0fc49f8 | 2019-05-01 12:29:25 -0700 | [diff] [blame] | 137 | field := fieldDescs.ByNumber(num) |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 138 | if field == nil { |
Joe Tsai | 0fc49f8 | 2019-05-01 12:29:25 -0700 | [diff] [blame] | 139 | field = knownFields.ExtensionTypes().ByNumber(num).Descriptor() |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 140 | if field == nil { |
Joe Tsai | 0fc49f8 | 2019-05-01 12:29:25 -0700 | [diff] [blame] | 141 | panic(fmt.Errorf("no descriptor for field %d in %q", num, m.Descriptor().FullName())) |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 142 | } |
| 143 | } |
| 144 | b, err = o.marshalField(b, field, value) |
Damien Neil | 96c229a | 2019-04-03 12:17:24 -0700 | [diff] [blame] | 145 | if nerr.Merge(err) { |
| 146 | err = nil |
| 147 | return true |
| 148 | } |
| 149 | return false |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 150 | }) |
| 151 | if err != nil { |
Damien Neil | 96c229a | 2019-04-03 12:17:24 -0700 | [diff] [blame] | 152 | return b, err |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 153 | } |
| 154 | m.UnknownFields().Range(func(_ protoreflect.FieldNumber, raw protoreflect.RawFields) bool { |
| 155 | b = append(b, raw...) |
| 156 | return true |
| 157 | }) |
Damien Neil | 96c229a | 2019-04-03 12:17:24 -0700 | [diff] [blame] | 158 | return b, nerr.E |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 159 | } |
| 160 | |
| 161 | // rangeKnown visits known fields in field number order when deterministic |
| 162 | // serialization is enabled. |
| 163 | func (o MarshalOptions) rangeKnown(knownFields protoreflect.KnownFields, f func(protoreflect.FieldNumber, protoreflect.Value) bool) { |
| 164 | if !o.Deterministic { |
| 165 | knownFields.Range(f) |
| 166 | return |
| 167 | } |
| 168 | nums := make([]protoreflect.FieldNumber, 0, knownFields.Len()) |
| 169 | knownFields.Range(func(num protoreflect.FieldNumber, _ protoreflect.Value) bool { |
| 170 | nums = append(nums, num) |
| 171 | return true |
| 172 | }) |
| 173 | sort.Slice(nums, func(a, b int) bool { |
| 174 | return nums[a] < nums[b] |
| 175 | }) |
| 176 | for _, num := range nums { |
| 177 | if !f(num, knownFields.Get(num)) { |
| 178 | break |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 183 | func (o MarshalOptions) marshalField(b []byte, fd protoreflect.FieldDescriptor, value protoreflect.Value) ([]byte, error) { |
| 184 | num := fd.Number() |
| 185 | kind := fd.Kind() |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 186 | switch { |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 187 | case fd.IsList(): |
| 188 | return o.marshalList(b, num, fd, value.List()) |
| 189 | case fd.IsMap(): |
| 190 | return o.marshalMap(b, num, fd, value.Map()) |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 191 | default: |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 192 | b = wire.AppendTag(b, num, wireTypes[kind]) |
| 193 | return o.marshalSingular(b, num, fd, value) |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 194 | } |
| 195 | } |
| 196 | |
Joe Tsai | ac31a35 | 2019-05-13 14:32:56 -0700 | [diff] [blame] | 197 | func (o MarshalOptions) marshalList(b []byte, num wire.Number, fd protoreflect.FieldDescriptor, list protoreflect.List) ([]byte, error) { |
| 198 | if fd.IsPacked() { |
| 199 | b = wire.AppendTag(b, num, wire.BytesType) |
| 200 | b, pos := appendSpeculativeLength(b) |
| 201 | var nerr errors.NonFatal |
| 202 | for i, llen := 0, list.Len(); i < llen; i++ { |
| 203 | var err error |
| 204 | b, err = o.marshalSingular(b, num, fd, list.Get(i)) |
| 205 | if !nerr.Merge(err) { |
| 206 | return b, err |
| 207 | } |
| 208 | } |
| 209 | b = finishSpeculativeLength(b, pos) |
| 210 | return b, nerr.E |
| 211 | } |
| 212 | |
| 213 | kind := fd.Kind() |
| 214 | var nerr errors.NonFatal |
| 215 | for i, llen := 0, list.Len(); i < llen; i++ { |
| 216 | var err error |
| 217 | b = wire.AppendTag(b, num, wireTypes[kind]) |
| 218 | b, err = o.marshalSingular(b, num, fd, list.Get(i)) |
| 219 | if !nerr.Merge(err) { |
| 220 | return b, err |
| 221 | } |
| 222 | } |
| 223 | return b, nerr.E |
| 224 | } |
| 225 | |
| 226 | func (o MarshalOptions) marshalMap(b []byte, num wire.Number, fd protoreflect.FieldDescriptor, mapv protoreflect.Map) ([]byte, error) { |
| 227 | keyf := fd.MapKey() |
| 228 | valf := fd.MapValue() |
Damien Neil | 96c229a | 2019-04-03 12:17:24 -0700 | [diff] [blame] | 229 | var nerr errors.NonFatal |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 230 | var err error |
| 231 | o.rangeMap(mapv, keyf.Kind(), func(key protoreflect.MapKey, value protoreflect.Value) bool { |
| 232 | b = wire.AppendTag(b, num, wire.BytesType) |
| 233 | var pos int |
| 234 | b, pos = appendSpeculativeLength(b) |
| 235 | |
| 236 | b, err = o.marshalField(b, keyf, key.Value()) |
Damien Neil | 96c229a | 2019-04-03 12:17:24 -0700 | [diff] [blame] | 237 | if !nerr.Merge(err) { |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 238 | return false |
| 239 | } |
| 240 | b, err = o.marshalField(b, valf, value) |
Damien Neil | 96c229a | 2019-04-03 12:17:24 -0700 | [diff] [blame] | 241 | if !nerr.Merge(err) { |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 242 | return false |
| 243 | } |
Damien Neil | 96c229a | 2019-04-03 12:17:24 -0700 | [diff] [blame] | 244 | err = nil |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 245 | |
| 246 | b = finishSpeculativeLength(b, pos) |
| 247 | return true |
| 248 | }) |
| 249 | if err != nil { |
Damien Neil | 96c229a | 2019-04-03 12:17:24 -0700 | [diff] [blame] | 250 | return b, err |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 251 | } |
Damien Neil | 96c229a | 2019-04-03 12:17:24 -0700 | [diff] [blame] | 252 | return b, nerr.E |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 253 | } |
| 254 | |
| 255 | func (o MarshalOptions) rangeMap(mapv protoreflect.Map, kind protoreflect.Kind, f func(protoreflect.MapKey, protoreflect.Value) bool) { |
| 256 | if !o.Deterministic { |
| 257 | mapv.Range(f) |
| 258 | return |
| 259 | } |
| 260 | mapsort.Range(mapv, kind, f) |
| 261 | } |
| 262 | |
Damien Neil | 99f24c3 | 2019-03-13 17:06:42 -0700 | [diff] [blame] | 263 | // When encoding length-prefixed fields, we speculatively set aside some number of bytes |
| 264 | // for the length, encode the data, and then encode the length (shifting the data if necessary |
| 265 | // to make room). |
| 266 | const speculativeLength = 1 |
| 267 | |
| 268 | func appendSpeculativeLength(b []byte) ([]byte, int) { |
| 269 | pos := len(b) |
| 270 | b = append(b, "\x00\x00\x00\x00"[:speculativeLength]...) |
| 271 | return b, pos |
| 272 | } |
| 273 | |
| 274 | func finishSpeculativeLength(b []byte, pos int) []byte { |
| 275 | mlen := len(b) - pos - speculativeLength |
| 276 | msiz := wire.SizeVarint(uint64(mlen)) |
| 277 | if msiz != speculativeLength { |
| 278 | for i := 0; i < msiz-speculativeLength; i++ { |
| 279 | b = append(b, 0) |
| 280 | } |
| 281 | copy(b[pos+msiz:], b[pos+speculativeLength:]) |
| 282 | b = b[:pos+msiz+mlen] |
| 283 | } |
| 284 | wire.AppendVarint(b[:pos], uint64(mlen)) |
| 285 | return b |
| 286 | } |