|
| 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 | +impl<K, V> StableMap<K, V> |
| 52 | +where |
| 53 | + K: Eq + Hash, |
| 54 | +{ |
| 55 | + pub fn new() -> StableMap<K, V> { |
| 56 | + StableMap { base: FxHashMap::default() } |
| 57 | + } |
| 58 | + |
| 59 | + pub fn into_sorted_vector(self) -> Vec<(K, V)> |
| 60 | + where |
| 61 | + K: Ord + Copy, |
| 62 | + { |
| 63 | + let mut vector = self.base.into_iter().collect::<Vec<_>>(); |
| 64 | + vector.sort_unstable_by_key(|pair| pair.0); |
| 65 | + vector |
| 66 | + } |
| 67 | + |
| 68 | + pub fn entry(&mut self, k: K) -> Entry<'_, K, V> { |
| 69 | + self.base.entry(k) |
| 70 | + } |
| 71 | + |
| 72 | + pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> |
| 73 | + where |
| 74 | + K: Borrow<Q>, |
| 75 | + Q: Hash + Eq, |
| 76 | + { |
| 77 | + self.base.get(k) |
| 78 | + } |
| 79 | + |
| 80 | + pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V> |
| 81 | + where |
| 82 | + K: Borrow<Q>, |
| 83 | + Q: Hash + Eq, |
| 84 | + { |
| 85 | + self.base.get_mut(k) |
| 86 | + } |
| 87 | + |
| 88 | + pub fn insert(&mut self, k: K, v: V) -> Option<V> { |
| 89 | + self.base.insert(k, v) |
| 90 | + } |
| 91 | + |
| 92 | + pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V> |
| 93 | + where |
| 94 | + K: Borrow<Q>, |
| 95 | + Q: Hash + Eq, |
| 96 | + { |
| 97 | + self.base.remove(k) |
| 98 | + } |
| 99 | +} |
0 commit comments