1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//! Wrapper around a data decrementing its underlying counter on [`Drop`].

use std::{ops::Deref, rc::Rc};

use crate::ObservableCell;

/// Wrapper around a data `T` decrementing its underlying counter on [`Drop`].
#[derive(Debug)]
pub struct Guarded<T> {
    /// Guarded value of data `T`.
    value: T,

    /// Guard itself guarding the value.
    guard: Guard,
}

impl<T> Guarded<T> {
    /// Wraps the `value` into a new [`Guarded`] basing on the `counter`.
    pub(super) fn wrap(value: T, counter: Rc<ObservableCell<u32>>) -> Self {
        Self {
            value,
            guard: Guard::new(counter),
        }
    }

    /// Unwraps this [`Guarded`] into its inner value and its [`Guard`].
    // false positive: destructors cannot be evaluated at compile-time
    #[allow(clippy::missing_const_for_fn)]
    #[must_use]
    pub fn into_parts(self) -> (T, Guard) {
        (self.value, self.guard)
    }

    /// Unwraps this [`Guarded`] into its inner value dropping its [`Guard`]
    /// in-place.
    // false positive: destructors cannot be evaluated at compile-time
    #[allow(clippy::missing_const_for_fn)]
    #[must_use]
    pub fn into_inner(self) -> T {
        self.value
    }
}

impl<T> Guarded<Option<T>> {
    /// Transposes an [`Guarded`] [`Option`] into a [`Option`] with a
    /// [`Guarded`] value within.
    #[must_use]
    pub fn transpose(self) -> Option<Guarded<T>> {
        let (value, guard) = self.into_parts();
        value.map(move |v| Guarded { value: v, guard })
    }
}

impl<T> AsRef<T> for Guarded<T> {
    fn as_ref(&self) -> &T {
        &self.value
    }
}

impl<T> Deref for Guarded<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

/// Guard backed by a counter incrementing on its creation and decrementing on
/// [`Drop`]ping.
#[derive(Debug)]
pub struct Guard(Rc<ObservableCell<u32>>);

impl Guard {
    /// Creates new [`Guard`] on the given `counter`.
    fn new(counter: Rc<ObservableCell<u32>>) -> Self {
        #[allow(clippy::expect_used)]
        counter.mutate(|mut c| {
            *c = c
                .checked_add(1)
                .expect("`progressable::Guard` counter overflow");
        });
        Self(counter)
    }
}

impl Drop for Guard {
    /// Decrements the counter backing this [`Guard`].
    fn drop(&mut self) {
        self.0.mutate(|mut c| {
            *c = c.saturating_sub(1);
        });
    }
}