/// UUIDs (RFC 9562): version 7, and short text forms that sort like the /// IDs themselves. /// /// import uuid /// /// let id = uuid.v7() // reads `clock` and `random` /// uuid.to_rfc(id) // "0190f5a2-7c1e-7d3a-9b2c-4e5f60718293" /// show(id) // Crockford base 32, 26 characters /// uuid.encode(id, uuid.base62()) // 22 characters /// uuid.decode("01J3TT8Z0Y7MX6PB5S0SJ8S4WK", uuid.crockford()) // Ok(...) or an error /// /// A version 7 UUID starts with its creation time in milliseconds, so IDs /// sort by creation time (`<`, and the text of every alphabet here). Within /// one millisecond, the order is random. The time is readable by anyone who /// sees the ID: don't use v7 IDs where the creation time is a secret. They /// are not secrets either: session tokens should stay `random.token`. /// /// Text forms: `to_rfc`/`from_rfc` (the 36-character hex form), and /// `encode`/`decode` with an alphabet: `crockford()` (the default, used by /// `show`), `hex()`, `base58()`, `base62()`, or your own (`alphabet`). /// Every encoding has a fixed width, padded with the alphabet's first /// character, and alphabets must be in ascending ASCII order: so comparing /// two encoded IDs as text gives the same order as comparing the IDs. import std/bytes as raw import std/int as bits import std/list import std/random.{type random} import std/time.{type clock} /// A UUID: 16 bytes. Compared byte by byte, so version 7 IDs compare by /// creation time. @derive Eq Ord Hash pub opaque type Uuid { Uuid(Bytes) } /// The UUID whose bytes are `b`; `None` unless there are 16. pub fn from_bytes :: b: Bytes -> Option { if raw.length b == 16 { Some(Uuid(b)) } else { None } } /// The 16 bytes of `id`. pub fn to_bytes :: id: Uuid -> Bytes { match id { Uuid(b) -> b } } /// The nil UUID: every bit 0. pub fn nil :: -> Uuid { Uuid(raw.from_list (list.map (list.range 1 16) fn _ { 0 })) } /// The max UUID: every bit 1. pub fn max :: -> Uuid { Uuid(raw.from_list (list.map (list.range 1 16) fn _ { 255 })) } // ---- version 7 --------------------------------------------------------------------- /// A new version 7 UUID: the current Unix time in milliseconds, then 74 /// random bits. Panics if the clock is before 1970. pub fn v7 :: -> Uuid / { v7_from (time.unix_ms (time.now ())) (random.bytes 10) } /// The version 7 UUID of `unix_ms` and 10 bytes of `randomness` (RFC 9562, /// section 5.7): the time as 48 bits, big-endian; the version (7); 12 bits /// from the first two bytes; the variant (`10`); 62 bits from the rest. /// Panics unless `unix_ms` is in `[0, 2^48)` and there are 10 bytes. pub fn v7_from :: unix_ms: Int randomness: Bytes -> Uuid { if unix_ms < 0 || unix_ms >= 281474976710656 { panic "uuid.v7_from: the time {unix_ms} is not in [0, 2^48) milliseconds" } if raw.length randomness != 10 { panic "uuid.v7_from: expected 10 random bytes, got {raw.length randomness}" } let r = raw.to_list randomness match r { [r0, r1, r2, ..rest] -> { let time_bytes = list.map (list.range 0 5) fn i { bits.low_bits (bits.shift_right unix_ms (8 * (5 - i))) 8 } Uuid( raw.from_list (list.append time_bytes [112 + r0 % 16, r1, 128 + r2 % 64, ..rest]) ) } , _ -> panic "uuid.v7_from: expected 10 random bytes" } } /// The version: 4 for random UUIDs, 7 for time-ordered ones (the high /// nibble of byte 6). pub fn version :: id: Uuid -> Int { byte id 6 / 16 } /// When a version 7 UUID was made, in Unix milliseconds; `None` for any /// other UUID (another version, or not RFC 9562's variant). pub fn timestamp :: id: Uuid -> Option { if version id == 7 && byte id 8 / 64 == 2 { Some(list.fold (list.range 0 5) 0 fn acc i { acc * 256 + byte id i }) } else { None } } fn byte :: id: Uuid i: Int -> Int { match raw.get (to_bytes id) i { Some(b) -> b, None -> 0 } } /// 2^128: one more than the largest UUID. fn limit :: -> Int { bits.shift_left 1 128 } // ---- the RFC 9562 text form ---------------------------------------------------------- /// `id` as 32 lowercase hex digits in groups of 8-4-4-4-12: /// `017f22e2-79b0-7cc3-98c4-dc0c0c07398f`. pub fn to_rfc :: id: Uuid -> String { let digits = raw.from_string (encode id (hex ())) let part = fn start: Int end: Int { raw.to_string_lossy (raw.slice digits start end) } "{part 0 8}-{part 8 12}-{part 12 16}-{part 16 20}-{part 20 32}" } /// The UUID of an RFC 9562 text form: exactly 36 characters, hex digits in /// either case, dashes after the 8th, 12th, 16th and 20th digit. pub fn from_rfc :: text: String -> Option { let b = raw.from_string text let dashes = [8, 13, 18, 23] let dashed = list.all dashes fn i { raw.get b i == Some(45) } if raw.length b != 36 || !dashed { None } else { let digits = list.filter (raw.to_list b) fn c { c != 45 } match raw.to_string (raw.from_list digits) { Ok(hex_digits) -> decode hex_digits (hex ()) |> ok_or_none , Error(_) -> None } } } fn ok_or_none :: r: Result -> Option { match r { Ok(x) -> Some(x), Error(_) -> None } } // ---- alphabets ----------------------------------------------------------------------- /// The characters of a text form, from digit 0 up. Built by `alphabet`, /// or one of the presets. pub opaque type Alphabet { /// `chars` (in ascending ASCII order), the number of them, the digits of /// an encoding, the bits per digit when the base is a power of 2 (0 /// otherwise), whether `decode` also reads a letter in the other case, /// and other characters `decode` reads, with their digit. Alphabet( chars: Bytes , base: Int , width: Int , bits: Int , fold_case: Bool , aliases: List<(Int, Int)> ) } /// Why `alphabet` refused some characters. @derive Eq Show Debug pub type AlphabetError { /// Fewer than 2 characters. TooShort /// A character that appears twice. , Repeated(String) /// A character outside RFC 3986's unreserved set (`A-Z a-z 0-9 - . _ ~`), /// which would need escaping in a URL. , NotUrlSafe(String) /// A character that is not after the one before it in ASCII, so text /// would not sort like the IDs. The character is named. , NotAscending(String) } /// An alphabet of the characters of `chars`, digit 0 first: at least 2, /// each once, URL-safe, in ascending ASCII order. Checking them takes a /// few microseconds: build an alphabet once and keep it. pub fn alphabet :: chars: String -> Result { let codes = raw.to_list (raw.from_string chars) match ( list.filter codes fn c { !url_safe c } , first_repeated codes [] , first_descent codes ) { _ if list.length codes < 2 -> Error(TooShort) , ([c, ..], _, _) -> Error(NotUrlSafe(char c)) , (_, Some(c), _) -> Error(Repeated(char c)) , (_, _, Some(c)) -> Error(NotAscending(char c)) , _ -> { let base = list.length codes Ok( Alphabet( raw.from_list codes , base , width_for base 0 1 , bits_for base , False , [] ) ) } } } /// A preset: `chars` are known to be valid, and `width` and `k` right /// (the tests check them against `alphabet`), so nothing is computed per /// call. fn preset :: chars: String width: Int k: Int fold_case: Bool aliases: List<(Int, Int)> -> Alphabet { let b = raw.from_string chars Alphabet(b, raw.length b, width, k, fold_case, aliases) } /// The smallest `n` with `base^n >= 2^128`. fn width_for :: base: Int n: Int reach: Int -> Int { if reach >= limit () { n } else { width_for base (n + 1) (reach * base) } } /// `k` when `base` is `2^k`, else 0. fn bits_for :: base: Int -> Int { if bits.and base (base - 1) == 0 { bits.bit_length base - 1 } else { 0 } } /// RFC 3986's unreserved characters. fn url_safe :: c: Int -> Bool { c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || c == 45 || c == 46 || c == 95 || c == 126 } fn first_repeated :: codes: List seen: List -> Option { match codes { [] -> None , [c, ..rest] -> if list.any seen fn s { s == c } { Some(c) } else { first_repeated rest [c, ..seen] } } } fn first_descent :: codes: List -> Option { match codes { [a, b, ..rest] -> if b <= a { Some(b) } else { first_descent [b, ..rest] } , _ -> None } } /// The one-character string of an ASCII code. fn char :: c: Int -> String { raw.to_string_lossy (raw.from_list [c]) } /// The number of characters of every encoding with `a`. pub fn width :: a: Alphabet -> Int { match a { Alphabet(_, _, w, _, _, _) -> w } } /// Lowercase hex, 32 characters (`decode` also reads uppercase). pub fn hex :: -> Alphabet { preset "0123456789abcdef" 32 4 True [] } /// Crockford's base 32, 26 characters: digits and uppercase letters /// without I, L, O and U. `decode` also reads lowercase, and I and L as 1, /// O as 0 (in either case), as Crockford specifies. The default: `show` /// uses it. pub fn crockford :: -> Alphabet { preset "0123456789ABCDEFGHJKMNPQRSTVWXYZ" 26 5 True [(73, 1), (76, 1), (79, 0)] } /// Bitcoin's base 58, 22 characters: no 0, O, I or l, which look alike. pub fn base58 :: -> Alphabet { preset "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" 22 0 False [] } /// Digits, uppercase, then lowercase letters: 22 characters. pub fn base62 :: -> Alphabet { preset "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 22 0 False [] } /// The digit of the character `c`, or -1. `chars` is in ascending order, /// so it is searched by halves. fn digit_of :: c: Int chars: Bytes fold_case: Bool aliases: List<(Int, Int)> -> Int { let d = search chars c 0 (raw.length chars) if d >= 0 { d } else { match list.find aliases fn alias { alias.0 == c } { Some((_, alias)) -> alias , None if fold_case && is_letter c -> digit_of (other_case c) chars False aliases , None -> -1 } } } /// The index of `c` in `chars[lo..hi)`, or -1. fn search :: chars: Bytes c: Int lo: Int hi: Int -> Int { if lo >= hi { -1 } else { let mid = (lo + hi) / 2 let x = raw.read_u8 chars mid if x == c { mid } else if x < c { search chars c (mid + 1) hi } else { search chars c lo mid } } } /// A letter in the other case (ASCII). fn other_case :: c: Int -> Int { if c >= 97 { c - 32 } else { c + 32 } } fn is_letter :: c: Int -> Bool { c >= 65 && c <= 90 || c >= 97 && c <= 122 } // ---- encoding ------------------------------------------------------------------------ // An alphabet of 2^k characters is read and written k bits at a time, in // small `Int`s: the bits not yet consumed are `acc`, with `p` = 2^(their // number), so plain arithmetic (inlined) does what shifts and masks // would (calls into the runtime). Other bases go through the id's value, // a 128-bit `Int`. /// `id` with `a`'s characters: its 128 bits as a number in base /// `a`'s size, padded to `width(a)` with the first character. pub fn encode :: id: Uuid a: Alphabet -> String { match a { Alphabet(chars, base, w, k, _, _) if k > 0 -> { // `w * k` bits: the id's 128 after `w * k - 128` zero bits, which // count as already read. let out = raw.builder_with_capacity w raw.build_string (encode_bits (to_bytes id) 0 chars base 0 (pow2 (w * k - 128)) out) } , Alphabet(chars, base, w, _, _, _) -> { let value = list.fold (raw.to_list (to_bytes id)) 0 fn acc b { acc * 256 + b } raw.to_string_lossy (raw.from_list (digits value base w chars [])) } } } /// The digits of bytes `i..16` of `b`, after the bits `acc` (`p` = 2^n). fn encode_bits :: b: Bytes i: Int chars: Bytes base: Int acc: Int p: Int out: raw.Builder -> raw.Builder { if p >= base { let p = p / base let out = raw.append_byte out (raw.read_u8 chars (acc / p)) encode_bits b i chars base (acc % p) p out } else if i == 16 { out } else { encode_bits b (i + 1) chars base (acc * 256 + raw.read_u8 b i) (p * 256) out } } fn pow2 :: n: Int -> Int { if n == 0 { 1 } else { 2 * pow2 (n - 1) } } /// The last `n` digits of `value` in base `base`, as `chars`' codes, /// before `acc`. fn digits :: value: Int base: Int n: Int chars: Bytes acc: List -> List { if n == 0 { acc } else { let code = raw.read_u8 chars (value % base) digits (value / base) base (n - 1) chars [code, ..acc] } } /// Why `decode` refused a text. @derive Eq Show Debug pub type DecodeError { /// Not the alphabet's width: the length found. WrongLength(Int) /// A character that is not one of the alphabet's: its position. , InvalidChar(Int) /// The value is 2^128 or more: it is no UUID's. , TooLarge } /// The UUID `text` encodes with `a`. pub fn decode :: text: String a: Alphabet -> Result { let text = raw.from_string text match a { Alphabet(_, _, w, _, _, _) if raw.length text != w -> Error(WrongLength(raw.length text)) , Alphabet(chars, base, w, k, fold, aliases) if k > 0 -> { // The first digit only holds the id's top bits: the rest of its // bits are the padding, and must be 0. let top = base / pow2 (w * k - 128) let out = raw.builder_with_capacity 16 decode_bits text 0 chars fold aliases base top False 0 1 out } , Alphabet ( chars , base , _ , _ , fold , aliases ) -> match value_of text 0 0 chars base fold aliases { Error(e) -> Error(e) , Ok(v) if v >= limit () -> Error(TooLarge) , Ok(v) -> Ok(Uuid(raw.from_list (bytes_of v 16 []))) } } } /// The bytes of characters `i..` of `text`, after the bits `acc` (`p` = /// 2^n). A first digit of `top` or more makes the id too large, which is /// only reported when no character is invalid. fn decode_bits :: text: Bytes i: Int chars: Bytes fold: Bool aliases: List<(Int, Int)> base: Int top: Int too_large: Bool acc: Int p: Int out: raw.Builder -> Result { if p >= 256 { let p = p / 256 let out = raw.append_byte out (acc / p) decode_bits text i chars fold aliases base top too_large (acc % p) p out } else if i == raw.length text { if too_large { Error(TooLarge) } else { Ok(Uuid(raw.build out)) } } else { let d = digit_of (raw.read_u8 text i) chars fold aliases if d < 0 { Error(InvalidChar(i)) } else if i == 0 { decode_bits text 1 chars fold aliases base top (d >= top) (d % top) top out } else { decode_bits text (i + 1) chars fold aliases base top too_large (acc * base + d) (p * base) out } } } /// The value of `text` from character `at`, after `acc`. fn value_of :: text: Bytes at: Int acc: Int chars: Bytes base: Int fold: Bool aliases: List<(Int, Int)> -> Result { if at == raw.length text { Ok(acc) } else { let d = digit_of (raw.read_u8 text at) chars fold aliases if d < 0 { Error(InvalidChar(at)) } else { value_of text (at + 1) (acc * base + d) chars base fold aliases } } } /// The last `n` bytes of `v`, big-endian, before `acc`. fn bytes_of :: v: Int n: Int acc: List -> List { if n == 0 { acc } else { bytes_of (v / 256) (n - 1) [v % 256, ..acc] } } impl Show { fn show :: id { encode id (crockford ()) } } impl Debug { fn debug :: id { "uuid.Uuid({to_rfc id})" } }