Skip to main content

witness_core/
util.rs

1//! Small helpers shared by the crates that keep files on disk.
2
3use std::fs::{self, File};
4use std::io::Write;
5use std::path::Path;
6use std::time::{SystemTime, UNIX_EPOCH};
7
8/// Replaces `path` so that a crash leaves the old contents or the new ones,
9/// never part of them: the bytes are synced to a temporary file, the file is
10/// renamed, and the directory is synced so that the rename survives too.
11pub fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
12    let tmp = path.with_extension("tmp");
13    {
14        let mut f = File::create(&tmp)?;
15        f.write_all(bytes)?;
16        f.sync_all()?;
17    }
18    fs::rename(&tmp, path)?;
19    if let Some(parent) = path.parent()
20        && let Ok(d) = File::open(parent)
21    {
22        d.sync_all().ok();
23    }
24    Ok(())
25}
26
27/// Milliseconds since the Unix epoch, or 0 if the clock is before it.
28pub fn now_ms() -> u64 {
29    SystemTime::now()
30        .duration_since(UNIX_EPOCH)
31        .map(|d| d.as_millis() as u64)
32        .unwrap_or(0)
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn write_atomic_replaces_the_file_and_leaves_no_temporary() {
41        let dir = std::env::temp_dir().join(format!("witness-util-{}", std::process::id()));
42        fs::create_dir_all(&dir).unwrap();
43        let path = dir.join("state.json");
44        write_atomic(&path, b"one").unwrap();
45        write_atomic(&path, b"two").unwrap();
46        assert_eq!(fs::read(&path).unwrap(), b"two");
47        assert!(!path.with_extension("tmp").exists());
48        fs::remove_dir_all(&dir).unwrap();
49    }
50}