You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
1.7 KiB

  1. package bytes
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "encoding/json"
  6. "fmt"
  7. "strings"
  8. )
  9. // HexBytes enables HEX-encoding for json/encoding.
  10. type HexBytes []byte
  11. var (
  12. _ json.Marshaler = HexBytes{}
  13. _ json.Unmarshaler = &HexBytes{}
  14. )
  15. // Marshal needed for protobuf compatibility
  16. func (bz HexBytes) Marshal() ([]byte, error) {
  17. return bz, nil
  18. }
  19. // Unmarshal needed for protobuf compatibility
  20. func (bz *HexBytes) Unmarshal(data []byte) error {
  21. *bz = data
  22. return nil
  23. }
  24. // MarshalJSON implements the json.Marshaler interface. The hex bytes is a
  25. // quoted hexadecimal encoded string.
  26. func (bz HexBytes) MarshalJSON() ([]byte, error) {
  27. s := strings.ToUpper(hex.EncodeToString(bz))
  28. jbz := make([]byte, len(s)+2)
  29. jbz[0] = '"'
  30. copy(jbz[1:], s)
  31. jbz[len(jbz)-1] = '"'
  32. return jbz, nil
  33. }
  34. // UnmarshalJSON implements the json.Umarshaler interface.
  35. func (bz *HexBytes) UnmarshalJSON(data []byte) error {
  36. if bytes.Equal(data, []byte("null")) {
  37. return nil
  38. }
  39. if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
  40. return fmt.Errorf("invalid hex string: %s", data)
  41. }
  42. bz2, err := hex.DecodeString(string(data[1 : len(data)-1]))
  43. if err != nil {
  44. return err
  45. }
  46. *bz = bz2
  47. return nil
  48. }
  49. // Bytes fulfills various interfaces in light-client, etc...
  50. func (bz HexBytes) Bytes() []byte {
  51. return bz
  52. }
  53. func (bz HexBytes) String() string {
  54. return strings.ToUpper(hex.EncodeToString(bz))
  55. }
  56. // Format writes either address of 0th element in a slice in base 16 notation,
  57. // with leading 0x (%p), or casts HexBytes to bytes and writes as hexadecimal
  58. // string to s.
  59. func (bz HexBytes) Format(s fmt.State, verb rune) {
  60. switch verb {
  61. case 'p':
  62. s.Write([]byte(fmt.Sprintf("%p", bz)))
  63. default:
  64. s.Write([]byte(fmt.Sprintf("%X", []byte(bz))))
  65. }
  66. }