Skip to main content

ic_storage/adapter/
map.rs

1//! Governed map operations over the independent ordered engine.
2use super::bridge::{self, TreeMemory};
3use super::error::{CollectionError as Error, Result, ensure};
4use super::{MapIter, Memory, Storable};
5use crate::{DefaultMemoryImpl, RuntimeMemory};
6use std::ops::RangeBounds;
7
8///
9/// `StableBTreeMap`
10///
11/// Ordered map owning one governed allocation. Stored codec and
12/// engine failures trap. Native callers must discard the runtime after a mutation panic.
13///
14pub struct StableBTreeMap<K: Storable + Ord + Clone, V: Storable, M: Memory = DefaultMemoryImpl> {
15    inner: bridge::Map<K, V, M>,
16}
17impl<K: Storable + Ord + Clone, V: Storable, M: Memory> StableBTreeMap<K, V, M> {
18    /// Create only in empty admitted memory.
19    /// # Errors
20    /// Refuses nonempty memory or initial growth refusal.
21    pub fn create(memory: RuntimeMemory<M>) -> Result<Self> {
22        ensure(memory.size() == 0, Error::NotEmpty)?;
23        Self::reset(memory)
24    }
25    /// Explicitly replace this allocation's collection image.
26    /// # Errors
27    /// Refuses initial growth before creating the map.
28    pub fn reset(memory: RuntimeMemory<M>) -> Result<Self> {
29        bridge::reserve(&memory)?;
30        #[cfg(not(target_arch = "wasm32"))]
31        let _guard = memory.poison_on_unwind();
32        Ok(Self {
33            inner: bridge::Map::new(TreeMemory::Allocation(memory)),
34        })
35    }
36    /// Load the current ordered-map format without initialization or migration.
37    /// # Errors
38    /// Refuses empty or foreign framing.
39    pub fn load(memory: RuntimeMemory<M>) -> Result<Self> {
40        Ok(Self {
41            inner: bridge::Map::load(TreeMemory::Allocation(memory)).ok_or(Error::Format)?,
42        })
43    }
44    /// Clear entries and reuse the map's existing backing capacity.
45    pub fn clear(&mut self) {
46        #[cfg(not(target_arch = "wasm32"))]
47        let _guard = self.inner.memory().allocation().poison_on_unwind();
48        self.inner.clear();
49    }
50    /// Reserve backing pages without promising entry capacity.
51    pub fn reserve_pages(
52        self,
53        minimum: u64,
54    ) -> (Self, std::result::Result<(), crate::RuntimeGrowError>) {
55        let additional = minimum.saturating_sub(self.inner.memory().allocation().size());
56        let result = self
57            .inner
58            .memory()
59            .allocation()
60            .grow(additional)
61            .map(|_| ());
62        (self, result)
63    }
64    /// Observe allocated pages while retaining exclusive custody.
65    #[must_use]
66    pub fn allocated_pages(self) -> (Self, u64) {
67        let pages = self.inner.memory().allocation().size();
68        (self, pages)
69    }
70    /// Insert or replace. Invalid codecs and allocation failures trap.
71    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
72        #[cfg(not(target_arch = "wasm32"))]
73        let _guard = self.inner.memory().allocation().poison_on_unwind();
74        self.inner.insert(key, value)
75    }
76    /// Insert or replace without reading or decoding the previous value payload.
77    /// Returns whether an existing entry was replaced. Stored lengths and allocation
78    /// metadata remain checked; callers own any required old-payload validation.
79    ///
80    /// # Panics
81    /// Invalid new codecs, keys, metadata and allocation failures trap.
82    pub fn insert_discard(&mut self, key: K, value: V) -> bool {
83        #[cfg(not(target_arch = "wasm32"))]
84        let _guard = self.inner.memory().allocation().poison_on_unwind();
85        self.inner.insert_discard(key, value)
86    }
87    /// Read a matching value; malformed stored values trap.
88    pub fn get(&self, key: &K) -> Option<V> {
89        self.inner.get(key)
90    }
91    /// Test key membership without decoding values.
92    pub fn contains_key(&self, key: &K) -> bool {
93        self.inner.contains_key(key)
94    }
95    /// Whether no entries are committed.
96    #[must_use]
97    pub const fn is_empty(&self) -> bool {
98        self.inner.is_empty()
99    }
100    /// Number of entries.
101    #[must_use]
102    pub const fn len(&self) -> u64 {
103        self.inner.len()
104    }
105    /// Remove a matching value; codec and engine failures trap.
106    pub fn remove(&mut self, key: &K) -> Option<V> {
107        #[cfg(not(target_arch = "wasm32"))]
108        let _guard = self.inner.memory().allocation().poison_on_unwind();
109        self.inner.remove(key)
110    }
111    /// Remove without reading or decoding the removed value payload.
112    /// Returns whether an entry was removed. Stored lengths and allocation metadata
113    /// remain checked; callers own any required old-payload validation.
114    ///
115    /// # Panics
116    /// Key codec and engine failures trap.
117    pub fn remove_discard(&mut self, key: &K) -> bool {
118        #[cfg(not(target_arch = "wasm32"))]
119        let _guard = self.inner.memory().allocation().poison_on_unwind();
120        self.inner.remove_discard(key)
121    }
122    /// First ordered key/value pair.
123    #[must_use]
124    pub fn first_key_value(&self) -> Option<(K, V)> {
125        self.inner.first_key_value()
126    }
127    /// Last ordered key/value pair.
128    #[must_use]
129    pub fn last_key_value(&self) -> Option<(K, V)> {
130        self.inner.last_key_value()
131    }
132    /// Iterate in key order.
133    #[must_use]
134    pub const fn iter(&self) -> MapIter<'_, K, V, M> {
135        MapIter(self.inner.iter())
136    }
137    /// Iterate a bounded key range.
138    pub fn range(&self, bounds: impl RangeBounds<K>) -> MapIter<'_, K, V, M> {
139        MapIter(self.inner.range(bounds))
140    }
141    /// Iterate keys without reading value payloads.
142    pub fn keys(&self) -> impl DoubleEndedIterator<Item = K> + '_ {
143        self.inner.keys()
144    }
145    /// Iterate bounded keys without reading value payloads.
146    pub fn keys_range(
147        &self,
148        bounds: impl RangeBounds<K>,
149    ) -> impl DoubleEndedIterator<Item = K> + '_ {
150        self.inner.keys_range(bounds)
151    }
152    /// Iterate decoded values.
153    pub fn values(&self) -> impl DoubleEndedIterator<Item = V> + '_ {
154        self.inner.values()
155    }
156}
157
158impl<'a, K: Storable + Ord + Clone, V: Storable, M: Memory> IntoIterator
159    for &'a StableBTreeMap<K, V, M>
160{
161    type Item = <MapIter<'a, K, V, M> as Iterator>::Item;
162    type IntoIter = MapIter<'a, K, V, M>;
163    fn into_iter(self) -> Self::IntoIter {
164        self.iter()
165    }
166}