uuid.go 1.9 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. InvalidID = errors.New("Invalid ID.")
  12. )
  13. type UUID struct {
  14. byteValue []byte
  15. stringValue string
  16. }
  17. func (this *UUID) String() string {
  18. return this.stringValue
  19. }
  20. func (this *UUID) Bytes() []byte {
  21. return this.byteValue
  22. }
  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. for {
  38. newid, _ := ParseBytes(md5hash.Sum(nil))
  39. if !newid.Equals(this) {
  40. return newid
  41. }
  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. stringValue: bytesToString(bytes),
  68. }, nil
  69. }
  70. func ParseString(str string) (*UUID, error) {
  71. text := []byte(str)
  72. if len(text) < 32 {
  73. return nil, InvalidID
  74. }
  75. uuid := &UUID{
  76. byteValue: make([]byte, 16),
  77. stringValue: str,
  78. }
  79. b := uuid.byteValue[:]
  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. }