encode.go 7.9 KB

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