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