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::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) -> Self {
24 BaseVec::<T, M>::new(memory, MAGIC)
25 .map(Self)
26 .expect("Failed to create a new vector")
27 }
28
29 /// Initializes a vector in the specified memory.
30 ///
31 /// Complexity: O(1)
32 ///
33 /// PRECONDITION: the memory is either empty or contains a valid
34 /// stable vector.
35 pub fn init(memory: M) -> Self {
36 BaseVec::<T, M>::init(memory, MAGIC)
37 .map(Self)
38 .expect("Failed to initialize a vector")
39 }
40
41 /// Returns the underlying memory instance.
42 pub fn into_memory(self) -> M {
43 self.0.into_memory()
44 }
45
46 /// Returns true if the vector is empty.
47 ///
48 /// Complexity: O(1)
49 pub fn is_empty(&self) -> bool {
50 self.0.is_empty()
51 }
52
53 /// Returns the number of items in the vector.
54 ///
55 /// Complexity: O(1)
56 pub fn len(&self) -> u64 {
57 self.0.len()
58 }
59
60 /// Sets the item at the specified index to the specified value.
61 ///
62 /// Complexity: O(max_size(T))
63 ///
64 /// PRECONDITION: index < self.len()
65 pub fn set(&self, index: u64, item: &T) {
66 self.0.set(index, item)
67 }
68
69 /// Returns the item at the specified index.
70 ///
71 /// Complexity: O(max_size(T))
72 pub fn get(&self, index: u64) -> Option<T> {
73 self.0.get(index)
74 }
75
76 /// Adds a new item at the end of the vector.
77 ///
78 /// Complexity: O(max_size(T))
79 pub fn push(&self, item: &T) {
80 self.0
81 .push(item)
82 .expect("Failed to push item to the vector");
83 }
84
85 /// Removes the item at the end of the vector.
86 ///
87 /// Complexity: O(max_size(T))
88 pub fn pop(&self) -> Option<T> {
89 self.0.pop()
90 }
91
92 pub fn iter(&self) -> impl DoubleEndedIterator<Item = T> + '_ {
93 self.0.iter()
94 }
95
96 #[cfg(test)]
97 fn to_vec(&self) -> std::vec::Vec<T> {
98 self.0.to_vec()
99 }
100}
101
102impl<T: Storable + fmt::Debug, M: Memory> fmt::Debug for Vec<T, M> {
103 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
104 self.0.fmt(fmt)
105 }
106}