uuid.go 2.1 KB

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