Skip to main content

ic_storage/
lib.rs

1//! Scoped scalar-vector operations for an already valid live allocation.
2//!
3//! This crate neither opens retained bytes nor establishes allocator custody.
4//! The vector caller owns admission, initialization, publication and failure policy.
5//! The optional `map` feature adds an allocator-owned scalar hash table with
6//! scoped access, host poisoning and portable recovery. No private Vec header
7//! is admitted for persistence. The installed provider uses the vector API.
8#![no_std]
9#![forbid(unsafe_code)]
10
11extern crate alloc;
12
13pub mod record;
14
15/// Native scalar hash tables, scoped mutation and portable recovery.
16#[cfg(feature = "map")]
17pub mod map;
18
19/// Declare a bounded scalar record; this does not grant persistence admission.
20///
21/// Requires `repr(C)`, `Copy`, one to sixteen u32/u64 fields, explicit nonzero
22/// field IDs, an eight-byte non-NUL ASCII schema ID and a nonzero version.
23/// Primitive types may use bare names or absolute `::core::primitive` paths.
24/// The optional validator checks logical encoding and decoding; `store_with`
25/// assumes an already valid record. Callers own admission and poison/trap policy.
26///
27/// ```
28/// use ic_storage::Store;
29/// #[repr(C)]
30/// #[derive(Clone, Copy, Store)]
31/// #[store(id = "APPVALUE", version = 1)]
32/// struct Value { #[store(field = 1)] count: ::core::primitive::u32 }
33/// let mut value = Value { count: 42 };
34/// assert_eq!(value.store_encode().unwrap(), [42, 0, 0, 0]);
35/// assert_eq!(Value::store_decode(&[42, 0, 0, 0]).unwrap().count, 42);
36/// assert_eq!(value.store_with(|view| view.count()), 42);
37/// ```
38///
39/// Borrowed fields refuse even if their record is Copy:
40/// ```compile_fail
41/// use ic_storage::Store;
42/// #[repr(C)]
43/// #[derive(Clone, Copy, Store)]
44/// #[store(id = "BADBORRO", version = 1)]
45/// struct Bad { #[store(field = 1)] value: &'static u64 }
46/// ```
47/// Owning fields are outside the admitted subset:
48/// ```compile_fail
49/// use ic_storage::Store;
50/// #[repr(C)]
51/// #[derive(Clone, Store)]
52/// #[store(id = "BADOWNER", version = 1)]
53/// struct Bad { #[store(field = 1)] values: Vec<u64> }
54/// ```
55/// Application Drop cannot bypass the generated Copy requirement:
56/// ```compile_fail
57/// use ic_storage::Store;
58/// #[repr(C)]
59/// #[derive(Clone, Store)]
60/// #[store(id = "BADDROPP", version = 1)]
61/// struct Bad { #[store(field = 1)] value: u64 }
62/// impl Drop for Bad { fn drop(&mut self) {} }
63/// ```
64/// Shadowing a scalar name cannot conceal a reference or a different width:
65/// ```compile_fail
66/// use ic_storage::Store;
67/// type u64 = &'static str;
68/// #[repr(C)]
69/// #[derive(Clone, Copy, Store)]
70/// #[store(id = "BADALIAS", version = 1)]
71/// struct Bad { #[store(field = 1)] value: u64 }
72/// ```
73/// ```compile_fail
74/// use ic_storage::Store;
75/// type u32 = u64;
76/// #[repr(C)]
77/// #[derive(Clone, Copy, Store)]
78/// #[store(id = "BADWIDTH", version = 1)]
79/// struct Bad { #[store(field = 1)] value: u32 }
80/// ```
81///
82/// Views cannot escape by return, outer capture or future:
83/// ```compile_fail
84/// use ic_storage::Store;
85/// #[repr(C)]
86/// #[derive(Clone, Copy, Store)]
87/// #[store(id = "APPVALUE", version = 1)]
88/// struct Value { #[store(field = 1)] count: u32 }
89/// let mut value = Value { count: 42 };
90/// let escaped = value.store_with(|view| view);
91/// ```
92/// ```compile_fail
93/// use ic_storage::Store;
94/// #[repr(C)]
95/// #[derive(Clone, Copy, Store)]
96/// #[store(id = "APPVALUE", version = 1)]
97/// struct Value { #[store(field = 1)] count: u32 }
98/// let mut value = Value { count: 42 };
99/// let mut escaped = None;
100/// value.store_with(|view| escaped = Some(view));
101/// ```
102/// ```compile_fail
103/// use ic_storage::Store;
104/// #[repr(C)]
105/// #[derive(Clone, Copy, Store)]
106/// #[store(id = "APPVALUE", version = 1)]
107/// struct Value { #[store(field = 1)] count: u32 }
108/// let mut value = Value { count: 42 };
109/// let future = value.store_with(|view| async move { view.count() });
110/// ```
111/// The view has no DerefMut route around reviewed application mutations:
112/// ```compile_fail
113/// use ic_storage::Store;
114/// #[repr(C)]
115/// #[derive(Clone, Copy, Store)]
116/// #[store(id = "APPVALUE", version = 1)]
117/// struct Value { #[store(field = 1)] count: u32 }
118/// let mut value = Value { count: 42 };
119/// value.store_with(|mut view| { let _: &mut Value = &mut *view; });
120/// ```
121#[cfg(feature = "derive")]
122pub use ic_storage_derive::Store;
123
124use alloc::vec::Vec;
125use core::alloc::Allocator;
126
127/// Expected refusal before this operation changes the logical vector.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129pub enum Refusal {
130    /// Initial length or an attempted append exceeds the caller's element limit.
131    Limit,
132    /// The allocator refused an append; previous values remain intact.
133    Allocation,
134}
135
136/// Lend a restricted view while keeping the owning Vec with the caller.
137///
138/// An oversized initial vector refuses before invoking the callback. Ordinary
139/// returned errors preserve preceding writes. This is not a transaction or a
140/// persistence admission API. A native host must arrange its own poisoning
141/// before invoking user code; IC callers must trap on unexpected failure.
142/// Forgetting the view does not leak the vector or leave an ownership ticket.
143///
144/// ```
145/// use ic_storage::with_vector;
146/// let mut values = vec![17, 23];
147/// let sum = with_vector(&mut values, 512, |mut view| {
148///     view.push(41).unwrap();
149///     view.values().iter().sum::<u64>()
150/// }).unwrap();
151/// assert_eq!(sum, 81);
152/// ```
153///
154/// A view cannot escape through a return value:
155/// ```compile_fail
156/// use ic_storage::with_vector;
157/// let mut values = vec![17];
158/// let escaped = with_vector(&mut values, 512, |view| view);
159/// ```
160/// An outer capture cannot retain it either:
161/// ```compile_fail
162/// use ic_storage::with_vector;
163/// let mut values = vec![17];
164/// let mut escaped = None;
165/// with_vector(&mut values, 512, |view| escaped = Some(view));
166/// ```
167/// Nor can a future carry it out of the scope:
168/// ```compile_fail
169/// use ic_storage::with_vector;
170/// let mut values = vec![17];
171/// let future = with_vector(&mut values, 512, |view| async move { view.values().len() });
172/// ```
173#[inline(always)]
174pub fn with_vector<A: Allocator, R>(
175    values: &mut Vec<u64, A>,
176    limit: usize,
177    operation: impl for<'scope> FnOnce(Vector<'scope, A>) -> R,
178) -> Result<R, Refusal> {
179    if values.len() > limit {
180        return Err(Refusal::Limit);
181    }
182    Ok(operation(Vector { values, limit }))
183}
184
185/// An exclusive scalar view, with no Deref, Clone or owning iterator.
186///
187/// Scalar slices cannot expose the Vec carrier to mem::take or mem::replace:
188/// ```compile_fail
189/// use ic_storage::with_vector;
190/// let mut values = vec![17];
191/// with_vector(&mut values, 512, |mut view| {
192///     let _: Vec<u64> = core::mem::take(view.values_mut());
193/// });
194/// ```
195/// ```compile_fail
196/// use ic_storage::with_vector;
197/// let mut values = vec![17];
198/// with_vector(&mut values, 512, |mut view| {
199///     let _ = core::mem::replace(view.values_mut(), Vec::<u64>::new());
200/// });
201/// ```
202/// Borrowed elements cannot escape:
203/// ```compile_fail
204/// use ic_storage::with_vector;
205/// let mut values = vec![17];
206/// let escaped = with_vector(&mut values, 512, |view| view.values());
207/// ```
208/// Consuming iteration cannot extract the carrier:
209/// ```compile_fail
210/// use ic_storage::with_vector;
211/// let mut values = vec![17];
212/// with_vector(&mut values, 512, |view| view.into_iter());
213/// ```
214/// The view cannot clone an owning carrier:
215/// ```compile_fail
216/// use ic_storage::with_vector;
217/// let mut values = vec![17];
218/// with_vector(&mut values, 512, |view| view.clone());
219/// ```
220pub struct Vector<'scope, A: Allocator> {
221    values: &'scope mut Vec<u64, A>,
222    limit: usize,
223}
224
225impl<A: Allocator> Vector<'_, A> {
226    /// Borrow only initialized scalar values, never spare capacity or the owner.
227    #[must_use]
228    #[inline(always)]
229    pub fn values(&self) -> &[u64] {
230        self.values
231    }
232
233    /// Mutate non-owning scalar elements without changing vector ownership.
234    #[inline(always)]
235    pub fn values_mut(&mut self) -> &mut [u64] {
236        self.values
237    }
238
239    /// Append one scalar after checking the logical limit and reserving space.
240    #[inline(always)]
241    pub fn push(&mut self, value: u64) -> Result<(), Refusal> {
242        if self.values.len() == self.limit {
243            return Err(Refusal::Limit);
244        }
245        self.values
246            .try_reserve_exact(1)
247            .map_err(|_| Refusal::Allocation)?;
248        self.values.push(value);
249        Ok(())
250    }
251
252    /// Remove the first scalar, preserving the order of remaining values.
253    #[inline(always)]
254    pub fn remove_first(&mut self) -> Option<u64> {
255        if self.values.is_empty() {
256            None
257        } else {
258            Some(self.values.remove(0))
259        }
260    }
261
262    /// Ask the existing allocator to reduce spare capacity; no platform-page claim.
263    #[inline(always)]
264    pub fn shrink_to_fit(&mut self) {
265        self.values.shrink_to_fit();
266    }
267
268    /// Remove all scalar elements while keeping the allocation available for reuse.
269    #[inline(always)]
270    pub fn clear(&mut self) {
271        self.values.clear();
272    }
273}
274
275#[cfg(test)]
276mod tests;