Skip to main content

ic_storage/adapter/
map.rs

1//! Governed map collection implementation.
2use super::{MapIter, Memory, Storable};
3use crate::{DefaultMemoryImpl, RuntimeMemory, substrate};
4use std::{collections::BTreeSet, ops::RangeBounds};
5
6///
7/// StableBTreeMap
8/// Governed upstream `BTreeMap`; initialization and failures follow upstream contracts.
9///
10
11pub struct StableBTreeMap<K: Storable + Ord + Clone, V: Storable, M: Memory = DefaultMemoryImpl> {
12    inner: substrate::BTreeMap<K, V, RuntimeMemory<M>>,
13}
14
15impl<K: Storable + Ord + Clone, V: Storable, M: Memory> StableBTreeMap<K, V, M> {
16    /// Create a collection only in zero-page memory.
17    ///
18    /// # Panics
19    /// Refuses nonempty memory before writing. Growth and codec failures retain
20    /// upstream behavior.
21    #[must_use]
22    pub fn create(memory: RuntimeMemory<M>) -> Self {
23        assert_eq!(memory.size(), 0, "collection memory is not empty");
24
25        Self::reset(memory)
26    }
27
28    /// Deliberately replace any contents in this admitted allocation.
29    ///
30    /// # Panics
31    /// Growth and codec failures retain upstream behavior.
32    #[must_use]
33    pub fn reset(memory: RuntimeMemory<M>) -> Self {
34        Self {
35            inner: substrate::BTreeMap::new(memory),
36        }
37    }
38
39    /// Load retained collection state without initializing a replacement.
40    ///
41    /// # Panics
42    /// Refuses empty or foreign memory and incompatible layouts/bounds without
43    /// writing. Record decoding and backing failures retain upstream behavior.
44    #[must_use]
45    pub fn load(memory: RuntimeMemory<M>) -> Self {
46        Self {
47            inner: substrate::BTreeMap::load(memory),
48        }
49    }
50
51    /// Clear entries while retaining this allocation's exclusive lease.
52    pub fn clear(&mut self) {
53        self.inner.clear_new();
54    }
55
56    /// Reserve a minimum virtual extent without exposing or duplicating the lease.
57    ///
58    /// Returns the map on both success and ordinary growth refusal. Entries are
59    /// preserved; reloading the upstream header refreshes its cached allocator.
60    /// Backing traps retain the upstream panic contract.
61    ///
62    /// `minimum` is an absolute virtual extent in 65,536-byte Wasm pages, not an
63    /// entry count or additional pages. Existing extents never shrink. A request
64    /// already covered performs no growth or writes. This reserves backing only:
65    /// it does not promise that any particular number or encoding of entries fits.
66    /// Callers own their byte/page budget and must qualify it for their codecs;
67    /// upstream node-layout constants are not a supported capacity contract.
68    pub fn reserve_pages(self, minimum: u64) -> (Self, Result<(), crate::RuntimeGrowError>) {
69        let memory = self.inner.into_memory();
70        let additional = minimum.saturating_sub(memory.size());
71        let result = memory.grow(additional).map(|_| ());
72
73        (Self::load(memory), result)
74    }
75
76    /// Observe the virtual extent in 65,536-byte pages while retaining the lease.
77    ///
78    /// Consumes and returns the map because upstream exposes memory only through
79    /// ownership transfer. Reloading reads the header without writing or growing.
80    /// This is allocated extent, not free space or guaranteed entry capacity.
81    #[must_use]
82    pub fn allocated_pages(self) -> (Self, u64) {
83        let memory = self.inner.into_memory();
84        let pages = memory.size();
85
86        (Self::load(memory), pages)
87    }
88
89    /// Delegates to upstream `BTreeMap::insert` with the governed allocation.
90    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
91        self.inner.insert(key, value)
92    }
93
94    /// Delegates to upstream `BTreeMap::get` with the governed allocation.
95    pub fn get(&self, key: &K) -> Option<V> {
96        self.inner.get(key)
97    }
98
99    /// Delegates to upstream `BTreeMap::contains_key` with the governed allocation.
100    pub fn contains_key(&self, key: &K) -> bool {
101        self.inner.contains_key(key)
102    }
103
104    /// Delegates to upstream `BTreeMap::is_empty` with the governed allocation.
105    #[must_use]
106    pub fn is_empty(&self) -> bool {
107        self.inner.is_empty()
108    }
109
110    /// Delegates to upstream `BTreeMap::len` with the governed allocation.
111    #[must_use]
112    pub fn len(&self) -> u64 {
113        self.inner.len()
114    }
115
116    /// Delegates to upstream `BTreeMap::remove` with the governed allocation.
117    pub fn remove(&mut self, key: &K) -> Option<V> {
118        self.inner.remove(key)
119    }
120
121    /// Consume a prepared set of distinct keys and return the number present.
122    /// Empty sets, missing keys and retries contribute zero. The caller bounds
123    /// the set during admission. The released engine performs one removal per key.
124    /// A caller relying on prior existence checks must trap on a count mismatch
125    /// in the same IC update to roll back its writes.
126    pub fn remove_many(&mut self, keys: BTreeSet<K>) -> u64 {
127        let mut removed = 0;
128        for key in keys {
129            removed += u64::from(self.inner.remove(&key).is_some());
130        }
131
132        removed
133    }
134
135    /// Delegates to upstream `BTreeMap::first_key_value` with the governed allocation.
136    #[must_use]
137    pub fn first_key_value(&self) -> Option<(K, V)> {
138        self.inner.first_key_value()
139    }
140
141    /// Delegates to upstream `BTreeMap::last_key_value` with the governed allocation.
142    #[must_use]
143    pub fn last_key_value(&self) -> Option<(K, V)> {
144        self.inner.last_key_value()
145    }
146
147    /// Delegates to upstream `BTreeMap::pop_first` with the governed allocation.
148    pub fn pop_first(&mut self) -> Option<(K, V)> {
149        self.inner.pop_first()
150    }
151
152    /// Delegates to upstream `BTreeMap::pop_last` with the governed allocation.
153    pub fn pop_last(&mut self) -> Option<(K, V)> {
154        self.inner.pop_last()
155    }
156
157    /// Delegates to upstream `BTreeMap::iter` with the governed allocation.
158    #[must_use]
159    pub fn iter(&self) -> MapIter<'_, K, V, M> {
160        self.inner.iter()
161    }
162
163    /// Delegates to upstream `BTreeMap::range` with the governed allocation.
164    pub fn range(&self, key_range: impl RangeBounds<K>) -> MapIter<'_, K, V, M> {
165        self.inner.range(key_range)
166    }
167
168    /// Delegates to upstream `BTreeMap::keys` with the governed allocation.
169    pub fn keys(&self) -> impl DoubleEndedIterator<Item = K> + '_ {
170        self.inner.keys()
171    }
172
173    /// Delegates to upstream `BTreeMap::values` with the governed allocation.
174    pub fn values(&self) -> impl DoubleEndedIterator<Item = V> + '_ {
175        self.inner.values()
176    }
177}
178
179impl<'a, K: Storable + Ord + Clone, V: Storable, M: Memory> IntoIterator
180    for &'a StableBTreeMap<K, V, M>
181{
182    type Item = <MapIter<'a, K, V, M> as Iterator>::Item;
183    type IntoIter = MapIter<'a, K, V, M>;
184    fn into_iter(self) -> Self::IntoIter {
185        self.iter()
186    }
187}