use std::sync::OnceLock;
pub struct RunId;
static RUN_ID: OnceLock<String> = OnceLock::new();
impl RunId {
pub fn value() -> &'static str {
RUN_ID.get_or_init(generate)
}
}
fn generate() -> String {
use std::time::{SystemTime, UNIX_EPOCH};
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let pid = std::process::id() as u128;
let mixed = nanos.wrapping_mul(0x9E37_79B9_7F4A_7C15).wrapping_add(pid);
let low32 = (mixed & 0xFFFF_FFFF) as u32;
format!("{low32:08x}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn value_is_eight_hex_chars() {
let v = RunId::value();
assert_eq!(v.len(), 8, "expected 8 hex chars, got '{v}'");
assert!(
v.chars().all(|c| c.is_ascii_hexdigit()),
"expected all hex digits, got '{v}'"
);
}
#[test]
fn value_is_stable_within_a_process() {
let a = RunId::value();
let b = RunId::value();
assert_eq!(a, b);
}
#[test]
fn generate_produces_eight_hex_chars_deterministically_shaped() {
let v = generate();
assert_eq!(v.len(), 8);
assert!(
v.chars()
.all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
);
}
}