* uuid: new module for generating and parsing UUIDs A port of the uuid package of Go 1.27 (RFC 9562): `uuid.UUID` is a `[16]u8`, comparable with `==` and usable as a map key; `new`, `new_v4` and `new_v7` take their random bits from `crypto.rand`; `parse` accepts the hex-and-dash, braced, URN and plain hex forms; `str` and `compare` follow the RFC; `nil_uuid` and `max_uuid` are the Nil and Max UUIDs (`nil` is a keyword, so they are constants). UUIDv7s keep a 12-bit fraction of the millisecond and always sort in increasing order, except when the clock moves backwards; the clock is read under the lock, so the order also holds across threads. Go's tests move the clock with testing/synctest; the port gives `new_v7_from` a fake clock instead. The code keeps Go's license notice. * uuid: cover every parser byte and UUIDv7 fraction boundaries --------- Co-authored-by: Alexander Medvednikov <alexander@medvednikov.com>
Description
uuid generates and parses UUIDs (Universally Unique Identifiers) as defined in
RFC 9562.
A uuid.UUID is a [16]u8, so UUIDs can be compared with == and used as map keys.
The random bits of new UUIDs come from the cryptographically secure random number
generator of the operating system (crypto.rand).
uuid.new()returns a new UUID made with an algorithm suitable for most purposes; at this time it is the same asuuid.new_v4().uuid.new_v4()returns a random (version 4) UUID, with 122 random bits.uuid.new_v7()returns a time-ordered (version 7) UUID: the Unix time in milliseconds, a 12-bit fraction of the millisecond and 62 random bits. The UUIDs it returns always sort in increasing order, except when the system clock moves backwards.uuid.parse(s)acceptsf81d4fae-7dec-11d0-a765-00a0c91e6bf6,{f81d4fae-7dec-11d0-a765-00a0c91e6bf6},urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6andf81d4fae7dec11d0a76500a0c91e6bf6, with hexadecimal digits in any case.u.str()returns the lowercase hex-and-dash form, andu.compare(v)orders UUIDs by their bytes, as RFC 9562 does.uuid.nil_uuidanduuid.max_uuidare the Nil and the Max UUIDs.
The module is a port of the uuid package of Go.
Examples
import uuid
fn main() {
id := uuid.parse('{F81D4FAE-7DEC-11D0-A765-00A0C91E6BF6}') or { panic(err) }
println(id.str())
println(id == uuid.parse('f81d4fae7dec11d0a76500a0c91e6bf6') or { panic(err) })
mut ids := [uuid.max_uuid, id, uuid.nil_uuid]
ids.sort_with_compare(fn (a &uuid.UUID, b &uuid.UUID) int {
return a.compare(*b)
})
for u in ids {
println(u.str())
}
mut seen := map[uuid.UUID]bool{}
seen[uuid.new_v7()] = true
println(seen.len)
}
f81d4fae-7dec-11d0-a765-00a0c91e6bf6
true
00000000-0000-0000-0000-000000000000
f81d4fae-7dec-11d0-a765-00a0c91e6bf6
ffffffff-ffff-ffff-ffff-ffffffffffff
1