encode.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. // Copyright 2018 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 prototext
  5. import (
  6. "fmt"
  7. "strconv"
  8. "unicode/utf8"
  9. "google.golang.org/protobuf/encoding/protowire"
  10. "google.golang.org/protobuf/internal/encoding/messageset"
  11. "google.golang.org/protobuf/internal/encoding/text"
  12. "google.golang.org/protobuf/internal/errors"
  13. "google.golang.org/protobuf/internal/flags"
  14. "google.golang.org/protobuf/internal/genid"
  15. "google.golang.org/protobuf/internal/order"
  16. "google.golang.org/protobuf/internal/pragma"
  17. "google.golang.org/protobuf/internal/strs"
  18. "google.golang.org/protobuf/proto"
  19. "google.golang.org/protobuf/reflect/protoreflect"
  20. pref "google.golang.org/protobuf/reflect/protoreflect"
  21. "google.golang.org/protobuf/reflect/protoregistry"
  22. )
  23. const defaultIndent = " "
  24. // Format formats the message as a multiline string.
  25. // This function is only intended for human consumption and ignores errors.
  26. // Do not depend on the output being stable. It may change over time across
  27. // different versions of the program.
  28. func Format(m proto.Message) string {
  29. return MarshalOptions{Multiline: true}.Format(m)
  30. }
  31. // Marshal writes the given proto.Message in textproto format using default
  32. // options. Do not depend on the output being stable. It may change over time
  33. // across different versions of the program.
  34. func Marshal(m proto.Message) ([]byte, error) {
  35. return MarshalOptions{}.Marshal(m)
  36. }
  37. // MarshalOptions is a configurable text format marshaler.
  38. type MarshalOptions struct {
  39. pragma.NoUnkeyedLiterals
  40. // Multiline specifies whether the marshaler should format the output in
  41. // indented-form with every textual element on a new line.
  42. // If Indent is an empty string, then an arbitrary indent is chosen.
  43. Multiline bool
  44. // Indent specifies the set of indentation characters to use in a multiline
  45. // formatted output such that every entry is preceded by Indent and
  46. // terminated by a newline. If non-empty, then Multiline is treated as true.
  47. // Indent can only be composed of space or tab characters.
  48. Indent string
  49. // EmitASCII specifies whether to format strings and bytes as ASCII only
  50. // as opposed to using UTF-8 encoding when possible.
  51. EmitASCII bool
  52. // allowInvalidUTF8 specifies whether to permit the encoding of strings
  53. // with invalid UTF-8. This is unexported as it is intended to only
  54. // be specified by the Format method.
  55. allowInvalidUTF8 bool
  56. // AllowPartial allows messages that have missing required fields to marshal
  57. // without returning an error. If AllowPartial is false (the default),
  58. // Marshal will return error if there are any missing required fields.
  59. AllowPartial bool
  60. // EmitUnknown specifies whether to emit unknown fields in the output.
  61. // If specified, the unmarshaler may be unable to parse the output.
  62. // The default is to exclude unknown fields.
  63. EmitUnknown bool
  64. // Resolver is used for looking up types when expanding google.protobuf.Any
  65. // messages. If nil, this defaults to using protoregistry.GlobalTypes.
  66. Resolver interface {
  67. protoregistry.ExtensionTypeResolver
  68. protoregistry.MessageTypeResolver
  69. }
  70. }
  71. // Format formats the message as a string.
  72. // This method is only intended for human consumption and ignores errors.
  73. // Do not depend on the output being stable. It may change over time across
  74. // different versions of the program.
  75. func (o MarshalOptions) Format(m proto.Message) string {
  76. if m == nil || !m.ProtoReflect().IsValid() {
  77. return "<nil>" // invalid syntax, but okay since this is for debugging
  78. }
  79. o.allowInvalidUTF8 = true
  80. o.AllowPartial = true
  81. o.EmitUnknown = true
  82. b, _ := o.Marshal(m)
  83. return string(b)
  84. }
  85. // Marshal writes the given proto.Message in textproto format using options in
  86. // MarshalOptions object. Do not depend on the output being stable. It may
  87. // change over time across different versions of the program.
  88. func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) {
  89. return o.marshal(m)
  90. }
  91. // marshal is a centralized function that all marshal operations go through.
  92. // For profiling purposes, avoid changing the name of this function or
  93. // introducing other code paths for marshal that do not go through this.
  94. func (o MarshalOptions) marshal(m proto.Message) ([]byte, error) {
  95. var delims = [2]byte{'{', '}'}
  96. if o.Multiline && o.Indent == "" {
  97. o.Indent = defaultIndent
  98. }
  99. if o.Resolver == nil {
  100. o.Resolver = protoregistry.GlobalTypes
  101. }
  102. internalEnc, err := text.NewEncoder(o.Indent, delims, o.EmitASCII)
  103. if err != nil {
  104. return nil, err
  105. }
  106. // Treat nil message interface as an empty message,
  107. // in which case there is nothing to output.
  108. if m == nil {
  109. return []byte{}, nil
  110. }
  111. enc := encoder{internalEnc, o}
  112. err = enc.marshalMessage(m.ProtoReflect(), false)
  113. if err != nil {
  114. return nil, err
  115. }
  116. out := enc.Bytes()
  117. if len(o.Indent) > 0 && len(out) > 0 {
  118. out = append(out, '\n')
  119. }
  120. if o.AllowPartial {
  121. return out, nil
  122. }
  123. return out, proto.CheckInitialized(m)
  124. }
  125. type encoder struct {
  126. *text.Encoder
  127. opts MarshalOptions
  128. }
  129. // marshalMessage marshals the given protoreflect.Message.
  130. func (e encoder) marshalMessage(m pref.Message, inclDelims bool) error {
  131. messageDesc := m.Descriptor()
  132. if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) {
  133. return errors.New("no support for proto1 MessageSets")
  134. }
  135. if inclDelims {
  136. e.StartMessage()
  137. defer e.EndMessage()
  138. }
  139. // Handle Any expansion.
  140. if messageDesc.FullName() == genid.Any_message_fullname {
  141. if e.marshalAny(m) {
  142. return nil
  143. }
  144. // If unable to expand, continue on to marshal Any as a regular message.
  145. }
  146. // Marshal fields.
  147. var err error
  148. order.RangeFields(m, order.IndexNameFieldOrder, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
  149. if err = e.marshalField(fd.TextName(), v, fd); err != nil {
  150. return false
  151. }
  152. return true
  153. })
  154. if err != nil {
  155. return err
  156. }
  157. // Marshal unknown fields.
  158. if e.opts.EmitUnknown {
  159. e.marshalUnknown(m.GetUnknown())
  160. }
  161. return nil
  162. }
  163. // marshalField marshals the given field with protoreflect.Value.
  164. func (e encoder) marshalField(name string, val pref.Value, fd pref.FieldDescriptor) error {
  165. switch {
  166. case fd.IsList():
  167. return e.marshalList(name, val.List(), fd)
  168. case fd.IsMap():
  169. return e.marshalMap(name, val.Map(), fd)
  170. default:
  171. e.WriteName(name)
  172. return e.marshalSingular(val, fd)
  173. }
  174. }
  175. // marshalSingular marshals the given non-repeated field value. This includes
  176. // all scalar types, enums, messages, and groups.
  177. func (e encoder) marshalSingular(val pref.Value, fd pref.FieldDescriptor) error {
  178. kind := fd.Kind()
  179. switch kind {
  180. case pref.BoolKind:
  181. e.WriteBool(val.Bool())
  182. case pref.StringKind:
  183. s := val.String()
  184. if !e.opts.allowInvalidUTF8 && strs.EnforceUTF8(fd) && !utf8.ValidString(s) {
  185. return errors.InvalidUTF8(string(fd.FullName()))
  186. }
  187. e.WriteString(s)
  188. case pref.Int32Kind, pref.Int64Kind,
  189. pref.Sint32Kind, pref.Sint64Kind,
  190. pref.Sfixed32Kind, pref.Sfixed64Kind:
  191. e.WriteInt(val.Int())
  192. case pref.Uint32Kind, pref.Uint64Kind,
  193. pref.Fixed32Kind, pref.Fixed64Kind:
  194. e.WriteUint(val.Uint())
  195. case pref.FloatKind:
  196. // Encoder.WriteFloat handles the special numbers NaN and infinites.
  197. e.WriteFloat(val.Float(), 32)
  198. case pref.DoubleKind:
  199. // Encoder.WriteFloat handles the special numbers NaN and infinites.
  200. e.WriteFloat(val.Float(), 64)
  201. case pref.BytesKind:
  202. e.WriteString(string(val.Bytes()))
  203. case pref.EnumKind:
  204. num := val.Enum()
  205. if desc := fd.Enum().Values().ByNumber(num); desc != nil {
  206. e.WriteLiteral(string(desc.Name()))
  207. } else {
  208. // Use numeric value if there is no enum description.
  209. e.WriteInt(int64(num))
  210. }
  211. case pref.MessageKind, pref.GroupKind:
  212. return e.marshalMessage(val.Message(), true)
  213. default:
  214. panic(fmt.Sprintf("%v has unknown kind: %v", fd.FullName(), kind))
  215. }
  216. return nil
  217. }
  218. // marshalList marshals the given protoreflect.List as multiple name-value fields.
  219. func (e encoder) marshalList(name string, list pref.List, fd pref.FieldDescriptor) error {
  220. size := list.Len()
  221. for i := 0; i < size; i++ {
  222. e.WriteName(name)
  223. if err := e.marshalSingular(list.Get(i), fd); err != nil {
  224. return err
  225. }
  226. }
  227. return nil
  228. }
  229. // marshalMap marshals the given protoreflect.Map as multiple name-value fields.
  230. func (e encoder) marshalMap(name string, mmap pref.Map, fd pref.FieldDescriptor) error {
  231. var err error
  232. order.RangeEntries(mmap, order.GenericKeyOrder, func(key pref.MapKey, val pref.Value) bool {
  233. e.WriteName(name)
  234. e.StartMessage()
  235. defer e.EndMessage()
  236. e.WriteName(string(genid.MapEntry_Key_field_name))
  237. err = e.marshalSingular(key.Value(), fd.MapKey())
  238. if err != nil {
  239. return false
  240. }
  241. e.WriteName(string(genid.MapEntry_Value_field_name))
  242. err = e.marshalSingular(val, fd.MapValue())
  243. if err != nil {
  244. return false
  245. }
  246. return true
  247. })
  248. return err
  249. }
  250. // marshalUnknown parses the given []byte and marshals fields out.
  251. // This function assumes proper encoding in the given []byte.
  252. func (e encoder) marshalUnknown(b []byte) {
  253. const dec = 10
  254. const hex = 16
  255. for len(b) > 0 {
  256. num, wtype, n := protowire.ConsumeTag(b)
  257. b = b[n:]
  258. e.WriteName(strconv.FormatInt(int64(num), dec))
  259. switch wtype {
  260. case protowire.VarintType:
  261. var v uint64
  262. v, n = protowire.ConsumeVarint(b)
  263. e.WriteUint(v)
  264. case protowire.Fixed32Type:
  265. var v uint32
  266. v, n = protowire.ConsumeFixed32(b)
  267. e.WriteLiteral("0x" + strconv.FormatUint(uint64(v), hex))
  268. case protowire.Fixed64Type:
  269. var v uint64
  270. v, n = protowire.ConsumeFixed64(b)
  271. e.WriteLiteral("0x" + strconv.FormatUint(v, hex))
  272. case protowire.BytesType:
  273. var v []byte
  274. v, n = protowire.ConsumeBytes(b)
  275. e.WriteString(string(v))
  276. case protowire.StartGroupType:
  277. e.StartMessage()
  278. var v []byte
  279. v, n = protowire.ConsumeGroup(num, b)
  280. e.marshalUnknown(v)
  281. e.EndMessage()
  282. default:
  283. panic(fmt.Sprintf("prototext: error parsing unknown field wire type: %v", wtype))
  284. }
  285. b = b[n:]
  286. }
  287. }
  288. // marshalAny marshals the given google.protobuf.Any message in expanded form.
  289. // It returns true if it was able to marshal, else false.
  290. func (e encoder) marshalAny(any pref.Message) bool {
  291. // Construct the embedded message.
  292. fds := any.Descriptor().Fields()
  293. fdType := fds.ByNumber(genid.Any_TypeUrl_field_number)
  294. typeURL := any.Get(fdType).String()
  295. mt, err := e.opts.Resolver.FindMessageByURL(typeURL)
  296. if err != nil {
  297. return false
  298. }
  299. m := mt.New().Interface()
  300. // Unmarshal bytes into embedded message.
  301. fdValue := fds.ByNumber(genid.Any_Value_field_number)
  302. value := any.Get(fdValue)
  303. err = proto.UnmarshalOptions{
  304. AllowPartial: true,
  305. Resolver: e.opts.Resolver,
  306. }.Unmarshal(value.Bytes(), m)
  307. if err != nil {
  308. return false
  309. }
  310. // Get current encoder position. If marshaling fails, reset encoder output
  311. // back to this position.
  312. pos := e.Snapshot()
  313. // Field name is the proto field name enclosed in [].
  314. e.WriteName("[" + typeURL + "]")
  315. err = e.marshalMessage(m.ProtoReflect(), true)
  316. if err != nil {
  317. e.Reset(pos)
  318. return false
  319. }
  320. return true
  321. }