simple_database/
state.rs

1use super::Error;
2
3use super::traits::{KeyValueStore, Field};
4
5use std::path::PathBuf;
6
7use serde::Deserialize;
8
9#[derive(Clone)]
10pub struct State {
11    store: Box<dyn KeyValueStore>,
12}
13
14impl State {
15    pub async fn new<KVS: KeyValueStore + 'static>(
16        path: PathBuf,
17    ) -> Result<Self, Error> {
18        Ok(State{
19            store: Box::new(KVS::new(path).await?)
20        })
21    }
22
23    pub async fn set<F: Field>(&self, field: F) -> Result<(), Error> {
24        self.store.set(&field.as_bytes(), &serde_json::to_vec(&field)?).await?;
25        Ok(())
26    }
27
28    pub async fn get_raw<F: Field>(&self, field: &F) -> Result<Option<Vec<u8>>, Error> {
29        self.store.get(&field.as_bytes()).await
30    }
31
32    pub async fn get<F: Field, T: for <'a> Deserialize<'a>>(&self, field: &F) -> Result<Option<T>, Error> {
33        Ok(self.get_raw(field).await?.map(|b|
34            serde_json::from_slice::<Option<T>>(&b)
35        ).transpose()?.flatten())
36    }
37
38    pub async fn get_or_default<F: Field, T: for <'a> Deserialize<'a> + Default>(&self, field: &F) -> Result<T, Error> {
39        Ok(self.get(field).await?.unwrap_or_default())
40    }
41
42    pub async fn get_or_err<F: Field, T: for <'a> Deserialize<'a>>(&self, field: &F) -> Result<T, Error> {
43        self.get(field).await?.ok_or(Error::err("State.get_or_err", &format!("Value not found for field: {:?}", field)))
44    }
45}