diff options
author | Alex Auvolat <alex@adnab.me> | 2023-01-04 13:07:13 +0100 |
---|---|---|
committer | Alex Auvolat <alex@adnab.me> | 2023-01-04 13:07:13 +0100 |
commit | f3f27293df83986ba29fb03f8af26a2177518e20 (patch) | |
tree | aebfa6b6936a974d40846a4c56b17aefac4f2526 /src/util/persister.rs | |
parent | 13c554988623663a9416439baf4f85f6fa91e502 (diff) | |
download | garage-f3f27293df83986ba29fb03f8af26a2177518e20.tar.gz garage-f3f27293df83986ba29fb03f8af26a2177518e20.zip |
Uniform framework for bg variable management
Diffstat (limited to 'src/util/persister.rs')
-rw-r--r-- | src/util/persister.rs | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/src/util/persister.rs b/src/util/persister.rs index 4b9adf51..5c66bbed 100644 --- a/src/util/persister.rs +++ b/src/util/persister.rs @@ -1,5 +1,6 @@ use std::io::{Read, Write}; use std::path::{Path, PathBuf}; +use std::sync::{Arc, RwLock}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -84,3 +85,36 @@ impl<T: Migrate> Persister<T> { Ok(()) } } + +pub struct PersisterShared<V: Migrate + Default>(Arc<(Persister<V>, RwLock<V>)>); + +impl<V: Migrate + Default> Clone for PersisterShared<V> { + fn clone(&self) -> PersisterShared<V> { + PersisterShared(self.0.clone()) + } +} + +impl<V: Migrate + Default> PersisterShared<V> { + pub fn new(base_dir: &Path, file_name: &str) -> Self { + let persister = Persister::new(base_dir, file_name); + let value = persister.load().unwrap_or_default(); + Self(Arc::new((persister, RwLock::new(value)))) + } + + pub fn get_with<F, R>(&self, f: F) -> R + where + F: FnOnce(&V) -> R, + { + let value = self.0 .1.read().unwrap(); + f(&value) + } + + pub fn set_with<F>(&self, f: F) -> Result<(), Error> + where + F: FnOnce(&mut V), + { + let mut value = self.0 .1.write().unwrap(); + f(&mut value); + self.0 .0.save(&value) + } +} |