mod error;
use core::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<
'a,
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<'a, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>,
}
impl<
'a,
E: 'static,
const EVENTS: usize,
const TASKS: usize,
const TASK_SIZE: usize,
const ROOT_TASK_SIZE: usize,
const TIMERS: usize,
const FDS: usize,
> EventLoop<'a, 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: &'a mut Selector,
f: F,
) -> Result<Self, EventLoopError>
where
F: FnOnce(Context<'a, E, EVENTS, TASKS, TASK_SIZE, ROOT_TASK_SIZE, TIMERS, FDS>) -> Fut,
Fut: Future<Output = ()> + 'a,
{
let (ctx, root) = storage.claim(selector).ok_or(EventLoopError::StorageAlreadyUsed)?;
let event_loop = Self { ctx };
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> {
let ctx = self.ctx;
if !ctx.storage.tasks.has_root() {
return Err(EventLoopError::RootFinished);
}
loop {
ctx.process_selector_events()?;
if !ctx.storage.tasks.has_woken() {
break;
}
if ctx.storage.tasks.run_ready().is_ready() {
ctx.storage.tasks.drop_all();
ctx.flush()?;
return Err(EventLoopError::RootFinished);
}
}
ctx.flush()?;
Ok(())
}
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;