gistools/data_store/multimap/
mod.rs

1// /// File based reader that implements the MultiMapStore trait
2// #[cfg(feature = "std")]
3// pub mod file;
4use super::U64;
5use alloc::{collections::btree_map::BTreeMap, vec::Vec};
6use s2json::Properties;
7use serde::{Serialize, de::DeserializeOwned};
8
9/// Represents a key-multiValue store
10pub trait MultiMapStore<K: U64 = u64, V: Serialize + DeserializeOwned + Clone = Properties>:
11    Clone
12{
13    /// New key-value store
14    fn new(name: Option<&str>) -> Self;
15    /// The length of the store
16    fn len(&self) -> u64;
17    /// Check if the store is empty
18    fn is_empty(&self) -> bool;
19    /// Get a value from the store
20    fn get(&self, key: K) -> Option<&Vec<V>>;
21    /// Get a mutable value from the store
22    fn get_mut(&mut self, key: K) -> Option<&mut Vec<V>>;
23    /// Set a value in the store
24    fn set(&mut self, key: K, value: V);
25    /// Check if a key exists
26    fn has(&self, key: K) -> bool;
27    /// Iterate over the store
28    fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a K, &'a Vec<V>)>
29    where
30        K: 'a,
31        V: 'a;
32    /// Iterate mutably over the store
33    fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = (&'a K, &'a mut Vec<V>)>
34    where
35        K: 'a,
36        V: 'a;
37    /// Cleanup the store
38    fn cleanup(&mut self) {}
39}
40
41/// A local key-multiValue store
42#[derive(Debug, Clone, Default)]
43pub struct MultiMap<K: U64 = u64, V: Serialize + DeserializeOwned + Clone = Properties> {
44    store: BTreeMap<K, Vec<V>>,
45}
46impl<K: U64, V: Serialize + DeserializeOwned + Clone> MultiMapStore<K, V> for MultiMap<K, V> {
47    fn new(_name: Option<&str>) -> Self {
48        Self { store: BTreeMap::new() }
49    }
50    fn len(&self) -> u64 {
51        self.store.len() as u64
52    }
53    fn is_empty(&self) -> bool {
54        self.store.is_empty()
55    }
56    fn get(&self, key: K) -> Option<&Vec<V>> {
57        self.store.get(&key)
58    }
59    fn get_mut(&mut self, key: K) -> Option<&mut Vec<V>> {
60        self.store.get_mut(&key)
61    }
62    fn set(&mut self, key: K, value: V) {
63        self.store.entry(key).or_default().push(value);
64    }
65    fn has(&self, key: K) -> bool {
66        self.store.contains_key(&key)
67    }
68    fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a K, &'a Vec<V>)>
69    where
70        K: 'a,
71        V: 'a,
72    {
73        self.store.iter()
74    }
75    fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = (&'a K, &'a mut Vec<V>)>
76    where
77        K: 'a,
78        V: 'a,
79    {
80        self.store.iter_mut()
81    }
82    fn cleanup(&mut self) {
83        self.store.clear();
84    }
85}