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