iddqd/bi_hash_map/ref_mut.rs
1use crate::{BiHashItem, DefaultHashBuilder, support::map_hash::MapHash};
2use core::{
3 fmt,
4 hash::BuildHasher,
5 ops::{Deref, DerefMut},
6};
7
8/// A mutable reference to a [`BiHashMap`] 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 [`BiHashMap`] will continue to work correctly. (But don't do this!)
24///
25/// It is also possible to deliberately write pathological `Hash`
26/// implementations that collide more often. (Don't do this either.)
27///
28/// Also, `RefMut`'s hash detection will not function if [`mem::forget`] is
29/// called on it. If a key is changed and `mem::forget` is then called on the
30/// `RefMut`, lookups by the affected key will return the wrong result (or no
31/// result at all). The map itself remains structurally valid: subsequent
32/// [`retain`](crate::BiHashMap::retain) and
33/// [`remove*`](crate::BiHashMap::remove1) operations still clean up the stale
34/// entry via a linear-scan fallback. This will not introduce memory safety
35/// issues.
36///
37/// The issues here are similar to using interior mutability (e.g. `RefCell` or
38/// `Mutex`) to mutate keys in a regular `HashMap`.
39///
40/// [`mem::forget`]: std::mem::forget
41///
42/// [^collision-chance]: The output of `Hash` is a [`u64`], so the probability
43/// of an individual hash colliding by chance is 1/2⁶⁴. Due to the [birthday
44/// problem], the probability of a collision by chance reaches 10⁻⁶ within
45/// around 6 × 10⁶ elements.
46///
47/// [`BiHashMap`]: crate::BiHashMap
48/// [birthday problem]: https://en.wikipedia.org/wiki/Birthday_problem#Probability_table
49pub struct RefMut<
50 'a,
51 T: BiHashItem,
52 S: Clone + BuildHasher = DefaultHashBuilder,
53> {
54 inner: Option<RefMutInner<'a, T, S>>,
55}
56
57impl<'a, T: BiHashItem, S: Clone + BuildHasher> RefMut<'a, T, S> {
58 pub(super) fn new(
59 state: S,
60 hashes: [MapHash; 2],
61 borrowed: &'a mut T,
62 ) -> Self {
63 Self { inner: Some(RefMutInner { state, hashes, borrowed }) }
64 }
65
66 /// Borrows self into a shorter-lived `RefMut`.
67 ///
68 /// This `RefMut` will also check hash equality on drop.
69 pub fn reborrow(&mut self) -> RefMut<'_, T, S> {
70 let inner = self.inner.as_mut().unwrap();
71 let borrowed = &mut *inner.borrowed;
72 RefMut::new(inner.state.clone(), inner.hashes.clone(), borrowed)
73 }
74
75 /// Converts this `RefMut` into a `&'a T`.
76 pub fn into_ref(mut self) -> &'a T {
77 let inner = self.inner.take().unwrap();
78 inner.into_ref()
79 }
80}
81
82impl<T: BiHashItem, S: Clone + BuildHasher> Drop for RefMut<'_, T, S> {
83 fn drop(&mut self) {
84 if let Some(inner) = self.inner.take() {
85 inner.into_ref();
86 }
87 }
88}
89
90impl<T: BiHashItem, S: Clone + BuildHasher> Deref for RefMut<'_, T, S> {
91 type Target = T;
92
93 fn deref(&self) -> &Self::Target {
94 self.inner.as_ref().unwrap().borrowed
95 }
96}
97
98impl<T: BiHashItem, S: Clone + BuildHasher> DerefMut for RefMut<'_, T, S> {
99 fn deref_mut(&mut self) -> &mut Self::Target {
100 self.inner.as_mut().unwrap().borrowed
101 }
102}
103
104impl<T: BiHashItem + fmt::Debug, S: Clone + BuildHasher> fmt::Debug
105 for RefMut<'_, T, S>
106{
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 match self.inner {
109 Some(ref inner) => inner.fmt(f),
110 None => {
111 f.debug_struct("RefMut").field("borrowed", &"missing").finish()
112 }
113 }
114 }
115}
116
117struct RefMutInner<'a, T: BiHashItem, S> {
118 state: S,
119 hashes: [MapHash; 2],
120 borrowed: &'a mut T,
121}
122
123impl<'a, T: BiHashItem, S: BuildHasher> RefMutInner<'a, T, S> {
124 fn into_ref(self) -> &'a T {
125 if !self.hashes[0].is_same_hash(&self.state, self.borrowed.key1()) {
126 panic!("key1 changed during RefMut borrow");
127 }
128 if !self.hashes[1].is_same_hash(&self.state, self.borrowed.key2()) {
129 panic!("key2 changed during RefMut borrow");
130 }
131
132 self.borrowed
133 }
134}
135
136impl<T: BiHashItem + 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}