forked from mtusi2026/mtusi2026lab4
76 lines
2.0 KiB
Go
76 lines
2.0 KiB
Go
// Package uuid generates and normalizes canonical lowercase UUIDs. The
|
|
// application, not PostgreSQL, assigns identifiers so every API replica and
|
|
// the database agree on the exact on-the-wire form.
|
|
package uuid
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"strings"
|
|
)
|
|
|
|
// New returns a canonical lowercase UUIDv4. A failure of crypto/rand means the
|
|
// process cannot safely create identifiers, so panicking is intentional; the
|
|
// HTTP layer turns it into a generic 500 response.
|
|
func New() string {
|
|
var b [16]byte
|
|
if _, err := rand.Read(b[:]); err != nil {
|
|
panic("crypto/rand failed: " + err.Error())
|
|
}
|
|
b[6] = (b[6] & 0x0f) | 0x40 // version 4
|
|
b[8] = (b[8] & 0x3f) | 0x80 // RFC 4122 variant
|
|
return format(b)
|
|
}
|
|
|
|
// NewRandom returns a lowercase hex string with n random bytes. It is used for
|
|
// request ids and stable per-process instance ids, not for resource ids.
|
|
func NewRandom(n int) string {
|
|
raw := make([]byte, n)
|
|
if _, err := rand.Read(raw); err != nil {
|
|
panic("crypto/rand failed: " + err.Error())
|
|
}
|
|
return hex.EncodeToString(raw)
|
|
}
|
|
|
|
func format(b [16]byte) string {
|
|
var out [36]byte
|
|
hex.Encode(out[0:8], b[0:4])
|
|
out[8] = '-'
|
|
hex.Encode(out[9:13], b[4:6])
|
|
out[13] = '-'
|
|
hex.Encode(out[14:18], b[6:8])
|
|
out[18] = '-'
|
|
hex.Encode(out[19:23], b[8:10])
|
|
out[23] = '-'
|
|
hex.Encode(out[24:36], b[10:16])
|
|
return string(out[:])
|
|
}
|
|
|
|
// Normalize accepts only the canonical 8-4-4-4-12 hyphenated form (ASCII hex,
|
|
// case-insensitive) and returns its lowercase representation. Braces, urn:
|
|
// prefixes, SQL uuid spellings and other aliases are rejected so resource
|
|
// identifiers have exactly one wire form.
|
|
func Normalize(value string) (string, bool) {
|
|
if len(value) != 36 {
|
|
return "", false
|
|
}
|
|
for i := 0; i < len(value); i++ {
|
|
c := value[i]
|
|
switch i {
|
|
case 8, 13, 18, 23:
|
|
if c != '-' {
|
|
return "", false
|
|
}
|
|
default:
|
|
if !isHex(c) {
|
|
return "", false
|
|
}
|
|
}
|
|
}
|
|
return strings.ToLower(value), true
|
|
}
|
|
|
|
func isHex(c byte) bool {
|
|
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
|
|
}
|