uuid.go 2.2 KB

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