Skip to main content

link_cli/sequences/
caching_converter_decorator.rs

1use std::collections::HashMap;
2use std::hash::Hash;
3
4#[derive(Clone, Debug)]
5pub struct CachingConverterDecorator<K, V> {
6    cache: HashMap<K, V>,
7}
8
9impl<K, V> Default for CachingConverterDecorator<K, V> {
10    fn default() -> Self {
11        Self {
12            cache: HashMap::new(),
13        }
14    }
15}
16
17impl<K, V> CachingConverterDecorator<K, V>
18where
19    K: Eq + Hash + Clone,
20    V: Clone,
21{
22    pub fn new() -> Self {
23        Self::default()
24    }
25
26    pub fn get(&self, input: &K) -> Option<V> {
27        self.cache.get(input).cloned()
28    }
29
30    pub fn insert(&mut self, input: K, output: V) -> V {
31        self.cache.insert(input, output.clone());
32        output
33    }
34
35    pub fn convert_with<F, E>(&mut self, input: K, convert: F) -> Result<V, E>
36    where
37        F: FnOnce(&K) -> Result<V, E>,
38    {
39        if let Some(output) = self.get(&input) {
40            return Ok(output);
41        }
42        let output = convert(&input)?;
43        Ok(self.insert(input, output))
44    }
45
46    pub fn len(&self) -> usize {
47        self.cache.len()
48    }
49
50    pub fn is_empty(&self) -> bool {
51        self.cache.is_empty()
52    }
53}