Skip to main content

arcis_compiler/utils/
hash_map_vec.rs

1use std::hash::Hash;
2
3type FxIndexSet<T> =
4    indexmap::set::IndexSet<T, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>;
5
6/// A container meant to be a collection of T with ids from 0 to n-1.
7///
8/// # Notes
9///
10/// This structure handles:
11/// * Insertion of a new T, returning its id. Either
12/// * it was there already, and we modify nothing and return the id.
13/// * it wasn't there, so we push it, and we return new id.
14/// * Finding an item by its id.
15/// * Returning a Vec of T, ordered by id.
16#[derive(Debug, Clone)]
17pub struct HashMapVec<T: Clone + Eq + Hash> {
18    index_set: FxIndexSet<T>,
19}
20
21impl<T: Clone + Eq + Hash> Default for HashMapVec<T> {
22    fn default() -> Self {
23        Self::new()
24    }
25}
26
27impl<T: Clone + Eq + Hash> HashMapVec<T> {
28    /// Constructor.
29    pub fn new() -> HashMapVec<T> {
30        HashMapVec {
31            index_set: FxIndexSet::default(),
32        }
33    }
34
35    /// Insertion of a new T, returning its id.
36    ///
37    /// # Note
38    ///
39    /// Either:
40    /// * it was there already, and we modify nothing and return the id.
41    /// * it wasn't there, so we push it, and we return new id.
42    pub fn push(&mut self, t: T) -> usize {
43        let (n, _) = self.index_set.insert_full(t);
44        n
45    }
46
47    pub fn len(&self) -> usize {
48        self.index_set.len()
49    }
50
51    pub fn is_empty(&self) -> bool {
52        self.index_set.len() == 0
53    }
54
55    /// Finding an item by its id.
56    pub fn get_val(&self, id: usize) -> &T {
57        &self.index_set[id]
58    }
59
60    /// Returning a [`Vec`] of T, ordered by id.
61    pub fn move_vec(self) -> Vec<T> {
62        self.index_set.into_iter().collect()
63    }
64
65    /// Returns whether contains id.
66    pub fn contains_id(&self, id: usize) -> bool {
67        id < self.len()
68    }
69}