You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

encode.go 9.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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/encoding/protowire"
  8. "google.golang.org/protobuf/internal/encoding/messageset"
  9. "google.golang.org/protobuf/internal/fieldsort"
  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. pragma.NoUnkeyedLiterals
  21. // AllowPartial allows messages that have missing required fields to marshal
  22. // without returning an error. If AllowPartial is false (the default),
  23. // Marshal will return an error if there are any missing required fields.
  24. AllowPartial bool
  25. // Deterministic controls whether the same message will always be
  26. // serialized to the same bytes within the same binary.
  27. //
  28. // Setting this option guarantees that repeated serialization of
  29. // the same message will return the same bytes, and that different
  30. // processes of the same binary (which may be executing on different
  31. // machines) will serialize equal messages to the same bytes.
  32. // It has no effect on the resulting size of the encoded message compared
  33. // to a non-deterministic marshal.
  34. //
  35. // Note that the deterministic serialization is NOT canonical across
  36. // languages. It is not guaranteed to remain stable over time. It is
  37. // unstable across different builds with schema changes due to unknown
  38. // fields. Users who need canonical serialization (e.g., persistent
  39. // storage in a canonical form, fingerprinting, etc.) must define
  40. // their own canonicalization specification and implement their own
  41. // serializer rather than relying on this API.
  42. //
  43. // If deterministic serialization is requested, map entries will be
  44. // sorted by keys in lexographical order. This is an implementation
  45. // detail and subject to change.
  46. Deterministic bool
  47. // UseCachedSize indicates that the result of a previous Size call
  48. // may be reused.
  49. //
  50. // Setting this option asserts that:
  51. //
  52. // 1. Size has previously been called on this message with identical
  53. // options (except for UseCachedSize itself).
  54. //
  55. // 2. The message and all its submessages have not changed in any
  56. // way since the Size call.
  57. //
  58. // If either of these invariants is violated,
  59. // the results are undefined and may include panics or corrupted output.
  60. //
  61. // Implementations MAY take this option into account to provide
  62. // better performance, but there is no guarantee that they will do so.
  63. // There is absolutely no guarantee that Size followed by Marshal with
  64. // UseCachedSize set will perform equivalently to Marshal alone.
  65. UseCachedSize bool
  66. }
  67. // Marshal returns the wire-format encoding of m.
  68. func Marshal(m Message) ([]byte, error) {
  69. out, err := MarshalOptions{}.marshal(nil, m.ProtoReflect())
  70. return out.Buf, err
  71. }
  72. // Marshal returns the wire-format encoding of m.
  73. func (o MarshalOptions) Marshal(m Message) ([]byte, error) {
  74. out, err := o.marshal(nil, m.ProtoReflect())
  75. return out.Buf, err
  76. }
  77. // MarshalAppend appends the wire-format encoding of m to b,
  78. // returning the result.
  79. func (o MarshalOptions) MarshalAppend(b []byte, m Message) ([]byte, error) {
  80. out, err := o.marshal(b, m.ProtoReflect())
  81. return out.Buf, err
  82. }
  83. // MarshalState returns the wire-format encoding of a message.
  84. //
  85. // This method permits fine-grained control over the marshaler.
  86. // Most users should use Marshal instead.
  87. func (o MarshalOptions) MarshalState(in protoiface.MarshalInput) (protoiface.MarshalOutput, error) {
  88. return o.marshal(in.Buf, in.Message)
  89. }
  90. func (o MarshalOptions) marshal(b []byte, m protoreflect.Message) (out protoiface.MarshalOutput, err error) {
  91. allowPartial := o.AllowPartial
  92. o.AllowPartial = true
  93. if methods := protoMethods(m); methods != nil && methods.Marshal != nil &&
  94. !(o.Deterministic && methods.Flags&protoiface.SupportMarshalDeterministic == 0) {
  95. in := protoiface.MarshalInput{
  96. Message: m,
  97. Buf: b,
  98. }
  99. if o.Deterministic {
  100. in.Flags |= protoiface.MarshalDeterministic
  101. }
  102. if o.UseCachedSize {
  103. in.Flags |= protoiface.MarshalUseCachedSize
  104. }
  105. if methods.Size != nil {
  106. sout := methods.Size(protoiface.SizeInput{
  107. Message: m,
  108. Flags: in.Flags,
  109. })
  110. if cap(b) < len(b)+sout.Size {
  111. in.Buf = make([]byte, len(b), growcap(cap(b), len(b)+sout.Size))
  112. copy(in.Buf, b)
  113. }
  114. in.Flags |= protoiface.MarshalUseCachedSize
  115. }
  116. out, err = methods.Marshal(in)
  117. } else {
  118. out.Buf, err = o.marshalMessageSlow(b, m)
  119. }
  120. if err != nil {
  121. return out, err
  122. }
  123. if allowPartial {
  124. return out, nil
  125. }
  126. return out, checkInitialized(m)
  127. }
  128. func (o MarshalOptions) marshalMessage(b []byte, m protoreflect.Message) ([]byte, error) {
  129. out, err := o.marshal(b, m)
  130. return out.Buf, err
  131. }
  132. // growcap scales up the capacity of a slice.
  133. //
  134. // Given a slice with a current capacity of oldcap and a desired
  135. // capacity of wantcap, growcap returns a new capacity >= wantcap.
  136. //
  137. // The algorithm is mostly identical to the one used by append as of Go 1.14.
  138. func growcap(oldcap, wantcap int) (newcap int) {
  139. if wantcap > oldcap*2 {
  140. newcap = wantcap
  141. } else if oldcap < 1024 {
  142. // The Go 1.14 runtime takes this case when len(s) < 1024,
  143. // not when cap(s) < 1024. The difference doesn't seem
  144. // significant here.
  145. newcap = oldcap * 2
  146. } else {
  147. newcap = oldcap
  148. for 0 < newcap && newcap < wantcap {
  149. newcap += newcap / 4
  150. }
  151. if newcap <= 0 {
  152. newcap = wantcap
  153. }
  154. }
  155. return newcap
  156. }
  157. func (o MarshalOptions) marshalMessageSlow(b []byte, m protoreflect.Message) ([]byte, error) {
  158. if messageset.IsMessageSet(m.Descriptor()) {
  159. return marshalMessageSet(b, m, o)
  160. }
  161. // There are many choices for what order we visit fields in. The default one here
  162. // is chosen for reasonable efficiency and simplicity given the protoreflect API.
  163. // It is not deterministic, since Message.Range does not return fields in any
  164. // defined order.
  165. //
  166. // When using deterministic serialization, we sort the known fields.
  167. var err error
  168. o.rangeFields(m, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
  169. b, err = o.marshalField(b, fd, v)
  170. return err == nil
  171. })
  172. if err != nil {
  173. return b, err
  174. }
  175. b = append(b, m.GetUnknown()...)
  176. return b, nil
  177. }
  178. // rangeFields visits fields in a defined order when deterministic serialization is enabled.
  179. func (o MarshalOptions) rangeFields(m protoreflect.Message, f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {
  180. if !o.Deterministic {
  181. m.Range(f)
  182. return
  183. }
  184. var fds []protoreflect.FieldDescriptor
  185. m.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool {
  186. fds = append(fds, fd)
  187. return true
  188. })
  189. sort.Slice(fds, func(a, b int) bool {
  190. return fieldsort.Less(fds[a], fds[b])
  191. })
  192. for _, fd := range fds {
  193. if !f(fd, m.Get(fd)) {
  194. break
  195. }
  196. }
  197. }
  198. func (o MarshalOptions) marshalField(b []byte, fd protoreflect.FieldDescriptor, value protoreflect.Value) ([]byte, error) {
  199. switch {
  200. case fd.IsList():
  201. return o.marshalList(b, fd, value.List())
  202. case fd.IsMap():
  203. return o.marshalMap(b, fd, value.Map())
  204. default:
  205. b = protowire.AppendTag(b, fd.Number(), wireTypes[fd.Kind()])
  206. return o.marshalSingular(b, fd, value)
  207. }
  208. }
  209. func (o MarshalOptions) marshalList(b []byte, fd protoreflect.FieldDescriptor, list protoreflect.List) ([]byte, error) {
  210. if fd.IsPacked() && list.Len() > 0 {
  211. b = protowire.AppendTag(b, fd.Number(), protowire.BytesType)
  212. b, pos := appendSpeculativeLength(b)
  213. for i, llen := 0, list.Len(); i < llen; i++ {
  214. var err error
  215. b, err = o.marshalSingular(b, fd, list.Get(i))
  216. if err != nil {
  217. return b, err
  218. }
  219. }
  220. b = finishSpeculativeLength(b, pos)
  221. return b, nil
  222. }
  223. kind := fd.Kind()
  224. for i, llen := 0, list.Len(); i < llen; i++ {
  225. var err error
  226. b = protowire.AppendTag(b, fd.Number(), wireTypes[kind])
  227. b, err = o.marshalSingular(b, fd, list.Get(i))
  228. if err != nil {
  229. return b, err
  230. }
  231. }
  232. return b, nil
  233. }
  234. func (o MarshalOptions) marshalMap(b []byte, fd protoreflect.FieldDescriptor, mapv protoreflect.Map) ([]byte, error) {
  235. keyf := fd.MapKey()
  236. valf := fd.MapValue()
  237. var err error
  238. o.rangeMap(mapv, keyf.Kind(), func(key protoreflect.MapKey, value protoreflect.Value) bool {
  239. b = protowire.AppendTag(b, fd.Number(), protowire.BytesType)
  240. var pos int
  241. b, pos = appendSpeculativeLength(b)
  242. b, err = o.marshalField(b, keyf, key.Value())
  243. if err != nil {
  244. return false
  245. }
  246. b, err = o.marshalField(b, valf, value)
  247. if err != nil {
  248. return false
  249. }
  250. b = finishSpeculativeLength(b, pos)
  251. return true
  252. })
  253. return b, err
  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. // When encoding length-prefixed fields, we speculatively set aside some number of bytes
  263. // for the length, encode the data, and then encode the length (shifting the data if necessary
  264. // to make room).
  265. const speculativeLength = 1
  266. func appendSpeculativeLength(b []byte) ([]byte, int) {
  267. pos := len(b)
  268. b = append(b, "\x00\x00\x00\x00"[:speculativeLength]...)
  269. return b, pos
  270. }
  271. func finishSpeculativeLength(b []byte, pos int) []byte {
  272. mlen := len(b) - pos - speculativeLength
  273. msiz := protowire.SizeVarint(uint64(mlen))
  274. if msiz != speculativeLength {
  275. for i := 0; i < msiz-speculativeLength; i++ {
  276. b = append(b, 0)
  277. }
  278. copy(b[pos+msiz:], b[pos+speculativeLength:])
  279. b = b[:pos+msiz+mlen]
  280. }
  281. protowire.AppendVarint(b[:pos], uint64(mlen))
  282. return b
  283. }