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