decode.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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. "fmt"
  8. "math"
  9. "strconv"
  10. "strings"
  11. "github.com/golang/protobuf/v2/internal/encoding/json"
  12. "github.com/golang/protobuf/v2/internal/errors"
  13. "github.com/golang/protobuf/v2/internal/pragma"
  14. "github.com/golang/protobuf/v2/internal/set"
  15. "github.com/golang/protobuf/v2/proto"
  16. pref "github.com/golang/protobuf/v2/reflect/protoreflect"
  17. "github.com/golang/protobuf/v2/reflect/protoregistry"
  18. )
  19. // Unmarshal reads the given []byte into the given proto.Message.
  20. func Unmarshal(m proto.Message, b []byte) error {
  21. return UnmarshalOptions{}.Unmarshal(m, b)
  22. }
  23. // UnmarshalOptions is a configurable JSON format parser.
  24. type UnmarshalOptions struct {
  25. pragma.NoUnkeyedLiterals
  26. // If AllowPartial is set, input for messages that will result in missing
  27. // required fields will not return an error.
  28. AllowPartial bool
  29. // If DiscardUnknown is set, unknown fields are ignored.
  30. DiscardUnknown bool
  31. // Resolver is the registry used for type lookups when unmarshaling extensions
  32. // and processing Any. If Resolver is not set, unmarshaling will default to
  33. // using protoregistry.GlobalTypes.
  34. Resolver *protoregistry.Types
  35. decoder *json.Decoder
  36. }
  37. // Unmarshal reads the given []byte and populates the given proto.Message using
  38. // options in UnmarshalOptions object. It will clear the message first before
  39. // setting the fields. If it returns an error, the given message may be
  40. // partially set.
  41. func (o UnmarshalOptions) Unmarshal(m proto.Message, b []byte) error {
  42. mr := m.ProtoReflect()
  43. // TODO: Determine if we would like to have an option for merging or only
  44. // have merging behavior. We should at least be consistent with textproto
  45. // marshaling.
  46. resetMessage(mr)
  47. if o.Resolver == nil {
  48. o.Resolver = protoregistry.GlobalTypes
  49. }
  50. o.decoder = json.NewDecoder(b)
  51. var nerr errors.NonFatal
  52. if err := o.unmarshalMessage(mr, false); !nerr.Merge(err) {
  53. return err
  54. }
  55. // Check for EOF.
  56. val, err := o.decoder.Read()
  57. if err != nil {
  58. return err
  59. }
  60. if val.Type() != json.EOF {
  61. return unexpectedJSONError{val}
  62. }
  63. if !o.AllowPartial {
  64. nerr.Merge(proto.IsInitialized(m))
  65. }
  66. return nerr.E
  67. }
  68. // resetMessage clears all fields of given protoreflect.Message.
  69. func resetMessage(m pref.Message) {
  70. knownFields := m.KnownFields()
  71. knownFields.Range(func(num pref.FieldNumber, _ pref.Value) bool {
  72. knownFields.Clear(num)
  73. return true
  74. })
  75. unknownFields := m.UnknownFields()
  76. unknownFields.Range(func(num pref.FieldNumber, _ pref.RawFields) bool {
  77. unknownFields.Set(num, nil)
  78. return true
  79. })
  80. extTypes := knownFields.ExtensionTypes()
  81. extTypes.Range(func(xt pref.ExtensionType) bool {
  82. extTypes.Remove(xt)
  83. return true
  84. })
  85. }
  86. // unexpectedJSONError is an error that contains the unexpected json.Value. This
  87. // is returned by methods to provide callers the read json.Value that it did not
  88. // expect.
  89. // TODO: Consider moving this to internal/encoding/json for consistency with
  90. // errors that package returns.
  91. type unexpectedJSONError struct {
  92. value json.Value
  93. }
  94. func (e unexpectedJSONError) Error() string {
  95. return newError("unexpected value %s", e.value).Error()
  96. }
  97. // newError returns an error object. If one of the values passed in is of
  98. // json.Value type, it produces an error with position info.
  99. func newError(f string, x ...interface{}) error {
  100. var hasValue bool
  101. var line, column int
  102. for i := 0; i < len(x); i++ {
  103. if val, ok := x[i].(json.Value); ok {
  104. line, column = val.Position()
  105. hasValue = true
  106. break
  107. }
  108. }
  109. e := errors.New(f, x...)
  110. if hasValue {
  111. return errors.New("(line %d:%d): %v", line, column, e)
  112. }
  113. return e
  114. }
  115. // unmarshalMessage unmarshals a message into the given protoreflect.Message.
  116. func (o UnmarshalOptions) unmarshalMessage(m pref.Message, skipTypeURL bool) error {
  117. var nerr errors.NonFatal
  118. if isCustomType(m.Type().FullName()) {
  119. return o.unmarshalCustomType(m)
  120. }
  121. jval, err := o.decoder.Read()
  122. if !nerr.Merge(err) {
  123. return err
  124. }
  125. if jval.Type() != json.StartObject {
  126. return unexpectedJSONError{jval}
  127. }
  128. if err := o.unmarshalFields(m, skipTypeURL); !nerr.Merge(err) {
  129. return err
  130. }
  131. return nerr.E
  132. }
  133. // unmarshalFields unmarshals the fields into the given protoreflect.Message.
  134. func (o UnmarshalOptions) unmarshalFields(m pref.Message, skipTypeURL bool) error {
  135. var nerr errors.NonFatal
  136. var seenNums set.Ints
  137. var seenOneofs set.Ints
  138. msgType := m.Type()
  139. knownFields := m.KnownFields()
  140. fieldDescs := msgType.Fields()
  141. xtTypes := knownFields.ExtensionTypes()
  142. Loop:
  143. for {
  144. // Read field name.
  145. jval, err := o.decoder.Read()
  146. if !nerr.Merge(err) {
  147. return err
  148. }
  149. switch jval.Type() {
  150. default:
  151. return unexpectedJSONError{jval}
  152. case json.EndObject:
  153. break Loop
  154. case json.Name:
  155. // Continue below.
  156. }
  157. name, err := jval.Name()
  158. if !nerr.Merge(err) {
  159. return err
  160. }
  161. // Unmarshaling a non-custom embedded message in Any will contain the
  162. // JSON field "@type" which should be skipped because it is not a field
  163. // of the embedded message, but simply an artifact of the Any format.
  164. if skipTypeURL && name == "@type" {
  165. o.decoder.Read()
  166. continue
  167. }
  168. // Get the FieldDescriptor.
  169. var fd pref.FieldDescriptor
  170. if strings.HasPrefix(name, "[") && strings.HasSuffix(name, "]") {
  171. // Only extension names are in [name] format.
  172. xtName := pref.FullName(name[1 : len(name)-1])
  173. xt := xtTypes.ByName(xtName)
  174. if xt == nil {
  175. xt, err = o.findExtension(xtName)
  176. if err != nil && err != protoregistry.NotFound {
  177. return errors.New("unable to resolve [%v]: %v", xtName, err)
  178. }
  179. if xt != nil {
  180. xtTypes.Register(xt)
  181. }
  182. }
  183. fd = xt
  184. } else {
  185. // The name can either be the JSON name or the proto field name.
  186. fd = fieldDescs.ByJSONName(name)
  187. if fd == nil {
  188. fd = fieldDescs.ByName(pref.Name(name))
  189. }
  190. }
  191. if fd == nil {
  192. // Field is unknown.
  193. if o.DiscardUnknown {
  194. if err := skipJSONValue(o.decoder); !nerr.Merge(err) {
  195. return err
  196. }
  197. continue
  198. }
  199. return newError("%v contains unknown field %s", msgType.FullName(), jval)
  200. }
  201. // Do not allow duplicate fields.
  202. num := uint64(fd.Number())
  203. if seenNums.Has(num) {
  204. return newError("%v contains repeated field %s", msgType.FullName(), jval)
  205. }
  206. seenNums.Set(num)
  207. // No need to set values for JSON null unless the field type is
  208. // google.protobuf.Value or google.protobuf.NullValue.
  209. if o.decoder.Peek() == json.Null && !isKnownValue(fd) && !isNullValue(fd) {
  210. o.decoder.Read()
  211. continue
  212. }
  213. if cardinality := fd.Cardinality(); cardinality == pref.Repeated {
  214. // Map or list fields have cardinality of repeated.
  215. if err := o.unmarshalRepeated(knownFields, fd); !nerr.Merge(err) {
  216. return errors.New("%v|%q: %v", fd.FullName(), name, err)
  217. }
  218. } else {
  219. // If field is a oneof, check if it has already been set.
  220. if od := fd.Oneof(); od != nil {
  221. idx := uint64(od.Index())
  222. if seenOneofs.Has(idx) {
  223. return errors.New("%v: oneof is already set", od.FullName())
  224. }
  225. seenOneofs.Set(idx)
  226. }
  227. // Required or optional fields.
  228. if err := o.unmarshalSingular(knownFields, fd); !nerr.Merge(err) {
  229. return errors.New("%v|%q: %v", fd.FullName(), name, err)
  230. }
  231. }
  232. }
  233. return nerr.E
  234. }
  235. // findExtension returns protoreflect.ExtensionType from the resolver if found.
  236. func (o UnmarshalOptions) findExtension(xtName pref.FullName) (pref.ExtensionType, error) {
  237. xt, err := o.Resolver.FindExtensionByName(xtName)
  238. if err == nil {
  239. return xt, nil
  240. }
  241. // Check if this is a MessageSet extension field.
  242. xt, err = o.Resolver.FindExtensionByName(xtName + ".message_set_extension")
  243. if err == nil && isMessageSetExtension(xt) {
  244. return xt, nil
  245. }
  246. return nil, protoregistry.NotFound
  247. }
  248. func isKnownValue(fd pref.FieldDescriptor) bool {
  249. md := fd.Message()
  250. return md != nil && md.FullName() == "google.protobuf.Value"
  251. }
  252. func isNullValue(fd pref.FieldDescriptor) bool {
  253. ed := fd.Enum()
  254. return ed != nil && ed.FullName() == "google.protobuf.NullValue"
  255. }
  256. // unmarshalSingular unmarshals to the non-repeated field specified by the given
  257. // FieldDescriptor.
  258. func (o UnmarshalOptions) unmarshalSingular(knownFields pref.KnownFields, fd pref.FieldDescriptor) error {
  259. var val pref.Value
  260. var err error
  261. num := fd.Number()
  262. switch fd.Kind() {
  263. case pref.MessageKind, pref.GroupKind:
  264. m := knownFields.NewMessage(num)
  265. err = o.unmarshalMessage(m, false)
  266. val = pref.ValueOf(m)
  267. default:
  268. val, err = o.unmarshalScalar(fd)
  269. }
  270. var nerr errors.NonFatal
  271. if !nerr.Merge(err) {
  272. return err
  273. }
  274. knownFields.Set(num, val)
  275. return nerr.E
  276. }
  277. // unmarshalScalar unmarshals to a scalar/enum protoreflect.Value specified by
  278. // the given FieldDescriptor.
  279. func (o UnmarshalOptions) unmarshalScalar(fd pref.FieldDescriptor) (pref.Value, error) {
  280. const b32 int = 32
  281. const b64 int = 64
  282. var nerr errors.NonFatal
  283. jval, err := o.decoder.Read()
  284. if !nerr.Merge(err) {
  285. return pref.Value{}, err
  286. }
  287. kind := fd.Kind()
  288. switch kind {
  289. case pref.BoolKind:
  290. return unmarshalBool(jval)
  291. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  292. return unmarshalInt(jval, b32)
  293. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  294. return unmarshalInt(jval, b64)
  295. case pref.Uint32Kind, pref.Fixed32Kind:
  296. return unmarshalUint(jval, b32)
  297. case pref.Uint64Kind, pref.Fixed64Kind:
  298. return unmarshalUint(jval, b64)
  299. case pref.FloatKind:
  300. return unmarshalFloat(jval, b32)
  301. case pref.DoubleKind:
  302. return unmarshalFloat(jval, b64)
  303. case pref.StringKind:
  304. pval, err := unmarshalString(jval)
  305. if !nerr.Merge(err) {
  306. return pval, err
  307. }
  308. return pval, nerr.E
  309. case pref.BytesKind:
  310. return unmarshalBytes(jval)
  311. case pref.EnumKind:
  312. return unmarshalEnum(jval, fd)
  313. }
  314. panic(fmt.Sprintf("invalid scalar kind %v", kind))
  315. }
  316. func unmarshalBool(jval json.Value) (pref.Value, error) {
  317. if jval.Type() != json.Bool {
  318. return pref.Value{}, unexpectedJSONError{jval}
  319. }
  320. b, err := jval.Bool()
  321. return pref.ValueOf(b), err
  322. }
  323. func unmarshalInt(jval json.Value, bitSize int) (pref.Value, error) {
  324. switch jval.Type() {
  325. case json.Number:
  326. return getInt(jval, bitSize)
  327. case json.String:
  328. // Decode number from string.
  329. s := strings.TrimSpace(jval.String())
  330. if len(s) != len(jval.String()) {
  331. return pref.Value{}, errors.New("invalid number %v", jval.Raw())
  332. }
  333. dec := json.NewDecoder([]byte(s))
  334. var nerr errors.NonFatal
  335. jval, err := dec.Read()
  336. if !nerr.Merge(err) {
  337. return pref.Value{}, err
  338. }
  339. return getInt(jval, bitSize)
  340. }
  341. return pref.Value{}, unexpectedJSONError{jval}
  342. }
  343. func getInt(jval json.Value, bitSize int) (pref.Value, error) {
  344. n, err := jval.Int(bitSize)
  345. if err != nil {
  346. return pref.Value{}, err
  347. }
  348. if bitSize == 32 {
  349. return pref.ValueOf(int32(n)), nil
  350. }
  351. return pref.ValueOf(n), nil
  352. }
  353. func unmarshalUint(jval json.Value, bitSize int) (pref.Value, error) {
  354. switch jval.Type() {
  355. case json.Number:
  356. return getUint(jval, bitSize)
  357. case json.String:
  358. // Decode number from string.
  359. s := strings.TrimSpace(jval.String())
  360. if len(s) != len(jval.String()) {
  361. return pref.Value{}, errors.New("invalid number %v", jval.Raw())
  362. }
  363. dec := json.NewDecoder([]byte(s))
  364. var nerr errors.NonFatal
  365. jval, err := dec.Read()
  366. if !nerr.Merge(err) {
  367. return pref.Value{}, err
  368. }
  369. return getUint(jval, bitSize)
  370. }
  371. return pref.Value{}, unexpectedJSONError{jval}
  372. }
  373. func getUint(jval json.Value, bitSize int) (pref.Value, error) {
  374. n, err := jval.Uint(bitSize)
  375. if err != nil {
  376. return pref.Value{}, err
  377. }
  378. if bitSize == 32 {
  379. return pref.ValueOf(uint32(n)), nil
  380. }
  381. return pref.ValueOf(n), nil
  382. }
  383. func unmarshalFloat(jval json.Value, bitSize int) (pref.Value, error) {
  384. switch jval.Type() {
  385. case json.Number:
  386. return getFloat(jval, bitSize)
  387. case json.String:
  388. s := jval.String()
  389. switch s {
  390. case "NaN":
  391. if bitSize == 32 {
  392. return pref.ValueOf(float32(math.NaN())), nil
  393. }
  394. return pref.ValueOf(math.NaN()), nil
  395. case "Infinity":
  396. if bitSize == 32 {
  397. return pref.ValueOf(float32(math.Inf(+1))), nil
  398. }
  399. return pref.ValueOf(math.Inf(+1)), nil
  400. case "-Infinity":
  401. if bitSize == 32 {
  402. return pref.ValueOf(float32(math.Inf(-1))), nil
  403. }
  404. return pref.ValueOf(math.Inf(-1)), nil
  405. }
  406. // Decode number from string.
  407. if len(s) != len(strings.TrimSpace(s)) {
  408. return pref.Value{}, errors.New("invalid number %v", jval.Raw())
  409. }
  410. dec := json.NewDecoder([]byte(s))
  411. var nerr errors.NonFatal
  412. jval, err := dec.Read()
  413. if !nerr.Merge(err) {
  414. return pref.Value{}, err
  415. }
  416. return getFloat(jval, bitSize)
  417. }
  418. return pref.Value{}, unexpectedJSONError{jval}
  419. }
  420. func getFloat(jval json.Value, bitSize int) (pref.Value, error) {
  421. n, err := jval.Float(bitSize)
  422. if err != nil {
  423. return pref.Value{}, err
  424. }
  425. if bitSize == 32 {
  426. return pref.ValueOf(float32(n)), nil
  427. }
  428. return pref.ValueOf(n), nil
  429. }
  430. func unmarshalString(jval json.Value) (pref.Value, error) {
  431. if jval.Type() != json.String {
  432. return pref.Value{}, unexpectedJSONError{jval}
  433. }
  434. return pref.ValueOf(jval.String()), nil
  435. }
  436. func unmarshalBytes(jval json.Value) (pref.Value, error) {
  437. if jval.Type() != json.String {
  438. return pref.Value{}, unexpectedJSONError{jval}
  439. }
  440. s := jval.String()
  441. enc := base64.StdEncoding
  442. if strings.ContainsAny(s, "-_") {
  443. enc = base64.URLEncoding
  444. }
  445. if len(s)%4 != 0 {
  446. enc = enc.WithPadding(base64.NoPadding)
  447. }
  448. b, err := enc.DecodeString(s)
  449. if err != nil {
  450. return pref.Value{}, err
  451. }
  452. return pref.ValueOf(b), nil
  453. }
  454. func unmarshalEnum(jval json.Value, fd pref.FieldDescriptor) (pref.Value, error) {
  455. switch jval.Type() {
  456. case json.String:
  457. // Lookup EnumNumber based on name.
  458. s := jval.String()
  459. if enumVal := fd.Enum().Values().ByName(pref.Name(s)); enumVal != nil {
  460. return pref.ValueOf(enumVal.Number()), nil
  461. }
  462. return pref.Value{}, newError("invalid enum value %q", jval)
  463. case json.Number:
  464. n, err := jval.Int(32)
  465. if err != nil {
  466. return pref.Value{}, err
  467. }
  468. return pref.ValueOf(pref.EnumNumber(n)), nil
  469. case json.Null:
  470. // This is only valid for google.protobuf.NullValue.
  471. if isNullValue(fd) {
  472. return pref.ValueOf(pref.EnumNumber(0)), nil
  473. }
  474. }
  475. return pref.Value{}, unexpectedJSONError{jval}
  476. }
  477. // unmarshalRepeated unmarshals into a repeated field.
  478. func (o UnmarshalOptions) unmarshalRepeated(knownFields pref.KnownFields, fd pref.FieldDescriptor) error {
  479. var nerr errors.NonFatal
  480. num := fd.Number()
  481. val := knownFields.Get(num)
  482. if !fd.IsMap() {
  483. if err := o.unmarshalList(val.List(), fd); !nerr.Merge(err) {
  484. return err
  485. }
  486. } else {
  487. if err := o.unmarshalMap(val.Map(), fd); !nerr.Merge(err) {
  488. return err
  489. }
  490. }
  491. return nerr.E
  492. }
  493. // unmarshalList unmarshals into given protoreflect.List.
  494. func (o UnmarshalOptions) unmarshalList(list pref.List, fd pref.FieldDescriptor) error {
  495. var nerr errors.NonFatal
  496. jval, err := o.decoder.Read()
  497. if !nerr.Merge(err) {
  498. return err
  499. }
  500. if jval.Type() != json.StartArray {
  501. return unexpectedJSONError{jval}
  502. }
  503. switch fd.Kind() {
  504. case pref.MessageKind, pref.GroupKind:
  505. for {
  506. m := list.NewMessage()
  507. err := o.unmarshalMessage(m, false)
  508. if !nerr.Merge(err) {
  509. if e, ok := err.(unexpectedJSONError); ok {
  510. if e.value.Type() == json.EndArray {
  511. // Done with list.
  512. return nerr.E
  513. }
  514. }
  515. return err
  516. }
  517. list.Append(pref.ValueOf(m))
  518. }
  519. default:
  520. for {
  521. val, err := o.unmarshalScalar(fd)
  522. if !nerr.Merge(err) {
  523. if e, ok := err.(unexpectedJSONError); ok {
  524. if e.value.Type() == json.EndArray {
  525. // Done with list.
  526. return nerr.E
  527. }
  528. }
  529. return err
  530. }
  531. list.Append(val)
  532. }
  533. }
  534. return nerr.E
  535. }
  536. // unmarshalMap unmarshals into given protoreflect.Map.
  537. func (o UnmarshalOptions) unmarshalMap(mmap pref.Map, fd pref.FieldDescriptor) error {
  538. var nerr errors.NonFatal
  539. jval, err := o.decoder.Read()
  540. if !nerr.Merge(err) {
  541. return err
  542. }
  543. if jval.Type() != json.StartObject {
  544. return unexpectedJSONError{jval}
  545. }
  546. fields := fd.Message().Fields()
  547. keyDesc := fields.ByNumber(1)
  548. valDesc := fields.ByNumber(2)
  549. // Determine ahead whether map entry is a scalar type or a message type in
  550. // order to call the appropriate unmarshalMapValue func inside the for loop
  551. // below.
  552. unmarshalMapValue := func() (pref.Value, error) {
  553. return o.unmarshalScalar(valDesc)
  554. }
  555. switch valDesc.Kind() {
  556. case pref.MessageKind, pref.GroupKind:
  557. unmarshalMapValue = func() (pref.Value, error) {
  558. var nerr errors.NonFatal
  559. m := mmap.NewMessage()
  560. if err := o.unmarshalMessage(m, false); !nerr.Merge(err) {
  561. return pref.Value{}, err
  562. }
  563. return pref.ValueOf(m), nerr.E
  564. }
  565. }
  566. Loop:
  567. for {
  568. // Read field name.
  569. jval, err := o.decoder.Read()
  570. if !nerr.Merge(err) {
  571. return err
  572. }
  573. switch jval.Type() {
  574. default:
  575. return unexpectedJSONError{jval}
  576. case json.EndObject:
  577. break Loop
  578. case json.Name:
  579. // Continue.
  580. }
  581. name, err := jval.Name()
  582. if !nerr.Merge(err) {
  583. return err
  584. }
  585. // Unmarshal field name.
  586. pkey, err := unmarshalMapKey(name, keyDesc)
  587. if !nerr.Merge(err) {
  588. return err
  589. }
  590. // Check for duplicate field name.
  591. if mmap.Has(pkey) {
  592. return newError("duplicate map key %q", jval)
  593. }
  594. // Read and unmarshal field value.
  595. pval, err := unmarshalMapValue()
  596. if !nerr.Merge(err) {
  597. return err
  598. }
  599. mmap.Set(pkey, pval)
  600. }
  601. return nerr.E
  602. }
  603. // unmarshalMapKey converts given string into a protoreflect.MapKey. A map key type is any
  604. // integral or string type.
  605. func unmarshalMapKey(name string, fd pref.FieldDescriptor) (pref.MapKey, error) {
  606. const b32 = 32
  607. const b64 = 64
  608. const base10 = 10
  609. kind := fd.Kind()
  610. switch kind {
  611. case pref.StringKind:
  612. return pref.ValueOf(name).MapKey(), nil
  613. case pref.BoolKind:
  614. switch name {
  615. case "true":
  616. return pref.ValueOf(true).MapKey(), nil
  617. case "false":
  618. return pref.ValueOf(false).MapKey(), nil
  619. }
  620. return pref.MapKey{}, errors.New("invalid value for boolean key %q", name)
  621. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  622. n, err := strconv.ParseInt(name, base10, b32)
  623. if err != nil {
  624. return pref.MapKey{}, err
  625. }
  626. return pref.ValueOf(int32(n)).MapKey(), nil
  627. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  628. n, err := strconv.ParseInt(name, base10, b64)
  629. if err != nil {
  630. return pref.MapKey{}, err
  631. }
  632. return pref.ValueOf(int64(n)).MapKey(), nil
  633. case pref.Uint32Kind, pref.Fixed32Kind:
  634. n, err := strconv.ParseUint(name, base10, b32)
  635. if err != nil {
  636. return pref.MapKey{}, err
  637. }
  638. return pref.ValueOf(uint32(n)).MapKey(), nil
  639. case pref.Uint64Kind, pref.Fixed64Kind:
  640. n, err := strconv.ParseUint(name, base10, b64)
  641. if err != nil {
  642. return pref.MapKey{}, err
  643. }
  644. return pref.ValueOf(uint64(n)).MapKey(), nil
  645. }
  646. panic(fmt.Sprintf("%s: invalid kind %s for map key", fd.FullName(), kind))
  647. }