uuid
UUIDs (RFC 9562) in pure Louise: version 7 IDs, the RFC text form, and short text forms that sort like the IDs.
import uuid
let id = uuid.v7() // / <clock, random>
uuid.to_rfc(id) // "0190f5a2-7c1e-7d3a-9b2c-4e5f60718293"
show(id) // Crockford base 32: 26 characters
uuid.encode(id, uuid.base62()) // 22 characters
Version 7
v7() reads the current time (std/time.clock) and 10 random bytes
(std/random.random), so a test can fix both:
let id =
time.with_fixed_clock
(time.from_unix_ms 1700000000000)
fn { random.with_seed 9 fn { uuid.v7 () } }
IDs sort by their creation time, to the millisecond; within a millisecond,
the order is random. Anyone who sees an ID can read when it was made, and an
ID is not a secret: session tokens should stay random.token.
Text forms
| Alphabet | Width | Notes |
|---|---|---|
crockford() | 26 | The default (show). Decoding ignores case and reads I and L as 1, O as 0. |
hex() | 32 | Lowercase; decoding also reads uppercase. |
base58() | 22 | No 0, O, I or l. |
base62() | 22 | Case-sensitive. |
alphabet(chars) | depends | Your own: at least 2 URL-safe characters, each once, in ascending ASCII order. |
Every encoding has its alphabet's width, padded with its first character, and alphabets are in ascending order: so encoded IDs compare as text exactly as the IDs compare.
In a route
Decode the ID from the path, and answer 404 when it isn't one:
fn show_order :: req: Request id: String -> Response / <orders>
{
match uuid.decode id (uuid.crockford ())
{ Ok(id) -> render (find_order id)
, Error(_) -> http.text 404 "no such order"
}
}
Cost
In a release build, a Crockford decode and encode take about 1.3 µs and
0.5 µs, and a preset like crockford() about 50 ns, so calling it per use
is fine. Hex, Crockford and any alphabet of 2, 4, 8, 16, 32 or 64
characters are read and written a few bits at a time; base 58, base 62
and other sizes go through a 128-bit integer and cost about ten times
more. alphabet(chars) checks its characters: build a custom alphabet
once and keep it. bench/ measures all of this (issue gabla108/louise#303):
louise build --release there, then build/uuid_bench.