Skip to main content

canic_cdk/structures/
btreemap.rs

1pub use ic_stable_structures::btreemap::*;
2
3use ic_stable_structures::{Memory, Storable, btreemap::BTreeMap as WrappedBTreeMap};
4use std::ops::{Deref, DerefMut};
5
6///
7/// BTreeMap
8/// a wrapper around BTreeMap that uses the default VirtualMemory
9///
10
11pub struct BTreeMap<K, V, M>
12where
13    K: Storable + Ord + Clone,
14    V: Storable + Clone,
15    M: Memory,
16{
17    data: WrappedBTreeMap<K, V, M>,
18}
19
20impl<K, V, M> BTreeMap<K, V, M>
21where
22    K: Storable + Ord + Clone,
23    V: Storable + Clone,
24    M: Memory,
25{
26    #[must_use]
27    pub fn init(memory: M) -> Self {
28        Self {
29            data: WrappedBTreeMap::init(memory),
30        }
31    }
32
33    pub fn view(&self) -> impl Iterator<Item = (K, V)> + '_ {
34        self.iter().map(|e| (e.key().clone(), e.value()))
35    }
36
37    /// Collect all key/value pairs into a Vec.
38    pub fn to_vec(&self) -> Vec<(K, V)> {
39        self.iter().map(|e| (e.key().clone(), e.value())).collect()
40    }
41
42    /// clear
43    /// the original clear() method in the ic-stable-structures library
44    /// couldn't be wrapped as it took ownership, so they made a new one
45    pub fn clear(&mut self) {
46        self.clear_new();
47    }
48}
49
50impl<K, V, M> Deref for BTreeMap<K, V, M>
51where
52    K: Storable + Ord + Clone,
53    V: Storable + Clone,
54    M: Memory,
55{
56    type Target = WrappedBTreeMap<K, V, M>;
57
58    // Expose the wrapped stable map through the wrapper transparently.
59    fn deref(&self) -> &Self::Target {
60        &self.data
61    }
62}
63
64impl<K, V, M> DerefMut for BTreeMap<K, V, M>
65where
66    K: Storable + Ord + Clone,
67    V: Storable + Clone,
68    M: Memory,
69{
70    // Expose mutable access to the wrapped stable map.
71    fn deref_mut(&mut self) -> &mut Self::Target {
72        &mut self.data
73    }
74}