aboutsummaryrefslogtreecommitdiff
path: root/src/util
diff options
context:
space:
mode:
authorAlex Auvolat <alex@adnab.me>2021-04-05 19:55:53 +0200
committerAlex Auvolat <alex@adnab.me>2021-04-27 16:37:08 +0200
commit9ced9f78dcc3894b3c2f13b8a95653f990278f03 (patch)
tree00b5180edcfab392eef203f594edb1332ccfce5d /src/util
parent3a449badb125b4f5bf0497639745a583bc949da2 (diff)
downloadgarage-9ced9f78dcc3894b3c2f13b8a95653f990278f03.tar.gz
garage-9ced9f78dcc3894b3c2f13b8a95653f990278f03.zip
Improve bootstraping: do it regularly; persist peer list
Diffstat (limited to 'src/util')
-rw-r--r--src/util/lib.rs1
-rw-r--r--src/util/persister.rs62
2 files changed, 63 insertions, 0 deletions
diff --git a/src/util/lib.rs b/src/util/lib.rs
index e544a872..055e9ab0 100644
--- a/src/util/lib.rs
+++ b/src/util/lib.rs
@@ -5,4 +5,5 @@ pub mod background;
pub mod config;
pub mod data;
pub mod error;
+pub mod persister;
pub mod time;
diff --git a/src/util/persister.rs b/src/util/persister.rs
new file mode 100644
index 00000000..f4e8cd72
--- /dev/null
+++ b/src/util/persister.rs
@@ -0,0 +1,62 @@
+use std::io::{Read, Write};
+use std::path::PathBuf;
+
+use tokio::io::AsyncWriteExt;
+
+use serde::{Deserialize, Serialize};
+
+use crate::data::*;
+use crate::error::Error;
+
+pub struct Persister<T: Serialize + for<'de> Deserialize<'de>> {
+ path: PathBuf,
+
+ _marker: std::marker::PhantomData<T>,
+}
+
+impl<T> Persister<T>
+where
+ T: Serialize + for<'de> Deserialize<'de>,
+{
+ pub fn new(base_dir: &PathBuf, file_name: &str) -> Self {
+ let mut path = base_dir.clone();
+ path.push(file_name);
+ Self {
+ path,
+ _marker: Default::default(),
+ }
+ }
+
+ pub fn load(&self) -> Result<T, Error> {
+ let mut file = std::fs::OpenOptions::new().read(true).open(&self.path)?;
+
+ let mut bytes = vec![];
+ file.read_to_end(&mut bytes)?;
+
+ let value = rmp_serde::decode::from_read_ref(&bytes[..])?;
+ Ok(value)
+ }
+
+ pub fn save(&self, t: &T) -> Result<(), Error> {
+ let bytes = rmp_to_vec_all_named(t)?;
+
+ let mut file = std::fs::OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .open(&self.path)?;
+
+ file.write_all(&bytes[..])?;
+
+ Ok(())
+ }
+
+ pub async fn save_async(&self, t: &T) -> Result<(), Error> {
+ let bytes = rmp_to_vec_all_named(t)?;
+
+ let mut file = tokio::fs::File::create(&self.path).await?;
+ file.write_all(&bytes[..]).await?;
+
+ Ok(())
+ }
+}