Skip to main content

luct_store/
switch.rs

1use luct_core::store::{
2    AppendableStore, OrderedStoreRead, SearchableStoreRead, StoreRead, StoreWrite,
3};
4
5/// [`Store`](luct_core::store::Store) implementation that switches between two different
6/// inner [`Stores`](luct_core::store::Store).
7///
8/// This can be used, if you want to switch at runtime between the [`Stores`](luct_core::store::Store)
9/// [`A`](Self::A) and [`B`](Self::B),
10pub enum StoreSwitch<A, B> {
11    A(A),
12    B(B),
13}
14
15impl<A, B, K, V> StoreRead<K, V> for StoreSwitch<A, B>
16where
17    A: StoreRead<K, V>,
18    B: StoreRead<K, V>,
19{
20    fn get(&self, key: &K) -> Option<V> {
21        match self {
22            StoreSwitch::A(a) => a.get(key),
23            StoreSwitch::B(b) => b.get(key),
24        }
25    }
26
27    fn len(&self) -> usize {
28        match self {
29            StoreSwitch::A(a) => a.len(),
30            StoreSwitch::B(b) => b.len(),
31        }
32    }
33}
34
35impl<A, B, K, V> StoreWrite<K, V> for StoreSwitch<A, B>
36where
37    A: StoreWrite<K, V>,
38    B: StoreWrite<K, V>,
39{
40    fn insert(&self, key: K, value: V) {
41        match self {
42            StoreSwitch::A(a) => a.insert(key, value),
43            StoreSwitch::B(b) => b.insert(key, value),
44        }
45    }
46
47    fn delete(&self, key: &K) -> bool {
48        match self {
49            StoreSwitch::A(a) => a.delete(key),
50            StoreSwitch::B(b) => b.delete(key),
51        }
52    }
53}
54
55impl<A, B, K, V> OrderedStoreRead<K, V> for StoreSwitch<A, B>
56where
57    K: Ord,
58    A: OrderedStoreRead<K, V>,
59    B: OrderedStoreRead<K, V>,
60{
61    fn last(&self) -> Option<(K, V)> {
62        match self {
63            StoreSwitch::A(a) => a.last(),
64            StoreSwitch::B(b) => b.last(),
65        }
66    }
67}
68
69impl<A, B, K, V> AppendableStore<K, V> for StoreSwitch<A, B>
70where
71    K: Ord,
72    A: AppendableStore<K, V>,
73    B: AppendableStore<K, V>,
74{
75    fn append(&self, value: V) -> K {
76        match self {
77            StoreSwitch::A(a) => a.append(value),
78            StoreSwitch::B(b) => b.append(value),
79        }
80    }
81}
82
83impl<A, B, K, V> SearchableStoreRead<K, V> for StoreSwitch<A, B>
84where
85    K: Ord,
86    A: SearchableStoreRead<K, V>,
87    B: SearchableStoreRead<K, V>,
88{
89    fn filter(&self, pred: impl FnMut(&K, &V) -> bool) -> Vec<(K, V)> {
90        match self {
91            StoreSwitch::A(a) => a.filter(pred),
92            StoreSwitch::B(b) => b.filter(pred),
93        }
94    }
95
96    fn find(&self, pred: impl FnMut(&K, &V) -> bool) -> Option<(K, V)> {
97        match self {
98            StoreSwitch::A(a) => a.find(pred),
99            StoreSwitch::B(b) => b.find(pred),
100        }
101    }
102}