50 lines
854 B
Go
50 lines
854 B
Go
|
package scn
|
||
|
|
||
|
import (
|
||
|
"crypto/rand"
|
||
|
"encoding/hex"
|
||
|
"io"
|
||
|
)
|
||
|
|
||
|
func mustHexUUID() string {
|
||
|
v, err := NewHexUUID()
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
return v
|
||
|
}
|
||
|
|
||
|
func NewHexUUID() (string, error) {
|
||
|
uuid, err := NewUUID()
|
||
|
if err != nil {
|
||
|
return "", err
|
||
|
}
|
||
|
|
||
|
// Result: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
|
||
|
|
||
|
var dst = make([]byte, 36)
|
||
|
|
||
|
hex.Encode(dst, uuid[:4])
|
||
|
dst[8] = '-'
|
||
|
hex.Encode(dst[9:13], uuid[4:6])
|
||
|
dst[13] = '-'
|
||
|
hex.Encode(dst[14:18], uuid[6:8])
|
||
|
dst[18] = '-'
|
||
|
hex.Encode(dst[19:23], uuid[8:10])
|
||
|
dst[23] = '-'
|
||
|
hex.Encode(dst[24:], uuid[10:])
|
||
|
|
||
|
return string(dst), nil
|
||
|
}
|
||
|
|
||
|
func NewUUID() ([16]byte, error) {
|
||
|
var uuid [16]byte
|
||
|
_, err := io.ReadFull(rand.Reader, uuid[:])
|
||
|
if err != nil {
|
||
|
return [16]byte{}, err
|
||
|
}
|
||
|
uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4
|
||
|
uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10
|
||
|
return uuid, nil
|
||
|
}
|