uuid.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. InvalidID = errors.New("Invalid ID.")
  12. )
  13. type UUID struct {
  14. byteValue []byte
  15. }
  16. func (this *UUID) String() string {
  17. return bytesToString(this.byteValue)
  18. }
  19. func (this *UUID) Bytes() []byte {
  20. return this.byteValue
  21. }
  22. func (this *UUID) Equals(another *UUID) bool {
  23. if this == nil && another == nil {
  24. return true
  25. }
  26. if this == nil || another == nil {
  27. return false
  28. }
  29. return bytes.Equal(this.Bytes(), another.Bytes())
  30. }
  31. // Next generates a deterministic random UUID based on this UUID.
  32. func (this *UUID) Next() *UUID {
  33. md5hash := md5.New()
  34. md5hash.Write(this.Bytes())
  35. md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81"))
  36. for {
  37. newid, _ := ParseBytes(md5hash.Sum(nil))
  38. if !newid.Equals(this) {
  39. return newid
  40. }
  41. md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2"))
  42. }
  43. }
  44. func bytesToString(bytes []byte) string {
  45. result := hex.EncodeToString(bytes[0 : byteGroups[0]/2])
  46. start := byteGroups[0] / 2
  47. for i := 1; i < len(byteGroups); i++ {
  48. nBytes := byteGroups[i] / 2
  49. result += "-"
  50. result += hex.EncodeToString(bytes[start : start+nBytes])
  51. start += nBytes
  52. }
  53. return result
  54. }
  55. func New() *UUID {
  56. bytes := make([]byte, 16)
  57. rand.Read(bytes)
  58. uuid, _ := ParseBytes(bytes)
  59. return uuid
  60. }
  61. func ParseBytes(bytes []byte) (*UUID, error) {
  62. if len(bytes) != 16 {
  63. return nil, InvalidID
  64. }
  65. return &UUID{
  66. byteValue: bytes,
  67. }, nil
  68. }
  69. func ParseString(str string) (*UUID, error) {
  70. text := []byte(str)
  71. if len(text) < 32 {
  72. return nil, InvalidID
  73. }
  74. uuid := &UUID{
  75. byteValue: make([]byte, 16),
  76. }
  77. b := uuid.byteValue[:]
  78. for _, byteGroup := range byteGroups {
  79. if text[0] == '-' {
  80. text = text[1:]
  81. }
  82. _, err := hex.Decode(b[:byteGroup/2], text[:byteGroup])
  83. if err != nil {
  84. return nil, err
  85. }
  86. text = text[byteGroup:]
  87. b = b[byteGroup/2:]
  88. }
  89. return uuid, nil
  90. }