wasmtime_environ/collections/
secondary_map.rs1use crate::error::OutOfMemory;
2use core::{fmt, ops::Index};
3use cranelift_entity::{EntityRef, SecondaryMap as Inner};
4
5pub struct SecondaryMap<K, V>
7where
8 K: EntityRef,
9 V: Clone,
10{
11 inner: Inner<K, V>,
12}
13
14impl<K, V> fmt::Debug for SecondaryMap<K, V>
15where
16 K: EntityRef + fmt::Debug,
17 V: fmt::Debug + Clone,
18{
19 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20 fmt::Debug::fmt(&self.inner, f)
21 }
22}
23
24impl<K, V> SecondaryMap<K, V>
25where
26 K: EntityRef,
27 V: Clone,
28{
29 pub fn new() -> Self
31 where
32 V: Default,
33 {
34 Self {
35 inner: Inner::new(),
36 }
37 }
38
39 pub fn with_capacity(capacity: usize) -> Result<Self, OutOfMemory>
41 where
42 V: Default,
43 {
44 Ok(Self {
45 inner: Inner::try_with_capacity(capacity)?,
46 })
47 }
48
49 pub fn with_default(default: V) -> Self {
51 Self {
52 inner: Inner::with_default(default),
53 }
54 }
55
56 pub fn capacity(&self) -> usize {
58 self.inner.capacity()
59 }
60
61 pub fn get(&self, k: K) -> Option<&V> {
63 self.inner.get(k)
64 }
65
66 pub fn get_mut(&mut self, k: K) -> Option<&mut V> {
68 self.inner.get_mut(k)
69 }
70
71 pub fn insert(&mut self, k: K, v: V) -> Result<Option<V>, OutOfMemory> {
73 self.inner.try_insert(k, v)
74 }
75
76 pub fn remove(&mut self, k: K) -> Option<V> {
78 self.inner.remove(k)
79 }
80
81 pub fn is_empty(&self) -> bool {
83 self.inner.is_empty()
84 }
85
86 pub fn clear(&mut self) {
88 self.inner.clear()
89 }
90
91 pub fn iter(&self) -> cranelift_entity::Iter<'_, K, V> {
93 self.inner.iter()
94 }
95
96 pub fn iter_mut(&mut self) -> cranelift_entity::IterMut<'_, K, V> {
98 self.inner.iter_mut()
99 }
100
101 pub fn keys(&self) -> cranelift_entity::Keys<K> {
103 self.inner.keys()
104 }
105
106 pub fn values(&self) -> core::slice::Iter<'_, V> {
108 self.inner.values()
109 }
110
111 pub fn values_mut(&mut self) -> core::slice::IterMut<'_, V> {
113 self.inner.values_mut()
114 }
115
116 pub fn resize(&mut self, n: usize) -> Result<(), OutOfMemory> {
118 self.inner.try_resize(n)
119 }
120}
121
122impl<K, V> Default for SecondaryMap<K, V>
123where
124 K: EntityRef,
125 V: Clone + Default,
126{
127 fn default() -> SecondaryMap<K, V> {
128 SecondaryMap::new()
129 }
130}
131
132impl<K, V> Index<K> for SecondaryMap<K, V>
135where
136 K: EntityRef,
137 V: Clone,
138{
139 type Output = V;
140
141 fn index(&self, k: K) -> &V {
142 &self.inner[k]
143 }
144}