encode.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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 jsonpb
  5. import (
  6. "encoding/base64"
  7. "math"
  8. "sort"
  9. json "github.com/golang/protobuf/v2/internal/encoding/jsonx"
  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 JSON format using default options.
  16. func Marshal(m proto.Message) ([]byte, error) {
  17. return MarshalOptions{}.Marshal(m)
  18. }
  19. // MarshalOptions is a configurable JSON format marshaler.
  20. type MarshalOptions struct {
  21. pragma.NoUnkeyedLiterals
  22. // Set Compact to true to have output in a single line with no line breaks.
  23. Compact bool
  24. }
  25. // Marshal writes the given proto.Message in JSON format using options in MarshalOptions object.
  26. func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) {
  27. var nerr errors.NonFatal
  28. v, err := o.marshalMessage(m.ProtoReflect())
  29. if !nerr.Merge(err) {
  30. return nil, err
  31. }
  32. indent := " "
  33. if o.Compact {
  34. indent = ""
  35. }
  36. b, err := json.Marshal(v, indent)
  37. if !nerr.Merge(err) {
  38. return nil, err
  39. }
  40. return b, nerr.E
  41. }
  42. // marshalMessage converts a protoreflect.Message to a json.Value.
  43. func (o MarshalOptions) marshalMessage(m pref.Message) (json.Value, error) {
  44. var nerr errors.NonFatal
  45. var msgFields [][2]json.Value
  46. msgType := m.Type()
  47. fieldDescs := msgType.Fields()
  48. knownFields := m.KnownFields()
  49. size := fieldDescs.Len()
  50. for i := 0; i < size; i++ {
  51. fd := fieldDescs.Get(i)
  52. num := fd.Number()
  53. if !knownFields.Has(num) {
  54. if fd.Cardinality() == pref.Required {
  55. // Treat unset required fields as a non-fatal error.
  56. nerr.AppendRequiredNotSet(string(fd.FullName()))
  57. }
  58. continue
  59. }
  60. name := json.ValueOf(fd.JSONName())
  61. pval := knownFields.Get(num)
  62. var err error
  63. msgFields, err = o.appendField(msgFields, name, pval, fd)
  64. if !nerr.Merge(err) {
  65. return json.Value{}, err
  66. }
  67. }
  68. return json.ValueOf(msgFields), nerr.E
  69. }
  70. // appendField marshals a protoreflect.Value and appends it to the given
  71. // [][2]json.Value.
  72. func (o MarshalOptions) appendField(msgFields [][2]json.Value, name json.Value, pval pref.Value, fd pref.FieldDescriptor) ([][2]json.Value, error) {
  73. var nerr errors.NonFatal
  74. var jval json.Value
  75. var err error
  76. if fd.Cardinality() == pref.Repeated {
  77. // Map or repeated fields.
  78. if fd.IsMap() {
  79. jval, err = o.marshalMap(pval.Map(), fd)
  80. if !nerr.Merge(err) {
  81. return msgFields, err
  82. }
  83. } else {
  84. jval, err = o.marshalList(pval.List(), fd)
  85. if !nerr.Merge(err) {
  86. return msgFields, err
  87. }
  88. }
  89. } else {
  90. // Required or optional fields.
  91. jval, err = o.marshalSingular(pval, fd)
  92. if !nerr.Merge(err) {
  93. return msgFields, err
  94. }
  95. }
  96. msgFields = append(msgFields, [2]json.Value{name, jval})
  97. return msgFields, nerr.E
  98. }
  99. // marshalSingular converts a non-repeated field value to json.Value.
  100. // This includes all scalar types, enums, messages, and groups.
  101. func (o MarshalOptions) marshalSingular(val pref.Value, fd pref.FieldDescriptor) (json.Value, error) {
  102. kind := fd.Kind()
  103. switch kind {
  104. case pref.BoolKind, pref.StringKind,
  105. pref.Int32Kind, pref.Sint32Kind, pref.Uint32Kind,
  106. pref.Sfixed32Kind, pref.Fixed32Kind:
  107. return json.ValueOf(val.Interface()), nil
  108. case pref.Int64Kind, pref.Sint64Kind, pref.Uint64Kind,
  109. pref.Sfixed64Kind, pref.Fixed64Kind:
  110. return json.ValueOf(val.String()), nil
  111. case pref.FloatKind, pref.DoubleKind:
  112. n := val.Float()
  113. switch {
  114. case math.IsNaN(n):
  115. return json.ValueOf("NaN"), nil
  116. case math.IsInf(n, +1):
  117. return json.ValueOf("Infinity"), nil
  118. case math.IsInf(n, -1):
  119. return json.ValueOf("-Infinity"), nil
  120. default:
  121. return json.ValueOf(n), nil
  122. }
  123. case pref.BytesKind:
  124. return json.ValueOf(base64.StdEncoding.EncodeToString(val.Bytes())), nil
  125. case pref.EnumKind:
  126. num := val.Enum()
  127. if desc := fd.EnumType().Values().ByNumber(num); desc != nil {
  128. return json.ValueOf(string(desc.Name())), nil
  129. }
  130. // Use numeric value if there is no enum value descriptor.
  131. return json.ValueOf(int32(num)), nil
  132. case pref.MessageKind, pref.GroupKind:
  133. return o.marshalMessage(val.Message())
  134. }
  135. return json.Value{}, errors.New("%v has unknown kind: %v", fd.FullName(), kind)
  136. }
  137. // marshalList converts a protoreflect.List to json.Value.
  138. func (o MarshalOptions) marshalList(list pref.List, fd pref.FieldDescriptor) (json.Value, error) {
  139. var nerr errors.NonFatal
  140. size := list.Len()
  141. values := make([]json.Value, 0, size)
  142. for i := 0; i < size; i++ {
  143. item := list.Get(i)
  144. val, err := o.marshalSingular(item, fd)
  145. if !nerr.Merge(err) {
  146. return json.Value{}, err
  147. }
  148. values = append(values, val)
  149. }
  150. return json.ValueOf(values), nerr.E
  151. }
  152. type mapEntry struct {
  153. key pref.MapKey
  154. value pref.Value
  155. }
  156. // marshalMap converts a protoreflect.Map to json.Value.
  157. func (o MarshalOptions) marshalMap(mmap pref.Map, fd pref.FieldDescriptor) (json.Value, error) {
  158. msgFields := fd.MessageType().Fields()
  159. keyType := msgFields.ByNumber(1)
  160. valType := msgFields.ByNumber(2)
  161. // Get a sorted list based on keyType first.
  162. entries := make([]mapEntry, 0, mmap.Len())
  163. mmap.Range(func(key pref.MapKey, val pref.Value) bool {
  164. entries = append(entries, mapEntry{key: key, value: val})
  165. return true
  166. })
  167. sortMap(keyType.Kind(), entries)
  168. // Convert to list of [2]json.Value.
  169. var nerr errors.NonFatal
  170. values := make([][2]json.Value, 0, len(entries))
  171. for _, entry := range entries {
  172. jkey := json.ValueOf(entry.key.String())
  173. jval, err := o.marshalSingular(entry.value, valType)
  174. if !nerr.Merge(err) {
  175. return json.Value{}, err
  176. }
  177. values = append(values, [2]json.Value{jkey, jval})
  178. }
  179. return json.ValueOf(values), nerr.E
  180. }
  181. // sortMap orders list based on value of key field for deterministic output.
  182. func sortMap(keyKind pref.Kind, values []mapEntry) {
  183. less := func(i, j int) bool {
  184. return values[i].key.String() < values[j].key.String()
  185. }
  186. switch keyKind {
  187. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind,
  188. pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  189. less = func(i, j int) bool {
  190. return values[i].key.Int() < values[j].key.Int()
  191. }
  192. case pref.Uint32Kind, pref.Fixed32Kind,
  193. pref.Uint64Kind, pref.Fixed64Kind:
  194. less = func(i, j int) bool {
  195. return values[i].key.Uint() < values[j].key.Uint()
  196. }
  197. }
  198. sort.Slice(values, less)
  199. }