uuid.go 2.1 KB

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