wl_proxy/state/destructor.rs
1use {
2 crate::state::State,
3 std::{
4 cell::Cell,
5 os::fd::OwnedFd,
6 rc::Rc,
7 sync::{
8 Arc,
9 atomic::{
10 AtomicBool,
11 Ordering::{Relaxed, Release},
12 },
13 },
14 },
15};
16
17/// A destructor for a [`State`].
18///
19/// Dropping this object might destroy the state if the destructor is enabled.
20///
21/// This object can be constructed with [`State::create_destructor`].
22pub struct Destructor {
23 pub(super) state: Rc<State>,
24 pub(super) enabled: Cell<bool>,
25}
26
27/// A remote destructor for a [`State`].
28///
29/// This type serves the same purpose as [`Destructor`] but also implements `Send+Sync`.
30///
31/// This object can be constructed with [`State::create_remote_destructor`].
32pub struct RemoteDestructor {
33 pub(super) destroy: Arc<AtomicBool>,
34 pub(super) _fd: OwnedFd,
35 pub(super) enabled: AtomicBool,
36}
37
38impl Destructor {
39 /// Returns the underlying state.
40 pub fn state(&self) -> &Rc<State> {
41 &self.state
42 }
43
44 /// Returns whether this destructor is currently enabled.
45 ///
46 /// If the destructor is enabled when it is dropped, the underlying state is
47 /// destroyed.
48 pub fn enabled(&self) -> bool {
49 self.enabled.get()
50 }
51
52 /// Enables this destructor.
53 ///
54 /// This is the default.
55 pub fn enable(&self) {
56 self.enabled.set(true);
57 }
58
59 /// Disables this destructor.
60 pub fn disable(&self) {
61 self.enabled.set(false);
62 }
63}
64
65impl Drop for Destructor {
66 fn drop(&mut self) {
67 if self.enabled.get() {
68 self.state.destroy();
69 }
70 }
71}
72
73impl RemoteDestructor {
74 /// Returns whether this destructor is currently enabled.
75 ///
76 /// If the destructor is enabled when it is dropped, the underlying state is
77 /// destroyed.
78 pub fn enabled(&self) -> bool {
79 self.enabled.load(Relaxed)
80 }
81
82 /// Enables this destructor.
83 ///
84 /// This is the default.
85 pub fn enable(&self) {
86 self.enabled.store(true, Relaxed);
87 }
88
89 /// Disables this destructor.
90 pub fn disable(&self) {
91 self.enabled.store(false, Relaxed);
92 }
93}
94
95impl Drop for RemoteDestructor {
96 fn drop(&mut self) {
97 if self.enabled.load(Relaxed) {
98 self.destroy.store(true, Release);
99 }
100 }
101}