blob.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * Copyright (c)2019 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2023-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. package zerotier
  14. // This is copied from the LF code base to make JSON blob encoding uniform
  15. import (
  16. "encoding/json"
  17. "unicode/utf8"
  18. )
  19. // Blob is a byte array that serializes to a string or a base62 string prefixed by \b (binary)
  20. type Blob []byte
  21. // MarshalJSON returns this blob marshaled as a string using \b<base62> for non-UTF8 binary data.
  22. func (b Blob) MarshalJSON() ([]byte, error) {
  23. if utf8.Valid(b) {
  24. return json.Marshal(string(b))
  25. }
  26. return []byte("\"\\b" + Base62Encode(b) + "\""), nil
  27. }
  28. // UnmarshalJSON unmarshals this blob from a string or byte array.
  29. func (b *Blob) UnmarshalJSON(j []byte) error {
  30. var s string
  31. err := json.Unmarshal(j, &s)
  32. if err == nil {
  33. if len(s) == 0 {
  34. *b = nil
  35. } else if s[0] == '\b' {
  36. *b = Base62Decode(s[1:])
  37. return nil
  38. }
  39. *b = []byte(s)
  40. return nil
  41. }
  42. // Byte arrays are also accepted
  43. var bb []byte
  44. if json.Unmarshal(j, &bb) != nil {
  45. return err
  46. }
  47. *b = bb
  48. return nil
  49. }