Skip to main content

shepherd_rs/config/
inmem.rs

1use std::collections::HashMap;
2
3use async_trait::async_trait;
4use serde::Serialize;
5use serde::de::DeserializeOwned;
6use thiserror::Error;
7
8use crate::config::Config;
9
10#[derive(Debug, Error)]
11pub enum InMemoryConfigError {
12    #[error("Key not found in configuration")]
13    KeyNotFound,
14}
15
16pub struct InMemoryConfig<KeyType, ValueType> {
17    config: HashMap<KeyType, ValueType>,
18}
19
20#[async_trait]
21impl<KeyType, ValueType> Config for InMemoryConfig<KeyType, ValueType>
22where
23    KeyType: std::hash::Hash + Eq + Send + Sync + Clone + 'static,
24    ValueType: Send + Sync + Serialize + DeserializeOwned + Clone + 'static,
25{
26    type Error = InMemoryConfigError;
27    type KeyType = KeyType;
28    type StaticConfigHandle = ();
29    type ValueType = ValueType;
30
31    async fn new(_handle: Self::StaticConfigHandle) -> Result<Self, Self::Error> {
32        Ok(InMemoryConfig {
33            config: HashMap::new(),
34        })
35    }
36
37    async fn set(&mut self, key: Self::KeyType, value: Self::ValueType) -> Result<(), Self::Error> {
38        self.config.insert(key, value);
39        Ok(())
40    }
41
42    async fn set_bulk(
43        &mut self,
44        values: Vec<(Self::KeyType, Self::ValueType)>,
45    ) -> Result<(), Self::Error> {
46        for (key, value) in values {
47            self.config.insert(key, value);
48        }
49        Ok(())
50    }
51
52    async fn get(&self, key: Self::KeyType) -> Result<Self::ValueType, Self::Error> {
53        self.config
54            .get(&key)
55            .cloned()
56            .ok_or_else(|| InMemoryConfigError::KeyNotFound)
57    }
58}