marshal.go 973 B

123456789101112131415161718192021222324252627282930313233343536373839
  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 "fmt"
  6. // MarshalText implements encoding.TextMarshaler.
  7. func (uuid UUID) MarshalText() ([]byte, error) {
  8. var js [36]byte
  9. encodeHex(js[:], uuid)
  10. return js[:], nil
  11. }
  12. // UnmarshalText implements encoding.TextUnmarshaler.
  13. func (uuid *UUID) UnmarshalText(data []byte) error {
  14. // See comment in ParseBytes why we do this.
  15. // id, err := ParseBytes(data)
  16. id, err := ParseBytes(data)
  17. if err == nil {
  18. *uuid = id
  19. }
  20. return err
  21. }
  22. // MarshalBinary implements encoding.BinaryMarshaler.
  23. func (uuid UUID) MarshalBinary() ([]byte, error) {
  24. return uuid[:], nil
  25. }
  26. // UnmarshalBinary implements encoding.BinaryUnmarshaler.
  27. func (uuid *UUID) UnmarshalBinary(data []byte) error {
  28. if len(data) != 16 {
  29. return fmt.Errorf("invalid UUID (got %d bytes)", len(data))
  30. }
  31. copy(uuid[:], data)
  32. return nil
  33. }