Skip to main content

php_std/
system.rs

1//! Process and host functions.
2
3use std::time::{SystemTime, UNIX_EPOCH};
4
5/// PHP `gethostname()`: the kernel's node name.
6pub fn gethostname() -> String {
7    rustix::system::uname().nodename().to_string_lossy().into_owned()
8}
9
10/// PHP `getmypid()`.
11pub fn getmypid() -> u32 {
12    std::process::id()
13}
14
15/// PHP `uniqid($prefix, $more_entropy)`: seconds and microseconds in hex
16/// (`%08x%05x`), plus `%.8F` of a random value in `[0, 10)` with more entropy.
17///
18/// Without more entropy, like PHP, two calls never return the same value in
19/// one process: a call in the same microsecond as the previous one waits for
20/// the clock to move on.
21pub 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}