uuid - generate and parse UUIDs
Enable with use uuid;. RFC 9562 UUIDs: version 4 (random) and version 7 (time-ordered), the 8-4-4-4-12 hex form, and parse / validate helpers. Self-contained and TinyGo-clean.
Surface
| Call | Returns | Notes |
|---|---|---|
uuid.v4() | string | A new random (version 4) UUID. |
uuid.v7() | string | A new time-ordered (version 7) UUID. |
uuid.parse(s) | bytes | The 16 bytes of a well-formed UUID string; errors on malformed input. |
uuid.isValid(s) | bool | Whether s is a well-formed UUID string. |
uuid.version(s) | int | The version digit (4, 7, ...; 0 for uuid.NIL); errors on malformed input. |
uuid.NIL | string | The all-zero UUID "00000000-0000-0000-0000-000000000000". |
v4 and v7 draw from the crypto library's secure random source. If the operating system's source cannot be read they raise a catchable secure random source unavailable error instead of returning a predictable UUID - see crypto errors (relevant to jennifer-tiny on an image without /dev/urandom).
use io;
use uuid;
def id as string init uuid.v4();
io.printf("%s (v%d)\n", $id, uuid.version($id)); # e.g. 524f1d03-...-042736d40bd9 (v4)
if (uuid.isValid($id)) {
def raw as bytes init uuid.parse($id); # 16 bytes
}Errors
| Kind | Raised for |
|---|---|
"uuid" | a malformed UUID string in parse / version |
"runtime" | misuse: a wrong argument count or type; the secure random source unavailable in v4 / v7 |
v4 vs v7
uuid.v4()- fully random. Use for opaque identifiers with no ordering.uuid.v7()- a 48-bit millisecond timestamp in the leading bytes, random after. Within one process a later v7 sorts lexically after an earlier one, also within one millisecond and across tasks: the random tail is incremented by a random step instead of redrawn (RFC 9562 section 6.2, "Monotonic Random"). They make good database keys (index locality) while staying globally unique.
def a as string init uuid.v7();
# ... later ...
def b as string init uuid.v7();
# $a < $b (string comparison reflects creation order)Randomness
v4/v7 randomness comes from the crypto library's crypto-grade source. v4 carries 122 random bits and is unguessable. v7 carries 74 random bits plus a readable millisecond timestamp; use it for ordering, not as a secret. For tokens prefer crypto.randBytes(32). Neither is seedable; for a fast, seedable, reproducible identifier stream, use math.
See also
- crypto.md - the crypto-grade random source behind v4 / v7.
- cheatsheet.md - every builtin at a glance.