uuid.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package uuid // import "github.com/xtls/xray-core/common/uuid"
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "crypto/sha1"
  6. "encoding/hex"
  7. "github.com/xtls/xray-core/common"
  8. "github.com/xtls/xray-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. // New creates a UUID with random value.
  42. func New() UUID {
  43. var uuid UUID
  44. common.Must2(rand.Read(uuid.Bytes()))
  45. uuid[6] = (uuid[6] & 0x0f) | (4 << 4)
  46. uuid[8] = (uuid[8]&(0xff>>2) | (0x02 << 6))
  47. return uuid
  48. }
  49. // ParseBytes converts a UUID in byte form to object.
  50. func ParseBytes(b []byte) (UUID, error) {
  51. var uuid UUID
  52. if len(b) != 16 {
  53. return uuid, errors.New("invalid UUID: ", b)
  54. }
  55. copy(uuid[:], b)
  56. return uuid, nil
  57. }
  58. // ParseString converts a UUID in string form to object.
  59. func ParseString(str string) (UUID, error) {
  60. var uuid UUID
  61. text := []byte(str)
  62. if l := len(text); l < 32 || l > 36 {
  63. if l == 0 || l > 30 {
  64. return uuid, errors.New("invalid UUID: ", str)
  65. }
  66. h := sha1.New()
  67. h.Write(uuid[:])
  68. h.Write(text)
  69. u := h.Sum(nil)[:16]
  70. u[6] = (u[6] & 0x0f) | (5 << 4)
  71. u[8] = (u[8]&(0xff>>2) | (0x02 << 6))
  72. copy(uuid[:], u)
  73. return uuid, nil
  74. }
  75. b := uuid.Bytes()
  76. for _, byteGroup := range byteGroups {
  77. if text[0] == '-' {
  78. text = text[1:]
  79. }
  80. if _, err := hex.Decode(b[:byteGroup/2], text[:byteGroup]); err != nil {
  81. return uuid, err
  82. }
  83. text = text[byteGroup:]
  84. b = b[byteGroup/2:]
  85. }
  86. return uuid, nil
  87. }