musli/context/
access.rs

1use core::cell::Cell;
2
3/// Guarded access to some underlying state.
4pub(crate) struct Access {
5    state: Cell<isize>,
6}
7
8impl Access {
9    pub(crate) fn new() -> Self {
10        Self {
11            state: Cell::new(0),
12        }
13    }
14
15    #[inline]
16    pub(crate) fn shared(&self) -> Shared<'_> {
17        let state = self.state.get();
18
19        if state > 0 {
20            panic!("Context is exclusively held")
21        }
22
23        if state == isize::MIN {
24            crate::no_std::abort("access state overflowed");
25        }
26
27        self.state.set(state - 1);
28        Shared { access: self }
29    }
30
31    #[inline]
32    pub(crate) fn exclusive(&self) -> Exlusive<'_> {
33        let state = self.state.get();
34
35        if state != 0 {
36            panic!("Context is already in shared use")
37        }
38
39        if state == isize::MIN {
40            crate::no_std::abort("access state overflowed");
41        }
42
43        self.state.set(1);
44        Exlusive { access: self }
45    }
46}
47
48/// A shared access to some underlying state.
49pub(crate) struct Shared<'a> {
50    access: &'a Access,
51}
52
53impl Drop for Shared<'_> {
54    fn drop(&mut self) {
55        self.access.state.set(self.access.state.get() + 1);
56    }
57}
58
59impl Clone for Shared<'_> {
60    fn clone(&self) -> Self {
61        // Shared state is already acquired, so we simply decrement it one more.
62        self.access.state.set(self.access.state.get() - 1);
63        Shared {
64            access: self.access,
65        }
66    }
67}
68
69/// An exclusive access to some underlying state.
70pub(crate) struct Exlusive<'a> {
71    access: &'a Access,
72}
73
74impl Drop for Exlusive<'_> {
75    fn drop(&mut self) {
76        self.access.state.set(0);
77    }
78}