Skip to content

Commit

Permalink
Improve UUID generator
Browse files Browse the repository at this point in the history
  • Loading branch information
RPRX authored Jan 12, 2021
1 parent 1579188 commit 822afb0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
2 changes: 2 additions & 0 deletions common/uuid/uuid.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
32 changes: 25 additions & 7 deletions main/commands/all/uuid.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 init() {
cmdUUID.Run = executeUUID // break init loop
}

var input = cmdUUID.Flag.String("i", "", "")

func executeUUID(cmd *base.Command, args []string) {
u := uuid.New()
fmt.Println(u.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)
}

0 comments on commit 822afb0

Please sign in to comment.