uuid.go 1.8 KB

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