Skip to main content

ic_storage/adapter/
vector.rs

1//! Governed vector collection implementation.
2use super::{Memory, Storable};
3use crate::RuntimeMemory;
4use crate::{DefaultMemoryImpl, substrate};
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 collection only in zero-page memory.
12    ///
13    /// # Panics
14    /// Refuses nonempty memory before writing. Growth and codec failures retain
15    /// upstream behavior.
16    #[must_use]
17    pub fn create(memory: RuntimeMemory<M>) -> Self {
18        assert_eq!(memory.size(), 0, "collection memory is not empty");
19        Self::reset(memory)
20    }
21
22    /// Deliberately replace any contents in this admitted allocation.
23    ///
24    /// # Panics
25    /// Growth and codec failures retain upstream behavior.
26    #[must_use]
27    pub fn reset(memory: RuntimeMemory<M>) -> Self {
28        Self {
29            inner: substrate::Vec::new(memory),
30        }
31    }
32
33    /// Load retained collection state without initializing a replacement.
34    ///
35    /// # Panics
36    /// Refuses empty or foreign memory and incompatible layouts/bounds without
37    /// writing. Record decoding and backing failures retain upstream behavior.
38    #[must_use]
39    pub fn load(memory: RuntimeMemory<M>) -> Self {
40        assert!(memory.size() > 0, "collection memory is empty");
41        Self {
42            inner: substrate::Vec::init(memory),
43        }
44    }
45    /// Delegates to upstream `Vec::get` with the governed allocation.
46    #[must_use]
47    pub fn get(&self, index: u64) -> Option<T> {
48        self.inner.get(index)
49    }
50    /// Delegates to upstream `Vec::set` with the governed allocation.
51    pub fn set(&self, index: u64, item: &T) {
52        self.inner.set(index, item);
53    }
54    /// Delegates to upstream `Vec::push` with the governed allocation.
55    pub fn push(&self, item: &T) {
56        self.inner.push(item);
57    }
58    /// Delegates to upstream `Vec::pop` with the governed allocation.
59    #[must_use]
60    pub fn pop(&self) -> Option<T> {
61        self.inner.pop()
62    }
63    /// Delegates to upstream `Vec::len` with the governed allocation.
64    #[must_use]
65    pub fn len(&self) -> u64 {
66        self.inner.len()
67    }
68    /// Delegates to upstream `Vec::is_empty` with the governed allocation.
69    #[must_use]
70    pub fn is_empty(&self) -> bool {
71        self.inner.is_empty()
72    }
73    /// Delegates to upstream `Vec::iter` with the governed allocation.
74    pub fn iter(&self) -> impl DoubleEndedIterator<Item = T> + '_ {
75        self.inner.iter()
76    }
77}