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