iddqd/id_ord_map/
ref_mut.rs

1use super::IdOrdItem;
2use crate::support::map_hash::MapHash;
3use core::{
4    fmt,
5    hash::Hash,
6    ops::{Deref, DerefMut},
7};
8
9/// A mutable reference to an [`IdOrdMap`] entry.
10///
11/// This is a wrapper around a `&mut T` that panics when dropped, if the
12/// borrowed value's key has changed since the wrapper was created.
13///
14/// # Change detection
15///
16/// It is illegal to change the keys of a borrowed `&mut T`. `RefMut` attempts
17/// to enforce this invariant, and as part of that, it requires that the key
18/// type implement [`Hash`].
19///
20/// `RefMut` stores the `Hash` output of keys at creation time, and recomputes
21/// these hashes when it is dropped or when [`Self::into_ref`] is called. If a
22/// key changes, there's a small but non-negligible chance that its hash value
23/// stays the same[^collision-chance]. In that case, the map will no longer
24/// function correctly and might panic on access. This will not introduce memory
25/// safety issues, however.
26///
27/// It is also possible to deliberately write pathological `Hash`
28/// implementations that collide more often. (Don't do this.)
29///
30/// Also, `RefMut`'s hash detection will not function if [`mem::forget`] is
31/// called on it. If a key is changed and `mem::forget` is then called on the
32/// `RefMut`, the [`IdOrdMap`] will no longer function correctly and might panic
33/// on access. This will not introduce memory safety issues, however.
34///
35/// The issues here are similar to using interior mutability (e.g. `RefCell` or
36/// `Mutex`) to mutate keys in a regular `HashMap`.
37///
38/// [`mem::forget`]: std::mem::forget
39///
40/// [^collision-chance]: The output of `Hash` is a [`u64`], so the probability
41/// of an individual hash colliding by chance is 1/2⁶⁴. Due to the [birthday
42/// problem], the probability of a collision by chance reaches 10⁻⁶ within
43/// around 6 × 10⁶ elements.
44///
45/// [`IdOrdMap`]: crate::IdOrdMap
46/// [birthday problem]: https://en.wikipedia.org/wiki/Birthday_problem#Probability_table
47pub struct RefMut<'a, T: IdOrdItem>
48where
49    T::Key<'a>: Hash,
50{
51    inner: Option<RefMutInner<'a, T>>,
52}
53
54impl<'a, T: IdOrdItem> RefMut<'a, T>
55where
56    T::Key<'a>: Hash,
57{
58    pub(super) fn new(
59        hash: MapHash<foldhash::fast::RandomState>,
60        borrowed: &'a mut T,
61    ) -> Self {
62        let inner = RefMutInner { hash, borrowed };
63        Self { inner: Some(inner) }
64    }
65
66    /// Converts this `RefMut` into a `&'a T`.
67    pub fn into_ref(mut self) -> &'a T {
68        let inner = self.inner.take().unwrap();
69        inner.into_ref()
70    }
71}
72
73impl<'a, T: for<'k> IdOrdItemMut<'k>> RefMut<'a, T> {
74    /// Borrows self into a shorter-lived `RefMut`.
75    ///
76    /// This `RefMut` will also check hash equality on drop.
77    pub fn reborrow<'b>(&'b mut self) -> RefMut<'b, T> {
78        let inner = self.inner.as_mut().unwrap();
79        let borrowed = &mut *inner.borrowed;
80        RefMut::new(inner.hash.clone(), borrowed)
81    }
82}
83
84impl<'a, T: IdOrdItem> Drop for RefMut<'a, T>
85where
86    T::Key<'a>: Hash,
87{
88    fn drop(&mut self) {
89        if let Some(inner) = self.inner.take() {
90            inner.into_ref();
91        }
92    }
93}
94
95impl<'a, T: IdOrdItem> Deref for RefMut<'a, T>
96where
97    T::Key<'a>: Hash,
98{
99    type Target = T;
100
101    fn deref(&self) -> &Self::Target {
102        self.inner.as_ref().unwrap().borrowed
103    }
104}
105
106impl<'a, T: IdOrdItem> DerefMut for RefMut<'a, T>
107where
108    T::Key<'a>: Hash,
109{
110    fn deref_mut(&mut self) -> &mut Self::Target {
111        self.inner.as_mut().unwrap().borrowed
112    }
113}
114
115impl<'a, T: IdOrdItem + fmt::Debug> fmt::Debug for RefMut<'a, T>
116where
117    T::Key<'a>: Hash,
118{
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        match self.inner {
121            Some(ref inner) => inner.fmt(f),
122            None => {
123                f.debug_struct("RefMut").field("borrowed", &"missing").finish()
124            }
125        }
126    }
127}
128
129struct RefMutInner<'a, T: IdOrdItem> {
130    hash: MapHash<foldhash::fast::RandomState>,
131    borrowed: &'a mut T,
132}
133
134impl<'a, T: IdOrdItem> RefMutInner<'a, T>
135where
136    T::Key<'a>: Hash,
137{
138    fn into_ref(self) -> &'a T {
139        let key: T::Key<'_> = self.borrowed.key();
140        // SAFETY: The key is borrowed, then dropped immediately. T is valid for
141        // 'a so T::Key is valid for 'a.
142        let key: T::Key<'a> =
143            unsafe { std::mem::transmute::<T::Key<'_>, T::Key<'a>>(key) };
144        if !self.hash.is_same_hash(&key) {
145            panic!("key changed during RefMut borrow");
146        }
147
148        self.borrowed
149    }
150}
151
152impl<T: IdOrdItem + fmt::Debug> fmt::Debug for RefMutInner<'_, T> {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        self.borrowed.fmt(f)
155    }
156}
157
158/// A trait for mutable access to items in an [`IdOrdMap`].
159///
160/// This is a non-public trait used to work around a Rust borrow checker
161/// limitation. [This will produce a documentation warning if it becomes
162/// public].
163///
164/// This is automatically implemented whenever `T::Key` implements [`Hash`].
165///
166/// [`IdOrdMap`]: crate::IdOrdMap
167pub trait IdOrdItemMut<'a>: IdOrdItem<Key<'a>: Hash> + 'a {}
168
169impl<'a, T> IdOrdItemMut<'a> for T where T: 'a + IdOrdItem<Key<'a>: Hash> {}