1use std::fs::{self, File};
4use std::io::Write;
5use std::path::Path;
6use std::time::{SystemTime, UNIX_EPOCH};
7
8pub 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
27pub 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}