Skip to main content

forge/os/
event.rs

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