1use std::io::Write;
9use std::path::{Path, PathBuf};
10use std::sync::atomic::{AtomicU64, Ordering};
11
12#[derive(Debug, Clone, Copy)]
13pub struct WriteOpts {
14 pub mode: Option<u32>,
15 pub fsync: bool,
16}
17
18impl WriteOpts {
19 pub const DURABLE: Self = Self {
20 mode: None,
21 fsync: true,
22 };
23 pub const PRIVATE: Self = Self {
24 mode: Some(0o600),
25 fsync: true,
26 };
27 pub const FAST: Self = Self {
28 mode: None,
29 fsync: false,
30 };
31}
32
33fn temp_sibling(path: &Path) -> PathBuf {
34 static NEXT: AtomicU64 = AtomicU64::new(0);
35 let name = path
36 .file_name()
37 .map(|n| n.to_string_lossy().into_owned())
38 .unwrap_or_default();
39 let nanos = std::time::SystemTime::now()
40 .duration_since(std::time::UNIX_EPOCH)
41 .map_or(0, |d| d.subsec_nanos());
42 path.with_file_name(format!(
43 ".{name}.{}-{}-{nanos:08x}.tmp",
44 std::process::id(),
45 NEXT.fetch_add(1, Ordering::Relaxed),
46 ))
47}
48
49pub fn write_atomic(path: &Path, bytes: &[u8], opts: WriteOpts) -> std::io::Result<()> {
51 let tmp = temp_sibling(path);
52 let result = write_temp(&tmp, bytes, opts).and_then(|()| std::fs::rename(&tmp, path));
53 if result.is_err() {
54 let _ = std::fs::remove_file(&tmp);
55 return result;
56 }
57 #[cfg(unix)]
58 if opts.fsync {
59 if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
60 if let Ok(d) = std::fs::File::open(dir) {
61 let _ = d.sync_all();
62 }
63 }
64 }
65 Ok(())
66}
67
68fn write_temp(tmp: &Path, bytes: &[u8], opts: WriteOpts) -> std::io::Result<()> {
69 let mut options = std::fs::OpenOptions::new();
70 options.write(true).create_new(true);
71 #[cfg(unix)]
72 if let Some(mode) = opts.mode {
73 use std::os::unix::fs::OpenOptionsExt;
74 options.mode(mode);
75 }
76 let mut file = options.open(tmp)?;
77 #[cfg(unix)]
78 if let Some(mode) = opts.mode {
79 use std::os::unix::fs::PermissionsExt;
80 file.set_permissions(std::fs::Permissions::from_mode(mode))?;
81 }
82 file.write_all(bytes)?;
83 if opts.fsync {
84 file.sync_all()?;
85 }
86 Ok(())
87}
88
89#[cfg(test)]
90mod tests {
91 use super::*;
92
93 #[test]
94 fn replaces_the_file_and_leaves_no_temp_behind() {
95 let dir = tempfile::tempdir().unwrap();
96 let path = dir.path().join("a.json");
97 write_atomic(&path, b"one", WriteOpts::DURABLE).unwrap();
98 write_atomic(&path, b"two", WriteOpts::FAST).unwrap();
99 assert_eq!(std::fs::read(&path).unwrap(), b"two");
100 assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
101 }
102
103 #[test]
104 fn a_missing_parent_is_an_error_not_created() {
105 let dir = tempfile::tempdir().unwrap();
106 let path = dir.path().join("missing").join("a");
107 assert!(write_atomic(&path, b"x", WriteOpts::DURABLE).is_err());
108 assert!(!dir.path().join("missing").exists());
109 }
110
111 #[cfg(unix)]
112 #[test]
113 fn private_mode_survives_a_permissive_umask_and_a_rewrite() {
114 use std::os::unix::fs::PermissionsExt;
115 let dir = tempfile::tempdir().unwrap();
116 let path = dir.path().join("secret");
117 write_atomic(&path, b"1", WriteOpts::PRIVATE).unwrap();
118 write_atomic(&path, b"2", WriteOpts::PRIVATE).unwrap();
119 let mode = std::fs::metadata(&path).unwrap().permissions().mode();
120 assert_eq!(mode & 0o777, 0o600);
121 }
122
123 #[test]
124 fn temp_names_differ_within_one_process() {
125 let p = Path::new("/x/y.json");
126 assert_ne!(temp_sibling(p), temp_sibling(p));
127 }
128}