Skip to main content

ic_storage/adapter/
vector.rs

1//! Governed vector collection implementation.
2use super::{Memory, Storable};
3use crate::{DefaultMemoryImpl, RuntimeMemory, substrate};
4
5/// Governed upstream `Vec`; initialization and failures follow upstream contracts.
6pub struct StableVec<T: Storable, M: Memory = DefaultMemoryImpl> {
7    inner: substrate::Vec<T, RuntimeMemory<M>>,
8}
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
46    /// Delegates to upstream `Vec::get` with the governed allocation.
47    #[must_use]
48    pub fn get(&self, index: u64) -> Option<T> {
49        self.inner.get(index)
50    }
51
52    /// Delegates to upstream `Vec::set` with the governed allocation.
53    pub fn set(&self, index: u64, item: &T) {
54        self.inner.set(index, item);
55    }
56
57    /// Delegates to upstream `Vec::push` with the governed allocation.
58    pub fn push(&self, item: &T) {
59        self.inner.push(item);
60    }
61
62    /// Delegates to upstream `Vec::pop` with the governed allocation.
63    #[must_use]
64    pub fn pop(&self) -> Option<T> {
65        self.inner.pop()
66    }
67
68    /// Delegates to upstream `Vec::len` with the governed allocation.
69    #[must_use]
70    pub fn len(&self) -> u64 {
71        self.inner.len()
72    }
73
74    /// Delegates to upstream `Vec::is_empty` with the governed allocation.
75    #[must_use]
76    pub fn is_empty(&self) -> bool {
77        self.inner.is_empty()
78    }
79
80    /// Delegates to upstream `Vec::iter` with the governed allocation.
81    pub fn iter(&self) -> impl DoubleEndedIterator<Item = T> + '_ {
82        self.inner.iter()
83    }
84}