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

encode.go 11KB

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