musli_common/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::system::abort();
25 }
26
27 self.state.set(state - 1);
28
29 Shared { access: self }
30 }
31
32 #[inline]
33 pub(crate) fn exclusive(&self) -> Exlusive<'_> {
34 let state = self.state.get();
35
36 if state != 0 {
37 panic!("Context is already in shared use")
38 }
39
40 if state == isize::MIN {
41 crate::system::abort();
42 }
43
44 self.state.set(1);
45 Exlusive { access: self }
46 }
47}
48
49/// A shared access to some underlying state.
50pub(crate) struct Shared<'a> {
51 access: &'a Access,
52}
53
54impl Drop for Shared<'_> {
55 fn drop(&mut self) {
56 self.access.state.set(self.access.state.get() + 1);
57 }
58}
59
60/// An exclusive access to some underlying state.
61pub(crate) struct Exlusive<'a> {
62 access: &'a Access,
63}
64
65impl Drop for Exlusive<'_> {
66 fn drop(&mut self) {
67 self.access.state.set(0);
68 }
69}