uuid.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 byteGroups = []int{8, 4, 4, 4, 12}
  11. type UUID [16]byte
  12. // String returns the string representation of this UUID.
  13. func (u *UUID) String() string {
  14. bytes := u.Bytes()
  15. result := hex.EncodeToString(bytes[0 : byteGroups[0]/2])
  16. start := byteGroups[0] / 2
  17. for i := 1; i < len(byteGroups); i++ {
  18. nBytes := byteGroups[i] / 2
  19. result += "-"
  20. result += hex.EncodeToString(bytes[start : start+nBytes])
  21. start += nBytes
  22. }
  23. return result
  24. }
  25. // Bytes returns the bytes representation of this UUID.
  26. func (u *UUID) Bytes() []byte {
  27. return u[:]
  28. }
  29. // Equals returns true if this UUID equals another UUID by value.
  30. func (u *UUID) Equals(another *UUID) bool {
  31. if u == nil && another == nil {
  32. return true
  33. }
  34. if u == nil || another == nil {
  35. return false
  36. }
  37. return bytes.Equal(u.Bytes(), another.Bytes())
  38. }
  39. // New creates a UUID with random value.
  40. func New() UUID {
  41. var uuid UUID
  42. common.Must2(rand.Read(uuid.Bytes()))
  43. uuid[6] = (uuid[6] & 0x0f) | (4 << 4)
  44. uuid[8] = (uuid[8]&(0xff>>2) | (0x02 << 6))
  45. return uuid
  46. }
  47. // ParseBytes converts a UUID in byte form to object.
  48. func ParseBytes(b []byte) (UUID, error) {
  49. var uuid UUID
  50. if len(b) != 16 {
  51. return uuid, errors.New("invalid UUID: ", b)
  52. }
  53. copy(uuid[:], b)
  54. return uuid, nil
  55. }
  56. // ParseString converts a UUID in string form to object.
  57. func ParseString(str string) (UUID, error) {
  58. var uuid UUID
  59. text := []byte(str)
  60. if l := len(text); l < 32 || l > 36 {
  61. if l == 0 || l > 30 {
  62. return uuid, errors.New("invalid UUID: ", str)
  63. }
  64. h := sha1.New()
  65. h.Write(uuid[:])
  66. h.Write(text)
  67. u := h.Sum(nil)[:16]
  68. u[6] = (u[6] & 0x0f) | (5 << 4)
  69. u[8] = (u[8]&(0xff>>2) | (0x02 << 6))
  70. copy(uuid[:], u)
  71. return uuid, nil
  72. }
  73. b := uuid.Bytes()
  74. for _, byteGroup := range byteGroups {
  75. if text[0] == '-' {
  76. text = text[1:]
  77. }
  78. if _, err := hex.Decode(b[:byteGroup/2], text[:byteGroup]); err != nil {
  79. return uuid, err
  80. }
  81. text = text[byteGroup:]
  82. b = b[byteGroup/2:]
  83. }
  84. return uuid, nil
  85. }