mod error;
use core::{mem::DropGuard, task::Poll};
use rustix::fd::{AsFd, BorrowedFd};
pub use self::error::EventLoopError;
use crate::{context::Context, selector::Selector, storage::LoopStorage};
#[must_use]
pub struct EventLoop<
'sel,
E: 'static,
const EVENTS: usize,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
> {
pub(crate) ctx: Context<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
poisoned: bool,
}
impl<
'sel,
E: 'static,
const EVENTS: usize,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
> EventLoop<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
{
pub fn new<F, Fut>(
storage: &'static LoopStorage<E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
selector: &'sel mut Selector,
f: F,
) -> Result<Self, EventLoopError>
where
F: FnOnce(Context<'sel, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>) -> Fut,
Fut: Future<Output = ()> + 'sel,
{
let (ctx, root) = storage.claim(selector).ok_or(EventLoopError::StorageAlreadyUsed)?;
let event_loop = Self {
ctx,
poisoned: false,
};
ctx.storage.tasks.spawn_root(root, ctx.claimed, f(ctx));
match ctx.storage.tasks.run_ready() {
Poll::Pending => {}
Poll::Ready(()) => return Err(EventLoopError::RootFinished),
}
ctx.flush()?;
Ok(event_loop)
}
pub fn drain_events_without_blocking(&mut self) -> Result<(), EventLoopError> {
if self.poisoned {
return Err(EventLoopError::Poisoned);
}
let ctx = self.ctx;
let poison = DropGuard::new(&mut self.poisoned, |poisoned: &mut bool| *poisoned = true);
let result = ctx.drain();
DropGuard::dismiss(poison);
result
}
pub fn notify(&self) -> rustix::io::Result<()> {
self.ctx.selector.notify()
}
pub fn events(&self) -> impl Iterator<Item = E> {
self.ctx.storage.events.iter_removing()
}
}
impl<
E: 'static,
const EVENTS: usize,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
> Drop for EventLoop<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
{
fn drop(&mut self) {
self.ctx.clear();
}
}
impl<
E: 'static,
const EVENTS: usize,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
> AsFd for EventLoop<'_, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>
{
fn as_fd(&self) -> BorrowedFd<'_> {
self.ctx.selector.as_fd()
}
}
#[cfg(test)]
mod tests;