uuid.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package uuid
  2. import (
  3. "crypto/rand"
  4. "encoding/hex"
  5. "fmt"
  6. "io"
  7. )
  8. // GenerateRandomBytes is used to generate random bytes of given size.
  9. func GenerateRandomBytes(size int) ([]byte, error) {
  10. return GenerateRandomBytesWithReader(size, rand.Reader)
  11. }
  12. // GenerateRandomBytesWithReader is used to generate random bytes of given size read from a given reader.
  13. func GenerateRandomBytesWithReader(size int, reader io.Reader) ([]byte, error) {
  14. if reader == nil {
  15. return nil, fmt.Errorf("provided reader is nil")
  16. }
  17. buf := make([]byte, size)
  18. if _, err := io.ReadFull(reader, buf); err != nil {
  19. return nil, fmt.Errorf("failed to read random bytes: %v", err)
  20. }
  21. return buf, nil
  22. }
  23. const uuidLen = 16
  24. // GenerateUUID is used to generate a random UUID
  25. func GenerateUUID() (string, error) {
  26. return GenerateUUIDWithReader(rand.Reader)
  27. }
  28. // GenerateUUIDWithReader is used to generate a random UUID with a given Reader
  29. func GenerateUUIDWithReader(reader io.Reader) (string, error) {
  30. if reader == nil {
  31. return "", fmt.Errorf("provided reader is nil")
  32. }
  33. buf, err := GenerateRandomBytesWithReader(uuidLen, reader)
  34. if err != nil {
  35. return "", err
  36. }
  37. return FormatUUID(buf)
  38. }
  39. func FormatUUID(buf []byte) (string, error) {
  40. if buflen := len(buf); buflen != uuidLen {
  41. return "", fmt.Errorf("wrong length byte slice (%d)", buflen)
  42. }
  43. return fmt.Sprintf("%x-%x-%x-%x-%x",
  44. buf[0:4],
  45. buf[4:6],
  46. buf[6:8],
  47. buf[8:10],
  48. buf[10:16]), nil
  49. }
  50. func ParseUUID(uuid string) ([]byte, error) {
  51. if len(uuid) != 2 * uuidLen + 4 {
  52. return nil, fmt.Errorf("uuid string is wrong length")
  53. }
  54. if uuid[8] != '-' ||
  55. uuid[13] != '-' ||
  56. uuid[18] != '-' ||
  57. uuid[23] != '-' {
  58. return nil, fmt.Errorf("uuid is improperly formatted")
  59. }
  60. hexStr := uuid[0:8] + uuid[9:13] + uuid[14:18] + uuid[19:23] + uuid[24:36]
  61. ret, err := hex.DecodeString(hexStr)
  62. if err != nil {
  63. return nil, err
  64. }
  65. if len(ret) != uuidLen {
  66. return nil, fmt.Errorf("decoded hex is the wrong length")
  67. }
  68. return ret, nil
  69. }