marshal.go 944 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. "strconv"
  8. )
  9. // MarshalText implements encoding.TextMarshaler.
  10. func (uuid UUID) MarshalText() ([]byte, error) {
  11. var js [36]byte
  12. encodeHex(js[:], uuid)
  13. return js[:], nil
  14. }
  15. // UnmarshalText implements encoding.TextUnmarshaler.
  16. func (uuid *UUID) UnmarshalText(data []byte) error {
  17. id, err := ParseBytes(data)
  18. if err != nil {
  19. return err
  20. }
  21. *uuid = id
  22. return nil
  23. }
  24. // MarshalBinary implements encoding.BinaryMarshaler.
  25. func (uuid UUID) MarshalBinary() ([]byte, error) {
  26. return uuid[:], nil
  27. }
  28. // UnmarshalBinary implements encoding.BinaryUnmarshaler.
  29. func (uuid *UUID) UnmarshalBinary(data []byte) error {
  30. if len(data) != 16 {
  31. return errors.New("invalid UUID (got " + strconv.Itoa(len(data)) + " bytes)")
  32. }
  33. copy(uuid[:], data)
  34. return nil
  35. }