1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
use std::{fs as std_fs, io::Write, path::Path};
use tokio::{fs as tokio_fs, io::AsyncWriteExt};
/// Write file to filesystem atomically using std::fs synchronously.
pub fn atomically_write_file_sync(
tempfile: impl AsRef<Path>,
dest: impl AsRef<Path>,
content: &[u8],
) -> std::io::Result<()> {
let mut file = std_fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(tempfile.as_ref())?;
if let Err(err) = file.write_all(content) {
let _ = std_fs::remove_file(tempfile);
return Err(err);
}
if let Err(err) = std_fs::rename(tempfile.as_ref(), dest) {
let _ = std_fs::remove_file(tempfile);
return Err(err);
}
Ok(())
}
/// Write file to filesystem atomically using tokio::fs asynchronously.
pub async fn atomically_write_file_async(
tempfile: impl AsRef<Path>,
dest: impl AsRef<Path>,
content: &[u8],
) -> std::io::Result<()> {
let mut file = tokio_fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(tempfile.as_ref())
.await?;
if let Err(err) = file.write_all(content).await {
let () = tokio_fs::remove_file(tempfile).await?;
return Err(err);
}
if let Err(err) = tokio_fs::rename(tempfile.as_ref(), dest).await {
let () = tokio_fs::remove_file(tempfile).await?;
return Err(err);
}
Ok(())
}
#[cfg(test)]
mod tests {
use crate::fs::{atomically_write_file_async, atomically_write_file_sync};
use tempfile::tempdir;
#[tokio::test]
async fn atomically_write_file_file_async() {
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().join("test1");
let destination_path = temp_dir.path().join("test2");
let content = "test_data";
let () = atomically_write_file_async(&temp_path, &destination_path, content.as_bytes())
.await
.unwrap();
std::fs::File::open(&temp_path).unwrap_err();
if let Ok(destination_content) = std::fs::read(&destination_path) {
assert_eq!(destination_content, content.as_bytes());
} else {
panic!("failed to read the new file");
}
}
#[test]
fn atomically_write_file_file_sync() {
let temp_dir = tempdir().unwrap();
let temp_path = temp_dir.path().join("test1");
let destination_path = temp_dir.path().join("test2");
let content = "test_data";
let () =
atomically_write_file_sync(&temp_path, &destination_path, content.as_bytes()).unwrap();
std::fs::File::open(&temp_path).unwrap_err();
if let Ok(destination_content) = std::fs::read(&destination_path) {
assert_eq!(destination_content, content.as_bytes());
} else {
panic!("failed to read the new file");
}
}
}
|