encode.go 7.9 KB

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