externally_driven_async_rt/event_loop/
mod.rs1mod 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#[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 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 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 pub fn notify(&self) -> rustix::io::Result<()> {
110 self.ctx.selector.notify()
111 }
112
113 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;