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 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. // Treat nil message interface as an empty message; nothing to output.
  70. if m == nil {
  71. return nil, nil
  72. }
  73. out, err := MarshalOptions{}.marshal(nil, m.ProtoReflect())
  74. if len(out.Buf) == 0 && err == nil {
  75. out.Buf = emptyBytesForMessage(m)
  76. }
  77. return out.Buf, err
  78. }
  79. // Marshal returns the wire-format encoding of m.
  80. func (o MarshalOptions) Marshal(m Message) ([]byte, error) {
  81. // Treat nil message interface as an empty message; nothing to output.
  82. if m == nil {
  83. return nil, nil
  84. }
  85. out, err := o.marshal(nil, m.ProtoReflect())
  86. if len(out.Buf) == 0 && err == nil {
  87. out.Buf = emptyBytesForMessage(m)
  88. }
  89. return out.Buf, err
  90. }
  91. // emptyBytesForMessage returns a nil buffer if and only if m is invalid,
  92. // otherwise it returns a non-nil empty buffer.
  93. //
  94. // This is to assist the edge-case where user-code does the following:
  95. // m1.OptionalBytes, _ = proto.Marshal(m2)
  96. // where they expect the proto2 "optional_bytes" field to be populated
  97. // if any only if m2 is a valid message.
  98. func emptyBytesForMessage(m Message) []byte {
  99. if m == nil || !m.ProtoReflect().IsValid() {
  100. return nil
  101. }
  102. return emptyBuf[:]
  103. }
  104. // MarshalAppend appends the wire-format encoding of m to b,
  105. // returning the result.
  106. func (o MarshalOptions) MarshalAppend(b []byte, m Message) ([]byte, error) {
  107. // Treat nil message interface as an empty message; nothing to append.
  108. if m == nil {
  109. return b, nil
  110. }
  111. out, err := o.marshal(b, m.ProtoReflect())
  112. return out.Buf, err
  113. }
  114. // MarshalState returns the wire-format encoding of a message.
  115. //
  116. // This method permits fine-grained control over the marshaler.
  117. // Most users should use Marshal instead.
  118. func (o MarshalOptions) MarshalState(in protoiface.MarshalInput) (protoiface.MarshalOutput, error) {
  119. return o.marshal(in.Buf, in.Message)
  120. }
  121. func (o MarshalOptions) marshal(b []byte, m protoreflect.Message) (out protoiface.MarshalOutput, err error) {
  122. allowPartial := o.AllowPartial
  123. o.AllowPartial = true
  124. if methods := protoMethods(m); methods != nil && methods.Marshal != nil &&
  125. !(o.Deterministic && methods.Flags&protoiface.SupportMarshalDeterministic == 0) {
  126. in := protoiface.MarshalInput{
  127. Message: m,
  128. Buf: b,
  129. }
  130. if o.Deterministic {
  131. in.Flags |= protoiface.MarshalDeterministic
  132. }
  133. if o.UseCachedSize {
  134. in.Flags |= protoiface.MarshalUseCachedSize
  135. }
  136. if methods.Size != nil {
  137. sout := methods.Size(protoiface.SizeInput{
  138. Message: m,
  139. Flags: in.Flags,
  140. })
  141. if cap(b) < len(b)+sout.Size {
  142. in.Buf = make([]byte, len(b), growcap(cap(b), len(b)+sout.Size))
  143. copy(in.Buf, b)
  144. }
  145. in.Flags |= protoiface.MarshalUseCachedSize
  146. }
  147. out, err = methods.Marshal(in)
  148. } else {
  149. out.Buf, err = o.marshalMessageSlow(b, m)
  150. }
  151. if err != nil {
  152. return out, err
  153. }
  154. if allowPartial {
  155. return out, nil
  156. }
  157. return out, checkInitialized(m)
  158. }
  159. func (o MarshalOptions) marshalMessage(b []byte, m protoreflect.Message) ([]byte, error) {
  160. out, err := o.marshal(b, m)
  161. return out.Buf, err
  162. }
  163. // growcap scales up the capacity of a slice.
  164. //
  165. // Given a slice with a current capacity of oldcap and a desired
  166. // capacity of wantcap, growcap returns a new capacity >= wantcap.
  167. //
  168. // The algorithm is mostly identical to the one used by append as of Go 1.14.
  169. func growcap(oldcap, wantcap int) (newcap int) {
  170. if wantcap > oldcap*2 {
  171. newcap = wantcap
  172. } else if oldcap < 1024 {
  173. // The Go 1.14 runtime takes this case when len(s) < 1024,
  174. // not when cap(s) < 1024. The difference doesn't seem
  175. // significant here.
  176. newcap = oldcap * 2
  177. } else {
  178. newcap = oldcap
  179. for 0 < newcap && newcap < wantcap {
  180. newcap += newcap / 4
  181. }
  182. if newcap <= 0 {
  183. newcap = wantcap
  184. }
  185. }
  186. return newcap
  187. }
  188. func (o MarshalOptions) marshalMessageSlow(b []byte, m protoreflect.Message) ([]byte, error) {
  189. if messageset.IsMessageSet(m.Descriptor()) {
  190. return marshalMessageSet(b, m, o)
  191. }
  192. // There are many choices for what order we visit fields in. The default one here
  193. // is chosen for reasonable efficiency and simplicity given the protoreflect API.
  194. // It is not deterministic, since Message.Range does not return fields in any
  195. // defined order.
  196. //
  197. // When using deterministic serialization, we sort the known fields.
  198. var err error
  199. o.rangeFields(m, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
  200. b, err = o.marshalField(b, fd, v)
  201. return err == nil
  202. })
  203. if err != nil {
  204. return b, err
  205. }
  206. b = append(b, m.GetUnknown()...)
  207. return b, nil
  208. }
  209. // rangeFields visits fields in a defined order when deterministic serialization is enabled.
  210. func (o MarshalOptions) rangeFields(m protoreflect.Message, f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {
  211. if !o.Deterministic {
  212. m.Range(f)
  213. return
  214. }
  215. var fds []protoreflect.FieldDescriptor
  216. m.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool {
  217. fds = append(fds, fd)
  218. return true
  219. })
  220. sort.Slice(fds, func(a, b int) bool {
  221. return fieldsort.Less(fds[a], fds[b])
  222. })
  223. for _, fd := range fds {
  224. if !f(fd, m.Get(fd)) {
  225. break
  226. }
  227. }
  228. }
  229. func (o MarshalOptions) marshalField(b []byte, fd protoreflect.FieldDescriptor, value protoreflect.Value) ([]byte, error) {
  230. switch {
  231. case fd.IsList():
  232. return o.marshalList(b, fd, value.List())
  233. case fd.IsMap():
  234. return o.marshalMap(b, fd, value.Map())
  235. default:
  236. b = protowire.AppendTag(b, fd.Number(), wireTypes[fd.Kind()])
  237. return o.marshalSingular(b, fd, value)
  238. }
  239. }
  240. func (o MarshalOptions) marshalList(b []byte, fd protoreflect.FieldDescriptor, list protoreflect.List) ([]byte, error) {
  241. if fd.IsPacked() && list.Len() > 0 {
  242. b = protowire.AppendTag(b, fd.Number(), protowire.BytesType)
  243. b, pos := appendSpeculativeLength(b)
  244. for i, llen := 0, list.Len(); i < llen; i++ {
  245. var err error
  246. b, err = o.marshalSingular(b, fd, list.Get(i))
  247. if err != nil {
  248. return b, err
  249. }
  250. }
  251. b = finishSpeculativeLength(b, pos)
  252. return b, nil
  253. }
  254. kind := fd.Kind()
  255. for i, llen := 0, list.Len(); i < llen; i++ {
  256. var err error
  257. b = protowire.AppendTag(b, fd.Number(), wireTypes[kind])
  258. b, err = o.marshalSingular(b, fd, list.Get(i))
  259. if err != nil {
  260. return b, err
  261. }
  262. }
  263. return b, nil
  264. }
  265. func (o MarshalOptions) marshalMap(b []byte, fd protoreflect.FieldDescriptor, mapv protoreflect.Map) ([]byte, error) {
  266. keyf := fd.MapKey()
  267. valf := fd.MapValue()
  268. var err error
  269. o.rangeMap(mapv, keyf.Kind(), func(key protoreflect.MapKey, value protoreflect.Value) bool {
  270. b = protowire.AppendTag(b, fd.Number(), protowire.BytesType)
  271. var pos int
  272. b, pos = appendSpeculativeLength(b)
  273. b, err = o.marshalField(b, keyf, key.Value())
  274. if err != nil {
  275. return false
  276. }
  277. b, err = o.marshalField(b, valf, value)
  278. if err != nil {
  279. return false
  280. }
  281. b = finishSpeculativeLength(b, pos)
  282. return true
  283. })
  284. return b, err
  285. }
  286. func (o MarshalOptions) rangeMap(mapv protoreflect.Map, kind protoreflect.Kind, f func(protoreflect.MapKey, protoreflect.Value) bool) {
  287. if !o.Deterministic {
  288. mapv.Range(f)
  289. return
  290. }
  291. mapsort.Range(mapv, kind, f)
  292. }
  293. // When encoding length-prefixed fields, we speculatively set aside some number of bytes
  294. // for the length, encode the data, and then encode the length (shifting the data if necessary
  295. // to make room).
  296. const speculativeLength = 1
  297. func appendSpeculativeLength(b []byte) ([]byte, int) {
  298. pos := len(b)
  299. b = append(b, "\x00\x00\x00\x00"[:speculativeLength]...)
  300. return b, pos
  301. }
  302. func finishSpeculativeLength(b []byte, pos int) []byte {
  303. mlen := len(b) - pos - speculativeLength
  304. msiz := protowire.SizeVarint(uint64(mlen))
  305. if msiz != speculativeLength {
  306. for i := 0; i < msiz-speculativeLength; i++ {
  307. b = append(b, 0)
  308. }
  309. copy(b[pos+msiz:], b[pos+speculativeLength:])
  310. b = b[:pos+msiz+mlen]
  311. }
  312. protowire.AppendVarint(b[:pos], uint64(mlen))
  313. return b
  314. }