Skip to main content

uuid_v4/
uuid_v4.rs

1//! UUID v4 deep dive — random IDs and round-trip parsing.
2//!
3//! Demonstrates:
4//!   * `Uuid::v4` (random, RFC 9562 §5.4)
5//!   * `Uuid::nil` and `Uuid::max`
6//!   * `parse_str` round-trip with each kind of `ParseError`
7//!   * `as_bytes` storage round-trip
8//!
9//! Run with: `cargo run --release --example uuid_v4`
10
11use id_forge::uuid::{ParseError, Uuid};
12
13fn main() {
14    println!("== UUID v4 ==");
15
16    let a = Uuid::v4();
17    let b = Uuid::v4();
18    println!("a            = {a}");
19    println!("b            = {b}");
20    println!("a == b       = {}", a == b);
21    println!("a.version()  = {}", a.version());
22
23    println!("\n== Nil and Max ==");
24    println!("nil          = {}", Uuid::nil());
25    println!("max          = {}", Uuid::max());
26
27    println!("\n== parse_str round-trip ==");
28    let canonical = "f47ac10b-58cc-4372-a567-0e02b2c3d479";
29    let parsed = Uuid::parse_str(canonical).expect("canonical UUID parses");
30    println!("parse(\"{canonical}\") = {parsed}");
31    println!("round-trip ok = {}", parsed.to_string() == canonical);
32
33    println!("\n== Case-insensitive parse ==");
34    let upper = "F47AC10B-58CC-4372-A567-0E02B2C3D479";
35    let lower_round = Uuid::parse_str(upper).unwrap();
36    println!("upper input  -> {lower_round}  (Display is always lowercase)");
37
38    println!("\n== ParseError variants ==");
39    show_err("too short", Uuid::parse_str("abc"));
40    show_err(
41        "missing hyphen",
42        Uuid::parse_str("f47ac10b_58cc-4372-a567-0e02b2c3d479"),
43    );
44    show_err(
45        "non-hex digit",
46        Uuid::parse_str("g47ac10b-58cc-4372-a567-0e02b2c3d479"),
47    );
48
49    println!("\n== Byte storage round-trip ==");
50    let id = Uuid::v4();
51    let bytes: [u8; 16] = *id.as_bytes();
52    let restored = Uuid::from_bytes(&bytes);
53    println!("id           = {id}");
54    println!("restored     = {restored}");
55    println!("equal        = {}", id == restored);
56}
57
58fn show_err(label: &str, result: Result<Uuid, ParseError>) {
59    match result {
60        Ok(id) => println!("{label:<18} OK ({id})"),
61        Err(e) => println!("{label:<18} Err({e})"),
62    }
63}