decode.go 18 KB

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