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