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.

53 lines
1.1 KiB

  1. package common
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "strings"
  6. )
  7. // The main purpose of Bytes is to enable HEX-encoding for json/encoding.
  8. type Bytes []byte
  9. // Marshal needed for protobuf compatibility
  10. func (b Bytes) Marshal() ([]byte, error) {
  11. return b, nil
  12. }
  13. // Unmarshal needed for protobuf compatibility
  14. func (b *Bytes) Unmarshal(data []byte) error {
  15. *b = data
  16. return nil
  17. }
  18. // This is the point of Bytes.
  19. func (b Bytes) MarshalJSON() ([]byte, error) {
  20. s := strings.ToUpper(hex.EncodeToString(b))
  21. jb := make([]byte, len(s)+2)
  22. jb[0] = '"'
  23. copy(jb[1:], []byte(s))
  24. jb[1] = '"'
  25. return jb, nil
  26. }
  27. // This is the point of Bytes.
  28. func (b *Bytes) UnmarshalJSON(data []byte) error {
  29. if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
  30. return fmt.Errorf("Invalid hex string: %s", data)
  31. }
  32. bytes, err := hex.DecodeString(string(data[1 : len(data)-1]))
  33. if err != nil {
  34. return err
  35. }
  36. *b = bytes
  37. return nil
  38. }
  39. // Allow it to fulfill various interfaces in light-client, etc...
  40. func (b Bytes) Bytes() []byte {
  41. return b
  42. }
  43. func (b Bytes) String() string {
  44. return strings.ToUpper(hex.EncodeToString(b))
  45. }