ic_stable_structures/
vec.rs

1//! This module implements a growable array in stable memory.
2
3use crate::base_vec::BaseVec;
4pub use crate::base_vec::InitError;
5use crate::storable::Storable;
6use crate::{GrowFailed, Memory};
7use std::fmt;
8
9#[cfg(test)]
10mod tests;
11
12const MAGIC: [u8; 3] = *b"SVC"; // Short for "stable vector".
13
14/// An implementation of growable arrays in stable memory.
15pub struct Vec<T: Storable, M: Memory>(BaseVec<T, M>);
16
17impl<T: Storable, M: Memory> Vec<T, M> {
18    /// Creates a new empty vector in the specified memory,
19    /// overwriting any data structures the memory might have
20    /// contained previously.
21    ///
22    /// Complexity: O(1)
23    pub fn new(memory: M) -> Result<Self, GrowFailed> {
24        BaseVec::<T, M>::new(memory, MAGIC).map(Self)
25    }
26
27    /// Initializes a vector in the specified memory.
28    ///
29    /// Complexity: O(1)
30    ///
31    /// PRECONDITION: the memory is either empty or contains a valid
32    /// stable vector.
33    pub fn init(memory: M) -> Result<Self, InitError> {
34        BaseVec::<T, M>::init(memory, MAGIC).map(Self)
35    }
36
37    /// Returns the underlying memory instance.
38    pub fn into_memory(self) -> M {
39        self.0.into_memory()
40    }
41
42    /// Returns true if the vector is empty.
43    ///
44    /// Complexity: O(1)
45    pub fn is_empty(&self) -> bool {
46        self.0.is_empty()
47    }
48
49    /// Returns the number of items in the vector.
50    ///
51    /// Complexity: O(1)
52    pub fn len(&self) -> u64 {
53        self.0.len()
54    }
55
56    /// Sets the item at the specified index to the specified value.
57    ///
58    /// Complexity: O(max_size(T))
59    ///
60    /// PRECONDITION: index < self.len()
61    pub fn set(&self, index: u64, item: &T) {
62        self.0.set(index, item)
63    }
64
65    /// Returns the item at the specified index.
66    ///
67    /// Complexity: O(max_size(T))
68    pub fn get(&self, index: u64) -> Option<T> {
69        self.0.get(index)
70    }
71
72    /// Adds a new item at the end of the vector.
73    ///
74    /// Complexity: O(max_size(T))
75    pub fn push(&self, item: &T) -> Result<(), GrowFailed> {
76        self.0.push(item)
77    }
78
79    /// Removes the item at the end of the vector.
80    ///
81    /// Complexity: O(max_size(T))
82    pub fn pop(&self) -> Option<T> {
83        self.0.pop()
84    }
85
86    pub fn iter(&self) -> impl DoubleEndedIterator<Item = T> + '_ {
87        self.0.iter()
88    }
89
90    #[cfg(test)]
91    fn to_vec(&self) -> std::vec::Vec<T> {
92        self.0.to_vec()
93    }
94}
95
96impl<T: Storable + fmt::Debug, M: Memory> fmt::Debug for Vec<T, M> {
97    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
98        self.0.fmt(fmt)
99    }
100}