marshal.go 907 B

1234567891011121314151617181920212223242526272829303132333435363738
  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. id, err := ParseBytes(data)
  15. if err != nil {
  16. return err
  17. }
  18. *uuid = id
  19. return nil
  20. }
  21. // MarshalBinary implements encoding.BinaryMarshaler.
  22. func (uuid UUID) MarshalBinary() ([]byte, error) {
  23. return uuid[:], nil
  24. }
  25. // UnmarshalBinary implements encoding.BinaryUnmarshaler.
  26. func (uuid *UUID) UnmarshalBinary(data []byte) error {
  27. if len(data) != 16 {
  28. return fmt.Errorf("invalid UUID (got %d bytes)", len(data))
  29. }
  30. copy(uuid[:], data)
  31. return nil
  32. }