Path: blob/main/cranelift/entity/src/primary.rs
1692 views
//! Densely numbered entity references as mapping keys.1use crate::EntityRef;2use crate::boxed_slice::BoxedSlice;3use crate::iter::{IntoIter, Iter, IterMut};4use crate::keys::Keys;5use alloc::boxed::Box;6use alloc::vec::Vec;7use core::fmt;8use core::marker::PhantomData;9use core::ops::{Index, IndexMut};10use core::slice;11#[cfg(feature = "enable-serde")]12use serde_derive::{Deserialize, Serialize};1314/// A primary mapping `K -> V` allocating dense entity references.15///16/// The `PrimaryMap` data structure uses the dense index space to implement a map with a vector.17///18/// A primary map contains the main definition of an entity, and it can be used to allocate new19/// entity references with the `push` method.20///21/// There should only be a single `PrimaryMap` instance for a given `EntityRef` type, otherwise22/// conflicting references will be created. Using unknown keys for indexing will cause a panic.23///24/// Note that `PrimaryMap` doesn't implement `Deref` or `DerefMut`, which would allow25/// `&PrimaryMap<K, V>` to convert to `&[V]`. One of the main advantages of `PrimaryMap` is26/// that it only allows indexing with the distinct `EntityRef` key type, so converting to a27/// plain slice would make it easier to use incorrectly. To make a slice of a `PrimaryMap`, use28/// `into_boxed_slice`.29#[derive(Clone, Hash, PartialEq, Eq)]30#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]31pub struct PrimaryMap<K, V>32where33K: EntityRef,34{35elems: Vec<V>,36unused: PhantomData<K>,37}3839impl<K, V> PrimaryMap<K, V>40where41K: EntityRef,42{43/// Create a new empty map.44pub fn new() -> Self {45Self {46elems: Vec::new(),47unused: PhantomData,48}49}5051/// Create a new empty map with the given capacity.52pub fn with_capacity(capacity: usize) -> Self {53Self {54elems: Vec::with_capacity(capacity),55unused: PhantomData,56}57}5859/// Check if `k` is a valid key in the map.60pub fn is_valid(&self, k: K) -> bool {61k.index() < self.elems.len()62}6364/// Get the element at `k` if it exists.65pub fn get(&self, k: K) -> Option<&V> {66self.elems.get(k.index())67}6869/// Get the element at `k` if it exists, mutable version.70pub fn get_mut(&mut self, k: K) -> Option<&mut V> {71self.elems.get_mut(k.index())72}7374/// Is this map completely empty?75pub fn is_empty(&self) -> bool {76self.elems.is_empty()77}7879/// Get the total number of entity references created.80pub fn len(&self) -> usize {81self.elems.len()82}8384/// Iterate over all the keys in this map.85pub fn keys(&self) -> Keys<K> {86Keys::with_len(self.elems.len())87}8889/// Iterate over all the values in this map.90pub fn values(&self) -> slice::Iter<'_, V> {91self.elems.iter()92}9394/// Iterate over all the values in this map, mutable edition.95pub fn values_mut(&mut self) -> slice::IterMut<'_, V> {96self.elems.iter_mut()97}9899/// Iterate over all the keys and values in this map.100pub fn iter(&self) -> Iter<'_, K, V> {101Iter::new(self.elems.iter())102}103104/// Iterate over all the keys and values in this map, mutable edition.105pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {106IterMut::new(self.elems.iter_mut())107}108109/// Remove all entries from this map.110pub fn clear(&mut self) {111self.elems.clear()112}113114/// Get the key that will be assigned to the next pushed value.115pub fn next_key(&self) -> K {116K::new(self.elems.len())117}118119/// Append `v` to the mapping, assigning a new key which is returned.120pub fn push(&mut self, v: V) -> K {121let k = self.next_key();122self.elems.push(v);123k124}125126/// Returns the last element that was inserted in the map.127pub fn last(&self) -> Option<(K, &V)> {128let len = self.elems.len();129let last = self.elems.last()?;130Some((K::new(len - 1), last))131}132133/// Returns the last element that was inserted in the map.134pub fn last_mut(&mut self) -> Option<(K, &mut V)> {135let len = self.elems.len();136let last = self.elems.last_mut()?;137Some((K::new(len - 1), last))138}139140/// Reserves capacity for at least `additional` more elements to be inserted.141pub fn reserve(&mut self, additional: usize) {142self.elems.reserve(additional)143}144145/// Reserves the minimum capacity for exactly `additional` more elements to be inserted.146pub fn reserve_exact(&mut self, additional: usize) {147self.elems.reserve_exact(additional)148}149150/// Shrinks the capacity of the `PrimaryMap` as much as possible.151pub fn shrink_to_fit(&mut self) {152self.elems.shrink_to_fit()153}154155/// Consumes this `PrimaryMap` and produces a `BoxedSlice`.156pub fn into_boxed_slice(self) -> BoxedSlice<K, V> {157unsafe { BoxedSlice::<K, V>::from_raw(Box::<[V]>::into_raw(self.elems.into_boxed_slice())) }158}159160/// Returns mutable references to many elements at once.161///162/// Returns an error if an element does not exist, or if the same key was passed more than163/// once.164pub fn get_disjoint_mut<const N: usize>(165&mut self,166indices: [K; N],167) -> Result<[&mut V; N], slice::GetDisjointMutError> {168self.elems.get_disjoint_mut(indices.map(|k| k.index()))169}170171/// Performs a binary search on the values with a key extraction function.172///173/// Assumes that the values are sorted by the key extracted by the function.174///175/// If the value is found then `Ok(K)` is returned, containing the entity key176/// of the matching value.177///178/// If there are multiple matches, then any one of the matches could be returned.179///180/// If the value is not found then Err(K) is returned, containing the entity key181/// where a matching element could be inserted while maintaining sorted order.182pub fn binary_search_values_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<K, K>183where184F: FnMut(&'a V) -> B,185B: Ord,186{187self.elems188.binary_search_by_key(b, f)189.map(|i| K::new(i))190.map_err(|i| K::new(i))191}192193/// Analog of `get_raw` except that a raw pointer is returned rather than a194/// mutable reference.195///196/// The default accessors of items in [`PrimaryMap`] will invalidate all197/// previous borrows obtained from the map according to miri. This function198/// can be used to acquire a pointer and then subsequently acquire a second199/// pointer later on without invalidating the first one. In other words200/// this is only here to help borrow two elements simultaneously with miri.201pub fn get_raw_mut(&mut self, k: K) -> Option<*mut V> {202if k.index() < self.elems.len() {203// SAFETY: the `add` function requires that the index is in-bounds204// with respect to the allocation which is satisfied here due to205// the bounds-check above.206unsafe { Some(self.elems.as_mut_ptr().add(k.index())) }207} else {208None209}210}211}212213impl<K, V> Default for PrimaryMap<K, V>214where215K: EntityRef,216{217fn default() -> PrimaryMap<K, V> {218PrimaryMap::new()219}220}221222/// Immutable indexing into an `PrimaryMap`.223/// The indexed value must be in the map.224impl<K, V> Index<K> for PrimaryMap<K, V>225where226K: EntityRef,227{228type Output = V;229230fn index(&self, k: K) -> &V {231&self.elems[k.index()]232}233}234235/// Mutable indexing into an `PrimaryMap`.236impl<K, V> IndexMut<K> for PrimaryMap<K, V>237where238K: EntityRef,239{240fn index_mut(&mut self, k: K) -> &mut V {241&mut self.elems[k.index()]242}243}244245impl<K, V> IntoIterator for PrimaryMap<K, V>246where247K: EntityRef,248{249type Item = (K, V);250type IntoIter = IntoIter<K, V>;251252fn into_iter(self) -> Self::IntoIter {253IntoIter::new(self.elems.into_iter())254}255}256257impl<'a, K, V> IntoIterator for &'a PrimaryMap<K, V>258where259K: EntityRef,260{261type Item = (K, &'a V);262type IntoIter = Iter<'a, K, V>;263264fn into_iter(self) -> Self::IntoIter {265Iter::new(self.elems.iter())266}267}268269impl<'a, K, V> IntoIterator for &'a mut PrimaryMap<K, V>270where271K: EntityRef,272{273type Item = (K, &'a mut V);274type IntoIter = IterMut<'a, K, V>;275276fn into_iter(self) -> Self::IntoIter {277IterMut::new(self.elems.iter_mut())278}279}280281impl<K, V> FromIterator<V> for PrimaryMap<K, V>282where283K: EntityRef,284{285fn from_iter<T>(iter: T) -> Self286where287T: IntoIterator<Item = V>,288{289Self {290elems: Vec::from_iter(iter),291unused: PhantomData,292}293}294}295296impl<K, V> From<Vec<V>> for PrimaryMap<K, V>297where298K: EntityRef,299{300fn from(elems: Vec<V>) -> Self {301Self {302elems,303unused: PhantomData,304}305}306}307308impl<K, V> From<PrimaryMap<K, V>> for Vec<V>309where310K: EntityRef,311{312fn from(map: PrimaryMap<K, V>) -> Self {313map.elems314}315}316317impl<K: EntityRef + fmt::Debug, V: fmt::Debug> fmt::Debug for PrimaryMap<K, V> {318fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {319let mut struct_ = f.debug_struct("PrimaryMap");320for (k, v) in self {321struct_.field(&alloc::format!("{k:?}"), v);322}323struct_.finish()324}325}326327#[cfg(test)]328mod tests {329use super::*;330331// `EntityRef` impl for testing.332#[derive(Clone, Copy, Debug, PartialEq, Eq)]333struct E(u32);334335impl EntityRef for E {336fn new(i: usize) -> Self {337E(i as u32)338}339fn index(self) -> usize {340self.0 as usize341}342}343344#[test]345fn basic() {346let r0 = E(0);347let r1 = E(1);348let m = PrimaryMap::<E, isize>::new();349350let v: Vec<E> = m.keys().collect();351assert_eq!(v, []);352353assert!(!m.is_valid(r0));354assert!(!m.is_valid(r1));355}356357#[test]358fn push() {359let mut m = PrimaryMap::new();360let k0: E = m.push(12);361let k1 = m.push(33);362363assert_eq!(m[k0], 12);364assert_eq!(m[k1], 33);365366let v: Vec<E> = m.keys().collect();367assert_eq!(v, [k0, k1]);368}369370#[test]371fn iter() {372let mut m: PrimaryMap<E, usize> = PrimaryMap::new();373m.push(12);374m.push(33);375376let mut i = 0;377for (key, value) in &m {378assert_eq!(key.index(), i);379match i {3800 => assert_eq!(*value, 12),3811 => assert_eq!(*value, 33),382_ => panic!(),383}384i += 1;385}386i = 0;387for (key_mut, value_mut) in m.iter_mut() {388assert_eq!(key_mut.index(), i);389match i {3900 => assert_eq!(*value_mut, 12),3911 => assert_eq!(*value_mut, 33),392_ => panic!(),393}394i += 1;395}396}397398#[test]399fn iter_rev() {400let mut m: PrimaryMap<E, usize> = PrimaryMap::new();401m.push(12);402m.push(33);403404let mut i = 2;405for (key, value) in m.iter().rev() {406i -= 1;407assert_eq!(key.index(), i);408match i {4090 => assert_eq!(*value, 12),4101 => assert_eq!(*value, 33),411_ => panic!(),412}413}414415i = 2;416for (key, value) in m.iter_mut().rev() {417i -= 1;418assert_eq!(key.index(), i);419match i {4200 => assert_eq!(*value, 12),4211 => assert_eq!(*value, 33),422_ => panic!(),423}424}425}426#[test]427fn keys() {428let mut m: PrimaryMap<E, usize> = PrimaryMap::new();429m.push(12);430m.push(33);431432let mut i = 0;433for key in m.keys() {434assert_eq!(key.index(), i);435i += 1;436}437}438439#[test]440fn keys_rev() {441let mut m: PrimaryMap<E, usize> = PrimaryMap::new();442m.push(12);443m.push(33);444445let mut i = 2;446for key in m.keys().rev() {447i -= 1;448assert_eq!(key.index(), i);449}450}451452#[test]453fn values() {454let mut m: PrimaryMap<E, usize> = PrimaryMap::new();455m.push(12);456m.push(33);457458let mut i = 0;459for value in m.values() {460match i {4610 => assert_eq!(*value, 12),4621 => assert_eq!(*value, 33),463_ => panic!(),464}465i += 1;466}467i = 0;468for value_mut in m.values_mut() {469match i {4700 => assert_eq!(*value_mut, 12),4711 => assert_eq!(*value_mut, 33),472_ => panic!(),473}474i += 1;475}476}477478#[test]479fn values_rev() {480let mut m: PrimaryMap<E, usize> = PrimaryMap::new();481m.push(12);482m.push(33);483484let mut i = 2;485for value in m.values().rev() {486i -= 1;487match i {4880 => assert_eq!(*value, 12),4891 => assert_eq!(*value, 33),490_ => panic!(),491}492}493i = 2;494for value_mut in m.values_mut().rev() {495i -= 1;496match i {4970 => assert_eq!(*value_mut, 12),4981 => assert_eq!(*value_mut, 33),499_ => panic!(),500}501}502}503504#[test]505fn from_iter() {506let mut m: PrimaryMap<E, usize> = PrimaryMap::new();507m.push(12);508m.push(33);509510let n = m.values().collect::<PrimaryMap<E, _>>();511assert!(m.len() == n.len());512for (me, ne) in m.values().zip(n.values()) {513assert!(*me == **ne);514}515}516517#[test]518fn from_vec() {519let mut m: PrimaryMap<E, usize> = PrimaryMap::new();520m.push(12);521m.push(33);522523let n = PrimaryMap::<E, &usize>::from(m.values().collect::<Vec<_>>());524assert!(m.len() == n.len());525for (me, ne) in m.values().zip(n.values()) {526assert!(*me == **ne);527}528}529530#[test]531fn get_many_mut() {532let mut m: PrimaryMap<E, usize> = PrimaryMap::new();533let _0 = m.push(0);534let _1 = m.push(1);535let _2 = m.push(2);536537assert_eq!([&mut 0, &mut 2], m.get_disjoint_mut([_0, _2]).unwrap());538assert_eq!(539m.get_disjoint_mut([_0, _0]),540Err(slice::GetDisjointMutError::OverlappingIndices)541);542assert_eq!(543m.get_disjoint_mut([E(4)]),544Err(slice::GetDisjointMutError::IndexOutOfBounds)545);546}547}548549550