Skip to main content

uuid_v7/
uuid_v7.rs

1//! UUID v7 deep dive โ€” time-ordered random UUIDs.
2//!
3//! Demonstrates:
4//!   * `Uuid::v7` (RFC 9562 ยง5.7 โ€” 48-bit ms prefix + 74 random bits)
5//!   * Byte-wise sort order matches time order
6//!   * Suitability as a database primary key
7//!
8//! Run with: `cargo run --release --example uuid_v7`
9
10use id_forge::uuid::Uuid;
11use std::thread::sleep;
12use std::time::Duration;
13
14fn main() {
15    println!("== UUID v7 time-ordered IDs ==");
16
17    let mut ids = Vec::new();
18    for i in 0..5 {
19        let id = Uuid::v7();
20        println!("#{i} {id}");
21        ids.push(id);
22        sleep(Duration::from_millis(2));
23    }
24
25    println!("\n== Byte-wise sort matches creation order ==");
26    let mut sorted = ids.clone();
27    sorted.sort();
28    println!("same order   = {}", sorted == ids);
29
30    println!("\n== Version field ==");
31    println!("first.version() = {}", ids[0].version());
32
33    println!("\n== As a database primary key ==");
34    // v7 IDs cluster recent inserts in B-tree leaves โ€” better cache
35    // locality than v4 for time-windowed queries.
36    let rows: Vec<(Uuid, &str)> = vec![
37        (Uuid::v7(), "alice signed up"),
38        (Uuid::v7(), "bob signed up"),
39        (Uuid::v7(), "carol signed up"),
40    ];
41    println!("Insert order (recent rows live near the tip of the index):");
42    for (id, evt) in &rows {
43        println!("  {id}  {evt}");
44    }
45}