forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

value_register.rs52 lines, 1.2 KiBHistoryRawDownload
1use rustc_hash::FxHashMap;
2
3#[derive(Debug)]
4pub struct ValueRegister<T> {
5 map_value_to_index: FxHashMap<T, usize>,
6 vec: Vec<T>,
7}
8
9impl<T: std::hash::Hash + Clone + PartialEq + Eq> Default for ValueRegister<T> {
10 fn default() -> Self {
11 Self::new()
12 }
13}
14
15impl<T: std::hash::Hash + Clone + PartialEq + Eq> ValueRegister<T> {
16 pub fn new() -> Self {
17 Self {
18 map_value_to_index: FxHashMap::default(),
19 vec: Vec::new(),
20 }
21 }
22
23 /// Return the index of the given value. If it does not exist,
24 /// insert it and return the new index.
25 pub fn register(&mut self, key: &T) -> usize {
26 if let Some(index) = self.map_value_to_index.get(key) {
27 *index
28 } else {
29 let idx = self.vec.len();
30 self.vec.push(key.clone());
31 self.map_value_to_index.insert(key.clone(), idx);
32 idx
33 }
34 }
35
36 pub fn get(&self, key: &T) -> Option<usize> {
37 self.map_value_to_index.get(key).copied()
38 }
39
40 pub fn unwrap_vec(self) -> Vec<T> {
41 self.vec
42 }
43
44 #[allow(unused)]
45 pub fn get_value(&self, index: usize) -> Option<&T> {
46 self.vec.get(index)
47 }
48
49 pub fn vec(&self) -> &Vec<T> {
50 &self.vec
51 }
52}