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    /// Check whether the map contains a key.
154    ///
155    /// # Panics
156    /// Panics on backing, record integrity, or codec failure.
157    pub fn contains_key(&self, key: &K) -> bool {
158        self.inner
159            .contains_key(key)
160            .expect("B-tree contains_key failed")
161    }
162
163    /// Whether the map contains no entries.
164    #[must_use]
165    pub fn is_empty(&self) -> bool {
166        self.len() == 0
167    }
168
169    /// Number of committed entries.
170    #[must_use]
171    pub fn len(&self) -> u64 {
172        self.inner.len()
173    }
174
175    /// Remove a matching entry and return its value.
176    ///
177    /// # Panics
178    /// Panics on backing, record integrity, or codec failure.
179    pub fn remove(&mut self, key: &K) -> Option<V> {
180        self.inner.remove(key).expect("B-tree remove failed")
181    }
182
183    /// Consume a prepared set of distinct keys and return the number present.
184    /// Empty sets, missing keys and retries contribute zero. The caller bounds
185    /// the set during admission. Groups of keys share staged writes and root publication.
186    /// A caller relying on prior existence checks must trap on a count mismatch
187    /// in the same IC update to roll back its writes.
188    ///
189    /// # Panics
190    /// Panics on backing, record integrity, or codec failure.
191    pub fn remove_many(&mut self, keys: BTreeSet<K>) -> u64 {
192        self.inner
193            .remove_many(keys)
194            .expect("B-tree remove_many failed")
195    }
196
197    /// Read the smallest key and its value.
198    #[must_use]
199    pub fn first_key_value(&self) -> Option<(K, V)> {
200        self.iter().next().map(|e| e.into_pair())
201    }
202
203    /// Read the largest key and its value.
204    #[must_use]
205    pub fn last_key_value(&self) -> Option<(K, V)> {
206        self.iter().next_back().map(|e| e.into_pair())
207    }
208
209    /// Remove and return the first entry.
210    pub fn pop_first(&mut self) -> Option<(K, V)> {
211        let key = self.keys().next()?;
212        self.remove(&key).map(|value| (key, value))
213    }
214
215    /// Remove and return the last entry.
216    pub fn pop_last(&mut self) -> Option<(K, V)> {
217        let key = self.keys().next_back()?;
218        self.remove(&key).map(|value| (key, value))
219    }
220
221    /// Iterate over all entries in key order.
222    #[must_use]
223    pub fn iter(&self) -> MapIter<'_, K, V, M> {
224        self.inner.range(..)
225    }
226
227    /// Iterate within the supplied key bounds.
228    pub fn range(&self, key_range: impl RangeBounds<K>) -> MapIter<'_, K, V, M> {
229        self.inner.range(key_range)
230    }
231
232    /// Iterate over keys without reading external values.
233    pub fn keys(&self) -> impl DoubleEndedIterator<Item = K> + '_ {
234        self.inner.keys_range(..)
235    }
236
237    /// Iterate over values in key order.
238    pub fn values(&self) -> impl DoubleEndedIterator<Item = V> + '_ {
239        self.iter().map(|e| e.into_value())
240    }
241}
242
243impl<'a, K: Storable + Ord + Clone, V: Storable, M: Memory> IntoIterator
244    for &'a StableBTreeMap<K, V, M>
245{
246    type Item = <MapIter<'a, K, V, M> as Iterator>::Item;
247    type IntoIter = MapIter<'a, K, V, M>;
248    fn into_iter(self) -> Self::IntoIter {
249        self.iter()
250    }
251}