ic_storage/adapter/map.rs
1//! Governed map collection implementation.
2use super::{MapIter, Memory, Storable};
3use crate::RuntimeMemory;
4use crate::{DefaultMemoryImpl, substrate};
5use std::ops::RangeBounds;
6
7/// Governed upstream `BTreeMap`; initialization and failures follow upstream contracts.
8pub struct StableBTreeMap<K: Storable + Ord + Clone, V: Storable, M: Memory = DefaultMemoryImpl> {
9 inner: substrate::BTreeMap<K, V, RuntimeMemory<M>>,
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 /// Clear entries while retaining this allocation's exclusive lease.
46 pub fn clear(&mut self) {
47 self.inner.clear_new();
48 }
49 /// Reserve a minimum virtual extent without exposing or duplicating the lease.
50 ///
51 /// Returns the map on both success and ordinary growth refusal. Entries are
52 /// preserved; reloading the upstream header refreshes its cached allocator.
53 /// Backing traps retain the upstream panic contract.
54 ///
55 /// `minimum` is an absolute virtual extent in 65,536-byte Wasm pages, not an
56 /// entry count or additional pages. Existing extents never shrink. A request
57 /// already covered performs no growth or writes. This reserves backing only:
58 /// it does not promise that any particular number or encoding of entries fits.
59 /// Callers own their byte/page budget and must qualify it for their codecs;
60 /// upstream node-layout constants are not a supported capacity contract.
61 pub fn reserve_pages(self, minimum: u64) -> (Self, Result<(), crate::RuntimeGrowError>) {
62 let memory = self.inner.into_memory();
63 let additional = minimum.saturating_sub(memory.size());
64 let result = memory.grow(additional).map(|_| ());
65 (Self::load(memory), result)
66 }
67 /// Observe the virtual extent in 65,536-byte pages while retaining the lease.
68 ///
69 /// Consumes and returns the map because upstream exposes memory only through
70 /// ownership transfer. Reloading reads the header without writing or growing.
71 /// This is allocated extent, not free space or guaranteed entry capacity.
72 #[must_use]
73 pub fn allocated_pages(self) -> (Self, u64) {
74 let memory = self.inner.into_memory();
75 let pages = memory.size();
76 (Self::load(memory), pages)
77 }
78 /// Delegates to upstream `BTreeMap::insert` with the governed allocation.
79 pub fn insert(&mut self, key: K, value: V) -> Option<V> {
80 self.inner.insert(key, value)
81 }
82 /// Delegates to upstream `BTreeMap::get` with the governed allocation.
83 pub fn get(&self, key: &K) -> Option<V> {
84 self.inner.get(key)
85 }
86 /// Delegates to upstream `BTreeMap::contains_key` with the governed allocation.
87 pub fn contains_key(&self, key: &K) -> bool {
88 self.inner.contains_key(key)
89 }
90 /// Delegates to upstream `BTreeMap::is_empty` with the governed allocation.
91 #[must_use]
92 pub fn is_empty(&self) -> bool {
93 self.inner.is_empty()
94 }
95 /// Delegates to upstream `BTreeMap::len` with the governed allocation.
96 #[must_use]
97 pub fn len(&self) -> u64 {
98 self.inner.len()
99 }
100 /// Delegates to upstream `BTreeMap::remove` with the governed allocation.
101 pub fn remove(&mut self, key: &K) -> Option<V> {
102 self.inner.remove(key)
103 }
104 /// Delegates to upstream `BTreeMap::first_key_value` with the governed allocation.
105 #[must_use]
106 pub fn first_key_value(&self) -> Option<(K, V)> {
107 self.inner.first_key_value()
108 }
109 /// Delegates to upstream `BTreeMap::last_key_value` with the governed allocation.
110 #[must_use]
111 pub fn last_key_value(&self) -> Option<(K, V)> {
112 self.inner.last_key_value()
113 }
114 /// Delegates to upstream `BTreeMap::pop_first` with the governed allocation.
115 pub fn pop_first(&mut self) -> Option<(K, V)> {
116 self.inner.pop_first()
117 }
118 /// Delegates to upstream `BTreeMap::pop_last` with the governed allocation.
119 pub fn pop_last(&mut self) -> Option<(K, V)> {
120 self.inner.pop_last()
121 }
122 /// Delegates to upstream `BTreeMap::iter` with the governed allocation.
123 #[must_use]
124 pub fn iter(&self) -> MapIter<'_, K, V, M> {
125 self.inner.iter()
126 }
127 /// Delegates to upstream `BTreeMap::range` with the governed allocation.
128 pub fn range(&self, key_range: impl RangeBounds<K>) -> MapIter<'_, K, V, M> {
129 self.inner.range(key_range)
130 }
131 /// Delegates to upstream `BTreeMap::keys` with the governed allocation.
132 pub fn keys(&self) -> impl DoubleEndedIterator<Item = K> + '_ {
133 self.inner.keys()
134 }
135 /// Delegates to upstream `BTreeMap::values` with the governed allocation.
136 pub fn values(&self) -> impl DoubleEndedIterator<Item = V> + '_ {
137 self.inner.values()
138 }
139}
140
141impl<'a, K: Storable + Ord + Clone, V: Storable, M: Memory> IntoIterator
142 for &'a StableBTreeMap<K, V, M>
143{
144 type Item = <MapIter<'a, K, V, M> as Iterator>::Item;
145 type IntoIter = MapIter<'a, K, V, M>;
146 fn into_iter(self) -> Self::IntoIter {
147 self.iter()
148 }
149}