Skip to main content

wasmtime_environ/collections/
primary_map.rs

1use crate::error::OutOfMemory;
2use crate::prelude::*;
3use core::{
4    fmt,
5    ops::{Index, IndexMut},
6};
7use cranelift_entity::EntityRef;
8use serde::{Serialize, ser::SerializeSeq};
9
10/// Like [`cranelift_entity::PrimaryMap`] but enforces fallible allocation for
11/// all methods that allocate.
12#[derive(Hash, PartialEq, Eq)]
13pub struct TryPrimaryMap<K, V>
14where
15    K: EntityRef,
16{
17    inner: cranelift_entity::PrimaryMap<K, V>,
18}
19
20impl<K, V> Default for TryPrimaryMap<K, V>
21where
22    K: EntityRef,
23{
24    fn default() -> Self {
25        Self {
26            inner: cranelift_entity::PrimaryMap::default(),
27        }
28    }
29}
30
31impl<K, V> fmt::Debug for TryPrimaryMap<K, V>
32where
33    K: EntityRef + fmt::Debug,
34    V: fmt::Debug,
35{
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        fmt::Debug::fmt(&self.inner, f)
38    }
39}
40
41impl<K, V> From<TryVec<V>> for TryPrimaryMap<K, V>
42where
43    K: EntityRef,
44{
45    fn from(values: TryVec<V>) -> Self {
46        let values: ::alloc::vec::Vec<V> = values.into();
47        let inner = cranelift_entity::PrimaryMap::from(values);
48        Self { inner }
49    }
50}
51
52impl<K, V> serde::ser::Serialize for TryPrimaryMap<K, V>
53where
54    K: EntityRef,
55    V: Serialize,
56{
57    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
58    where
59        S: serde::Serializer,
60    {
61        let mut seq = serializer.serialize_seq(Some(self.len()))?;
62        for val in self.values() {
63            seq.serialize_element(val)?;
64        }
65        seq.end()
66    }
67}
68
69impl<'de, K, V> serde::de::Deserialize<'de> for TryPrimaryMap<K, V>
70where
71    K: EntityRef,
72    V: serde::de::Deserialize<'de>,
73{
74    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
75    where
76        D: serde::Deserializer<'de>,
77    {
78        let v: TryVec<V> = serde::de::Deserialize::deserialize(deserializer)?;
79        Ok(Self::from(v))
80    }
81}
82
83impl<K, V> TryPrimaryMap<K, V>
84where
85    K: EntityRef,
86{
87    /// Same as [`cranelift_entity::PrimaryMap::new`].
88    pub fn new() -> Self {
89        Self {
90            inner: cranelift_entity::PrimaryMap::new(),
91        }
92    }
93
94    /// Same as [`cranelift_entity::PrimaryMap::try_with_capacity`].
95    pub fn with_capacity(capacity: usize) -> Result<Self, OutOfMemory> {
96        let mut map = Self::new();
97        map.reserve(capacity)?;
98        Ok(map)
99    }
100
101    /// Same as [`cranelift_entity::PrimaryMap::is_valid`].
102    pub fn is_valid(&self, k: K) -> bool {
103        self.inner.is_valid(k)
104    }
105
106    /// Same as [`cranelift_entity::PrimaryMap::get`].
107    pub fn get(&self, k: K) -> Option<&V> {
108        self.inner.get(k)
109    }
110
111    /// Same as [`cranelift_entity::PrimaryMap::get_range`].
112    pub fn get_range(&self, range: core::ops::Range<K>) -> Option<&[V]> {
113        self.inner.get_range(range)
114    }
115
116    /// Same as [`cranelift_entity::PrimaryMap::get_mut`].
117    pub fn get_mut(&mut self, k: K) -> Option<&mut V> {
118        self.inner.get_mut(k)
119    }
120
121    /// Same as [`cranelift_entity::PrimaryMap::is_empty`].
122    pub fn is_empty(&self) -> bool {
123        self.inner.is_empty()
124    }
125
126    /// Same as [`cranelift_entity::PrimaryMap::len`].
127    pub fn len(&self) -> usize {
128        self.inner.len()
129    }
130
131    /// Same as [`cranelift_entity::PrimaryMap::keys`].
132    pub fn keys(&self) -> cranelift_entity::Keys<K> {
133        self.inner.keys()
134    }
135
136    /// Same as [`cranelift_entity::PrimaryMap::values`].
137    pub fn values(&self) -> core::slice::Iter<'_, V> {
138        self.inner.values()
139    }
140
141    /// Same as [`cranelift_entity::PrimaryMap::values_mut`].
142    pub fn values_mut(&mut self) -> core::slice::IterMut<'_, V> {
143        self.inner.values_mut()
144    }
145
146    /// Same as [`cranelift_entity::PrimaryMap::as_values_slice`].
147    pub fn as_values_slice(&self) -> &[V] {
148        self.inner.as_values_slice()
149    }
150
151    /// Same as [`cranelift_entity::PrimaryMap::iter`].
152    pub fn iter(&self) -> cranelift_entity::Iter<'_, K, V> {
153        self.inner.iter()
154    }
155
156    /// Same as [`cranelift_entity::PrimaryMap::iter_mut`].
157    pub fn iter_mut(&mut self) -> cranelift_entity::IterMut<'_, K, V> {
158        self.inner.iter_mut()
159    }
160
161    /// Same as [`cranelift_entity::PrimaryMap::clear`].
162    pub fn clear(&mut self) {
163        self.inner.clear()
164    }
165
166    /// Same as [`cranelift_entity::PrimaryMap::next_key`].
167    pub fn next_key(&self) -> K {
168        self.inner.next_key()
169    }
170
171    /// Same as [`cranelift_entity::PrimaryMap::push`] but returns an error on
172    /// allocation failure.
173    pub fn push(&mut self, v: V) -> Result<K, OutOfMemory> {
174        self.reserve(1)?;
175        Ok(self.inner.push(v))
176    }
177
178    /// Same as [`cranelift_entity::PrimaryMap::last`].
179    pub fn last(&self) -> Option<(K, &V)> {
180        self.inner.last()
181    }
182
183    /// Same as [`cranelift_entity::PrimaryMap::last_mut`].
184    pub fn last_mut(&mut self) -> Option<(K, &mut V)> {
185        self.inner.last_mut()
186    }
187
188    /// Same as [`cranelift_entity::PrimaryMap::try_reserve`].
189    pub fn reserve(&mut self, additional: usize) -> Result<(), OutOfMemory> {
190        self.inner.try_reserve(additional)
191    }
192
193    /// Same as [`cranelift_entity::PrimaryMap::try_reserve_exact`].
194    pub fn reserve_exact(&mut self, additional: usize) -> Result<(), OutOfMemory> {
195        self.inner.try_reserve_exact(additional)
196    }
197
198    /// Same as [`cranelift_entity::PrimaryMap::get_disjoint_mut`].
199    pub fn get_disjoint_mut<const N: usize>(
200        &mut self,
201        indices: [K; N],
202    ) -> Result<[&mut V; N], core::slice::GetDisjointMutError> {
203        self.inner.get_disjoint_mut(indices)
204    }
205
206    /// Same as [`cranelift_entity::PrimaryMap::binary_search_values_by_key`].
207    pub fn binary_search_values_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<K, K>
208    where
209        F: FnMut(&'a V) -> B,
210        B: Ord,
211    {
212        self.inner.binary_search_values_by_key(b, f)
213    }
214
215    /// Same as [`cranelift_entity::PrimaryMap::get_raw_mut`].
216    pub fn get_raw_mut(&mut self, k: K) -> Option<*mut V> {
217        self.inner.get_raw_mut(k)
218    }
219}
220
221impl<K, V> TryExtend<V> for TryPrimaryMap<K, V>
222where
223    K: EntityRef,
224{
225    fn try_extend<I>(&mut self, iter: I) -> Result<(), OutOfMemory>
226    where
227        I: IntoIterator<Item = V>,
228    {
229        let iter = iter.into_iter();
230        let (min, max) = iter.size_hint();
231        let cap = max.unwrap_or(min);
232        self.reserve(cap)?;
233        for v in iter {
234            self.push(v)?;
235        }
236        Ok(())
237    }
238}
239
240impl<K, V> Index<K> for TryPrimaryMap<K, V>
241where
242    K: EntityRef,
243{
244    type Output = V;
245
246    fn index(&self, k: K) -> &V {
247        &self.inner[k]
248    }
249}
250
251impl<K, V> IndexMut<K> for TryPrimaryMap<K, V>
252where
253    K: EntityRef,
254{
255    fn index_mut(&mut self, k: K) -> &mut V {
256        &mut self.inner[k]
257    }
258}
259
260impl<K, V> IntoIterator for TryPrimaryMap<K, V>
261where
262    K: EntityRef,
263{
264    type Item = (K, V);
265    type IntoIter = cranelift_entity::IntoIter<K, V>;
266    fn into_iter(self) -> Self::IntoIter {
267        self.inner.into_iter()
268    }
269}
270
271impl<'a, K, V> IntoIterator for &'a TryPrimaryMap<K, V>
272where
273    K: EntityRef,
274{
275    type Item = (K, &'a V);
276    type IntoIter = cranelift_entity::Iter<'a, K, V>;
277    fn into_iter(self) -> Self::IntoIter {
278        self.iter()
279    }
280}
281
282impl<'a, K, V> IntoIterator for &'a mut TryPrimaryMap<K, V>
283where
284    K: EntityRef,
285{
286    type Item = (K, &'a mut V);
287    type IntoIter = cranelift_entity::IterMut<'a, K, V>;
288    fn into_iter(self) -> Self::IntoIter {
289        self.iter_mut()
290    }
291}