1
//! Helpers for reference counting
2
//!
3
//! Two main purposes:
4
//!
5
//!  * Consistent handling of overflow and underflow
6
//!  * Assurance of incrementing/decrementing as appropriate,
7
//!    including in combination with a slotmap containing the referenced data.
8
//!
9
//! The caller is responsible for making sure that the *right instance*'s
10
//! [`Count`] is passed to the methods on [`Ref`].
11
//
12
// There are no separate tests for this module.  Many of the tests would want to
13
// exercise the `Ref`s drop bomb, which is troublesome since it's panic in drop,
14
// which they're making Rust treat as an abort upstream.
15
// (This scheme did detect a bug or two during development testing,
16
// so the drop bomb is known to work.)
17
//
18
// Anyway, these functions are mostly newtype veneers over existing functionality.
19
// They're tested by the MemoryQuotaTracker's tests.
20

            
21
use crate::internal_prelude::*;
22

            
23
/// Local alias for the counter type
24
pub(crate) type RawCount = u32;
25

            
26
/// Decrement a refcount and maybe remove a corresponding slotmap entry
27
///
28
/// ```rust,ignore
29
/// fn slotmap_dec_ref!<K, V>(
30
///    slotmap: &mut SlotMap<K, V>,
31
///    ref_: Ref<K>,
32
///    refcount: &mut Count<K>, // (typically) borrows from slotmap
33
/// )
34
/// ```
35
//
36
// This macro is a bit out-of-position, up here, because we want to be able to link
37
// to it in our rustdocs.
38
macro_rules! slotmap_dec_ref { { $slotmap:expr, $ref_:expr, $refcount:expr } => { { {
39
    use $crate::refcount::*;
40
    let key: Ref<_> = $ref_;
41
    let refcount: &mut Count<_> = $refcount;
42
    if let Some(Garbage(key)) = key.dispose(refcount) {
43
        let slotmap: &mut SlotMap<_, _> = $slotmap;
44
        let removed = slotmap.remove(key).expect("entry vanished or wrong key passed?!");
45
        Some(Garbage(removed))
46
    } else {
47
        None
48
    }
49
} } } }
50

            
51
/// A reference count, counting references with id type `K`
52
#[derive(Default, Educe, Ord, PartialOrd, Eq, PartialEq, Deref)]
53
#[educe(Debug)]
54
pub(crate) struct Count<K> {
55
    /// Actual count of references
56
    #[deref]
57
    count: RawCount,
58
    /// Bind to the specific key type
59
    // K is generally Send + Sync + 'static so we don't care about variance etc.
60
    #[educe(Debug(ignore))]
61
    marker: PhantomData<K>,
62
}
63

            
64
/// An copy of a [`slotmap_careful::Key`] `K`, which is counted by a `RefCount`
65
///
66
/// Ie, a key of type `K` with the property that it
67
/// keeps the refcounted data structure alive.
68
///
69
/// Must always be deleted using [`dispose`](Ref::dispose), not dropped.
70
/// In tests, dropping a `RefCounted` will panic.
71
///
72
/// The `Default` value does *not* contribute to a reference count,
73
/// and is fine to drop.
74
#[derive(Deref, Educe)]
75
#[educe(Debug, Default, Ord, PartialOrd, Eq, PartialEq)]
76
pub(crate) struct Ref<K: slotmap_careful::Key> {
77
    /// Actual key (without generics)
78
    #[deref]
79
    raw_key: K,
80
    /// Bind to the specific key type
81
    #[educe(Debug(ignore))]
82
    marker: PhantomData<K>,
83
    /// Drop bomb
84
    ///
85
    /// Also forces `Ref` not to be Clone
86
    #[educe(Debug(ignore), Ord(ignore), PartialEq(ignore))]
87
    #[allow(dead_code)]
88
    bomb: DropBombCondition,
89
}
90

            
91
// Ideally we'd assert_not_impl on Ref but it has generics
92
assert_not_impl_any!(DropBombCondition: Clone);
93

            
94
/// Error: refcount overflowed
95
#[derive(Debug, Clone, Error, Eq, PartialEq)]
96
#[error("memory tracking refcount overflowed")]
97
pub(crate) struct Overflow;
98

            
99
/// Something which has become garbage
100
///
101
/// Often used within `Option`, for clarity.  Examples:
102
///
103
///  * Key whose reference count has reached zero - see [`Ref::dispose`]
104
///  * Value removed from a SlotMap - see [`slotmap_dec_ref!`]
105
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
106
pub(crate) struct Garbage<K>(pub(crate) K);
107

            
108
impl<K> Count<K> {
109
    /// Make a new refcount with a specified value
110
173
    const fn new_raw(count: RawCount) -> Self {
111
173
        Count {
112
173
            count,
113
173
            marker: PhantomData,
114
173
        }
115
173
    }
116

            
117
    /// Obtain this counter as a `usize`
118
    ///
119
    /// (Reference counts are `u32`, so this might be a conversion.)
120
4
    pub(crate) fn as_usize(&self) -> usize {
121
        // On a 16-bit platform this could theoretically overflow,
122
        // but there would have to be >2^16 clones, which would be impossible.
123
4
        let r: u32 = **self;
124
4
        r as usize
125
4
    }
126
}
127

            
128
/// Increment this refcount, but don't care about any [`Ref`]s
129
6693
fn inc_raw(c: &mut RawCount) -> Result<(), Overflow> {
130
6693
    *c = c.checked_add(1).ok_or(Overflow)?;
131
6693
    Ok(())
132
6693
}
133

            
134
/// Decrement this refcount, but don't care about any [`Ref`]s
135
///
136
/// Returns `Some(Garbage(()))` if the count reached zero.
137
6740
fn dec_raw(c: &mut RawCount) -> Option<Garbage<()>> {
138
6740
    *c = c
139
6740
        .checked_sub(1)
140
6740
        // if this happens, our data structure is corrupted, very bad
141
6740
        .expect("refcount underflow");
142
6740
    (*c == 0).then_some(Garbage(()))
143
6740
}
144

            
145
impl<K: slotmap_careful::Key> Ref<K> {
146
    /// Create a refcounted reference `Ref` from an un-counted key, incrementing the count
147
6693
    pub(crate) fn new(key: K, count: &mut Count<K>) -> Result<Self, Overflow> {
148
6693
        inc_raw(&mut count.count)?;
149
6693
        Ok(Ref::from_raw(key))
150
6693
    }
151

            
152
    /// Creates a null `Ref`, which doesn't refer to any slot (lookups always give `None`)
153
4
    pub(crate) fn null() -> Self {
154
4
        Ref::from_raw(K::null())
155
4
    }
156

            
157
    /// Internal function for creating a `Ref`
158
6697
    fn from_raw(raw_key: K) -> Self {
159
6697
        Ref {
160
6697
            raw_key,
161
6697
            marker: PhantomData,
162
6697
            bomb: DropBombCondition::new_armed(),
163
6697
        }
164
6697
    }
165

            
166
    /// Dispose of a refcounted reference `Ref`, decrementing the count
167
    ///
168
    /// If the count reaches zero, the raw key is returned;
169
    /// the caller should remove the corresponding data from the data structure.
170
6740
    pub(crate) fn dispose(mut self, refcount: &mut Count<K>) -> Option<Garbage<K>> {
171
6740
        let was = mem::take(&mut self.raw_key);
172
6740
        assert!(!was.is_null());
173
6740
        dec_raw(&mut refcount.count).map(|_: Garbage<()>| Garbage(was))
174
6740
    }
175

            
176
    /// Dispose of a refcounted reference whose container no longer exists
177
    ///
178
    /// # CORRECTNESS
179
    ///
180
    /// This just forgets the reference, without decrementing any refcount.
181
    /// If the container *does* still exist, a ref count ref will be leaked.
182
80598
    pub(crate) fn dispose_container_destroyed(mut self) {
183
80598
        let _: K = mem::take(&mut self.raw_key);
184
80598
    }
185
}
186

            
187
impl<K: slotmap_careful::Key> DefaultExtTake for Ref<K> {}
188

            
189
/// Insert a new entry into a slotmap using refcounted keys
190
///
191
/// `value_maker` should take the provided `Count`,
192
/// and incorporate it into a new value.
193
///
194
/// On return, the entry will be in the map, and there will be one reference,
195
/// which is returned.
196
///
197
/// There is no corresponding `slotmap_remove` in this module.
198
/// Use [`Ref::dispose`] and handle any [`Garbage`] it returns.
199
88
pub(crate) fn slotmap_insert<K: slotmap_careful::Key, V>(
200
88
    slotmap: &mut SlotMap<K, V>,
201
88
    value_maker: impl FnOnce(Count<K>) -> V,
202
88
) -> Ref<K> {
203
88
    let (ref_, ()) = slotmap_try_insert(slotmap, move |refcount| {
204
88
        Ok::<_, Void>((value_maker(refcount), ()))
205
88
    })
206
    .void_unwrap();
207
88
    ref_
208
88
}
209

            
210
/// Insert a new entry into a slotmap using refcounted keys, fallibly and with extra data
211
///
212
/// Like [`slotmap_insert`] but:
213
///  * `value_maker` can also return extra return data `RD` to the caller
214
///  * `value_maker` is allowed to fail.
215
///
216
/// On successful return, the entry will be in the map, and
217
/// the new `Ref` is returned along with the data `D`.
218
173
pub(crate) fn slotmap_try_insert<K: slotmap_careful::Key, V, E, RD>(
219
173
    slotmap: &mut SlotMap<K, V>,
220
173
    value_maker: impl FnOnce(Count<K>) -> Result<(V, RD), E>,
221
173
) -> Result<(Ref<K>, RD), E> {
222
173
    let refcount = Count::new_raw(1);
223
173
    let (value, data) = value_maker(refcount)?;
224
172
    let raw_key = slotmap.insert(value);
225
172
    let ref_ = Ref {
226
172
        raw_key,
227
172
        marker: PhantomData,
228
172
        bomb: DropBombCondition::new_armed(),
229
172
    };
230
172
    Ok((ref_, data))
231
173
}
232

            
233
/// Unconditionally remove en entry from the slotmap, given a strong ref
234
///
235
/// Other references to this entry will become dangling.
236
12
pub(crate) fn slotmap_remove_early<K: slotmap_careful::Key, V>(
237
12
    slotmap: &mut SlotMap<K, V>,
238
12
    key: Ref<K>,
239
12
) -> Option<V> {
240
12
    let r = slotmap.remove(*key);
241
    // Correctness: this becomes a reference to a missing entry
242
12
    key.dispose_container_destroyed();
243
12
    r
244
12
}
245

            
246
#[cfg(test)]
247
impl<K: slotmap_careful::Key> Drop for Ref<K> {
248
13767
    fn drop(&mut self) {
249
13767
        drop_bomb_disarm_assert!(self.bomb, self.raw_key.is_null(),);
250
13767
    }
251
}
252

            
253
impl From<Overflow> for Error {
254
    fn from(_overflow: Overflow) -> Error {
255
        internal!("reference count overflow in memory tracking (out-of-control subsystem?)").into()
256
    }
257
}
258

            
259
#[cfg(test)]
260
mod test {
261
    // @@ begin test lint list maintained by maint/add_warning @@
262
    #![allow(clippy::bool_assert_comparison)]
263
    #![allow(clippy::clone_on_copy)]
264
    #![allow(clippy::dbg_macro)]
265
    #![allow(clippy::mixed_attributes_style)]
266
    #![allow(clippy::print_stderr)]
267
    #![allow(clippy::print_stdout)]
268
    #![allow(clippy::single_char_pattern)]
269
    #![allow(clippy::unwrap_used)]
270
    #![allow(clippy::unchecked_time_subtraction)]
271
    #![allow(clippy::useless_vec)]
272
    #![allow(clippy::needless_pass_by_value)]
273
    #![allow(clippy::string_slice)] // See arti#2571
274
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
275
    #![allow(clippy::let_and_return)] // TODO this lint is annoying and we should disable it
276

            
277
    use super::*;
278

            
279
    slotmap_careful::new_key_type! {
280
        struct Id;
281
    }
282
    #[derive(Eq, PartialEq, Debug)]
283
    struct Record {
284
        refcount: Count<Id>,
285
    }
286
    type Map = SlotMap<Id, Record>;
287

            
288
    fn setup() -> (Map, Ref<Id>) {
289
        let mut map = Map::default();
290
        let ref_ = slotmap_insert(&mut map, |refcount| Record { refcount });
291
        (map, ref_)
292
    }
293

            
294
    #[test]
295
    fn good() {
296
        let (mut map, ref1) = setup();
297

            
298
        let ent = map.get_mut(*ref1).unwrap();
299
        let ref2 = Ref::new(*ref1, &mut ent.refcount).unwrap();
300

            
301
        let g1: Option<Garbage<Record>> = slotmap_dec_ref!(&mut map, ref1, &mut ent.refcount);
302
        assert_eq!(g1, None);
303

            
304
        let ent = map.get_mut(*ref2).unwrap();
305
        let g2: Option<Garbage<Record>> = slotmap_dec_ref!(&mut map, ref2, &mut ent.refcount);
306
        assert!(g2.is_some());
307
    }
308

            
309
    #[test]
310
    fn try_insert_fail() {
311
        let mut map = Map::default();
312
        let () = slotmap_try_insert::<_, _, _, String>(&mut map, |_refcount| Err(())).unwrap_err();
313
    }
314

            
315
    #[test]
316
    fn drop_ref_without_decrement() {
317
        let (_map, mut ref1) = setup();
318
        let h = ref1.bomb.make_simulated();
319
        drop(ref1);
320
        h.expect_exploded();
321
    }
322
}