Skip to main content

externally_driven_async_rt/event_loop/
mod.rs

1mod error;
2
3use core::{mem::DropGuard, task::Poll};
4
5use rustix::fd::{AsFd, BorrowedFd};
6
7pub use self::error::EventLoopError;
8
9use crate::{context::Context, selector::Selector, storage::LoopStorage};
10
11/// The main type, an event loop.
12#[must_use]
13pub struct EventLoop<
14    'sel,
15    E: 'static,
16    const EVENTS: usize,
17    const TASKS: usize,
18    const TASK_SIZE: usize,
19    const ROOT_TASK_SIZE: usize,
20    const TIMERS: usize,
21    const FDS: usize,
22> {
23    pub(crate) ctx: Context<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
24    poisoned: bool,
25}
26
27impl<
28    'sel,
29    E: 'static,
30    const EVENTS: usize,
31    const TASKS: usize,
32    const TASK_SIZE: usize,
33    const ROOT_TASK_SIZE: usize,
34    const TIMERS: usize,
35    const FDS: usize,
36> EventLoop<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
37{
38    /// Creates an event loop and polls given future once.
39    ///
40    /// The future must fit `ROOT_TASK_SIZE` bytes and be aligned to at most 16 bytes, otherwise
41    /// the program doesn't compile.
42    ///
43    /// # Errors
44    ///
45    /// Returns an error if:
46    ///
47    /// 1. `storage` has already been used by another event loop, `f` isn't called then
48    /// 2. epoll/kqueue returned an error during initial poll
49    /// 3. given future completed during initial poll.
50    pub fn new<F, Fut>(
51        storage: &'static LoopStorage<E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
52        selector: &'sel mut Selector,
53        f: F,
54    ) -> Result<Self, EventLoopError>
55    where
56        F: FnOnce(Context<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>) -> Fut,
57        Fut: Future<Output = ()> + 'sel,
58    {
59        let (ctx, root) = storage.claim(selector).ok_or(EventLoopError::StorageAlreadyUsed)?;
60        let event_loop = Self {
61            ctx,
62            poisoned: false,
63        };
64        ctx.storage.tasks.spawn_root(root, ctx.claimed, f(ctx));
65        match ctx.storage.tasks.run_ready() {
66            Poll::Pending => {}
67            Poll::Ready(()) => return Err(EventLoopError::RootFinished),
68        }
69        ctx.flush()?;
70        Ok(event_loop)
71    }
72
73    /// Drains all events from the underlying `epollfd` or `kqueuefd`,
74    /// polls woken futures until none is ready,
75    /// submits them back to epoll/kqueue.
76    ///
77    /// It keeps polling until no future is woken, so a future that wakes itself
78    /// every time it's polled makes this method loop forever.
79    ///
80    /// # Errors
81    ///
82    /// Returns an error if:
83    ///
84    /// 1. epoll/kqueue returned an error
85    /// 2. root future completed
86    /// 3. a previous call panicked, the event loop is poisoned then
87    pub fn drain_events_without_blocking(&mut self) -> Result<(), EventLoopError> {
88        if self.poisoned {
89            return Err(EventLoopError::Poisoned);
90        }
91        let ctx = self.ctx;
92        let poison = DropGuard::new(&mut self.poisoned, |poisoned: &mut bool| *poisoned = true);
93        let result = ctx.drain();
94        DropGuard::dismiss(poison);
95        result
96    }
97
98    /// Makes the event loop's file descriptor readable and wakes up a task
99    /// that waits on [`Context::notified`](crate::Context::notified)
100    /// once you call [`drain_events_without_blocking`](Self::drain_events_without_blocking).
101    ///
102    /// This is the way to pass data from the external world into the event loop:
103    /// store the data somewhere the task can reach it, then call this method.
104    ///
105    /// # Errors
106    ///
107    /// Returns an error if a syscall fails.
108    pub fn notify(&self) -> rustix::io::Result<()> {
109        self.ctx.selector.notify()
110    }
111
112    /// Returns an iterator that pops events pushed by [`Context::dispatch`](crate::Context::dispatch).
113    ///
114    /// This is the way to pass data from the event loop to the external world.
115    pub fn events(&self) -> impl Iterator<Item = E> {
116        self.ctx.storage.events.iter_removing()
117    }
118}
119
120impl<
121    E: 'static,
122    const EVENTS: usize,
123    const TASKS: usize,
124    const TASK_SIZE: usize,
125    const ROOT_TASK_SIZE: usize,
126    const TIMERS: usize,
127    const FDS: usize,
128> Drop for EventLoop<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
129{
130    fn drop(&mut self) {
131        self.ctx.clear();
132    }
133}
134
135impl<
136    E: 'static,
137    const EVENTS: usize,
138    const TASKS: usize,
139    const TASK_SIZE: usize,
140    const ROOT_TASK_SIZE: usize,
141    const TIMERS: usize,
142    const FDS: usize,
143> AsFd for EventLoop<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
144{
145    fn as_fd(&self) -> BorrowedFd<'_> {
146        self.ctx.selector.as_fd()
147    }
148}
149
150#[cfg(test)]
151mod tests;