encode.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. )
  15. // Marshal writes the given proto.Message in textproto format using default options.
  16. // TODO: may want to describe when Marshal returns error.
  17. func Marshal(m proto.Message) ([]byte, error) {
  18. return MarshalOptions{}.Marshal(m)
  19. }
  20. // MarshalOptions is a configurable text format marshaler.
  21. type MarshalOptions struct {
  22. pragma.NoUnkeyedLiterals
  23. // Set Compact to true to have output in a single line with no line breaks.
  24. Compact bool
  25. }
  26. // Marshal writes the given proto.Message in textproto format using options in MarshalOptions object.
  27. func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) {
  28. var nerr errors.NonFatal
  29. var v text.Value
  30. var err error
  31. v, err = o.marshalMessage(m.ProtoReflect())
  32. if !nerr.Merge(err) {
  33. return nil, err
  34. }
  35. indent := " "
  36. if o.Compact {
  37. indent = ""
  38. }
  39. delims := [2]byte{'{', '}'}
  40. const outputASCII = false
  41. b, err := text.Marshal(v, indent, delims, outputASCII)
  42. if !nerr.Merge(err) {
  43. return nil, err
  44. }
  45. return b, nerr.E
  46. }
  47. // marshalMessage converts a protoreflect.Message to a text.Value.
  48. func (o MarshalOptions) marshalMessage(m pref.Message) (text.Value, error) {
  49. var nerr errors.NonFatal
  50. var msgFields [][2]text.Value
  51. // Handle known fields.
  52. msgType := m.Type()
  53. fieldDescs := msgType.Fields()
  54. knownFields := m.KnownFields()
  55. size := fieldDescs.Len()
  56. for i := 0; i < size; i++ {
  57. fd := fieldDescs.Get(i)
  58. num := fd.Number()
  59. if !knownFields.Has(num) {
  60. if fd.Cardinality() == pref.Required {
  61. // Treat unset required fields as a non-fatal error.
  62. nerr.AppendRequiredNotSet(string(fd.FullName()))
  63. }
  64. continue
  65. }
  66. tname := text.ValueOf(fd.Name())
  67. pval := knownFields.Get(num)
  68. if fd.Cardinality() == pref.Repeated {
  69. // Map or repeated fields.
  70. var items []text.Value
  71. var err error
  72. if fd.IsMap() {
  73. items, err = o.marshalMap(pval.Map(), fd)
  74. if !nerr.Merge(err) {
  75. return text.Value{}, err
  76. }
  77. } else {
  78. items, err = o.marshalList(pval.List(), fd)
  79. if !nerr.Merge(err) {
  80. return text.Value{}, err
  81. }
  82. }
  83. // Add each item as key: value field.
  84. for _, item := range items {
  85. msgFields = append(msgFields, [2]text.Value{tname, item})
  86. }
  87. } else {
  88. // Required or optional fields.
  89. tval, err := o.marshalSingular(pval, fd)
  90. if !nerr.Merge(err) {
  91. return text.Value{}, err
  92. }
  93. msgFields = append(msgFields, [2]text.Value{tname, tval})
  94. }
  95. }
  96. // Marshal out unknown fields.
  97. // TODO: Provide option to exclude or include unknown fields.
  98. m.UnknownFields().Range(func(_ pref.FieldNumber, raw pref.RawFields) bool {
  99. msgFields = appendUnknown(msgFields, raw)
  100. return true
  101. })
  102. // TODO: Handle extensions and Any expansion.
  103. return text.ValueOf(msgFields), nerr.E
  104. }
  105. // marshalSingular converts a non-repeated field value to text.Value.
  106. // This includes all scalar types, enums, messages, and groups.
  107. func (o MarshalOptions) marshalSingular(val pref.Value, fd pref.FieldDescriptor) (text.Value, error) {
  108. kind := fd.Kind()
  109. switch kind {
  110. case pref.BoolKind,
  111. pref.Int32Kind, pref.Sint32Kind, pref.Uint32Kind,
  112. pref.Int64Kind, pref.Sint64Kind, pref.Uint64Kind,
  113. pref.Sfixed32Kind, pref.Fixed32Kind,
  114. pref.Sfixed64Kind, pref.Fixed64Kind,
  115. pref.FloatKind, pref.DoubleKind,
  116. pref.StringKind, pref.BytesKind:
  117. return text.ValueOf(val.Interface()), nil
  118. case pref.EnumKind:
  119. num := val.Enum()
  120. if desc := fd.EnumType().Values().ByNumber(num); desc != nil {
  121. return text.ValueOf(desc.Name()), nil
  122. }
  123. // Use numeric value if there is no enum description.
  124. return text.ValueOf(int32(num)), nil
  125. case pref.MessageKind, pref.GroupKind:
  126. return o.marshalMessage(val.Message())
  127. }
  128. return text.Value{}, errors.New("%v has unknown kind: %v", fd.FullName(), kind)
  129. }
  130. // marshalList converts a protoreflect.List to []text.Value.
  131. func (o MarshalOptions) marshalList(list pref.List, fd pref.FieldDescriptor) ([]text.Value, error) {
  132. var nerr errors.NonFatal
  133. size := list.Len()
  134. values := make([]text.Value, 0, size)
  135. for i := 0; i < size; i++ {
  136. item := list.Get(i)
  137. val, err := o.marshalSingular(item, fd)
  138. if !nerr.Merge(err) {
  139. // Return already marshaled values.
  140. return values, err
  141. }
  142. values = append(values, val)
  143. }
  144. return values, nerr.E
  145. }
  146. var (
  147. mapKeyName = text.ValueOf(pref.Name("key"))
  148. mapValueName = text.ValueOf(pref.Name("value"))
  149. )
  150. // marshalMap converts a protoreflect.Map to []text.Value.
  151. func (o MarshalOptions) marshalMap(mmap pref.Map, fd pref.FieldDescriptor) ([]text.Value, error) {
  152. var nerr errors.NonFatal
  153. // values is a list of messages.
  154. values := make([]text.Value, 0, mmap.Len())
  155. msgFields := fd.MessageType().Fields()
  156. keyType := msgFields.ByNumber(1)
  157. valType := msgFields.ByNumber(2)
  158. mmap.Range(func(key pref.MapKey, val pref.Value) bool {
  159. keyTxtVal, err := o.marshalSingular(key.Value(), keyType)
  160. if !nerr.Merge(err) {
  161. return false
  162. }
  163. valTxtVal, err := o.marshalSingular(val, valType)
  164. if !nerr.Merge(err) {
  165. return false
  166. }
  167. // Map entry (message) contains 2 fields, first field for key and second field for value.
  168. msg := text.ValueOf([][2]text.Value{
  169. {mapKeyName, keyTxtVal},
  170. {mapValueName, valTxtVal},
  171. })
  172. values = append(values, msg)
  173. return true
  174. })
  175. sortMap(keyType.Kind(), values)
  176. return values, nerr.E
  177. }
  178. // sortMap orders list based on value of key field for deterministic output.
  179. // TODO: Improve sort comparison of text.Value for map keys.
  180. func sortMap(keyKind pref.Kind, values []text.Value) {
  181. less := func(i, j int) bool {
  182. mi := values[i].Message()
  183. mj := values[j].Message()
  184. return mi[0][1].String() < mj[0][1].String()
  185. }
  186. switch keyKind {
  187. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  188. less = func(i, j int) bool {
  189. mi := values[i].Message()
  190. mj := values[j].Message()
  191. ni, _ := mi[0][1].Int(false)
  192. nj, _ := mj[0][1].Int(false)
  193. return ni < nj
  194. }
  195. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  196. less = func(i, j int) bool {
  197. mi := values[i].Message()
  198. mj := values[j].Message()
  199. ni, _ := mi[0][1].Int(true)
  200. nj, _ := mj[0][1].Int(true)
  201. return ni < nj
  202. }
  203. case pref.Uint32Kind, pref.Fixed32Kind:
  204. less = func(i, j int) bool {
  205. mi := values[i].Message()
  206. mj := values[j].Message()
  207. ni, _ := mi[0][1].Uint(false)
  208. nj, _ := mj[0][1].Uint(false)
  209. return ni < nj
  210. }
  211. case pref.Uint64Kind, pref.Fixed64Kind:
  212. less = func(i, j int) bool {
  213. mi := values[i].Message()
  214. mj := values[j].Message()
  215. ni, _ := mi[0][1].Uint(true)
  216. nj, _ := mj[0][1].Uint(true)
  217. return ni < nj
  218. }
  219. }
  220. sort.Slice(values, less)
  221. }
  222. // appendUnknown parses the given []byte and appends field(s) into the given fields slice.
  223. // This function assumes proper encoding in the given []byte.
  224. func appendUnknown(fields [][2]text.Value, b []byte) [][2]text.Value {
  225. for len(b) > 0 {
  226. var value interface{}
  227. num, wtype, n := wire.ConsumeTag(b)
  228. b = b[n:]
  229. switch wtype {
  230. case wire.VarintType:
  231. value, n = wire.ConsumeVarint(b)
  232. case wire.Fixed32Type:
  233. value, n = wire.ConsumeFixed32(b)
  234. case wire.Fixed64Type:
  235. value, n = wire.ConsumeFixed64(b)
  236. case wire.BytesType:
  237. value, n = wire.ConsumeBytes(b)
  238. case wire.StartGroupType:
  239. var v []byte
  240. v, n = wire.ConsumeGroup(num, b)
  241. var msg [][2]text.Value
  242. value = appendUnknown(msg, v)
  243. default:
  244. panic(fmt.Sprintf("error parsing unknown field wire type: %v", wtype))
  245. }
  246. fields = append(fields, [2]text.Value{text.ValueOf(uint32(num)), text.ValueOf(value)})
  247. b = b[n:]
  248. }
  249. return fields
  250. }