generational_cache/map/impls/
alloc_btree_map.rs

1//! Module providing a map implementation based on [`alloc::collections::BTreeMap`].
2
3extern crate alloc;
4
5use crate::map::Map;
6use alloc::collections::BTreeMap;
7
8/// A [`Map`] implementation based on [`alloc::collections::BTreeMap`].
9pub struct AllocBTreeMap<K, V> {
10    btree_map: BTreeMap<K, V>,
11}
12
13impl<K, V> Default for AllocBTreeMap<K, V> {
14    fn default() -> Self {
15        Self::new()
16    }
17}
18
19impl<K, V> AllocBTreeMap<K, V> {
20    /// Creates a new [`AllocBTreeMap`] with the given [`BTreeMap`].
21    pub fn with_btree_map(btree_map: BTreeMap<K, V>) -> Self {
22        Self { btree_map }
23    }
24
25    /// Creates a new empty [`AllocBTreeMap`].
26    pub fn new() -> Self {
27        Self {
28            btree_map: BTreeMap::new(),
29        }
30    }
31}
32
33impl<K: Ord, V> Map<K, V> for AllocBTreeMap<K, V> {
34    type Error = core::convert::Infallible;
35
36    fn insert(&mut self, key: K, value: V) -> Result<Option<V>, Self::Error> {
37        Ok(self.btree_map.insert(key, value))
38    }
39
40    fn get(&self, key: &K) -> Option<&V> {
41        self.btree_map.get(key)
42    }
43
44    fn get_mut(&mut self, key: &K) -> Option<&mut V> {
45        self.btree_map.get_mut(key)
46    }
47
48    fn remove(&mut self, key: &K) -> Option<V> {
49        self.btree_map.remove(key)
50    }
51
52    fn clear(&mut self) -> Result<(), Self::Error> {
53        self.btree_map.clear();
54
55        Ok(())
56    }
57
58    fn is_empty(&self) -> bool {
59        self.btree_map.is_empty()
60    }
61
62    fn capacity(&self) -> Option<usize> {
63        None
64    }
65
66    fn len(&self) -> usize {
67        self.btree_map.len()
68    }
69}