encode.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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 textpb
  5. import (
  6. "fmt"
  7. "sort"
  8. "github.com/golang/protobuf/v2/internal/encoding/text"
  9. "github.com/golang/protobuf/v2/internal/encoding/wire"
  10. "github.com/golang/protobuf/v2/internal/errors"
  11. "github.com/golang/protobuf/v2/internal/pragma"
  12. "github.com/golang/protobuf/v2/proto"
  13. pref "github.com/golang/protobuf/v2/reflect/protoreflect"
  14. "github.com/golang/protobuf/v2/reflect/protoregistry"
  15. descpb "github.com/golang/protobuf/v2/types/descriptor"
  16. )
  17. // Marshal writes the given proto.Message in textproto format using default options.
  18. // TODO: may want to describe when Marshal returns error.
  19. func Marshal(m proto.Message) ([]byte, error) {
  20. return MarshalOptions{}.Marshal(m)
  21. }
  22. // MarshalOptions is a configurable text format marshaler.
  23. type MarshalOptions struct {
  24. pragma.NoUnkeyedLiterals
  25. // Set Compact to true to have output in a single line with no line breaks.
  26. Compact bool
  27. // Resolver is the registry used for type lookups when marshaling out
  28. // google.protobuf.Any messages in expanded form. If Resolver is not set,
  29. // marshaling will default to using protoregistry.GlobalTypes. If a type is
  30. // not found, an Any message will be marshaled as a regular message.
  31. Resolver *protoregistry.Types
  32. }
  33. // Marshal writes the given proto.Message in textproto format using options in MarshalOptions object.
  34. func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) {
  35. if o.Resolver == nil {
  36. o.Resolver = protoregistry.GlobalTypes
  37. }
  38. var nerr errors.NonFatal
  39. v, err := o.marshalMessage(m.ProtoReflect())
  40. if !nerr.Merge(err) {
  41. return nil, err
  42. }
  43. indent := " "
  44. if o.Compact {
  45. indent = ""
  46. }
  47. delims := [2]byte{'{', '}'}
  48. const outputASCII = false
  49. b, err := text.Marshal(v, indent, delims, outputASCII)
  50. if !nerr.Merge(err) {
  51. return nil, err
  52. }
  53. return b, nerr.E
  54. }
  55. // marshalMessage converts a protoreflect.Message to a text.Value.
  56. func (o MarshalOptions) marshalMessage(m pref.Message) (text.Value, error) {
  57. var nerr errors.NonFatal
  58. var msgFields [][2]text.Value
  59. msgType := m.Type()
  60. // Handle Any expansion.
  61. if msgType.FullName() == "google.protobuf.Any" {
  62. msg, err := o.marshalAny(m)
  63. if err == nil || nerr.Merge(err) {
  64. // Return as is for nil or non-fatal error.
  65. return msg, nerr.E
  66. }
  67. // For other errors, continue on to marshal Any as a regular message.
  68. }
  69. // Handle known fields.
  70. fieldDescs := msgType.Fields()
  71. knownFields := m.KnownFields()
  72. size := fieldDescs.Len()
  73. for i := 0; i < size; i++ {
  74. fd := fieldDescs.Get(i)
  75. num := fd.Number()
  76. if !knownFields.Has(num) {
  77. if fd.Cardinality() == pref.Required {
  78. // Treat unset required fields as a non-fatal error.
  79. nerr.AppendRequiredNotSet(string(fd.FullName()))
  80. }
  81. continue
  82. }
  83. name := text.ValueOf(fd.Name())
  84. // Use type name for group field name.
  85. if fd.Kind() == pref.GroupKind {
  86. name = text.ValueOf(fd.MessageType().Name())
  87. }
  88. pval := knownFields.Get(num)
  89. var err error
  90. msgFields, err = o.appendField(msgFields, name, pval, fd)
  91. if !nerr.Merge(err) {
  92. return text.Value{}, err
  93. }
  94. }
  95. // Handle extensions.
  96. var err error
  97. msgFields, err = o.appendExtensions(msgFields, knownFields)
  98. if !nerr.Merge(err) {
  99. return text.Value{}, err
  100. }
  101. // Handle unknown fields.
  102. // TODO: Provide option to exclude or include unknown fields.
  103. m.UnknownFields().Range(func(_ pref.FieldNumber, raw pref.RawFields) bool {
  104. msgFields = appendUnknown(msgFields, raw)
  105. return true
  106. })
  107. return text.ValueOf(msgFields), nerr.E
  108. }
  109. // appendField marshals a protoreflect.Value and appends it to the given [][2]text.Value.
  110. func (o MarshalOptions) appendField(msgFields [][2]text.Value, name text.Value, pval pref.Value, fd pref.FieldDescriptor) ([][2]text.Value, error) {
  111. var nerr errors.NonFatal
  112. if fd.Cardinality() == pref.Repeated {
  113. // Map or repeated fields.
  114. var items []text.Value
  115. var err error
  116. if fd.IsMap() {
  117. items, err = o.marshalMap(pval.Map(), fd)
  118. if !nerr.Merge(err) {
  119. return msgFields, err
  120. }
  121. } else {
  122. items, err = o.marshalList(pval.List(), fd)
  123. if !nerr.Merge(err) {
  124. return msgFields, err
  125. }
  126. }
  127. // Add each item as key: value field.
  128. for _, item := range items {
  129. msgFields = append(msgFields, [2]text.Value{name, item})
  130. }
  131. } else {
  132. // Required or optional fields.
  133. tval, err := o.marshalSingular(pval, fd)
  134. if !nerr.Merge(err) {
  135. return msgFields, err
  136. }
  137. msgFields = append(msgFields, [2]text.Value{name, tval})
  138. }
  139. return msgFields, nerr.E
  140. }
  141. // marshalSingular converts a non-repeated field value to text.Value.
  142. // This includes all scalar types, enums, messages, and groups.
  143. func (o MarshalOptions) marshalSingular(val pref.Value, fd pref.FieldDescriptor) (text.Value, error) {
  144. kind := fd.Kind()
  145. switch kind {
  146. case pref.BoolKind,
  147. pref.Int32Kind, pref.Sint32Kind, pref.Uint32Kind,
  148. pref.Int64Kind, pref.Sint64Kind, pref.Uint64Kind,
  149. pref.Sfixed32Kind, pref.Fixed32Kind,
  150. pref.Sfixed64Kind, pref.Fixed64Kind,
  151. pref.FloatKind, pref.DoubleKind,
  152. pref.StringKind, pref.BytesKind:
  153. return text.ValueOf(val.Interface()), nil
  154. case pref.EnumKind:
  155. num := val.Enum()
  156. if desc := fd.EnumType().Values().ByNumber(num); desc != nil {
  157. return text.ValueOf(desc.Name()), nil
  158. }
  159. // Use numeric value if there is no enum description.
  160. return text.ValueOf(int32(num)), nil
  161. case pref.MessageKind, pref.GroupKind:
  162. return o.marshalMessage(val.Message())
  163. }
  164. return text.Value{}, errors.New("%v has unknown kind: %v", fd.FullName(), kind)
  165. }
  166. // marshalList converts a protoreflect.List to []text.Value.
  167. func (o MarshalOptions) marshalList(list pref.List, fd pref.FieldDescriptor) ([]text.Value, error) {
  168. var nerr errors.NonFatal
  169. size := list.Len()
  170. values := make([]text.Value, 0, size)
  171. for i := 0; i < size; i++ {
  172. item := list.Get(i)
  173. val, err := o.marshalSingular(item, fd)
  174. if !nerr.Merge(err) {
  175. // Return already marshaled values.
  176. return values, err
  177. }
  178. values = append(values, val)
  179. }
  180. return values, nerr.E
  181. }
  182. var (
  183. mapKeyName = text.ValueOf(pref.Name("key"))
  184. mapValueName = text.ValueOf(pref.Name("value"))
  185. )
  186. // marshalMap converts a protoreflect.Map to []text.Value.
  187. func (o MarshalOptions) marshalMap(mmap pref.Map, fd pref.FieldDescriptor) ([]text.Value, error) {
  188. var nerr errors.NonFatal
  189. // values is a list of messages.
  190. values := make([]text.Value, 0, mmap.Len())
  191. msgFields := fd.MessageType().Fields()
  192. keyType := msgFields.ByNumber(1)
  193. valType := msgFields.ByNumber(2)
  194. mmap.Range(func(key pref.MapKey, val pref.Value) bool {
  195. keyTxtVal, err := o.marshalSingular(key.Value(), keyType)
  196. if !nerr.Merge(err) {
  197. return false
  198. }
  199. valTxtVal, err := o.marshalSingular(val, valType)
  200. if !nerr.Merge(err) {
  201. return false
  202. }
  203. // Map entry (message) contains 2 fields, first field for key and second field for value.
  204. msg := text.ValueOf([][2]text.Value{
  205. {mapKeyName, keyTxtVal},
  206. {mapValueName, valTxtVal},
  207. })
  208. values = append(values, msg)
  209. return true
  210. })
  211. sortMap(keyType.Kind(), values)
  212. return values, nerr.E
  213. }
  214. // sortMap orders list based on value of key field for deterministic output.
  215. // TODO: Improve sort comparison of text.Value for map keys.
  216. func sortMap(keyKind pref.Kind, values []text.Value) {
  217. less := func(i, j int) bool {
  218. mi := values[i].Message()
  219. mj := values[j].Message()
  220. return mi[0][1].String() < mj[0][1].String()
  221. }
  222. switch keyKind {
  223. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  224. less = func(i, j int) bool {
  225. mi := values[i].Message()
  226. mj := values[j].Message()
  227. ni, _ := mi[0][1].Int(false)
  228. nj, _ := mj[0][1].Int(false)
  229. return ni < nj
  230. }
  231. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  232. less = func(i, j int) bool {
  233. mi := values[i].Message()
  234. mj := values[j].Message()
  235. ni, _ := mi[0][1].Int(true)
  236. nj, _ := mj[0][1].Int(true)
  237. return ni < nj
  238. }
  239. case pref.Uint32Kind, pref.Fixed32Kind:
  240. less = func(i, j int) bool {
  241. mi := values[i].Message()
  242. mj := values[j].Message()
  243. ni, _ := mi[0][1].Uint(false)
  244. nj, _ := mj[0][1].Uint(false)
  245. return ni < nj
  246. }
  247. case pref.Uint64Kind, pref.Fixed64Kind:
  248. less = func(i, j int) bool {
  249. mi := values[i].Message()
  250. mj := values[j].Message()
  251. ni, _ := mi[0][1].Uint(true)
  252. nj, _ := mj[0][1].Uint(true)
  253. return ni < nj
  254. }
  255. }
  256. sort.Slice(values, less)
  257. }
  258. // appendExtensions marshals extension fields and appends them to the given [][2]text.Value.
  259. func (o MarshalOptions) appendExtensions(msgFields [][2]text.Value, knownFields pref.KnownFields) ([][2]text.Value, error) {
  260. var nerr errors.NonFatal
  261. xtTypes := knownFields.ExtensionTypes()
  262. xtFields := make([][2]text.Value, 0, xtTypes.Len())
  263. var err error
  264. xtTypes.Range(func(xt pref.ExtensionType) bool {
  265. name := xt.FullName()
  266. // If extended type is a MessageSet, set field name to be the message type name.
  267. if isMessageSetExtension(xt) {
  268. name = xt.MessageType().FullName()
  269. }
  270. num := xt.Number()
  271. if knownFields.Has(num) {
  272. // Use string type to produce [name] format.
  273. tname := text.ValueOf(string(name))
  274. pval := knownFields.Get(num)
  275. xtFields, err = o.appendField(xtFields, tname, pval, xt)
  276. if err != nil {
  277. return false
  278. }
  279. }
  280. return true
  281. })
  282. if !nerr.Merge(err) {
  283. return msgFields, err
  284. }
  285. // Sort extensions lexicographically and append to output.
  286. sort.SliceStable(xtFields, func(i, j int) bool {
  287. return xtFields[i][0].String() < xtFields[j][0].String()
  288. })
  289. return append(msgFields, xtFields...), nerr.E
  290. }
  291. // isMessageSetExtension reports whether extension extends a message set.
  292. func isMessageSetExtension(xt pref.ExtensionType) bool {
  293. if xt.Name() != "message_set_extension" {
  294. return false
  295. }
  296. mt := xt.MessageType()
  297. if mt == nil {
  298. return false
  299. }
  300. if xt.FullName().Parent() != mt.FullName() {
  301. return false
  302. }
  303. xmt := xt.ExtendedType()
  304. if xmt.Fields().Len() != 0 {
  305. return false
  306. }
  307. opt := xmt.Options().(*descpb.MessageOptions)
  308. if opt == nil {
  309. return false
  310. }
  311. return opt.GetMessageSetWireFormat()
  312. }
  313. // appendUnknown parses the given []byte and appends field(s) into the given fields slice.
  314. // This function assumes proper encoding in the given []byte.
  315. func appendUnknown(fields [][2]text.Value, b []byte) [][2]text.Value {
  316. for len(b) > 0 {
  317. var value interface{}
  318. num, wtype, n := wire.ConsumeTag(b)
  319. b = b[n:]
  320. switch wtype {
  321. case wire.VarintType:
  322. value, n = wire.ConsumeVarint(b)
  323. case wire.Fixed32Type:
  324. value, n = wire.ConsumeFixed32(b)
  325. case wire.Fixed64Type:
  326. value, n = wire.ConsumeFixed64(b)
  327. case wire.BytesType:
  328. value, n = wire.ConsumeBytes(b)
  329. case wire.StartGroupType:
  330. var v []byte
  331. v, n = wire.ConsumeGroup(num, b)
  332. var msg [][2]text.Value
  333. value = appendUnknown(msg, v)
  334. default:
  335. panic(fmt.Sprintf("error parsing unknown field wire type: %v", wtype))
  336. }
  337. fields = append(fields, [2]text.Value{text.ValueOf(uint32(num)), text.ValueOf(value)})
  338. b = b[n:]
  339. }
  340. return fields
  341. }
  342. // marshalAny converts a google.protobuf.Any protoreflect.Message to a text.Value.
  343. func (o MarshalOptions) marshalAny(m pref.Message) (text.Value, error) {
  344. var nerr errors.NonFatal
  345. fds := m.Type().Fields()
  346. tfd := fds.ByName("type_url")
  347. if tfd == nil || tfd.Kind() != pref.StringKind {
  348. return text.Value{}, errors.New("invalid google.protobuf.Any message")
  349. }
  350. vfd := fds.ByName("value")
  351. if vfd == nil || vfd.Kind() != pref.BytesKind {
  352. return text.Value{}, errors.New("invalid google.protobuf.Any message")
  353. }
  354. knownFields := m.KnownFields()
  355. typeURL := knownFields.Get(tfd.Number()).String()
  356. value := knownFields.Get(vfd.Number())
  357. emt, err := o.Resolver.FindMessageByURL(typeURL)
  358. if !nerr.Merge(err) {
  359. return text.Value{}, err
  360. }
  361. em := emt.New().Interface()
  362. // TODO: Need to set types registry in binary unmarshaling.
  363. err = proto.Unmarshal(value.Bytes(), em)
  364. if !nerr.Merge(err) {
  365. return text.Value{}, err
  366. }
  367. msg, err := o.marshalMessage(em.ProtoReflect())
  368. if !nerr.Merge(err) {
  369. return text.Value{}, err
  370. }
  371. // Expanded Any field value contains only a single field with the type_url field value as the
  372. // field name in [] and a text marshaled field value of the embedded message.
  373. msgFields := [][2]text.Value{
  374. {
  375. text.ValueOf(typeURL),
  376. msg,
  377. },
  378. }
  379. return text.ValueOf(msgFields), nerr.E
  380. }