From 31a21bef089c4d5547daed8a8f7b2931061067d5 Mon Sep 17 00:00:00 2001 From: Darien Raymond Date: Wed, 22 Feb 2017 11:59:01 +0100 Subject: [PATCH] refactor uuid --- common/uuid/uuid.go | 72 ++++++++++++++++++++++----------------------- 1 file changed, 35 insertions(+), 37 deletions(-) diff --git a/common/uuid/uuid.go b/common/uuid/uuid.go index 17f0bd279..736955b4f 100644 --- a/common/uuid/uuid.go +++ b/common/uuid/uuid.go @@ -5,6 +5,7 @@ import ( "crypto/md5" "crypto/rand" "encoding/hex" + "v2ray.com/core/common/errors" ) @@ -15,42 +16,8 @@ var ( type UUID [16]byte // String returns the string representation of this UUID. -func (v *UUID) String() string { - return bytesToString(v.Bytes()) -} - -// Bytes returns the bytes representation of this UUID. -func (v *UUID) Bytes() []byte { - return v[:] -} - -// Equals returns true if this UUID equals another UUID by value. -func (v *UUID) Equals(another *UUID) bool { - if v == nil && another == nil { - return true - } - if v == nil || another == nil { - return false - } - return bytes.Equal(v.Bytes(), another.Bytes()) -} - -// Next generates a deterministic random UUID based on this UUID. -func (v *UUID) Next() *UUID { - md5hash := md5.New() - md5hash.Write(v.Bytes()) - md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81")) - newid := new(UUID) - for { - md5hash.Sum(newid[:0]) - if !newid.Equals(v) { - return newid - } - md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2")) - } -} - -func bytesToString(bytes []byte) string { +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++ { @@ -62,6 +29,37 @@ func bytesToString(bytes []byte) string { 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()) +} + +// Next generates a deterministic random UUID based on this UUID. +func (u *UUID) Next() *UUID { + md5hash := md5.New() + md5hash.Write(u.Bytes()) + md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81")) + newid := new(UUID) + for { + md5hash.Sum(newid[:0]) + if !newid.Equals(u) { + return newid + } + md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2")) + } +} + // New creates an UUID with random value. func New() *UUID { uuid := new(UUID) @@ -69,7 +67,7 @@ func New() *UUID { return uuid } -// PraseBytes converts an UUID in byte form to object. +// ParseBytes converts an UUID in byte form to object. func ParseBytes(b []byte) (*UUID, error) { if len(b) != 16 { return nil, errors.New("Invalid UUID: ", b)