1 //! Densely numbered entity references as mapping keys. 2 use crate::EntityRef; 3 use crate::boxed_slice::BoxedSlice; 4 use crate::iter::{IntoIter, Iter, IterMut}; 5 use crate::keys::Keys; 6 use alloc::boxed::Box; 7 use alloc::vec::Vec; 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_derive::{Deserialize, Serialize}; 14 use wasmtime_core::error::OutOfMemory; 15 16 /// A primary mapping `K -> V` allocating dense entity references. 17 /// 18 /// The `PrimaryMap` data structure uses the dense index space to implement a map with a vector. 19 /// 20 /// A primary map contains the main definition of an entity, and it can be used to allocate new 21 /// entity references with the `push` method. 22 /// 23 /// There should only be a single `PrimaryMap` instance for a given `EntityRef` type, otherwise 24 /// conflicting references will be created. Using unknown keys for indexing will cause a panic. 25 /// 26 /// Note that `PrimaryMap` doesn't implement `Deref` or `DerefMut`, which would allow 27 /// `&PrimaryMap<K, V>` to convert to `&[V]`. One of the main advantages of `PrimaryMap` is 28 /// that it only allows indexing with the distinct `EntityRef` key type, so converting to a 29 /// plain slice would make it easier to use incorrectly. To make a slice of a `PrimaryMap`, use 30 /// `into_boxed_slice`. 31 #[derive(Clone, Hash, PartialEq, Eq)] 32 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] 33 pub struct PrimaryMap<K, V> 34 where 35 K: EntityRef, 36 { 37 elems: Vec<V>, 38 unused: PhantomData<K>, 39 } 40 41 impl<K, V> PrimaryMap<K, V> 42 where 43 K: EntityRef, 44 { 45 /// Create a new empty map. new() -> Self46 pub fn new() -> Self { 47 Self { 48 elems: Vec::new(), 49 unused: PhantomData, 50 } 51 } 52 53 /// Create a new empty map with the given capacity. with_capacity(capacity: usize) -> Self54 pub fn with_capacity(capacity: usize) -> Self { 55 Self { 56 elems: Vec::with_capacity(capacity), 57 unused: PhantomData, 58 } 59 } 60 61 /// Like `with_capacity` but returns an error on allocation failure. try_with_capacity(capacity: usize) -> Result<Self, OutOfMemory>62 pub fn try_with_capacity(capacity: usize) -> Result<Self, OutOfMemory> { 63 let mut map = Self::new(); 64 map.try_reserve(capacity)?; 65 Ok(map) 66 } 67 68 /// Check if `k` is a valid key in the map. is_valid(&self, k: K) -> bool69 pub fn is_valid(&self, k: K) -> bool { 70 k.index() < self.elems.len() 71 } 72 73 /// Get the element at `k` if it exists. get(&self, k: K) -> Option<&V>74 pub fn get(&self, k: K) -> Option<&V> { 75 self.elems.get(k.index()) 76 } 77 78 /// Get the slice of values associated with the given range of keys, if any. get_range(&self, range: core::ops::Range<K>) -> Option<&[V]>79 pub fn get_range(&self, range: core::ops::Range<K>) -> Option<&[V]> { 80 self.elems.get(range.start.index()..range.end.index()) 81 } 82 83 /// Get the element at `k` if it exists, mutable version. get_mut(&mut self, k: K) -> Option<&mut V>84 pub fn get_mut(&mut self, k: K) -> Option<&mut V> { 85 self.elems.get_mut(k.index()) 86 } 87 88 /// Is this map completely empty? is_empty(&self) -> bool89 pub fn is_empty(&self) -> bool { 90 self.elems.is_empty() 91 } 92 93 /// Get the total number of entity references created. len(&self) -> usize94 pub fn len(&self) -> usize { 95 self.elems.len() 96 } 97 98 /// Iterate over all the keys in this map. keys(&self) -> Keys<K>99 pub fn keys(&self) -> Keys<K> { 100 Keys::with_len(self.elems.len()) 101 } 102 103 /// Iterate over all the values in this map. values(&self) -> slice::Iter<'_, V>104 pub fn values(&self) -> slice::Iter<'_, V> { 105 self.elems.iter() 106 } 107 108 /// Iterate over all the values in this map, mutable edition. values_mut(&mut self) -> slice::IterMut<'_, V>109 pub fn values_mut(&mut self) -> slice::IterMut<'_, V> { 110 self.elems.iter_mut() 111 } 112 113 /// Get this map's underlying values as a slice. as_values_slice(&self) -> &[V]114 pub fn as_values_slice(&self) -> &[V] { 115 &self.elems 116 } 117 118 /// Iterate over all the keys and values in this map. iter(&self) -> Iter<'_, K, V>119 pub fn iter(&self) -> Iter<'_, K, V> { 120 Iter::new(self.elems.iter()) 121 } 122 123 /// Iterate over all the keys and values in this map, mutable edition. iter_mut(&mut self) -> IterMut<'_, K, V>124 pub fn iter_mut(&mut self) -> IterMut<'_, K, V> { 125 IterMut::new(self.elems.iter_mut()) 126 } 127 128 /// Remove all entries from this map. clear(&mut self)129 pub fn clear(&mut self) { 130 self.elems.clear() 131 } 132 133 /// Get the key that will be assigned to the next pushed value. next_key(&self) -> K134 pub fn next_key(&self) -> K { 135 K::new(self.elems.len()) 136 } 137 138 /// Append `v` to the mapping, assigning a new key which is returned. push(&mut self, v: V) -> K139 pub fn push(&mut self, v: V) -> K { 140 let k = self.next_key(); 141 self.elems.push(v); 142 k 143 } 144 145 /// Returns the last element that was inserted in the map. last(&self) -> Option<(K, &V)>146 pub fn last(&self) -> Option<(K, &V)> { 147 let len = self.elems.len(); 148 let last = self.elems.last()?; 149 Some((K::new(len - 1), last)) 150 } 151 152 /// Returns the last element that was inserted in the map. last_mut(&mut self) -> Option<(K, &mut V)>153 pub fn last_mut(&mut self) -> Option<(K, &mut V)> { 154 let len = self.elems.len(); 155 let last = self.elems.last_mut()?; 156 Some((K::new(len - 1), last)) 157 } 158 159 /// Reserves capacity for at least `additional` more elements to be inserted. reserve(&mut self, additional: usize)160 pub fn reserve(&mut self, additional: usize) { 161 self.elems.reserve(additional) 162 } 163 164 /// Like `reserve` but returns an error on allocation failure. try_reserve(&mut self, additional: usize) -> Result<(), OutOfMemory>165 pub fn try_reserve(&mut self, additional: usize) -> Result<(), OutOfMemory> { 166 self.elems 167 .try_reserve(additional) 168 .map_err(|_| OutOfMemory::new(self.len().saturating_add(additional))) 169 } 170 171 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted. reserve_exact(&mut self, additional: usize)172 pub fn reserve_exact(&mut self, additional: usize) { 173 self.elems.reserve_exact(additional) 174 } 175 176 /// Like `reserve_exact` but returns an error on allocation failure. try_reserve_exact(&mut self, additional: usize) -> Result<(), OutOfMemory>177 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), OutOfMemory> { 178 self.elems 179 .try_reserve_exact(additional) 180 .map_err(|_| OutOfMemory::new(self.len().saturating_add(additional))) 181 } 182 183 /// Shrinks the capacity of the `PrimaryMap` as much as possible. shrink_to_fit(&mut self)184 pub fn shrink_to_fit(&mut self) { 185 self.elems.shrink_to_fit() 186 } 187 188 /// Consumes this `PrimaryMap` and produces a `BoxedSlice`. into_boxed_slice(self) -> BoxedSlice<K, V>189 pub fn into_boxed_slice(self) -> BoxedSlice<K, V> { 190 unsafe { BoxedSlice::<K, V>::from_raw(Box::<[V]>::into_raw(self.elems.into_boxed_slice())) } 191 } 192 193 /// Returns mutable references to many elements at once. 194 /// 195 /// Returns an error if an element does not exist, or if the same key was passed more than 196 /// once. get_disjoint_mut<const N: usize>( &mut self, indices: [K; N], ) -> Result<[&mut V; N], slice::GetDisjointMutError>197 pub fn get_disjoint_mut<const N: usize>( 198 &mut self, 199 indices: [K; N], 200 ) -> Result<[&mut V; N], slice::GetDisjointMutError> { 201 self.elems.get_disjoint_mut(indices.map(|k| k.index())) 202 } 203 204 /// Performs a binary search on the values with a key extraction function. 205 /// 206 /// Assumes that the values are sorted by the key extracted by the function. 207 /// 208 /// If the value is found then `Ok(K)` is returned, containing the entity key 209 /// of the matching value. 210 /// 211 /// If there are multiple matches, then any one of the matches could be returned. 212 /// 213 /// If the value is not found then Err(K) is returned, containing the entity key 214 /// where a matching element could be inserted while maintaining sorted order. binary_search_values_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<K, K> where F: FnMut(&'a V) -> B, B: Ord,215 pub fn binary_search_values_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<K, K> 216 where 217 F: FnMut(&'a V) -> B, 218 B: Ord, 219 { 220 self.elems 221 .binary_search_by_key(b, f) 222 .map(|i| K::new(i)) 223 .map_err(|i| K::new(i)) 224 } 225 226 /// Analog of `get_raw` except that a raw pointer is returned rather than a 227 /// mutable reference. 228 /// 229 /// The default accessors of items in [`PrimaryMap`] will invalidate all 230 /// previous borrows obtained from the map according to miri. This function 231 /// can be used to acquire a pointer and then subsequently acquire a second 232 /// pointer later on without invalidating the first one. In other words 233 /// this is only here to help borrow two elements simultaneously with miri. get_raw_mut(&mut self, k: K) -> Option<*mut V>234 pub fn get_raw_mut(&mut self, k: K) -> Option<*mut V> { 235 if k.index() < self.elems.len() { 236 // SAFETY: the `add` function requires that the index is in-bounds 237 // with respect to the allocation which is satisfied here due to 238 // the bounds-check above. 239 unsafe { Some(self.elems.as_mut_ptr().add(k.index())) } 240 } else { 241 None 242 } 243 } 244 } 245 246 impl<K, V> Default for PrimaryMap<K, V> 247 where 248 K: EntityRef, 249 { default() -> PrimaryMap<K, V>250 fn default() -> PrimaryMap<K, V> { 251 PrimaryMap::new() 252 } 253 } 254 255 /// Immutable indexing into an `PrimaryMap`. 256 /// The indexed value must be in the map. 257 impl<K, V> Index<K> for PrimaryMap<K, V> 258 where 259 K: EntityRef, 260 { 261 type Output = V; 262 index(&self, k: K) -> &V263 fn index(&self, k: K) -> &V { 264 &self.elems[k.index()] 265 } 266 } 267 268 /// Mutable indexing into an `PrimaryMap`. 269 impl<K, V> IndexMut<K> for PrimaryMap<K, V> 270 where 271 K: EntityRef, 272 { index_mut(&mut self, k: K) -> &mut V273 fn index_mut(&mut self, k: K) -> &mut V { 274 &mut self.elems[k.index()] 275 } 276 } 277 278 impl<K, V> IntoIterator for PrimaryMap<K, V> 279 where 280 K: EntityRef, 281 { 282 type Item = (K, V); 283 type IntoIter = IntoIter<K, V>; 284 into_iter(self) -> Self::IntoIter285 fn into_iter(self) -> Self::IntoIter { 286 IntoIter::new(self.elems.into_iter()) 287 } 288 } 289 290 impl<'a, K, V> IntoIterator for &'a PrimaryMap<K, V> 291 where 292 K: EntityRef, 293 { 294 type Item = (K, &'a V); 295 type IntoIter = Iter<'a, K, V>; 296 into_iter(self) -> Self::IntoIter297 fn into_iter(self) -> Self::IntoIter { 298 Iter::new(self.elems.iter()) 299 } 300 } 301 302 impl<'a, K, V> IntoIterator for &'a mut PrimaryMap<K, V> 303 where 304 K: EntityRef, 305 { 306 type Item = (K, &'a mut V); 307 type IntoIter = IterMut<'a, K, V>; 308 into_iter(self) -> Self::IntoIter309 fn into_iter(self) -> Self::IntoIter { 310 IterMut::new(self.elems.iter_mut()) 311 } 312 } 313 314 impl<K, V> FromIterator<V> for PrimaryMap<K, V> 315 where 316 K: EntityRef, 317 { from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = V>,318 fn from_iter<T>(iter: T) -> Self 319 where 320 T: IntoIterator<Item = V>, 321 { 322 Self { 323 elems: Vec::from_iter(iter), 324 unused: PhantomData, 325 } 326 } 327 } 328 329 impl<K, V> Extend<V> for PrimaryMap<K, V> 330 where 331 K: EntityRef, 332 { extend<T>(&mut self, iter: T) where T: IntoIterator<Item = V>,333 fn extend<T>(&mut self, iter: T) 334 where 335 T: IntoIterator<Item = V>, 336 { 337 self.elems.extend(iter); 338 } 339 } 340 341 impl<K, V> From<Vec<V>> for PrimaryMap<K, V> 342 where 343 K: EntityRef, 344 { from(elems: Vec<V>) -> Self345 fn from(elems: Vec<V>) -> Self { 346 Self { 347 elems, 348 unused: PhantomData, 349 } 350 } 351 } 352 353 impl<K, V> From<PrimaryMap<K, V>> for Vec<V> 354 where 355 K: EntityRef, 356 { from(map: PrimaryMap<K, V>) -> Self357 fn from(map: PrimaryMap<K, V>) -> Self { 358 map.elems 359 } 360 } 361 362 impl<K: EntityRef + fmt::Debug, V: fmt::Debug> fmt::Debug for PrimaryMap<K, V> { fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result363 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 364 let mut struct_ = f.debug_struct("PrimaryMap"); 365 for (k, v) in self { 366 struct_.field(&alloc::format!("{k:?}"), v); 367 } 368 struct_.finish() 369 } 370 } 371 372 #[cfg(test)] 373 mod tests { 374 use super::*; 375 376 // `EntityRef` impl for testing. 377 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 378 struct E(u32); 379 380 impl EntityRef for E { new(i: usize) -> Self381 fn new(i: usize) -> Self { 382 E(i as u32) 383 } index(self) -> usize384 fn index(self) -> usize { 385 self.0 as usize 386 } 387 } 388 389 #[test] basic()390 fn basic() { 391 let r0 = E(0); 392 let r1 = E(1); 393 let m = PrimaryMap::<E, isize>::new(); 394 395 let v: Vec<E> = m.keys().collect(); 396 assert_eq!(v, []); 397 398 assert!(!m.is_valid(r0)); 399 assert!(!m.is_valid(r1)); 400 } 401 402 #[test] push()403 fn push() { 404 let mut m = PrimaryMap::new(); 405 let k0: E = m.push(12); 406 let k1 = m.push(33); 407 408 assert_eq!(m[k0], 12); 409 assert_eq!(m[k1], 33); 410 411 let v: Vec<E> = m.keys().collect(); 412 assert_eq!(v, [k0, k1]); 413 } 414 415 #[test] iter()416 fn iter() { 417 let mut m: PrimaryMap<E, usize> = PrimaryMap::new(); 418 m.push(12); 419 m.push(33); 420 421 let mut i = 0; 422 for (key, value) in &m { 423 assert_eq!(key.index(), i); 424 match i { 425 0 => assert_eq!(*value, 12), 426 1 => assert_eq!(*value, 33), 427 _ => panic!(), 428 } 429 i += 1; 430 } 431 i = 0; 432 for (key_mut, value_mut) in m.iter_mut() { 433 assert_eq!(key_mut.index(), i); 434 match i { 435 0 => assert_eq!(*value_mut, 12), 436 1 => assert_eq!(*value_mut, 33), 437 _ => panic!(), 438 } 439 i += 1; 440 } 441 } 442 443 #[test] iter_rev()444 fn iter_rev() { 445 let mut m: PrimaryMap<E, usize> = PrimaryMap::new(); 446 m.push(12); 447 m.push(33); 448 449 let mut i = 2; 450 for (key, value) in m.iter().rev() { 451 i -= 1; 452 assert_eq!(key.index(), i); 453 match i { 454 0 => assert_eq!(*value, 12), 455 1 => assert_eq!(*value, 33), 456 _ => panic!(), 457 } 458 } 459 460 i = 2; 461 for (key, value) in m.iter_mut().rev() { 462 i -= 1; 463 assert_eq!(key.index(), i); 464 match i { 465 0 => assert_eq!(*value, 12), 466 1 => assert_eq!(*value, 33), 467 _ => panic!(), 468 } 469 } 470 } 471 #[test] keys()472 fn keys() { 473 let mut m: PrimaryMap<E, usize> = PrimaryMap::new(); 474 m.push(12); 475 m.push(33); 476 477 let mut i = 0; 478 for key in m.keys() { 479 assert_eq!(key.index(), i); 480 i += 1; 481 } 482 } 483 484 #[test] keys_rev()485 fn keys_rev() { 486 let mut m: PrimaryMap<E, usize> = PrimaryMap::new(); 487 m.push(12); 488 m.push(33); 489 490 let mut i = 2; 491 for key in m.keys().rev() { 492 i -= 1; 493 assert_eq!(key.index(), i); 494 } 495 } 496 497 #[test] values()498 fn values() { 499 let mut m: PrimaryMap<E, usize> = PrimaryMap::new(); 500 m.push(12); 501 m.push(33); 502 503 let mut i = 0; 504 for value in m.values() { 505 match i { 506 0 => assert_eq!(*value, 12), 507 1 => assert_eq!(*value, 33), 508 _ => panic!(), 509 } 510 i += 1; 511 } 512 i = 0; 513 for value_mut in m.values_mut() { 514 match i { 515 0 => assert_eq!(*value_mut, 12), 516 1 => assert_eq!(*value_mut, 33), 517 _ => panic!(), 518 } 519 i += 1; 520 } 521 } 522 523 #[test] values_rev()524 fn values_rev() { 525 let mut m: PrimaryMap<E, usize> = PrimaryMap::new(); 526 m.push(12); 527 m.push(33); 528 529 let mut i = 2; 530 for value in m.values().rev() { 531 i -= 1; 532 match i { 533 0 => assert_eq!(*value, 12), 534 1 => assert_eq!(*value, 33), 535 _ => panic!(), 536 } 537 } 538 i = 2; 539 for value_mut in m.values_mut().rev() { 540 i -= 1; 541 match i { 542 0 => assert_eq!(*value_mut, 12), 543 1 => assert_eq!(*value_mut, 33), 544 _ => panic!(), 545 } 546 } 547 } 548 549 #[test] from_iter()550 fn from_iter() { 551 let mut m: PrimaryMap<E, usize> = PrimaryMap::new(); 552 m.push(12); 553 m.push(33); 554 555 let n = m.values().collect::<PrimaryMap<E, _>>(); 556 assert!(m.len() == n.len()); 557 for (me, ne) in m.values().zip(n.values()) { 558 assert!(*me == **ne); 559 } 560 } 561 562 #[test] from_vec()563 fn from_vec() { 564 let mut m: PrimaryMap<E, usize> = PrimaryMap::new(); 565 m.push(12); 566 m.push(33); 567 568 let n = PrimaryMap::<E, &usize>::from(m.values().collect::<Vec<_>>()); 569 assert!(m.len() == n.len()); 570 for (me, ne) in m.values().zip(n.values()) { 571 assert!(*me == **ne); 572 } 573 } 574 575 #[test] get_many_mut()576 fn get_many_mut() { 577 let mut m: PrimaryMap<E, usize> = PrimaryMap::new(); 578 let _0 = m.push(0); 579 let _1 = m.push(1); 580 let _2 = m.push(2); 581 582 assert_eq!([&mut 0, &mut 2], m.get_disjoint_mut([_0, _2]).unwrap()); 583 assert_eq!( 584 m.get_disjoint_mut([_0, _0]), 585 Err(slice::GetDisjointMutError::OverlappingIndices) 586 ); 587 assert_eq!( 588 m.get_disjoint_mut([E(4)]), 589 Err(slice::GetDisjointMutError::IndexOutOfBounds) 590 ); 591 } 592 } 593