Skip to main content

ic_storage/adapter/
map.rs

1//! Governed map operations over the copied ICSS B-tree.
2use super::bridge::{self, Backing, Codec};
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/// ICSS-baseline 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, RuntimeMemory<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(Backing(memory)),
34        })
35    }
36    /// Load the current BTR version 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(Backing(memory)).ok_or(Error::Format)?,
42        })
43    }
44    /// Clear entries and reuse the map's existing backing capacity.
45    /// # Errors
46    /// Engine failures trap instead of returning an ordinary error.
47    pub fn clear(&mut self) -> Result<()> {
48        #[cfg(not(target_arch = "wasm32"))]
49        let _guard = self.inner.memory().0.poison_on_unwind();
50        self.inner.clear_new();
51        Ok(())
52    }
53    /// Bound routing-cache memory. The baseline engine caches no routing nodes,
54    /// so every supplied ceiling is satisfied with zero cached bytes.
55    pub const fn set_node_cache_budget(&mut self, _bytes: usize) {
56        let _ = &self.inner;
57    }
58    /// Reserve backing pages without promising entry capacity.
59    pub fn reserve_pages(
60        self,
61        minimum: u64,
62    ) -> (Self, std::result::Result<(), crate::RuntimeGrowError>) {
63        let additional = minimum.saturating_sub(self.inner.memory().0.size());
64        let result = self.inner.memory().0.grow(additional).map(|_| ());
65        (self, result)
66    }
67    /// Observe allocated pages while retaining exclusive custody.
68    #[must_use]
69    pub fn allocated_pages(self) -> (Self, u64) {
70        let pages = self.inner.memory().0.size();
71        (self, pages)
72    }
73    /// Insert or replace. Invalid codecs and allocation failures trap.
74    /// # Errors
75    /// Engine failures trap instead of returning an ordinary error.
76    pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>> {
77        #[cfg(not(target_arch = "wasm32"))]
78        let _guard = self.inner.memory().0.poison_on_unwind();
79        Ok(self.inner.insert(Codec(key), Codec(value)).map(|v| v.0))
80    }
81    /// Read a matching value; malformed stored values trap.
82    /// # Errors
83    /// Engine failures trap instead of returning an ordinary error.
84    pub fn get(&self, key: &K) -> Result<Option<V>> {
85        Ok(self.inner.get(Codec::borrowed(key)).map(|v| v.0))
86    }
87    /// Test key membership without decoding values.
88    /// # Errors
89    /// Engine failures trap instead of returning an ordinary error.
90    pub fn contains_key(&self, key: &K) -> Result<bool> {
91        Ok(self.inner.contains_key(Codec::borrowed(key)))
92    }
93    /// Whether no entries are committed.
94    #[must_use]
95    pub const fn is_empty(&self) -> bool {
96        self.inner.is_empty()
97    }
98    /// Number of entries.
99    #[must_use]
100    pub const fn len(&self) -> u64 {
101        self.inner.len()
102    }
103    /// Remove a matching value; codec and engine failures trap.
104    /// # Errors
105    /// Engine failures trap instead of returning an ordinary error.
106    pub fn remove(&mut self, key: &K) -> Result<Option<V>> {
107        #[cfg(not(target_arch = "wasm32"))]
108        let _guard = self.inner.memory().0.poison_on_unwind();
109        Ok(self.inner.remove(Codec::borrowed(key)).map(|v| v.0))
110    }
111    /// First ordered key/value pair.
112    /// # Errors
113    /// Engine failures trap instead of returning an ordinary error.
114    pub fn first_key_value(&self) -> Result<Option<(K, V)>> {
115        Ok(self.inner.first_key_value().map(|(k, v)| (k.0, v.0)))
116    }
117    /// Last ordered key/value pair.
118    /// # Errors
119    /// Engine failures trap instead of returning an ordinary error.
120    pub fn last_key_value(&self) -> Result<Option<(K, V)>> {
121        Ok(self.inner.last_key_value().map(|(k, v)| (k.0, v.0)))
122    }
123    /// Iterate in key order.
124    #[must_use]
125    pub fn iter(&self) -> MapIter<'_, K, V, M> {
126        MapIter(self.inner.iter())
127    }
128    /// Iterate a bounded key range.
129    pub fn range(&self, bounds: impl RangeBounds<K>) -> MapIter<'_, K, V, M> {
130        MapIter(self.inner.range(codec_bounds(&bounds)))
131    }
132    /// Iterate keys without reading value payloads.
133    pub fn keys(&self) -> impl DoubleEndedIterator<Item = Result<K>> + '_ {
134        self.inner.keys().map(|k| Ok(k.0))
135    }
136    /// Iterate bounded keys without reading value payloads.
137    pub fn keys_range(
138        &self,
139        bounds: impl RangeBounds<K>,
140    ) -> impl DoubleEndedIterator<Item = Result<K>> + '_ {
141        self.inner
142            .keys_range(codec_bounds(&bounds))
143            .map(|k| Ok(k.0))
144    }
145    /// Iterate decoded values.
146    pub fn values(&self) -> impl DoubleEndedIterator<Item = Result<V>> + '_ {
147        self.inner.values().map(|v| Ok(v.0))
148    }
149}
150
151pub(super) fn codec_bounds<K: Clone>(
152    range: &impl RangeBounds<K>,
153) -> (std::ops::Bound<Codec<K>>, std::ops::Bound<Codec<K>>) {
154    (
155        range.start_bound().map(|k| Codec(k.clone())),
156        range.end_bound().map(|k| Codec(k.clone())),
157    )
158}
159impl<'a, K: Storable + Ord + Clone, V: Storable, M: Memory> IntoIterator
160    for &'a StableBTreeMap<K, V, M>
161{
162    type Item = <MapIter<'a, K, V, M> as Iterator>::Item;
163    type IntoIter = MapIter<'a, K, V, M>;
164    fn into_iter(self) -> Self::IntoIter {
165        self.iter()
166    }
167}