iddqd/tri_hash_map/
ref_mut.rs

1use crate::{DefaultHashBuilder, TriHashItem, support::map_hash::MapHash};
2use core::{
3    fmt,
4    hash::BuildHasher,
5    ops::{Deref, DerefMut},
6};
7
8/// A mutable reference to a [`TriHashMap`] item.
9///
10/// This is a wrapper around a `&mut T` that panics when dropped, if the
11/// borrowed value's keys have changed since the wrapper was created.
12///
13/// # Change detection
14///
15/// It is illegal to change the keys of a borrowed `&mut T`. `RefMut` attempts
16/// to enforce this invariant.
17///
18/// `RefMut` stores the `Hash` output of keys at creation time, and recomputes
19/// these hashes when it is dropped or when [`Self::into_ref`] is called. If a
20/// key changes, there's a small but non-negligible chance that its hash value
21/// stays the same[^collision-chance]. In that case, as long as the new key is
22/// not the same as another existing one, internal invariants are not violated
23/// and the [`TriHashMap`] will continue to work correctly. (But don't rely on
24/// this!)
25///
26/// It is also possible to deliberately write pathological `Hash`
27/// implementations that collide more often. (Don't do this either.)
28///
29/// Also, `RefMut`'s hash detection will not function if [`mem::forget`] is
30/// called on it. If a key is changed and `mem::forget` is then called on the
31/// `RefMut`, the `TriHashMap` will stop functioning correctly. This will not
32/// introduce memory safety issues, however.
33///
34/// The issues here are similar to using interior mutability (e.g. `RefCell` or
35/// `Mutex`) to mutate keys in a regular `HashMap`.
36///
37/// [`mem::forget`]: std::mem::forget
38///
39/// [^collision-chance]: The output of `Hash` is a [`u64`], so the probability
40/// of an individual hash colliding by chance is 1/2⁶⁴. Due to the [birthday
41/// problem], the probability of a collision by chance reaches 10⁻⁶ within
42/// around 6 × 10⁶ elements.
43///
44/// [`TriHashMap`]: crate::TriHashMap
45/// [birthday problem]: https://en.wikipedia.org/wiki/Birthday_problem#Probability_table
46pub struct RefMut<
47    'a,
48    T: TriHashItem,
49    S: Clone + BuildHasher = DefaultHashBuilder,
50> {
51    inner: Option<RefMutInner<'a, T, S>>,
52}
53
54impl<'a, T: TriHashItem, S: Clone + BuildHasher> RefMut<'a, T, S> {
55    pub(super) fn new(
56        state: S,
57        hashes: [MapHash; 3],
58        borrowed: &'a mut T,
59    ) -> Self {
60        Self { inner: Some(RefMutInner { state, hashes, borrowed }) }
61    }
62
63    /// Borrows self into a shorter-lived `RefMut`.
64    ///
65    /// This `RefMut` will also check hash equality on drop.
66    pub fn reborrow(&mut self) -> RefMut<'_, T, S> {
67        let inner = self.inner.as_mut().unwrap();
68        let borrowed = &mut *inner.borrowed;
69        RefMut::new(inner.state.clone(), inner.hashes.clone(), borrowed)
70    }
71
72    /// Converts this `RefMut` into a `&'a T`.
73    pub fn into_ref(mut self) -> &'a T {
74        let inner = self.inner.take().unwrap();
75        inner.into_ref()
76    }
77}
78
79impl<T: TriHashItem, S: Clone + BuildHasher> Drop for RefMut<'_, T, S> {
80    fn drop(&mut self) {
81        if let Some(inner) = self.inner.take() {
82            inner.into_ref();
83        }
84    }
85}
86
87impl<T: TriHashItem, S: Clone + BuildHasher> Deref for RefMut<'_, T, S> {
88    type Target = T;
89
90    fn deref(&self) -> &Self::Target {
91        self.inner.as_ref().unwrap().borrowed
92    }
93}
94
95impl<T: TriHashItem, S: Clone + BuildHasher> DerefMut for RefMut<'_, T, S> {
96    fn deref_mut(&mut self) -> &mut Self::Target {
97        self.inner.as_mut().unwrap().borrowed
98    }
99}
100
101impl<T: TriHashItem + fmt::Debug, S: Clone + BuildHasher> fmt::Debug
102    for RefMut<'_, T, S>
103{
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        match self.inner {
106            Some(ref inner) => inner.fmt(f),
107            None => {
108                f.debug_struct("RefMut").field("borrowed", &"missing").finish()
109            }
110        }
111    }
112}
113
114struct RefMutInner<'a, T: TriHashItem, S> {
115    state: S,
116    hashes: [MapHash; 3],
117    borrowed: &'a mut T,
118}
119
120impl<'a, T: TriHashItem, S: BuildHasher> RefMutInner<'a, T, S> {
121    fn into_ref(self) -> &'a T {
122        if !self.hashes[0].is_same_hash(&self.state, self.borrowed.key1()) {
123            panic!("key1 changed during RefMut borrow");
124        }
125        if !self.hashes[1].is_same_hash(&self.state, self.borrowed.key2()) {
126            panic!("key2 changed during RefMut borrow");
127        }
128        if !self.hashes[2].is_same_hash(&self.state, self.borrowed.key3()) {
129            panic!("key3 changed during RefMut borrow");
130        }
131
132        self.borrowed
133    }
134}
135
136impl<T: TriHashItem + fmt::Debug, S> fmt::Debug for RefMutInner<'_, T, S> {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        self.borrowed.fmt(f)
139    }
140}