Skip to main content

nexus_memory_core/
fsutil.rs

1//! Filesystem utilities shared across crates.
2
3use std::io::Write;
4use std::path::Path;
5
6/// Write a file atomically: write to a temp file, sync, then rename.
7/// Prevents partial writes on crash. Uses PID-scoped tmp to avoid
8/// collision when concurrent processes write the same target.
9pub fn atomic_write(path: &Path, content: &str) -> std::io::Result<()> {
10    let tmp_path = path.with_extension(format!(
11        "tmp.{}-{}",
12        std::process::id(),
13        uuid::Uuid::new_v4()
14    ));
15    {
16        let mut f = std::fs::File::create(&tmp_path)?;
17        f.write_all(content.as_bytes())?;
18        f.sync_all()?;
19    }
20    let result = std::fs::rename(&tmp_path, path);
21    if result.is_err() {
22        let _ = std::fs::remove_file(&tmp_path);
23    }
24    result
25}