]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/stable_map.rs
Rollup merge of #69554 - GuillaumeGomez:cleanup-e0374, r=Dylan-DPC
[rust.git] / src / librustc_data_structures / stable_map.rs
1 pub use rustc_hash::FxHashMap;
2 use std::borrow::Borrow;
3 use std::collections::hash_map::Entry;
4 use std::fmt;
5 use std::hash::Hash;
6
7 /// A deterministic wrapper around FxHashMap that does not provide iteration support.
8 ///
9 /// It supports insert, remove, get and get_mut functions from FxHashMap.
10 /// It also allows to convert hashmap to a sorted vector with the method `into_sorted_vector()`.
11 #[derive(Clone)]
12 pub struct StableMap<K, V> {
13     base: FxHashMap<K, V>,
14 }
15
16 impl<K, V> Default for StableMap<K, V>
17 where
18     K: Eq + Hash,
19 {
20     fn default() -> StableMap<K, V> {
21         StableMap::new()
22     }
23 }
24
25 impl<K, V> fmt::Debug for StableMap<K, V>
26 where
27     K: Eq + Hash + fmt::Debug,
28     V: fmt::Debug,
29 {
30     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31         write!(f, "{:?}", self.base)
32     }
33 }
34
35 impl<K, V> PartialEq for StableMap<K, V>
36 where
37     K: Eq + Hash,
38     V: PartialEq,
39 {
40     fn eq(&self, other: &StableMap<K, V>) -> bool {
41         self.base == other.base
42     }
43 }
44
45 impl<K, V> Eq for StableMap<K, V>
46 where
47     K: Eq + Hash,
48     V: Eq,
49 {
50 }
51
52 impl<K, V> StableMap<K, V>
53 where
54     K: Eq + Hash,
55 {
56     pub fn new() -> StableMap<K, V> {
57         StableMap { base: FxHashMap::default() }
58     }
59
60     pub fn into_sorted_vector(self) -> Vec<(K, V)>
61     where
62         K: Ord + Copy,
63     {
64         let mut vector = self.base.into_iter().collect::<Vec<_>>();
65         vector.sort_unstable_by_key(|pair| pair.0);
66         vector
67     }
68
69     pub fn entry(&mut self, k: K) -> Entry<'_, K, V> {
70         self.base.entry(k)
71     }
72
73     pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V>
74     where
75         K: Borrow<Q>,
76         Q: Hash + Eq,
77     {
78         self.base.get(k)
79     }
80
81     pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V>
82     where
83         K: Borrow<Q>,
84         Q: Hash + Eq,
85     {
86         self.base.get_mut(k)
87     }
88
89     pub fn insert(&mut self, k: K, v: V) -> Option<V> {
90         self.base.insert(k, v)
91     }
92
93     pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V>
94     where
95         K: Borrow<Q>,
96         Q: Hash + Eq,
97     {
98         self.base.remove(k)
99     }
100 }