uuid.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package uuid
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "encoding/hex"
  6. "github.com/v2fly/v2ray-core/v5/common"
  7. "github.com/v2fly/v2ray-core/v5/common/errors"
  8. )
  9. var byteGroups = []int{8, 4, 4, 4, 12}
  10. type UUID [16]byte
  11. // String returns the string representation of this UUID.
  12. func (u *UUID) String() string {
  13. bytes := u.Bytes()
  14. result := hex.EncodeToString(bytes[0 : byteGroups[0]/2])
  15. start := byteGroups[0] / 2
  16. for i := 1; i < len(byteGroups); i++ {
  17. nBytes := byteGroups[i] / 2
  18. result += "-"
  19. result += hex.EncodeToString(bytes[start : start+nBytes])
  20. start += nBytes
  21. }
  22. return result
  23. }
  24. // Bytes returns the bytes representation of this UUID.
  25. func (u *UUID) Bytes() []byte {
  26. return u[:]
  27. }
  28. // Equals returns true if this UUID equals another UUID by value.
  29. func (u *UUID) Equals(another *UUID) bool {
  30. if u == nil && another == nil {
  31. return true
  32. }
  33. if u == nil || another == nil {
  34. return false
  35. }
  36. return bytes.Equal(u.Bytes(), another.Bytes())
  37. }
  38. // New creates a UUID with random value.
  39. func New() UUID {
  40. var uuid UUID
  41. common.Must2(rand.Read(uuid.Bytes()))
  42. return uuid
  43. }
  44. // ParseBytes converts a UUID in byte form to object.
  45. func ParseBytes(b []byte) (UUID, error) {
  46. var uuid UUID
  47. if len(b) != 16 {
  48. return uuid, errors.New("invalid UUID: ", b)
  49. }
  50. copy(uuid[:], b)
  51. return uuid, nil
  52. }
  53. // ParseString converts a UUID in string form to object.
  54. func ParseString(str string) (UUID, error) {
  55. var uuid UUID
  56. text := []byte(str)
  57. if len(text) < 32 {
  58. return uuid, errors.New("invalid UUID: ", str)
  59. }
  60. b := uuid.Bytes()
  61. for _, byteGroup := range byteGroups {
  62. if text[0] == '-' {
  63. text = text[1:]
  64. }
  65. if _, err := hex.Decode(b[:byteGroup/2], text[:byteGroup]); err != nil {
  66. return uuid, err
  67. }
  68. text = text[byteGroup:]
  69. b = b[byteGroup/2:]
  70. }
  71. return uuid, nil
  72. }