number.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package telemetry
  4. import (
  5. "encoding/json"
  6. "strconv"
  7. )
  8. // protoInt64 represents the protobuf encoding of integers which can be either
  9. // strings or integers.
  10. type protoInt64 int64
  11. // Int64 returns the protoInt64 as an int64.
  12. func (i *protoInt64) Int64() int64 { return int64(*i) }
  13. // UnmarshalJSON decodes both strings and integers.
  14. func (i *protoInt64) UnmarshalJSON(data []byte) error {
  15. if data[0] == '"' {
  16. var str string
  17. if err := json.Unmarshal(data, &str); err != nil {
  18. return err
  19. }
  20. parsedInt, err := strconv.ParseInt(str, 10, 64)
  21. if err != nil {
  22. return err
  23. }
  24. *i = protoInt64(parsedInt)
  25. } else {
  26. var parsedInt int64
  27. if err := json.Unmarshal(data, &parsedInt); err != nil {
  28. return err
  29. }
  30. *i = protoInt64(parsedInt)
  31. }
  32. return nil
  33. }
  34. // protoUint64 represents the protobuf encoding of integers which can be either
  35. // strings or integers.
  36. type protoUint64 uint64
  37. // Int64 returns the protoUint64 as a uint64.
  38. func (i *protoUint64) Uint64() uint64 { return uint64(*i) }
  39. // UnmarshalJSON decodes both strings and integers.
  40. func (i *protoUint64) UnmarshalJSON(data []byte) error {
  41. if data[0] == '"' {
  42. var str string
  43. if err := json.Unmarshal(data, &str); err != nil {
  44. return err
  45. }
  46. parsedUint, err := strconv.ParseUint(str, 10, 64)
  47. if err != nil {
  48. return err
  49. }
  50. *i = protoUint64(parsedUint)
  51. } else {
  52. var parsedUint uint64
  53. if err := json.Unmarshal(data, &parsedUint); err != nil {
  54. return err
  55. }
  56. *i = protoUint64(parsedUint)
  57. }
  58. return nil
  59. }