1 //! Densely numbered entity references as mapping keys. 2 3 use crate::EntityRef; 4 use crate::iter::{Iter, IterMut}; 5 use crate::keys::Keys; 6 use alloc::vec::Vec; 7 use core::cmp::min; 8 use core::fmt; 9 use core::marker::PhantomData; 10 use core::ops::{Index, IndexMut}; 11 use core::slice; 12 #[cfg(feature = "enable-serde")] 13 use serde::{ 14 Deserialize, Serialize, 15 de::{Deserializer, SeqAccess, Visitor}, 16 ser::{SerializeSeq, Serializer}, 17 }; 18 use wasmtime_core::error::OutOfMemory; 19 20 /// A mapping `K -> V` for densely indexed entity references. 21 /// 22 /// The `SecondaryMap` data structure uses the dense index space to implement a map with a vector. 23 /// Unlike `PrimaryMap`, an `SecondaryMap` can't be used to allocate entity references. It is used 24 /// to associate secondary information with entities. 25 /// 26 /// The map does not track if an entry for a key has been inserted or not. Instead it behaves as if 27 /// all keys have a default entry from the beginning. 28 #[derive(Clone, Hash)] 29 pub struct SecondaryMap<K, V> 30 where 31 K: EntityRef, 32 V: Clone, 33 { 34 elems: Vec<V>, 35 default: V, 36 unused: PhantomData<K>, 37 } 38 39 /// Shared `SecondaryMap` implementation for all value types. 40 impl<K, V> SecondaryMap<K, V> 41 where 42 K: EntityRef, 43 V: Clone, 44 { 45 /// Create a new empty map. 46 pub fn new() -> Self 47 where 48 V: Default, 49 { 50 Self { 51 elems: Vec::new(), 52 default: Default::default(), 53 unused: PhantomData, 54 } 55 } 56 57 /// Create a new, empty map with the specified capacity. 58 /// 59 /// The map will be able to hold exactly `capacity` elements without reallocating. 60 pub fn with_capacity(capacity: usize) -> Self 61 where 62 V: Default, 63 { 64 Self { 65 elems: Vec::with_capacity(capacity), 66 default: Default::default(), 67 unused: PhantomData, 68 } 69 } 70 71 /// Like `with_capacity` but returns an error on allocation failure. 72 pub fn try_with_capacity(capacity: usize) -> Result<Self, OutOfMemory> 73 where 74 V: Default, 75 { 76 let mut elems = Vec::new(); 77 elems 78 .try_reserve(capacity) 79 .map_err(|_| OutOfMemory::new(core::mem::size_of::<V>().saturating_mul(capacity)))?; 80 Ok(Self { 81 elems, 82 default: Default::default(), 83 unused: PhantomData, 84 }) 85 } 86 87 /// Create a new empty map with a specified default value. 88 /// 89 /// This constructor does not require V to implement Default. 90 pub fn with_default(default: V) -> Self { 91 Self { 92 elems: Vec::new(), 93 default, 94 unused: PhantomData, 95 } 96 } 97 98 /// Returns the number of elements the map can hold without reallocating. 99 pub fn capacity(&self) -> usize { 100 self.elems.capacity() 101 } 102 103 /// Get the element at `k` if it exists. 104 #[inline(always)] 105 pub fn get(&self, k: K) -> Option<&V> { 106 self.elems.get(k.index()) 107 } 108 109 /// Get the element at `k` mutably, if it exists. 110 pub fn get_mut(&mut self, k: K) -> Option<&mut V> { 111 self.elems.get_mut(k.index()) 112 } 113 114 /// Insert the given key-value pair, returning the old value if it exists. 115 pub fn insert(&mut self, k: K, v: V) -> Option<V> { 116 let i = k.index(); 117 if i < self.elems.len() { 118 Some(core::mem::replace(&mut self.elems[i], v)) 119 } else { 120 self.resize(i + 1); 121 self.elems[i] = v; 122 None 123 } 124 } 125 126 /// Like `insert` but returns an error on allocation failure. 127 pub fn try_insert(&mut self, k: K, v: V) -> Result<Option<V>, OutOfMemory> { 128 let i = k.index(); 129 if i < self.elems.len() { 130 Ok(Some(core::mem::replace(&mut self.elems[i], v))) 131 } else { 132 self.try_resize(i + 1)?; 133 self.elems[i] = v; 134 Ok(None) 135 } 136 } 137 138 /// Is this map completely empty? 139 #[inline(always)] 140 pub fn is_empty(&self) -> bool { 141 self.elems.is_empty() 142 } 143 144 /// Remove all entries from this map. 145 #[inline(always)] 146 pub fn clear(&mut self) { 147 self.elems.clear() 148 } 149 150 /// Iterate over all the keys and values in this map. 151 pub fn iter(&self) -> Iter<'_, K, V> { 152 Iter::new(self.elems.iter()) 153 } 154 155 /// Iterate over all the keys and values in this map, mutable edition. 156 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> { 157 IterMut::new(self.elems.iter_mut()) 158 } 159 160 /// Iterate over all the keys in this map. 161 pub fn keys(&self) -> Keys<K> { 162 Keys::with_len(self.elems.len()) 163 } 164 165 /// Iterate over all the values in this map. 166 pub fn values(&self) -> slice::Iter<'_, V> { 167 self.elems.iter() 168 } 169 170 /// Iterate over all the values in this map, mutable edition. 171 pub fn values_mut(&mut self) -> slice::IterMut<'_, V> { 172 self.elems.iter_mut() 173 } 174 175 /// Resize the map to have `n` entries by adding default entries as needed. 176 pub fn resize(&mut self, n: usize) { 177 self.elems.resize(n, self.default.clone()); 178 } 179 180 /// Like `resize` but returns an error on allocation failure. 181 pub fn try_resize(&mut self, n: usize) -> Result<(), OutOfMemory> { 182 if self.elems.capacity() < n { 183 self.elems 184 .try_reserve(n - self.elems.len()) 185 .map_err(|_| OutOfMemory::new(core::mem::size_of::<V>().saturating_mul(n)))?; 186 } 187 debug_assert!(self.elems.capacity() >= n); 188 self.elems.resize(n, self.default.clone()); 189 Ok(()) 190 } 191 192 /// Slow path for `index_mut` which resizes the vector. 193 #[cold] 194 fn resize_for_index_mut(&mut self, i: usize) -> &mut V { 195 self.elems.resize(i + 1, self.default.clone()); 196 &mut self.elems[i] 197 } 198 } 199 200 impl<K, V> Default for SecondaryMap<K, V> 201 where 202 K: EntityRef, 203 V: Clone + Default, 204 { 205 fn default() -> SecondaryMap<K, V> { 206 SecondaryMap::new() 207 } 208 } 209 210 impl<K, V> FromIterator<(K, V)> for SecondaryMap<K, V> 211 where 212 K: EntityRef, 213 V: Clone + Default, 214 { 215 fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self { 216 let iter = iter.into_iter(); 217 let (min, max) = iter.size_hint(); 218 let cap = max.unwrap_or_else(|| 2 * min); 219 let mut map = Self::with_capacity(cap); 220 for (k, v) in iter { 221 map[k] = v; 222 } 223 map 224 } 225 } 226 227 /// Immutable indexing into an `SecondaryMap`. 228 /// 229 /// All keys are permitted. Untouched entries have the default value. 230 impl<K, V> Index<K> for SecondaryMap<K, V> 231 where 232 K: EntityRef, 233 V: Clone, 234 { 235 type Output = V; 236 237 #[inline(always)] 238 fn index(&self, k: K) -> &V { 239 self.elems.get(k.index()).unwrap_or(&self.default) 240 } 241 } 242 243 /// Mutable indexing into an `SecondaryMap`. 244 /// 245 /// The map grows as needed to accommodate new keys. 246 impl<K, V> IndexMut<K> for SecondaryMap<K, V> 247 where 248 K: EntityRef, 249 V: Clone, 250 { 251 #[inline(always)] 252 fn index_mut(&mut self, k: K) -> &mut V { 253 let i = k.index(); 254 if i >= self.elems.len() { 255 return self.resize_for_index_mut(i); 256 } 257 &mut self.elems[i] 258 } 259 } 260 261 impl<K, V> PartialEq for SecondaryMap<K, V> 262 where 263 K: EntityRef, 264 V: Clone + PartialEq, 265 { 266 fn eq(&self, other: &Self) -> bool { 267 let min_size = min(self.elems.len(), other.elems.len()); 268 self.default == other.default 269 && self.elems[..min_size] == other.elems[..min_size] 270 && self.elems[min_size..].iter().all(|e| *e == self.default) 271 && other.elems[min_size..].iter().all(|e| *e == other.default) 272 } 273 } 274 275 impl<K, V> Eq for SecondaryMap<K, V> 276 where 277 K: EntityRef, 278 V: Clone + PartialEq + Eq, 279 { 280 } 281 282 #[cfg(feature = "enable-serde")] 283 impl<K, V> Serialize for SecondaryMap<K, V> 284 where 285 K: EntityRef, 286 V: Clone + PartialEq + Serialize, 287 { 288 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 289 where 290 S: Serializer, 291 { 292 // TODO: bincode encodes option as "byte for Some/None" and then optionally the content 293 // TODO: we can actually optimize it by encoding manually bitmask, then elements 294 let mut elems_cnt = self.elems.len(); 295 while elems_cnt > 0 && self.elems[elems_cnt - 1] == self.default { 296 elems_cnt -= 1; 297 } 298 let mut seq = serializer.serialize_seq(Some(1 + elems_cnt))?; 299 seq.serialize_element(&Some(self.default.clone()))?; 300 for e in self.elems.iter().take(elems_cnt) { 301 let some_e = Some(e); 302 seq.serialize_element(if *e == self.default { &None } else { &some_e })?; 303 } 304 seq.end() 305 } 306 } 307 308 #[cfg(feature = "enable-serde")] 309 impl<'de, K, V> Deserialize<'de> for SecondaryMap<K, V> 310 where 311 K: EntityRef, 312 V: Clone + Deserialize<'de>, 313 { 314 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 315 where 316 D: Deserializer<'de>, 317 { 318 use alloc::fmt; 319 struct SecondaryMapVisitor<K, V> { 320 unused: PhantomData<fn(K) -> V>, 321 } 322 323 impl<'de, K, V> Visitor<'de> for SecondaryMapVisitor<K, V> 324 where 325 K: EntityRef, 326 V: Clone + Deserialize<'de>, 327 { 328 type Value = SecondaryMap<K, V>; 329 330 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 331 formatter.write_str("struct SecondaryMap") 332 } 333 334 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> 335 where 336 A: SeqAccess<'de>, 337 { 338 match seq.next_element()? { 339 Some(Some(default_val)) => { 340 let default_val: V = default_val; // compiler can't infer the type 341 let mut m = SecondaryMap::with_default(default_val.clone()); 342 let mut idx = 0; 343 while let Some(val) = seq.next_element()? { 344 let val: Option<_> = val; // compiler can't infer the type 345 m[K::new(idx)] = val.unwrap_or_else(|| default_val.clone()); 346 idx += 1; 347 } 348 Ok(m) 349 } 350 _ => Err(serde::de::Error::custom("Default value required")), 351 } 352 } 353 } 354 355 deserializer.deserialize_seq(SecondaryMapVisitor { 356 unused: PhantomData {}, 357 }) 358 } 359 } 360 361 impl<K: EntityRef + fmt::Debug, V: fmt::Debug + Clone> fmt::Debug for SecondaryMap<K, V> { 362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 363 f.debug_struct("SecondaryMap") 364 .field("elems", &self.elems) 365 .field("default", &self.default) 366 .finish() 367 } 368 } 369 370 #[cfg(test)] 371 mod tests { 372 use super::*; 373 374 // `EntityRef` impl for testing. 375 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 376 struct E(u32); 377 378 impl EntityRef for E { 379 fn new(i: usize) -> Self { 380 E(i as u32) 381 } 382 fn index(self) -> usize { 383 self.0 as usize 384 } 385 } 386 387 #[test] 388 fn basic() { 389 let r0 = E(0); 390 let r1 = E(1); 391 let r2 = E(2); 392 let r3 = E(3); 393 let mut m = SecondaryMap::new(); 394 395 let v: Vec<E> = m.keys().collect(); 396 assert_eq!(v, []); 397 398 m[r2] = 3; 399 m[r1] = 5; 400 401 assert_eq!(m[r1], 5); 402 assert_eq!(m[r2], 3); 403 404 assert!(m.get(r3).is_none()); 405 assert!(m.get_mut(r3).is_none()); 406 407 let old = m.insert(r3, 99); 408 assert!(old.is_none()); 409 assert_eq!(m.get(r3), Some(&99)); 410 assert_eq!(m[r3], 99); 411 412 *m.get_mut(r3).unwrap() += 1; 413 assert_eq!(m.get(r3), Some(&100)); 414 assert_eq!(m[r3], 100); 415 416 let old = m.insert(r3, 42); 417 assert_eq!(old, Some(100)); 418 assert_eq!(m.get(r3), Some(&42)); 419 assert_eq!(m[r3], 42); 420 421 let v: Vec<E> = m.keys().collect(); 422 assert_eq!(v, [r0, r1, r2, r3]); 423 424 let shared = &m; 425 assert_eq!(shared[r0], 0); 426 assert_eq!(shared[r1], 5); 427 assert_eq!(shared[r2], 3); 428 assert_eq!(shared[r3], 42); 429 } 430 } 431