decode.go 18 KB

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