encode.go 8.8 KB

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