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 /// Visit each sorted, distinct probe in order, including misses. At most
154 /// one decoded value is passed to the visitor at a time.
155 ///
156 /// # Panics
157 /// Panics on unordered or duplicate keys, backing, record integrity or codec failure.
158 pub fn visit_sorted_keys(&self, keys: &[K], mut visit: impl FnMut(&K, Option<V>)) {
159 let Ok(()) = self.try_visit_sorted_keys(keys, |key, value| {
160 visit(key, value);
161 Ok::<(), std::convert::Infallible>(())
162 });
163 }
164
165 /// Visit sorted, distinct probes in order while sharing B-tree routing reads.
166 /// The caller bounds the input. Each hit or miss is delivered exactly once
167 /// until the visitor returns an error.
168 ///
169 /// # Errors
170 /// Returns the first visitor error immediately, skipping subsequent probes
171 /// and their subtree and payload reads.
172 ///
173 /// # Panics
174 /// Panics on unordered or duplicate keys before visiting. Backing, record
175 /// integrity and codec failures also panic.
176 pub fn try_visit_sorted_keys<E>(
177 &self,
178 keys: &[K],
179 visit: impl FnMut(&K, Option<V>) -> Result<(), E>,
180 ) -> Result<(), E> {
181 assert!(keys.windows(2).all(|pair| pair[0] < pair[1]));
182 self.inner
183 .visit_sorted_keys(keys, visit)
184 .expect("B-tree batch read failed")
185 }
186
187 /// Check whether the map contains a key.
188 ///
189 /// # Panics
190 /// Panics on backing, record integrity, or codec failure.
191 pub fn contains_key(&self, key: &K) -> bool {
192 self.inner
193 .contains_key(key)
194 .expect("B-tree contains_key failed")
195 }
196
197 /// Whether the map contains no entries.
198 #[must_use]
199 pub fn is_empty(&self) -> bool {
200 self.len() == 0
201 }
202
203 /// Number of committed entries.
204 #[must_use]
205 pub fn len(&self) -> u64 {
206 self.inner.len()
207 }
208
209 /// Remove a matching entry and return its value.
210 ///
211 /// # Panics
212 /// Panics on backing, record integrity, or codec failure.
213 pub fn remove(&mut self, key: &K) -> Option<V> {
214 self.inner.remove(key).expect("B-tree remove failed")
215 }
216
217 /// Consume a prepared set of distinct keys and return the number present.
218 /// Empty sets, missing keys and retries contribute zero. The caller bounds
219 /// the set during admission. Groups of keys share staged writes and root publication.
220 /// A caller relying on prior existence checks must trap on a count mismatch
221 /// in the same IC update to roll back its writes.
222 ///
223 /// # Panics
224 /// Panics on backing, record integrity, or codec failure.
225 pub fn remove_many(&mut self, keys: BTreeSet<K>) -> u64 {
226 self.inner
227 .remove_many(keys)
228 .expect("B-tree remove_many failed")
229 }
230
231 /// Read the smallest key and its value.
232 #[must_use]
233 pub fn first_key_value(&self) -> Option<(K, V)> {
234 self.iter().next().map(|e| e.into_pair())
235 }
236
237 /// Read the largest key and its value.
238 #[must_use]
239 pub fn last_key_value(&self) -> Option<(K, V)> {
240 self.iter().next_back().map(|e| e.into_pair())
241 }
242
243 /// Remove and return the first entry.
244 pub fn pop_first(&mut self) -> Option<(K, V)> {
245 let key = self.keys().next()?;
246 self.remove(&key).map(|value| (key, value))
247 }
248
249 /// Remove and return the last entry.
250 pub fn pop_last(&mut self) -> Option<(K, V)> {
251 let key = self.keys().next_back()?;
252 self.remove(&key).map(|value| (key, value))
253 }
254
255 /// Iterate over all entries in key order.
256 #[must_use]
257 pub fn iter(&self) -> MapIter<'_, K, V, M> {
258 self.inner.range(..)
259 }
260
261 /// Iterate within the supplied key bounds.
262 pub fn range(&self, key_range: impl RangeBounds<K>) -> MapIter<'_, K, V, M> {
263 self.inner.range(key_range)
264 }
265
266 /// Iterate over keys without reading external values.
267 pub fn keys(&self) -> impl DoubleEndedIterator<Item = K> + '_ {
268 self.keys_range(..)
269 }
270
271 /// Iterate over keys within the bounds in either direction, skipping external values.
272 pub fn keys_range(
273 &self,
274 bounds: impl RangeBounds<K>,
275 ) -> impl DoubleEndedIterator<Item = K> + '_ {
276 self.inner.keys_range(bounds)
277 }
278
279 /// Iterate over values in key order.
280 pub fn values(&self) -> impl DoubleEndedIterator<Item = V> + '_ {
281 self.iter().map(|e| e.into_value())
282 }
283}
284
285impl<'a, K: Storable + Ord + Clone, V: Storable, M: Memory> IntoIterator
286 for &'a StableBTreeMap<K, V, M>
287{
288 type Item = <MapIter<'a, K, V, M> as Iterator>::Item;
289 type IntoIter = MapIter<'a, K, V, M>;
290 fn into_iter(self) -> Self::IntoIter {
291 self.iter()
292 }
293}