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///
9/// Thin wrapper around `ic_stable_structures::BTreeMap` with a small helper
10/// API used across Canic.
11///
12
13pub struct BTreeMap<K, V, M>
14where
15    K: Storable + Ord + Clone,
16    V: Storable + Clone,
17    M: Memory,
18{
19    data: WrappedBTreeMap<K, V, M>,
20}
21
22impl<K, V, M> BTreeMap<K, V, M>
23where
24    K: Storable + Ord + Clone,
25    V: Storable + Clone,
26    M: Memory,
27{
28    #[must_use]
29    pub fn init(memory: M) -> Self {
30        Self {
31            data: WrappedBTreeMap::init(memory),
32        }
33    }
34
35    pub fn view(&self) -> impl Iterator<Item = (K, V)> + '_ {
36        self.iter().map(|e| (e.key().clone(), e.value()))
37    }
38
39    /// Collect all key/value pairs into a Vec.
40    pub fn to_vec(&self) -> Vec<(K, V)> {
41        self.iter().map(|e| (e.key().clone(), e.value())).collect()
42    }
43
44    /// Clear the map through the non-consuming helper exposed upstream.
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}