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