summaryrefslogtreecommitdiff
path: root/src/persistence.rs
diff options
context:
space:
mode:
authortroido <troido@protonmail.com>2020-03-05 18:30:38 +0100
committertroido <troido@protonmail.com>2020-03-05 18:30:38 +0100
commita8be1d11b929ffcc3cfb50880f4d489059fc9a0f (patch)
treed0d9fb21d6853b2dbbb5f376ac07fac0a282bb92 /src/persistence.rs
parent23675c3d5dd8ef912f9a46a1bc999e9732bd6526 (diff)
write files to a tempfile first
Diffstat (limited to 'src/persistence.rs')
-rw-r--r--src/persistence.rs13
1 files changed, 10 insertions, 3 deletions
diff --git a/src/persistence.rs b/src/persistence.rs
index e9ce787..f1ed845 100644
--- a/src/persistence.rs
+++ b/src/persistence.rs
@@ -1,5 +1,5 @@
-use std::path::PathBuf;
+use std::path::{PathBuf, Path};
use std::fs;
use std::env;
use serde_json;
@@ -85,7 +85,7 @@ impl PersistentStorage for FileStorage {
path.push(fname);
let text = state.to_json().to_string();
// todo: write to a temp file first
- fs::write(path, text)?;
+ write_file_safe(path, text)?;
Ok(())
}
@@ -97,8 +97,15 @@ impl PersistentStorage for FileStorage {
path.push(fname);
let text = state.to_json().to_string();
// todo: write to a temp file first
- fs::write(path, text)?;
+ write_file_safe(path, text)?;
Ok(())
}
}
+fn write_file_safe<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
+ let temppath = path.as_ref().with_file_name(format!("tempfile_{}.tmp", rand::random::<u64>()));
+ fs::write(&temppath, contents)?;
+ fs::rename(&temppath, path)?;
+ Ok(())
+}
+