Skip to main content

cranelift_isle/
stablemapset.rs

1//! Implementations of hashmap and hashset that asvoid observing non-determinism
2//! in iteration order. In a separate module so the compiler can prevent access to the internal
3//! implementation details.
4
5use std::collections::hash_map::Entry;
6use std::collections::{HashMap, HashSet};
7use std::hash::Hash;
8use std::ops::Index;
9
10/// A wrapper around a [HashSet] which prevents accidentally observing the non-deterministic
11/// iteration order.
12#[derive(Clone, Debug, Default)]
13pub struct StableSet<T>(HashSet<T>);
14
15impl<T> StableSet<T> {
16    pub(crate) fn new() -> Self {
17        StableSet(HashSet::new())
18    }
19}
20
21impl<T: Hash + Eq> StableSet<T> {
22    /// Adds a value to the set. Returns whether the value was newly inserted.
23    pub fn insert(&mut self, val: T) -> bool {
24        self.0.insert(val)
25    }
26
27    /// Returns true if the set contains a value.
28    pub fn contains(&self, val: &T) -> bool {
29        self.0.contains(val)
30    }
31
32    /// Returns the number of elements in the set.
33    pub fn len(&self) -> usize {
34        self.0.len()
35    }
36}
37
38/// A wrapper around a [HashMap] which prevents accidentally observing the non-deterministic
39/// iteration order.
40#[derive(Clone, Debug)]
41pub struct StableMap<K, V>(HashMap<K, V>);
42
43impl<K, V> StableMap<K, V> {
44    pub(crate) fn new() -> Self {
45        StableMap(HashMap::new())
46    }
47
48    pub(crate) fn len(&self) -> usize {
49        self.0.len()
50    }
51}
52
53// NOTE: Can't auto-derive this
54impl<K, V> Default for StableMap<K, V> {
55    fn default() -> Self {
56        StableMap(HashMap::new())
57    }
58}
59
60impl<K: Hash + Eq, V> StableMap<K, V> {
61    pub(crate) fn insert(&mut self, k: K, v: V) -> Option<V> {
62        self.0.insert(k, v)
63    }
64
65    pub(crate) fn contains_key(&self, k: &K) -> bool {
66        self.0.contains_key(k)
67    }
68
69    pub(crate) fn get(&self, k: &K) -> Option<&V> {
70        self.0.get(k)
71    }
72
73    pub(crate) fn entry(&mut self, k: K) -> Entry<'_, K, V> {
74        self.0.entry(k)
75    }
76}
77
78impl<K: Hash + Eq, V> Index<&K> for StableMap<K, V> {
79    type Output = V;
80
81    fn index(&self, index: &K) -> &Self::Output {
82        self.0.index(index)
83    }
84}
85
86impl<K, V> From<HashMap<K, V>> for StableMap<K, V> {
87    fn from(map: HashMap<K, V>) -> Self {
88        StableMap(map)
89    }
90}
91
92impl<K: Hash + Eq, V> FromIterator<(K, V)> for StableMap<K, V> {
93    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
94        StableMap(HashMap::from_iter(iter))
95    }
96}