Skip to main content

ic_storage/adapter/
map.rs

1//! Governed map collection implementation.
2use super::tree::Tree;
3use super::{MapIter, Memory, Storable};
4use crate::{DefaultMemoryImpl, RuntimeMemory};
5use std::{collections::BTreeSet, ops::RangeBounds};
6
7/// Allocation policy for one B-tree. The map persists this choice on creation.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub struct BTreeMapOptions {
10    /// Target reservation for an encoded node. Bounded codecs can use a smaller
11    /// target. The default is 1,024 bytes and the minimum is 256.
12    pub node_target_bytes: u16,
13    /// Smallest allocator block in bytes. Successive block sizes double.
14    /// The default and minimum are 256. For framed 1 MiB values, 257 saves
15    /// space by allowing the payload and frame to fit in 4,096 units.
16    pub allocation_unit_bytes: u16,
17}
18
19impl Default for BTreeMapOptions {
20    fn default() -> Self {
21        Self {
22            node_target_bytes: 1024,
23            allocation_unit_bytes: 256,
24        }
25    }
26}
27
28impl BTreeMapOptions {
29    pub(super) fn valid(self) -> bool {
30        self.node_target_bytes >= 256 && self.allocation_unit_bytes >= 256
31    }
32}
33
34///
35/// StableBTreeMap
36/// Degree-six ordered B-tree over an exclusive allocation.
37///
38
39pub struct StableBTreeMap<K: Storable + Ord + Clone, V: Storable, M: Memory = DefaultMemoryImpl> {
40    inner: Tree<K, V, RuntimeMemory<M>>,
41}
42
43impl<K: Storable + Ord + Clone, V: Storable, M: Memory> StableBTreeMap<K, V, M> {
44    /// Create a collection only in zero-page memory.
45    ///
46    /// # Panics
47    /// Refuses nonempty memory before writing. Growth and codec failures trap.
48    #[must_use]
49    pub fn create(memory: RuntimeMemory<M>) -> Self {
50        Self::create_with_options(memory, BTreeMapOptions::default())
51    }
52
53    /// Create an empty B-tree with per-allocation sizing options.
54    ///
55    /// # Panics
56    /// Refuses invalid options or occupied memory before writing.
57    #[must_use]
58    pub fn create_with_options(memory: RuntimeMemory<M>, options: BTreeMapOptions) -> Self {
59        assert_eq!(memory.size(), 0, "collection memory is not empty");
60
61        Self::reset_with_options(memory, options)
62    }
63
64    /// Deliberately replace any contents in this admitted allocation.
65    ///
66    /// # Panics
67    /// Growth and codec failures trap.
68    #[must_use]
69    pub fn reset(memory: RuntimeMemory<M>) -> Self {
70        Self::reset_with_options(memory, BTreeMapOptions::default())
71    }
72
73    /// Deliberately replace this allocation using the supplied sizing options.
74    ///
75    /// # Panics
76    /// Invalid options are refused before writing. Backing failures trap.
77    #[must_use]
78    pub fn reset_with_options(memory: RuntimeMemory<M>, options: BTreeMapOptions) -> Self {
79        Self {
80            inner: Tree::reset(memory, options).expect("cannot create B-tree"),
81        }
82    }
83
84    /// Load retained collection state without initializing a replacement.
85    ///
86    /// # Panics
87    /// Refuses empty or foreign memory and incompatible layouts/bounds without
88    /// writing. Record decoding and backing failures trap.
89    #[must_use]
90    pub fn load(memory: RuntimeMemory<M>) -> Self {
91        Self {
92            inner: Tree::load(memory).expect("invalid B-tree"),
93        }
94    }
95
96    /// Return the allocation policy recovered from this map’s header.
97    #[must_use]
98    pub fn options(&self) -> BTreeMapOptions {
99        self.inner.options()
100    }
101
102    /// Clear entries while retaining this allocation's exclusive lease.
103    ///
104    /// # Panics
105    /// Panics on backing, record integrity, or codec failure.
106    pub fn clear(&mut self) {
107        self.inner.clear().expect("cannot clear B-tree");
108    }
109
110    /// Reserve a minimum virtual extent without exposing or duplicating the lease.
111    ///
112    /// Returns the map on both success and ordinary growth refusal. The reservation preserves all entries.
113    ///
114    /// `minimum` is an absolute virtual extent in 65,536-byte Wasm pages, not an
115    /// entry count or additional pages. Existing extents never shrink. A request
116    /// already covered performs no growth or writes. This reserves backing only:
117    /// it does not promise that any particular number or encoding of entries fits.
118    /// Callers own their byte/page budget and must qualify it for their codecs;
119    /// owned node-layout constants are not a supported capacity contract.
120    pub fn reserve_pages(self, minimum: u64) -> (Self, Result<(), crate::RuntimeGrowError>) {
121        let additional = minimum.saturating_sub(self.inner.memory.size());
122        let result = self.inner.memory.grow(additional).map(|_| ());
123        (self, result)
124    }
125
126    /// Observe the virtual extent in 65,536-byte pages while retaining the lease.
127    ///
128    /// Consumes and returns the map together with its allocation size.
129    /// This is allocated extent, not free space or guaranteed entry capacity.
130    #[must_use]
131    pub fn allocated_pages(self) -> (Self, u64) {
132        let pages = self.inner.memory.size();
133
134        (self, pages)
135    }
136
137    /// Insert or replace a value, returning the previous value.
138    ///
139    /// # Panics
140    /// Panics on backing, record integrity, or codec failure.
141    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
142        self.inner.insert(key, value).expect("B-tree insert failed")
143    }
144
145    /// Read the value for an exact key.
146    ///
147    /// # Panics
148    /// Panics on backing, record integrity, or codec failure.
149    pub fn get(&self, key: &K) -> Option<V> {
150        self.inner.get(key).expect("B-tree get failed")
151    }
152
153    /// Qualification experiment. Visit sorted distinct probes in order, including misses.
154    ///
155    /// # Panics
156    /// Panics on unordered or duplicate keys, backing, record integrity or codec failure.
157    #[cfg(feature = "test-support")]
158    pub fn visit_sorted_keys(&self, keys: &[K], visit: impl FnMut(&K, Option<V>)) {
159        assert!(keys.windows(2).all(|pair| pair[0] < pair[1]));
160        self.inner
161            .visit_sorted_keys(keys, visit)
162            .expect("B-tree batch read failed");
163    }
164
165    /// Check whether the map contains a key.
166    ///
167    /// # Panics
168    /// Panics on backing, record integrity, or codec failure.
169    pub fn contains_key(&self, key: &K) -> bool {
170        self.inner
171            .contains_key(key)
172            .expect("B-tree contains_key failed")
173    }
174
175    /// Whether the map contains no entries.
176    #[must_use]
177    pub fn is_empty(&self) -> bool {
178        self.len() == 0
179    }
180
181    /// Number of committed entries.
182    #[must_use]
183    pub fn len(&self) -> u64 {
184        self.inner.len()
185    }
186
187    /// Remove a matching entry and return its value.
188    ///
189    /// # Panics
190    /// Panics on backing, record integrity, or codec failure.
191    pub fn remove(&mut self, key: &K) -> Option<V> {
192        self.inner.remove(key).expect("B-tree remove failed")
193    }
194
195    /// Consume a prepared set of distinct keys and return the number present.
196    /// Empty sets, missing keys and retries contribute zero. The caller bounds
197    /// the set during admission. Groups of keys share staged writes and root publication.
198    /// A caller relying on prior existence checks must trap on a count mismatch
199    /// in the same IC update to roll back its writes.
200    ///
201    /// # Panics
202    /// Panics on backing, record integrity, or codec failure.
203    pub fn remove_many(&mut self, keys: BTreeSet<K>) -> u64 {
204        self.inner
205            .remove_many(keys)
206            .expect("B-tree remove_many failed")
207    }
208
209    /// Read the smallest key and its value.
210    #[must_use]
211    pub fn first_key_value(&self) -> Option<(K, V)> {
212        self.iter().next().map(|e| e.into_pair())
213    }
214
215    /// Read the largest key and its value.
216    #[must_use]
217    pub fn last_key_value(&self) -> Option<(K, V)> {
218        self.iter().next_back().map(|e| e.into_pair())
219    }
220
221    /// Remove and return the first entry.
222    pub fn pop_first(&mut self) -> Option<(K, V)> {
223        let key = self.keys().next()?;
224        self.remove(&key).map(|value| (key, value))
225    }
226
227    /// Remove and return the last entry.
228    pub fn pop_last(&mut self) -> Option<(K, V)> {
229        let key = self.keys().next_back()?;
230        self.remove(&key).map(|value| (key, value))
231    }
232
233    /// Iterate over all entries in key order.
234    #[must_use]
235    pub fn iter(&self) -> MapIter<'_, K, V, M> {
236        self.inner.range(..)
237    }
238
239    /// Iterate within the supplied key bounds.
240    pub fn range(&self, key_range: impl RangeBounds<K>) -> MapIter<'_, K, V, M> {
241        self.inner.range(key_range)
242    }
243
244    /// Iterate over keys without reading external values.
245    pub fn keys(&self) -> impl DoubleEndedIterator<Item = K> + '_ {
246        self.keys_range(..)
247    }
248
249    /// Iterate over keys within the bounds in either direction, skipping external values.
250    pub fn keys_range(
251        &self,
252        bounds: impl RangeBounds<K>,
253    ) -> impl DoubleEndedIterator<Item = K> + '_ {
254        self.inner.keys_range(bounds)
255    }
256
257    /// Iterate over values in key order.
258    pub fn values(&self) -> impl DoubleEndedIterator<Item = V> + '_ {
259        self.iter().map(|e| e.into_value())
260    }
261}
262
263impl<'a, K: Storable + Ord + Clone, V: Storable, M: Memory> IntoIterator
264    for &'a StableBTreeMap<K, V, M>
265{
266    type Item = <MapIter<'a, K, V, M> as Iterator>::Item;
267    type IntoIter = MapIter<'a, K, V, M>;
268    fn into_iter(self) -> Self::IntoIter {
269        self.iter()
270    }
271}