Skip to main content

forge/os/
light_event.rs

1use core::{cell::UnsafeCell, time::Duration};
2
3use sys::os::{EventClearMode, TimeSpanType, light_event::*};
4
5/// A lightweight event object with the same API as [`Event`](super::event::Event) but suitable for `const` initialization.
6pub struct LightEvent {
7    inner: UnsafeCell<LightEventType>,
8}
9
10impl LightEvent {
11    /// Creates a new light event. If `signaled` is `true` the event starts in the signaled state.
12    pub const fn new(signaled: bool, clear_mode: EventClearMode) -> Self {
13        Self {
14            inner: UnsafeCell::new(LightEventType::new(signaled, clear_mode)),
15        }
16    }
17
18    /// Destroys the event. Called automatically on drop.
19    pub fn finalize(&self) {
20        unsafe { forge_nnosFinalizeLightEvent(self.ptr()) };
21    }
22
23    /// Signals the event, waking any threads currently blocked in [`wait`](Self::wait).
24    pub fn signal(&self) {
25        unsafe { forge_nnosSignalLightEvent(self.ptr()) };
26    }
27
28    /// Blocks the calling thread until the event is signaled.
29    pub fn wait(&self) {
30        unsafe { forge_nnosWaitLightEvent(self.ptr()) };
31    }
32
33    /// Returns `true` if the event is currently signaled without blocking.
34    pub fn try_wait(&self) -> bool {
35        unsafe { forge_nnosTryWaitLightEvent(self.ptr()) }
36    }
37
38    /// Blocks until the event is signaled or `timeout` elapses. Returns `true` if signaled.
39    pub fn wait_timeout(&self, timeout: Duration) -> bool {
40        let timeout = timeout.as_nanos() as u64;
41        unsafe { forge_nnosTimedWaitLightEvent(self.ptr(), TimeSpanType(timeout)) }
42    }
43
44    /// Clears the event, resetting it to the unsignaled state.
45    pub fn clear(&self) {
46        unsafe { forge_nnosClearLightEvent(self.ptr()) };
47    }
48
49    pub(crate) fn ptr(&self) -> *mut LightEventType {
50        self.inner.get()
51    }
52}
53
54impl Drop for LightEvent {
55    fn drop(&mut self) {
56        self.finalize();
57    }
58}