1use std::time::{SystemTime, UNIX_EPOCH};
4
5pub fn gethostname() -> String {
7 rustix::system::uname().nodename().to_string_lossy().into_owned()
8}
9
10pub fn getmypid() -> u32 {
12 std::process::id()
13}
14
15pub fn uniqid(prefix: &str, more_entropy: bool) -> String {
22 static LAST: std::sync::Mutex<(u64, u32)> = std::sync::Mutex::new((0, 0));
23 let mut now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
24 if !more_entropy {
25 let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());
26 while (now.as_secs(), now.subsec_micros()) == *last {
27 std::hint::spin_loop();
28 now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
29 }
30 *last = (now.as_secs(), now.subsec_micros());
31 }
32 let mut out = format!("{prefix}{:08x}{:05x}", now.as_secs(), now.subsec_micros());
33 if more_entropy {
34 let mut bytes = [0u8; 8];
35 let _ = getrandom::fill(&mut bytes);
36 let lcg = (u64::from_le_bytes(bytes) >> 11) as f64 / (1u64 << 53) as f64;
37 out.push_str(&format!("{:.8}", lcg * 10.0));
38 }
39 out
40}
41
42#[cfg(test)]
43mod tests {
44 use super::*;
45
46 #[test]
47 fn uniqid_shape() {
48 let id = uniqid("", true);
49 assert_eq!(id.len(), 23, "{id}");
50 assert_eq!(&id[14..15], ".");
51 assert_eq!(uniqid("p", false).len(), 14);
52 }
53}