Skip to main content

ic_storage/adapter/
map.rs

1//! Governed map collection implementation.
2use super::error::{CollectionError as Error, Result, ensure};
3use super::tree::Tree;
4use super::{MapIter, Memory, Storable};
5use crate::DefaultMemoryImpl;
6use crate::RuntimeMemory;
7use std::ops::RangeBounds;
8
9/// Governed ordered map backed by Storage’s owned B-tree and reusable blocks.
10pub struct StableBTreeMap<K: Storable + Ord + Clone, V: Storable, M: Memory = DefaultMemoryImpl> {
11    inner: Tree<K, V, RuntimeMemory<M>>,
12}
13impl<K: Storable + Ord + Clone, V: Storable, M: Memory> StableBTreeMap<K, V, M> {
14    /// Create a collection only in zero-page memory.
15    ///
16    /// # Errors
17    /// Refuses nonempty memory, invalid encoding or capacity exhaustion before writes.
18    pub fn create(memory: RuntimeMemory<M>) -> Result<Self> {
19        ensure(memory.size() == 0, Error::NotEmpty)?;
20        Self::reset(memory)
21    }
22
23    /// Deliberately replace any contents in this admitted allocation.
24    ///
25    /// # Errors
26    /// Returns encoding, capacity or structural admission errors.
27    pub fn reset(memory: RuntimeMemory<M>) -> Result<Self> {
28        Ok(Self {
29            inner: Tree::reset(memory)?,
30        })
31    }
32
33    /// Load retained collection state without initializing a replacement.
34    ///
35    /// # Errors
36    /// Refuses empty, foreign or corrupt memory and incompatible bounds without writing.
37    pub fn load(memory: RuntimeMemory<M>) -> Result<Self> {
38        Ok(Self {
39            inner: Tree::load(memory)?,
40        })
41    }
42    /// Clear entries while retaining this allocation's exclusive lease.
43    ///
44    /// # Errors
45    /// Reports a poisoned owner or metadata encoding/capacity refusal.
46    pub fn clear(&mut self) -> Result<()> {
47        self.inner.clear()
48    }
49    /// Set the heap budget for cached, validated routing nodes; zero disables it.
50    ///
51    /// Caching is disabled initially. Changing the budget discards cached nodes.
52    /// The budget accounts for buffer capacities and cache bookkeeping, excluding
53    /// allocator overhead and nodes retained by an active iterator. External
54    /// values are never cached. Writes invalidate affected nodes; reloads start
55    /// cold. The exclusive backing-custody contract applies while caching.
56    pub fn set_node_cache_budget(&mut self, bytes: usize) {
57        self.inner.set_cache_budget(bytes);
58    }
59    /// Reserve a minimum virtual extent without exposing or duplicating the lease.
60    ///
61    /// Returns the map on both success and ordinary growth refusal. Entries are
62    /// preserved; the cached tree remains unchanged.
63    /// Backing traps follow the host transaction contract.
64    ///
65    /// `minimum` is an absolute virtual extent in 65,536-byte Wasm pages, not an
66    /// entry count or additional pages. Existing extents never shrink. A request
67    /// already covered performs no growth or writes. This reserves backing only:
68    /// it does not promise that any particular number or encoding of entries fits.
69    /// Callers own their byte/page budget and must qualify it for their codecs;
70    /// internal node-layout constants are not a supported capacity contract.
71    pub fn reserve_pages(
72        self,
73        minimum: u64,
74    ) -> (Self, std::result::Result<(), crate::RuntimeGrowError>) {
75        let additional = minimum.saturating_sub(self.inner.memory.size());
76        let result = self.inner.memory.grow(additional).map(|_| ());
77        (self, result)
78    }
79    /// Observe the virtual extent in 65,536-byte pages while retaining the lease.
80    ///
81    /// Consumes and returns the map while retaining the exclusive lease.
82    /// Observing the allocation performs no writes or growth.
83    /// This is allocated extent, not free space or guaranteed entry capacity.
84    #[must_use]
85    pub fn allocated_pages(self) -> (Self, u64) {
86        let pages = self.inner.memory.size();
87        (self, pages)
88    }
89    /// Perform `insert` on the governed ordered map.
90    ///
91    /// # Errors
92    /// Rejects encoding, decoding, structural or capacity errors before committing writes.
93    pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>> {
94        self.inner.insert(key, value)
95    }
96    /// Perform `get` on the governed ordered map.
97    ///
98    /// # Errors
99    /// Reports structural, integrity or application decoding failures without writing.
100    pub fn get(&self, key: &K) -> Result<Option<V>> {
101        self.inner.get(key)
102    }
103    /// Perform `contains_key` on the governed ordered map.
104    ///
105    /// # Errors
106    /// Reports structural, integrity or application decoding failures without writing.
107    pub fn contains_key(&self, key: &K) -> Result<bool> {
108        self.inner.contains_key(key)
109    }
110    /// Perform `is_empty` on the governed ordered map.
111    ///
112    /// # Errors
113    /// Reports invalid region metadata or incompatible codec bounds.
114    pub fn is_empty(&self) -> bool {
115        self.inner.len() == 0
116    }
117    /// Perform `len` on the governed ordered map.
118    pub fn len(&self) -> u64 {
119        self.inner.len()
120    }
121    /// Perform `remove` on the governed ordered map.
122    ///
123    /// # Errors
124    /// Rejects decoding or structural errors before committing removal.
125    pub fn remove(&mut self, key: &K) -> Result<Option<V>> {
126        self.inner.remove(key)
127    }
128    /// Perform `first_key_value` on the governed ordered map.
129    ///
130    /// # Errors
131    /// Reports invalid structure, integrity failures or application codec errors.
132    pub fn first_key_value(&self) -> Result<Option<(K, V)>> {
133        self.iter()
134            .next()
135            .map(|entry| entry?.into_pair())
136            .transpose()
137    }
138    /// Perform `last_key_value` on the governed ordered map.
139    ///
140    /// # Errors
141    /// Reports invalid structure, integrity failures or application codec errors.
142    pub fn last_key_value(&self) -> Result<Option<(K, V)>> {
143        self.iter()
144            .next_back()
145            .map(|entry| entry?.into_pair())
146            .transpose()
147    }
148    /// Perform `iter` on the governed ordered map.
149    pub fn iter(&self) -> MapIter<'_, K, V, M> {
150        self.inner.range(..)
151    }
152    /// Perform `range` on the governed ordered map.
153    pub fn range(&self, key_range: impl RangeBounds<K>) -> MapIter<'_, K, V, M> {
154        self.inner.range(key_range)
155    }
156    /// Perform `keys` on the governed ordered map.
157    pub fn keys(&self) -> impl DoubleEndedIterator<Item = Result<K>> + '_ {
158        self.inner.keys_range(..)
159    }
160    /// Traverse bounded keys without reading external value records.
161    ///
162    /// Routing records and key codecs remain checked. External value integrity
163    /// is checked only by operations that request values.
164    pub fn keys_range(
165        &self,
166        bounds: impl RangeBounds<K>,
167    ) -> impl DoubleEndedIterator<Item = Result<K>> + '_ {
168        self.inner.keys_range(bounds)
169    }
170    /// Perform `values` on the governed ordered map.
171    pub fn values(&self) -> impl DoubleEndedIterator<Item = Result<V>> + '_ {
172        self.iter().map(|entry| entry?.into_value())
173    }
174}
175
176impl<'a, K: Storable + Ord + Clone, V: Storable, M: Memory> IntoIterator
177    for &'a StableBTreeMap<K, V, M>
178{
179    type Item = <MapIter<'a, K, V, M> as Iterator>::Item;
180    type IntoIter = MapIter<'a, K, V, M>;
181    fn into_iter(self) -> Self::IntoIter {
182        self.iter()
183    }
184}