xref: /wasmtime-44.0.1/crates/core/src/alloc/vec.rs (revision 47e1cd59)
1 use crate::error::OutOfMemory;
2 use core::{
3     fmt, mem,
4     ops::{Deref, DerefMut, Index, IndexMut},
5 };
6 use std_alloc::vec::Vec as StdVec;
7 
8 /// Like `std::vec::Vec` but all methods that allocate force handling allocation
9 /// failure.
10 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
11 pub struct Vec<T> {
12     inner: StdVec<T>,
13 }
14 
15 impl<T> Default for Vec<T> {
16     fn default() -> Self {
17         Self {
18             inner: Default::default(),
19         }
20     }
21 }
22 
23 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
24     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25         fmt::Debug::fmt(&self.inner, f)
26     }
27 }
28 
29 impl<T> Vec<T> {
30     /// Same as [`std::vec::Vec::new`].
31     pub fn new() -> Self {
32         Default::default()
33     }
34 
35     /// Same as [`std::vec::Vec::with_capacity`] but returns an error on
36     /// allocation failure.
37     pub fn with_capacity(capacity: usize) -> Result<Self, OutOfMemory> {
38         let mut v = Self::new();
39         v.reserve(capacity)?;
40         Ok(v)
41     }
42 
43     /// Same as [`std::vec::Vec::reserve`] but returns an error on allocation
44     /// failure.
45     pub fn reserve(&mut self, additional: usize) -> Result<(), OutOfMemory> {
46         self.inner.try_reserve(additional).map_err(|_| {
47             OutOfMemory::new(
48                 self.len()
49                     .saturating_add(additional)
50                     .saturating_mul(mem::size_of::<T>()),
51             )
52         })
53     }
54 
55     /// Same as [`std::vec::Vec::reserve_exact`] but returns an error on allocation
56     /// failure.
57     pub fn reserve_exact(&mut self, additional: usize) -> Result<(), OutOfMemory> {
58         self.inner
59             .try_reserve_exact(additional)
60             .map_err(|_| OutOfMemory::new(self.len().saturating_add(additional)))
61     }
62 
63     /// Same as [`std::vec::Vec::len`].
64     pub fn len(&self) -> usize {
65         self.inner.len()
66     }
67 
68     /// Same as [`std::vec::Vec::capacity`].
69     pub fn capacity(&self) -> usize {
70         self.inner.capacity()
71     }
72 
73     /// Same as [`std::vec::Vec::is_empty`].
74     pub fn is_empty(&self) -> bool {
75         self.inner.is_empty()
76     }
77 
78     /// Same as [`std::vec::Vec::push`] but returns an error on allocation
79     /// failure.
80     pub fn push(&mut self, value: T) -> Result<(), OutOfMemory> {
81         self.reserve(1)?;
82         self.inner.push(value);
83         Ok(())
84     }
85 
86     /// Same as [`std::vec::Vec::pop`].
87     pub fn pop(&mut self) -> Option<T> {
88         self.inner.pop()
89     }
90 
91     /// Same as [`std::vec::Vec::into_raw_parts`].
92     pub fn into_raw_parts(mut self) -> (*mut T, usize, usize) {
93         // NB: Can't use `Vec::into_raw_parts` until our MSRV is >= 1.93.
94         let ptr = self.as_mut_ptr();
95         let len = self.len();
96         let cap = self.capacity();
97         mem::forget(self);
98         (ptr, len, cap)
99     }
100 
101     /// Same as [`std::vec::Vec::from_raw_parts`].
102     pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
103         Vec {
104             // Safety: Same as our unsafe contract.
105             inner: unsafe { StdVec::from_raw_parts(ptr, length, capacity) },
106         }
107     }
108 
109     /// Same as [`std::vec::Vec::drain`].
110     pub fn drain<R>(&mut self, range: R) -> std_alloc::vec::Drain<'_, T>
111     where
112         R: core::ops::RangeBounds<usize>,
113     {
114         self.inner.drain(range)
115     }
116 }
117 
118 impl<T> Deref for Vec<T> {
119     type Target = [T];
120 
121     fn deref(&self) -> &Self::Target {
122         &self.inner
123     }
124 }
125 
126 impl<T> DerefMut for Vec<T> {
127     fn deref_mut(&mut self) -> &mut Self::Target {
128         &mut self.inner
129     }
130 }
131 
132 impl<T> Index<usize> for Vec<T> {
133     type Output = T;
134 
135     fn index(&self, index: usize) -> &Self::Output {
136         &self.inner[index]
137     }
138 }
139 
140 impl<T> IndexMut<usize> for Vec<T> {
141     fn index_mut(&mut self, index: usize) -> &mut Self::Output {
142         &mut self.inner[index]
143     }
144 }
145 
146 impl<T> IntoIterator for Vec<T> {
147     type Item = T;
148     type IntoIter = std_alloc::vec::IntoIter<T>;
149 
150     fn into_iter(self) -> Self::IntoIter {
151         self.inner.into_iter()
152     }
153 }
154 
155 impl<'a, T> IntoIterator for &'a Vec<T> {
156     type Item = &'a T;
157 
158     type IntoIter = core::slice::Iter<'a, T>;
159 
160     fn into_iter(self) -> Self::IntoIter {
161         (**self).iter()
162     }
163 }
164 
165 impl<'a, T> IntoIterator for &'a mut Vec<T> {
166     type Item = &'a mut T;
167 
168     type IntoIter = core::slice::IterMut<'a, T>;
169 
170     fn into_iter(self) -> Self::IntoIter {
171         (**self).iter_mut()
172     }
173 }
174