You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/common/uuid/uuid.go

109 lines
2.1 KiB

9 years ago
package uuid
import (
"bytes"
"crypto/md5"
9 years ago
"crypto/rand"
"encoding/hex"
8 years ago
"v2ray.com/core/common"
"v2ray.com/core/common/errors"
9 years ago
)
var (
byteGroups = []int{8, 4, 4, 4, 12}
)
type UUID [16]byte
9 years ago
9 years ago
// String returns the string representation of this UUID.
8 years ago
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
9 years ago
}
9 years ago
// Bytes returns the bytes representation of this UUID.
8 years ago
func (u *UUID) Bytes() []byte {
return u[:]
}
9 years ago
// Equals returns true if this UUID equals another UUID by value.
8 years ago
func (u *UUID) Equals(another *UUID) bool {
if u == nil && another == nil {
return true
}
8 years ago
if u == nil || another == nil {
return false
}
8 years ago
return bytes.Equal(u.Bytes(), another.Bytes())
}
// Next generates a deterministic random UUID based on this UUID.
func (u *UUID) Next() UUID {
md5hash := md5.New()
8 years ago
md5hash.Write(u.Bytes())
md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81"))
var newid UUID
for {
md5hash.Sum(newid[:0])
8 years ago
if !newid.Equals(u) {
return newid
}
md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2"))
}
9 years ago
}
7 years ago
// New creates a UUID with random value.
func New() UUID {
var uuid UUID
common.Must2(rand.Read(uuid.Bytes()))
return uuid
}
7 years ago
// 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
9 years ago
}
7 years ago
// ParseString converts a UUID in string form to object.
func ParseString(str string) (UUID, error) {
var uuid UUID
9 years ago
text := []byte(str)
if len(text) < 32 {
return uuid, errors.New("invalid UUID: ", str)
9 years ago
}
b := uuid.Bytes()
9 years ago
for _, byteGroup := range byteGroups {
if text[0] == '-' {
text = text[1:]
}
_, err := hex.Decode(b[:byteGroup/2], text[:byteGroup])
if err != nil {
return uuid, err
9 years ago
}
text = text[byteGroup:]
b = b[byteGroup/2:]
}
return uuid, nil
9 years ago
}