use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
fn scratch(path: &Path, pid: u32, seq: u64) -> PathBuf {
let mut name = path
.file_name()
.map(|n| n.to_os_string())
.unwrap_or_default();
name.push(format!(".{pid}-{seq}.tmp"));
path.with_file_name(name)
}
pub fn write_file_atomically(path: &Path, text: &str) -> std::io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let tmp = scratch(
path,
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed),
);
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
let written = (|| -> std::io::Result<()> {
let mut file = opts.open(&tmp)?;
file.write_all(text.as_bytes())?;
file.sync_all()?;
Ok(())
})();
if let Err(e) = written {
let _ = std::fs::remove_file(&tmp);
return Err(e);
}
if let Err(e) = std::fs::rename(&tmp, path) {
let _ = std::fs::remove_file(&tmp);
return Err(e);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_write_leaves_no_scratch_file_behind() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
write_file_atomically(&path, "a = 1\n").unwrap();
assert_eq!(std::fs::read_to_string(&path).unwrap(), "a = 1\n");
let names: Vec<String> = std::fs::read_dir(dir.path())
.unwrap()
.flatten()
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
assert_eq!(names, ["config.toml"], "the temporary file is gone");
}
#[test]
fn every_writer_gets_its_own_scratch_name() {
let path = Path::new("/tmp/x/config.toml");
let (a, b) = (scratch(path, 7, 1), scratch(path, 7, 2));
assert_ne!(a, b, "a counter, because two writers share one process");
assert_ne!(scratch(path, 7, 1), scratch(path, 8, 1), "and a pid");
assert_eq!(a.parent(), path.parent(), "same directory, so rename works");
assert_eq!(
a.file_name().unwrap().to_string_lossy(),
"config.toml.7-1.tmp"
);
}
#[test]
fn a_reader_never_sees_a_half_written_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
let big_a = "a".repeat(200_000);
let big_b = "b".repeat(200_000);
write_file_atomically(&path, &big_a).unwrap();
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let expect = big_a.len();
let reader = {
let path = path.clone();
let stop = stop.clone();
std::thread::spawn(move || {
let mut seen = 0usize;
while !stop.load(std::sync::atomic::Ordering::Relaxed) {
let text = std::fs::read_to_string(&path).unwrap_or_default();
assert_eq!(
text.len(),
expect,
"a reader saw a {}-byte file, not the {expect} bytes written",
text.len()
);
seen += 1;
}
seen
})
};
for i in 0..200 {
write_file_atomically(&path, if i % 2 == 0 { &big_b } else { &big_a }).unwrap();
}
stop.store(true, std::sync::atomic::Ordering::Relaxed);
let seen = reader.join().unwrap();
assert!(seen > 0, "the reader ran at least once");
}
#[test]
fn a_failed_write_leaves_the_old_file_intact() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("jobs.toml");
write_file_atomically(&path, "kept\n").unwrap();
let blocked = dir.path().join("blocked.toml");
std::fs::create_dir(&blocked).unwrap();
std::fs::write(blocked.join("inner"), "x").unwrap();
assert!(write_file_atomically(&blocked, "new\n").is_err());
assert_eq!(
std::fs::read_dir(&blocked).unwrap().count(),
1,
"the directory that was there is still there"
);
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
"kept\n",
"and an unrelated file is untouched"
);
}
}