Skip to main content

ulid_monotonic/
ulid_monotonic.rs

1//! ULID monotonic factory deep dive.
2//!
3//! Demonstrates:
4//!   * `Ulid::new` per the ULID spec
5//!   * Strict monotonicity inside a single millisecond
6//!   * `timestamp_ms` accessor and Crockford base32 round-trip
7//!
8//! Run with: `cargo run --release --example ulid_monotonic`
9
10use id_forge::ulid::Ulid;
11use std::collections::HashSet;
12
13fn main() {
14    println!("== Single-millisecond burst ==");
15
16    // 1000 ULIDs back-to-back. Most will share the same ms prefix;
17    // the monotonic factory guarantees b > a for every consecutive pair.
18    let mut ids: Vec<Ulid> = (0..1000).map(|_| Ulid::new()).collect();
19
20    let same_ms = ids
21        .windows(2)
22        .filter(|w| w[0].timestamp_ms() == w[1].timestamp_ms())
23        .count();
24    println!("count        = {}", ids.len());
25    println!("same-ms pairs = {same_ms} of {}", ids.len() - 1);
26
27    let strictly_increasing = ids.windows(2).all(|w| w[1] > w[0]);
28    println!("monotonic    = {strictly_increasing}");
29
30    let unique: HashSet<&Ulid> = ids.iter().collect();
31    println!("unique       = {} of {}", unique.len(), ids.len());
32
33    println!("\n== First and last of the burst ==");
34    let first = ids.first().unwrap();
35    let last = ids.last().unwrap();
36    println!("first        = {first}");
37    println!("last         = {last}");
38    println!("ts_first     = {} ms", first.timestamp_ms());
39    println!("ts_last      = {} ms", last.timestamp_ms());
40
41    println!("\n== Crockford base32 round-trip ==");
42    let sample = Ulid::new();
43    let s = sample.to_string();
44    let parsed = Ulid::parse_str(&s).unwrap();
45    println!("sample       = {sample}");
46    println!("parsed       = {parsed}");
47    println!("equal        = {}", sample == parsed);
48
49    println!("\n== Substitutions accepted by parse_str ==");
50    let with_subs = Ulid::parse_str("0IIIIIIIIIIIIIIIIIIIIIIIII").unwrap();
51    let canonical = Ulid::parse_str("01111111111111111111111111").unwrap();
52    println!("\"0III...\" == \"0111...\" = {}", with_subs == canonical);
53
54    println!("\n== Sorting by Display is sorting by time ==");
55    ids.sort_by_key(|u| u.to_string());
56    let same = ids.windows(2).all(|w| w[1] >= w[0]);
57    println!("string sort  = byte sort = {same}");
58}