marshal.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2016 Google Inc. 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 uuid
  5. import (
  6. "errors"
  7. "fmt"
  8. guuid "github.com/google/uuid"
  9. )
  10. // MarshalText implements encoding.TextMarshaler.
  11. func (u UUID) MarshalText() ([]byte, error) {
  12. if len(u) != 16 {
  13. return nil, nil
  14. }
  15. var js [36]byte
  16. encodeHex(js[:], u)
  17. return js[:], nil
  18. }
  19. // UnmarshalText implements encoding.TextUnmarshaler.
  20. func (u *UUID) UnmarshalText(data []byte) error {
  21. if len(data) == 0 {
  22. return nil
  23. }
  24. id := Parse(string(data))
  25. if id == nil {
  26. return errors.New("invalid UUID")
  27. }
  28. *u = id
  29. return nil
  30. }
  31. // MarshalBinary implements encoding.BinaryMarshaler.
  32. func (u UUID) MarshalBinary() ([]byte, error) {
  33. return u[:], nil
  34. }
  35. // UnmarshalBinary implements encoding.BinaryUnmarshaler.
  36. func (u *UUID) UnmarshalBinary(data []byte) error {
  37. if len(data) == 0 {
  38. return nil
  39. }
  40. if len(data) != 16 {
  41. return fmt.Errorf("invalid UUID (got %d bytes)", len(data))
  42. }
  43. var id [16]byte
  44. copy(id[:], data)
  45. *u = id[:]
  46. return nil
  47. }
  48. // MarshalText implements encoding.TextMarshaler.
  49. func (u Array) MarshalText() ([]byte, error) {
  50. var js [36]byte
  51. encodeHex(js[:], u[:])
  52. return js[:], nil
  53. }
  54. // UnmarshalText implements encoding.TextUnmarshaler.
  55. func (u *Array) UnmarshalText(data []byte) error {
  56. id, err := guuid.ParseBytes(data)
  57. if err != nil {
  58. return err
  59. }
  60. *u = Array(id)
  61. return nil
  62. }
  63. // MarshalBinary implements encoding.BinaryMarshaler.
  64. func (u Array) MarshalBinary() ([]byte, error) {
  65. return u[:], nil
  66. }
  67. // UnmarshalBinary implements encoding.BinaryUnmarshaler.
  68. func (u *Array) UnmarshalBinary(data []byte) error {
  69. if len(data) != 16 {
  70. return fmt.Errorf("invalid UUID (got %d bytes)", len(data))
  71. }
  72. copy(u[:], data)
  73. return nil
  74. }