| @@ -0,0 +1,356 @@ |
| 1 | +/// UUIDs (RFC 9562): version 7, and short text forms that sort like the |
| 2 | +/// IDs themselves. |
| 3 | +/// |
| 4 | +/// import uuid |
| 5 | +/// |
| 6 | +/// let id = uuid.v7() // reads `clock` and `random` |
| 7 | +/// uuid.to_rfc(id) // "0190f5a2-7c1e-7d3a-9b2c-4e5f60718293" |
| 8 | +/// show(id) // Crockford base 32, 26 characters |
| 9 | +/// uuid.encode(id, uuid.base62()) // 22 characters |
| 10 | +/// uuid.decode("01J3TT8Z0Y7MX6PB5S0SJ8S4WK", uuid.crockford()) // Ok(...) or an error |
| 11 | +/// |
| 12 | +/// A version 7 UUID starts with its creation time in milliseconds, so IDs |
| 13 | +/// sort by creation time (`<`, and the text of every alphabet here). Within |
| 14 | +/// one millisecond, the order is random. The time is readable by anyone who |
| 15 | +/// sees the ID: don't use v7 IDs where the creation time is a secret. They |
| 16 | +/// are not secrets either: session tokens should stay `random.token`. |
| 17 | +/// |
| 18 | +/// Text forms: `to_rfc`/`from_rfc` (the 36-character hex form), and |
| 19 | +/// `encode`/`decode` with an alphabet: `crockford()` (the default, used by |
| 20 | +/// `show`), `hex()`, `base58()`, `base62()`, or your own (`alphabet`). |
| 21 | +/// Every encoding has a fixed width, padded with the alphabet's first |
| 22 | +/// character, and alphabets must be in ascending ASCII order: so comparing |
| 23 | +/// two encoded IDs as text gives the same order as comparing the IDs. |
| 24 | + |
| 25 | +import std/bytes as raw |
| 26 | +import std/int as bits |
| 27 | +import std/list |
| 28 | +import std/random.{type random} |
| 29 | +import std/string |
| 30 | +import std/time.{type clock} |
| 31 | + |
| 32 | +/// A UUID: 16 bytes. Compared byte by byte, so version 7 IDs compare by |
| 33 | +/// creation time. |
| 34 | +@derive(Eq, Ord, Hash) |
| 35 | +pub opaque type Uuid { Uuid(Bytes) } |
| 36 | + |
| 37 | +/// The UUID whose bytes are `b`; `None` unless there are 16. |
| 38 | +pub fn from_bytes(b: Bytes) -> Option<Uuid> { |
| 39 | + if raw.length(b) == 16 { Some(Uuid(b)) } else { None } |
| 40 | +} |
| 41 | + |
| 42 | +/// The 16 bytes of `id`. |
| 43 | +pub fn to_bytes(id: Uuid) -> Bytes { |
| 44 | + match id { Uuid(b) -> b } |
| 45 | +} |
| 46 | + |
| 47 | +/// The nil UUID: every bit 0. |
| 48 | +pub fn nil() -> Uuid { |
| 49 | + Uuid(raw.from_list(list.map(list.range(1, 16), fn(_) { 0 }))) |
| 50 | +} |
| 51 | + |
| 52 | +/// The max UUID: every bit 1. |
| 53 | +pub fn max() -> Uuid { |
| 54 | + Uuid(raw.from_list(list.map(list.range(1, 16), fn(_) { 255 }))) |
| 55 | +} |
| 56 | + |
| 57 | +// ---- version 7 --------------------------------------------------------------------- |
| 58 | + |
| 59 | +/// A new version 7 UUID: the current Unix time in milliseconds, then 74 |
| 60 | +/// random bits. Panics if the clock is before 1970. |
| 61 | +pub fn v7() -> Uuid / <clock, random> { |
| 62 | + v7_from(time.unix_ms(time.now()), random.bytes(10)) |
| 63 | +} |
| 64 | + |
| 65 | +/// The version 7 UUID of `unix_ms` and 10 bytes of `randomness` (RFC 9562, |
| 66 | +/// section 5.7): the time as 48 bits, big-endian; the version (7); 12 bits |
| 67 | +/// from the first two bytes; the variant (`10`); 62 bits from the rest. |
| 68 | +/// Panics unless `unix_ms` is in `[0, 2^48)` and there are 10 bytes. |
| 69 | +pub fn v7_from(unix_ms: Int, randomness: Bytes) -> Uuid { |
| 70 | + if unix_ms < 0 || unix_ms >= 281474976710656 { |
| 71 | + panic("uuid.v7_from: the time {unix_ms} is not in [0, 2^48) milliseconds") |
| 72 | + } |
| 73 | + if raw.length(randomness) != 10 { |
| 74 | + panic("uuid.v7_from: expected 10 random bytes, got {raw.length(randomness)}") |
| 75 | + } |
| 76 | + let r = raw.to_list(randomness) |
| 77 | + match r { |
| 78 | + [r0, r1, r2, ..rest] -> { |
| 79 | + let time = list.map(list.range(0, 5), fn(i) { unix_ms / power(256, 5 - i) % 256 }) |
| 80 | + Uuid(raw.from_list(list.append(time, [112 + r0 % 16, r1, 128 + r2 % 64, ..rest]))) |
| 81 | + }, |
| 82 | + _ -> panic("uuid.v7_from: expected 10 random bytes"), |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +/// The version: 4 for random UUIDs, 7 for time-ordered ones (the high |
| 87 | +/// nibble of byte 6). |
| 88 | +pub fn version(id: Uuid) -> Int { |
| 89 | + byte(id, 6) / 16 |
| 90 | +} |
| 91 | + |
| 92 | +/// When a version 7 UUID was made, in Unix milliseconds; `None` for any |
| 93 | +/// other UUID (another version, or not RFC 9562's variant). |
| 94 | +pub fn timestamp(id: Uuid) -> Option<Int> { |
| 95 | + if version(id) == 7 && byte(id, 8) / 64 == 2 { |
| 96 | + Some(list.fold(list.range(0, 5), 0, fn(acc, i) { acc * 256 + byte(id, i) })) |
| 97 | + } else { |
| 98 | + None |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +fn byte(id: Uuid, i: Int) -> Int { |
| 103 | + match raw.get(to_bytes(id), i) { |
| 104 | + Some(b) -> b, |
| 105 | + None -> 0, |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +/// 2^128: one more than the largest UUID. |
| 110 | +fn limit() -> Int { |
| 111 | + bits.shift_left(1, 128) |
| 112 | +} |
| 113 | + |
| 114 | +fn power(base: Int, n: Int) -> Int { |
| 115 | + if n == 0 { 1 } else { base * power(base, n - 1) } |
| 116 | +} |
| 117 | + |
| 118 | +// ---- the RFC 9562 text form ---------------------------------------------------------- |
| 119 | + |
| 120 | +/// `id` as 32 lowercase hex digits in groups of 8-4-4-4-12: |
| 121 | +/// `017f22e2-79b0-7cc3-98c4-dc0c0c07398f`. |
| 122 | +pub fn to_rfc(id: Uuid) -> String { |
| 123 | + let digits = raw.from_string(encode(id, hex())) |
| 124 | + let part = fn(start: Int, end: Int) { raw.to_string_lossy(raw.slice(digits, start, end)) } |
| 125 | + "{part(0, 8)}-{part(8, 12)}-{part(12, 16)}-{part(16, 20)}-{part(20, 32)}" |
| 126 | +} |
| 127 | + |
| 128 | +/// The UUID of an RFC 9562 text form: exactly 36 characters, hex digits in |
| 129 | +/// either case, dashes after the 8th, 12th, 16th and 20th digit. |
| 130 | +pub fn from_rfc(text: String) -> Option<Uuid> { |
| 131 | + let b = raw.from_string(text) |
| 132 | + let dashes = [8, 13, 18, 23] |
| 133 | + let dashed = list.all(dashes, fn(i) { raw.get(b, i) == Some(45) }) |
| 134 | + if raw.length(b) != 36 || !dashed { |
| 135 | + None |
| 136 | + } else { |
| 137 | + let digits = list.filter(raw.to_list(b), fn(c) { c != 45 }) |
| 138 | + match raw.to_string(raw.from_list(digits)) { |
| 139 | + Ok(hex_digits) -> decode(hex_digits, hex()) |> ok_or_none, |
| 140 | + Error(_) -> None, |
| 141 | + } |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +fn ok_or_none(r: Result<a, e>) -> Option<a> { |
| 146 | + match r { |
| 147 | + Ok(x) -> Some(x), |
| 148 | + Error(_) -> None, |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +// ---- alphabets ----------------------------------------------------------------------- |
| 153 | + |
| 154 | +/// The characters of a text form, from digit 0 up. Built by `alphabet`, |
| 155 | +/// or one of the presets. |
| 156 | +pub opaque type Alphabet { |
| 157 | + /// `chars`, the number of them, the digits of an encoding, and other |
| 158 | + /// characters `decode` also reads (lowercase for uppercase, say), with |
| 159 | + /// their digit. |
| 160 | + Alphabet(chars: Bytes, base: Int, width: Int, aliases: List<(Int, Int)>) |
| 161 | +} |
| 162 | + |
| 163 | +/// Why `alphabet` refused some characters. |
| 164 | +@derive(Eq, Show, Debug) |
| 165 | +pub type AlphabetError { |
| 166 | + /// Fewer than 2 characters. |
| 167 | + TooShort |
| 168 | + /// A character that appears twice. |
| 169 | + Repeated(String) |
| 170 | + /// A character outside RFC 3986's unreserved set (`A-Z a-z 0-9 - . _ ~`), |
| 171 | + /// which would need escaping in a URL. |
| 172 | + NotUrlSafe(String) |
| 173 | + /// A character that is not after the one before it in ASCII, so text |
| 174 | + /// would not sort like the IDs. The character is named. |
| 175 | + NotAscending(String) |
| 176 | +} |
| 177 | + |
| 178 | +/// An alphabet of the characters of `chars`, digit 0 first: at least 2, |
| 179 | +/// each once, URL-safe, in ascending ASCII order. |
| 180 | +pub fn alphabet(chars: String) -> Result<Alphabet, AlphabetError> { |
| 181 | + let codes = raw.to_list(raw.from_string(chars)) |
| 182 | + match (list.filter(codes, fn(c) { !url_safe(c) }), first_repeated(codes, []), first_descent(codes)) { |
| 183 | + _ if list.length(codes) < 2 -> Error(TooShort), |
| 184 | + ([c, ..], _, _) -> Error(NotUrlSafe(char(c))), |
| 185 | + (_, Some(c), _) -> Error(Repeated(char(c))), |
| 186 | + (_, _, Some(c)) -> Error(NotAscending(char(c))), |
| 187 | + _ -> Ok(make(codes, [])), |
| 188 | + } |
| 189 | +} |
| 190 | + |
| 191 | +fn make(codes: List<Int>, aliases: List<(Int, Int)>) -> Alphabet { |
| 192 | + let base = list.length(codes) |
| 193 | + Alphabet(raw.from_list(codes), base, width_for(base, 0, 1), aliases) |
| 194 | +} |
| 195 | + |
| 196 | +/// The smallest `n` with `base^n >= 2^128`. |
| 197 | +fn width_for(base: Int, n: Int, reach: Int) -> Int { |
| 198 | + if reach >= limit() { |
| 199 | + n |
| 200 | + } else { |
| 201 | + width_for(base, n + 1, reach * base) |
| 202 | + } |
| 203 | +} |
| 204 | + |
| 205 | +/// RFC 3986's unreserved characters. |
| 206 | +fn url_safe(c: Int) -> Bool { |
| 207 | + c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || c == 45 || c == 46 || c == 95 || c == 126 |
| 208 | +} |
| 209 | + |
| 210 | +fn first_repeated(codes: List<Int>, seen: List<Int>) -> Option<Int> { |
| 211 | + match codes { |
| 212 | + [] -> None, |
| 213 | + [c, ..rest] -> if list.any(seen, fn(s) { s == c }) { Some(c) } else { first_repeated(rest, [c, ..seen]) }, |
| 214 | + } |
| 215 | +} |
| 216 | + |
| 217 | +fn first_descent(codes: List<Int>) -> Option<Int> { |
| 218 | + match codes { |
| 219 | + [a, b, ..rest] -> if b <= a { Some(b) } else { first_descent([b, ..rest]) }, |
| 220 | + _ -> None, |
| 221 | + } |
| 222 | +} |
| 223 | + |
| 224 | +/// The one-character string of an ASCII code. |
| 225 | +fn char(c: Int) -> String { |
| 226 | + raw.to_string_lossy(raw.from_list([c])) |
| 227 | +} |
| 228 | + |
| 229 | +/// The number of characters of every encoding with `a`. |
| 230 | +pub fn width(a: Alphabet) -> Int { |
| 231 | + match a { Alphabet(_, _, w, _) -> w } |
| 232 | +} |
| 233 | + |
| 234 | +/// Lowercase hex, 32 characters (`decode` also reads uppercase). |
| 235 | +pub fn hex() -> Alphabet { |
| 236 | + let digits = codes_of("0123456789abcdef") |
| 237 | + make(digits, list.map(list.range(0, 5), fn(i) { (65 + i, 10 + i) })) |
| 238 | +} |
| 239 | + |
| 240 | +/// Crockford's base 32, 26 characters: digits and uppercase letters |
| 241 | +/// without I, L, O and U. `decode` also reads lowercase, and I and L as 1, |
| 242 | +/// O as 0 (in either case), as Crockford specifies. The default: `show` |
| 243 | +/// uses it. |
| 244 | +pub fn crockford() -> Alphabet { |
| 245 | + let digits = codes_of("0123456789ABCDEFGHJKMNPQRSTVWXYZ") |
| 246 | + let lower = list.map(list.range(10, 31), fn(d) { (nth(digits, d) + 32, d) }) |
| 247 | + make(digits, list.append(lower, [(73, 1), (105, 1), (76, 1), (108, 1), (79, 0), (111, 0)])) |
| 248 | +} |
| 249 | + |
| 250 | +/// Bitcoin's base 58, 22 characters: no 0, O, I or l, which look alike. |
| 251 | +pub fn base58() -> Alphabet { |
| 252 | + make(codes_of("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"), []) |
| 253 | +} |
| 254 | + |
| 255 | +/// Digits, uppercase, then lowercase letters: 22 characters. |
| 256 | +pub fn base62() -> Alphabet { |
| 257 | + make(codes_of("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"), []) |
| 258 | +} |
| 259 | + |
| 260 | +fn codes_of(s: String) -> List<Int> { |
| 261 | + raw.to_list(raw.from_string(s)) |
| 262 | +} |
| 263 | + |
| 264 | +fn nth(xs: List<Int>, i: Int) -> Int { |
| 265 | + match xs { |
| 266 | + [] -> 0, |
| 267 | + [x, ..rest] -> if i == 0 { x } else { nth(rest, i - 1) }, |
| 268 | + } |
| 269 | +} |
| 270 | + |
| 271 | +// ---- encoding ------------------------------------------------------------------------ |
| 272 | + |
| 273 | +/// `id` with `a`'s characters: its 128 bits as a number in base |
| 274 | +/// `a`'s size, padded to `width(a)` with the first character. |
| 275 | +pub fn encode(id: Uuid, a: Alphabet) -> String { |
| 276 | + match a { |
| 277 | + Alphabet(chars, base, w, _) -> { |
| 278 | + let value = list.fold(raw.to_list(to_bytes(id)), 0, fn(acc, b) { acc * 256 + b }) |
| 279 | + raw.to_string_lossy(raw.from_list(digits(value, base, w, chars, []))) |
| 280 | + }, |
| 281 | + } |
| 282 | +} |
| 283 | + |
| 284 | +/// The last `n` digits of `value` in base `base`, as `chars`' codes, |
| 285 | +/// before `acc`. |
| 286 | +fn digits(value: Int, base: Int, n: Int, chars: Bytes, acc: List<Int>) -> List<Int> { |
| 287 | + if n == 0 { |
| 288 | + acc |
| 289 | + } else { |
| 290 | + let code = match raw.get(chars, value % base) { |
| 291 | + Some(c) -> c, |
| 292 | + None -> 0, |
| 293 | + } |
| 294 | + digits(value / base, base, n - 1, chars, [code, ..acc]) |
| 295 | + } |
| 296 | +} |
| 297 | + |
| 298 | +/// Why `decode` refused a text. |
| 299 | +@derive(Eq, Show, Debug) |
| 300 | +pub type DecodeError { |
| 301 | + /// Not the alphabet's width: the length found. |
| 302 | + WrongLength(Int) |
| 303 | + /// A character that is not one of the alphabet's: its position. |
| 304 | + InvalidChar(Int) |
| 305 | + /// The value is 2^128 or more: it is no UUID's. |
| 306 | + TooLarge |
| 307 | +} |
| 308 | + |
| 309 | +/// The UUID `text` encodes with `a`. |
| 310 | +pub fn decode(text: String, a: Alphabet) -> Result<Uuid, DecodeError> { |
| 311 | + match a { |
| 312 | + Alphabet(chars, base, w, aliases) -> { |
| 313 | + let codes = raw.to_list(raw.from_string(text)) |
| 314 | + if list.length(codes) != w { |
| 315 | + Error(WrongLength(list.length(codes))) |
| 316 | + } else { |
| 317 | + match value_of(codes, 0, 0, chars, base, aliases) { |
| 318 | + Error(e) -> Error(e), |
| 319 | + Ok(v) if v >= limit() -> Error(TooLarge), |
| 320 | + Ok(v) -> Ok(Uuid(raw.from_list(list.map(list.range(0, 15), fn(i) { v / power(256, 15 - i) % 256 })))), |
| 321 | + } |
| 322 | + } |
| 323 | + }, |
| 324 | + } |
| 325 | +} |
| 326 | + |
| 327 | +fn value_of(codes: List<Int>, at: Int, acc: Int, chars: Bytes, base: Int, aliases: List<(Int, Int)>) -> Result<Int, DecodeError> { |
| 328 | + match codes { |
| 329 | + [] -> Ok(acc), |
| 330 | + [c, ..rest] -> match digit_of(c, chars, 0, aliases) { |
| 331 | + Some(d) -> value_of(rest, at + 1, acc * base + d, chars, base, aliases), |
| 332 | + None -> Error(InvalidChar(at)), |
| 333 | + }, |
| 334 | + } |
| 335 | +} |
| 336 | + |
| 337 | +fn digit_of(c: Int, chars: Bytes, i: Int, aliases: List<(Int, Int)>) -> Option<Int> { |
| 338 | + match raw.get(chars, i) { |
| 339 | + Some(x) if x == c -> Some(i), |
| 340 | + Some(_) -> digit_of(c, chars, i + 1, aliases), |
| 341 | + None -> list.fold(aliases, None, fn(found, alias) { |
| 342 | + match alias { |
| 343 | + (code, d) if code == c -> Some(d), |
| 344 | + _ -> found, |
| 345 | + } |
| 346 | + }), |
| 347 | + } |
| 348 | +} |
| 349 | + |
| 350 | +impl Show<Uuid> { |
| 351 | + fn show(id) { encode(id, crockford()) } |
| 352 | +} |
| 353 | + |
| 354 | +impl Debug<Uuid> { |
| 355 | + fn debug(id) { "uuid.Uuid({to_rfc(id)})" } |
| 356 | +} |