pal_event/lib.rs
1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! An abstraction over platform-specific event primitives:
5//!
6//! Windows: [event objects](https://learn.microsoft.com/en-us/windows/win32/sync/event-objects)
7//! Linux: [eventfd](https://man7.org/linux/man-pages/man2/eventfd.2.html)
8//! Other Unix: [fifo](https://man.openbsd.org/mkfifo.2)
9
10// UNSAFETY: FFI into platform-specific APIs.
11#![expect(unsafe_code)]
12
13mod unix;
14mod windows;
15
16#[cfg(unix)]
17use unix as sys;
18#[cfg(windows)]
19use windows as sys;
20
21/// A platform-specific synchronization event.
22#[derive(Debug)]
23pub struct Event(sys::Inner);
24
25impl Event {
26 /// Creates a new event.
27 ///
28 /// Panics if the event cannot be created. This should only be due to low
29 /// resources.
30 pub fn new() -> Self {
31 match Self::new_inner() {
32 Ok(event) => event,
33 Err(err) => panic!("failed to create event: {}", err),
34 }
35 }
36
37 /// Signals the event.
38 pub fn signal(&self) {
39 self.signal_inner();
40 }
41
42 /// Waits for the event to be signaled and consumes the signal.
43 pub fn wait(&self) {
44 self.wait_inner();
45 }
46
47 /// Tries to consume the event signal.
48 ///
49 /// Returns `false` if the event is not currently signaled.
50 pub fn try_wait(&self) -> bool {
51 self.try_wait_inner()
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 #[test]
58 fn test_event() {
59 let event = crate::Event::new();
60 event.signal();
61 event.wait();
62 }
63}