1use std::fs::{self, OpenOptions};
5use std::io::{self, Write};
6use std::path::{Path, PathBuf};
7use std::time::{SystemTime, UNIX_EPOCH};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
11#[non_exhaustive]
12pub enum Access {
13 #[default]
15 Default,
16 OwnerOnly,
19}
20
21pub fn write_new(path: &Path, contents: &[u8], access: Access) -> io::Result<()> {
30 let temporary = written(path, contents, access)?;
31 let result = retried(|| fs::hard_link(&temporary, path));
32 let _ = fs::remove_file(&temporary);
33 result
34}
35
36pub fn replace(path: &Path, contents: &[u8], access: Access) -> io::Result<()> {
44 let temporary = written(path, contents, access)?;
45 let result = retried(|| fs::rename(&temporary, path));
46 if result.is_err() {
47 let _ = fs::remove_file(&temporary);
48 }
49 result
50}
51
52pub(crate) fn retried(mut operation: impl FnMut() -> io::Result<()>) -> io::Result<()> {
57 let mut wait = core::time::Duration::from_millis(2);
58 loop {
59 match operation() {
60 Err(error)
61 if cfg!(windows)
62 && error.kind() == io::ErrorKind::PermissionDenied
63 && wait <= core::time::Duration::from_millis(512) =>
64 {
65 std::thread::sleep(wait);
66 wait *= 2;
67 }
68 result => return result,
69 }
70 }
71}
72
73fn written(path: &Path, contents: &[u8], access: Access) -> io::Result<PathBuf> {
75 let parent = path
76 .parent()
77 .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?;
78 if !parent.as_os_str().is_empty() {
79 fs::create_dir_all(parent)?;
80 }
81 let temporary = temporary_path(path);
82 let mut options = OpenOptions::new();
83 options.write(true).create_new(true);
84 #[cfg(unix)]
85 if access == Access::OwnerOnly {
86 use std::os::unix::fs::OpenOptionsExt;
87 options.mode(0o600);
88 }
89 #[cfg(not(unix))]
90 let _ = access;
91 let mut file = options.open(&temporary)?;
92 let result = file.write_all(contents).and_then(|()| file.sync_all());
93 drop(file);
94 match result {
95 Ok(()) => Ok(temporary),
96 Err(error) => {
97 let _ = fs::remove_file(&temporary);
98 Err(error)
99 }
100 }
101}
102
103pub(crate) fn temporary_path(path: &Path) -> PathBuf {
106 static NEXT: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
107 let count = NEXT.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
108 let nonce = SystemTime::now()
109 .duration_since(UNIX_EPOCH)
110 .map_or(0, |elapsed| elapsed.as_nanos());
111 let mut name = path.file_name().unwrap_or_default().to_os_string();
112 name.push(format!(".{}.{}.{}.tmp", std::process::id(), nonce, count));
113 path.with_file_name(name)
114}