Skip to main content

externally_driven_async_rt/event_loop/
mod.rs

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