github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/common/uuid/uuid.go (about)

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