From 822afb0cc86c2ec26cfb88a0051dfa2e18f9fa54 Mon Sep 17 00:00:00 2001 From: RPRX <63339210+rprx@users.noreply.github.com> Date: Tue, 12 Jan 2021 18:23:54 +0000 Subject: [PATCH] Improve UUID generator https://github.com/XTLS/Xray-core/issues/158 --- common/uuid/uuid.go | 2 ++ main/commands/all/uuid.go | 34 ++++++++++++++++++++++++++-------- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/common/uuid/uuid.go b/common/uuid/uuid.go index de27ea63..0086f06b 100644 --- a/common/uuid/uuid.go +++ b/common/uuid/uuid.go @@ -50,6 +50,8 @@ func (u *UUID) Equals(another *UUID) bool { func New() UUID { var uuid UUID common.Must2(rand.Read(uuid.Bytes())) + uuid[6] = (uuid[6] & 0x0f) | (4 << 4) + uuid[8] = (uuid[8]&(0xff>>2) | (0x02 << 6)) return uuid } diff --git a/main/commands/all/uuid.go b/main/commands/all/uuid.go index ef819f17..b01e88f0 100644 --- a/main/commands/all/uuid.go +++ b/main/commands/all/uuid.go @@ -8,15 +8,33 @@ import ( ) var cmdUUID = &base.Command{ - UsageLine: "{{.Exec}} uuid", - Short: "Generate new UUIDs", + UsageLine: `{{.Exec}} uuid [-i "example"]`, + Short: `Generate UUIDv4 or UUIDv5`, Long: ` -Generate new UUIDs. - `, - Run: executeUUID, +Generate UUIDv4 or UUIDv5. + +UUIDv4 (random): {{.Exec}} uuid + +UUIDv5 (from input): {{.Exec}} uuid -i "example" +`, } -func executeUUID(cmd *base.Command, args []string) { - u := uuid.New() - fmt.Println(u.String()) +func init() { + cmdUUID.Run = executeUUID // break init loop +} + +var input = cmdUUID.Flag.String("i", "", "") + +func executeUUID(cmd *base.Command, args []string) { + var output string + if l := len(*input); l == 0 { + u := uuid.New() + output = u.String() + } else if l <= 30 { + u, _ := uuid.ParseString(*input) + output = u.String() + } else { + output = "Input must be within 30 bytes." + } + fmt.Println(output) }