uuid.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package uuid
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "crypto/rand"
  6. "encoding/hex"
  7. "errors"
  8. )
  9. var (
  10. byteGroups = []int{8, 4, 4, 4, 12}
  11. ErrInvalidID = errors.New("Invalid ID.")
  12. )
  13. type UUID [16]byte
  14. // String returns the string representation of this UUID.
  15. func (this *UUID) String() string {
  16. return bytesToString(this.Bytes())
  17. }
  18. // Bytes returns the bytes representation of this UUID.
  19. func (this *UUID) Bytes() []byte {
  20. return this[:]
  21. }
  22. // Equals returns true if this UUID equals another UUID by value.
  23. func (this *UUID) Equals(another *UUID) bool {
  24. if this == nil && another == nil {
  25. return true
  26. }
  27. if this == nil || another == nil {
  28. return false
  29. }
  30. return bytes.Equal(this.Bytes(), another.Bytes())
  31. }
  32. // Next generates a deterministic random UUID based on this UUID.
  33. func (this *UUID) Next() *UUID {
  34. md5hash := md5.New()
  35. md5hash.Write(this.Bytes())
  36. md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81"))
  37. newid := new(UUID)
  38. for {
  39. md5hash.Sum(newid[:0])
  40. if !newid.Equals(this) {
  41. return newid
  42. }
  43. md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2"))
  44. }
  45. }
  46. func bytesToString(bytes []byte) string {
  47. result := hex.EncodeToString(bytes[0 : byteGroups[0]/2])
  48. start := byteGroups[0] / 2
  49. for i := 1; i < len(byteGroups); i++ {
  50. nBytes := byteGroups[i] / 2
  51. result += "-"
  52. result += hex.EncodeToString(bytes[start : start+nBytes])
  53. start += nBytes
  54. }
  55. return result
  56. }
  57. // New creates an UUID with random value.
  58. func New() *UUID {
  59. uuid := new(UUID)
  60. rand.Read(uuid.Bytes())
  61. return uuid
  62. }
  63. // PraseBytes converts an UUID in byte form to object.
  64. func ParseBytes(b []byte) (*UUID, error) {
  65. if len(b) != 16 {
  66. return nil, ErrInvalidID
  67. }
  68. uuid := new(UUID)
  69. copy(uuid[:], b)
  70. return uuid, nil
  71. }
  72. // ParseString converts an UUID in string form to object.
  73. func ParseString(str string) (*UUID, error) {
  74. text := []byte(str)
  75. if len(text) < 32 {
  76. return nil, ErrInvalidID
  77. }
  78. uuid := new(UUID)
  79. b := uuid.Bytes()
  80. for _, byteGroup := range byteGroups {
  81. if text[0] == '-' {
  82. text = text[1:]
  83. }
  84. _, err := hex.Decode(b[:byteGroup/2], text[:byteGroup])
  85. if err != nil {
  86. return nil, err
  87. }
  88. text = text[byteGroup:]
  89. b = b[byteGroup/2:]
  90. }
  91. return uuid, nil
  92. }