Skip to main content

ic_storage/adapter/
vector.rs

1//! Governed vector collection implementation.
2use super::{Memory, Storable};
3use crate::substrate::{self, DefaultMemoryImpl};
4use ic_memory::RuntimeMemory;
5
6/// Governed upstream `Vec`; initialization and failures follow upstream contracts.
7pub struct StableVec<T: Storable, M: Memory = DefaultMemoryImpl> {
8    inner: substrate::Vec<T, RuntimeMemory<M>>,
9}
10impl<T: Storable, M: Memory> StableVec<T, M> {
11    /// Create a new collection, replacing any prior collection in the selected memory.
12    /// This is destructive even when a valid collection already exists.
13    ///
14    /// # Panics
15    /// Panics on insufficient memory or codec/backing failure.
16    pub fn new(memory: RuntimeMemory<M>) -> Self {
17        Self {
18            inner: substrate::Vec::new(memory),
19        }
20    }
21    /// Open a valid retained collection, or create one in zero-page memory.
22    ///
23    /// # Panics
24    /// Panics for foreign magic, unsupported layout, incompatible element bounds,
25    /// insufficient memory or codec/backing failure. Foreign memory is not reset.
26    pub fn init(memory: RuntimeMemory<M>) -> Self {
27        Self {
28            inner: substrate::Vec::init(memory),
29        }
30    }
31    /// Delegates to upstream `Vec::get` with the governed allocation.
32    pub fn get(&self, index: u64) -> Option<T> {
33        self.inner.get(index)
34    }
35    /// Delegates to upstream `Vec::set` with the governed allocation.
36    pub fn set(&self, index: u64, item: &T) {
37        self.inner.set(index, item);
38    }
39    /// Delegates to upstream `Vec::push` with the governed allocation.
40    pub fn push(&self, item: &T) {
41        self.inner.push(item);
42    }
43    /// Delegates to upstream `Vec::pop` with the governed allocation.
44    pub fn pop(&self) -> Option<T> {
45        self.inner.pop()
46    }
47    /// Reset to an empty vector while retaining this allocation's exclusive lease.
48    /// Existing payload bytes follow upstream `Vec::new` semantics.
49    #[must_use]
50    pub fn reset(self) -> Self {
51        Self::new(self.inner.into_memory())
52    }
53    /// Delegates to upstream `Vec::len` with the governed allocation.
54    pub fn len(&self) -> u64 {
55        self.inner.len()
56    }
57    /// Delegates to upstream `Vec::is_empty` with the governed allocation.
58    pub fn is_empty(&self) -> bool {
59        self.inner.is_empty()
60    }
61    /// Delegates to upstream `Vec::iter` with the governed allocation.
62    pub fn iter(&self) -> impl DoubleEndedIterator<Item = T> + '_ {
63        self.inner.iter()
64    }
65}