dope-core 0.77.0

Owned native I/O and completion driver for dope
Documentation
pub mod batch;
pub mod group;
pub mod storage;
pub mod time;
pub mod wait;

pub mod future;
mod race;
pub use race::Race;

use core::{convert, marker, pin, task::Poll};

use crate::{
    executor::task::{context::PollCall, storage::slots},
    signal,
};

pub mod context;

#[derive(Clone, Copy, Debug)]
enum Side {
    Left,
    Right,
}

impl Side {
    const fn other(self) -> Self {
        match self {
            Self::Left => Self::Right,
            Self::Right => Self::Left,
        }
    }
}

#[must_use = "a fiber does nothing unless it is driven"]
/// A pinned unit of cooperative work admitted by its live owner and driver.
/// Ready ends polling; the owning task drops this fiber before exposing its output.
/// [`Task`] retains standalone completion; nested polls share admission and budget.
pub trait Fiber<'d>: Sized {
    type Output;

    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output>;
}

/// A pinned sequence whose owner stops polling after `Ready(None)`.
/// Each admitted call yields at most one item; [`Task`] drops the child at end.
#[must_use = "a stream does nothing unless it is driven"]
pub trait Stream<'d>: Sized {
    type Item;

    fn poll_next(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Option<Self::Item>>;

    /// True after an item if the next poll would immediately return `Ready(None)` without effects.
    fn is_final(&self) -> bool {
        false
    }
}

impl<'d, F: Fiber<'d>> Fiber<'d> for pin::Pin<&mut Task<F>> {
    type Output = F::Output;

    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
        let (this, context) = call.into_parts();
        this.get_mut().as_mut().poll(context)
    }
}

impl<'d> Fiber<'d> for convert::Infallible {
    type Output = Self;

    fn poll(call: PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
        match *call.into_fiber().get_mut() {}
    }
}

impl<'d> Fiber<'d> for &mut signal::Wait<'_, 'd> {
    type Output = Result<(), crate::Errno>;

    fn poll(call: PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
        let (this, context) = call.into_parts();
        this.get_mut().poll(context.completion())
    }
}

/// One final pinned place that drops its child before releasing the output.
#[pin_project::pin_project]
#[repr(transparent)]
#[must_use = "a task does nothing unless it is driven"]
pub struct Task<F> {
    #[pin]
    state: Option<F>,
}

impl<F> Task<F> {
    pub const fn new(fiber: F) -> Self {
        Self { state: Some(fiber) }
    }

    pub(crate) fn poll<'d>(
        self: pin::Pin<&mut Self>,
        context: &mut context::Context<'_, 'd>,
    ) -> Poll<F::Output>
    where
        F: Fiber<'d>,
    {
        Self::poll_slot(self.project().state, context)
    }

    fn poll_slot<'d>(
        mut state: pin::Pin<&mut Option<F>>,
        context: &mut context::Context<'_, 'd>,
    ) -> Poll<F::Output>
    where
        F: Fiber<'d>,
    {
        let Some(fiber) = state.as_mut().as_pin_mut() else {
            return Poll::Pending;
        };
        let result = F::poll(PollCall { fiber, context });
        if result.is_ready() {
            state.set(None);
        }
        result
    }

    pub(crate) fn poll_next<'d>(
        self: pin::Pin<&mut Self>,
        context: &mut context::Context<'_, 'd>,
    ) -> Poll<Option<F::Item>>
    where
        F: Stream<'d>,
    {
        let mut state = self.project().state;
        let Some(fiber) = state.as_mut().as_pin_mut() else {
            return Poll::Ready(None);
        };
        let result = F::poll_next(PollCall { fiber, context });
        if matches!(result, Poll::Ready(None)) {
            state.set(None);
        }
        result
    }
}

#[repr(transparent)]
#[must_use = "a fiber does nothing unless it is driven"]
#[derive(Debug)]
pub struct Ready<T> {
    output: Option<T>,
}

impl<T> Unpin for Ready<T> {}

impl<T> Ready<T> {
    pub const fn new(output: T) -> Self {
        Self {
            output: Some(output),
        }
    }
}

impl<'d, T> Fiber<'d> for Ready<T> {
    type Output = T;

    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
        let this = call.into_fiber();
        let Some(output) = this.get_mut().output.take() else {
            return Poll::Pending;
        };
        Poll::Ready(output)
    }
}

#[repr(transparent)]
#[must_use = "a fiber does nothing unless it is driven"]
#[derive(Debug)]
pub struct PollFn<'d, F> {
    f: F,
    driver: marker::PhantomData<&'d mut &'d ()>,
}

impl<F> Unpin for PollFn<'_, F> {}

impl<'d, F> PollFn<'d, F> {
    pub const fn new<T>(
        mut f: F,
    ) -> PollFn<'d, impl FnMut(context::raw::Admission<'_, '_, 'd>) -> Poll<T>>
    where
        F: FnMut(&mut context::Context<'_, 'd>) -> Poll<T>,
    {
        PollFn::admitted(move |admit| f(admit.into_context()))
    }

    /// Retains the poll's initial admission for one child task or ready group.
    pub const fn admitted<T>(f: F) -> Self
    where
        F: FnMut(context::raw::Admission<'_, '_, 'd>) -> Poll<T>,
    {
        Self {
            f,
            driver: marker::PhantomData,
        }
    }
}

impl<'d, F, T> Fiber<'d> for PollFn<'d, F>
where
    F: FnMut(context::raw::Admission<'_, '_, 'd>) -> Poll<T>,
{
    type Output = T;

    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
        let (this, admit) = call.into_admit();
        let this = this.get_mut();
        (this.f)(admit)
    }
}

#[pin_project::pin_project]
#[must_use = "a fiber does nothing unless it is driven"]
pub struct Join<'d, L, R>
where
    L: Fiber<'d>,
    R: Fiber<'d>,
{
    #[pin]
    left: slots::raw::Entry<L, L::Output>,
    #[pin]
    right: slots::raw::Entry<R, R::Output>,
    next: Side,
    driver: marker::PhantomData<fn(&'d ()) -> &'d ()>,
}

impl<'d, L, R> Join<'d, L, R>
where
    L: Fiber<'d>,
    R: Fiber<'d>,
{
    pub fn new(left: L, right: R) -> Self {
        Self {
            left: slots::raw::Entry::new(left),
            right: slots::raw::Entry::new(right),
            next: Side::Left,
            driver: marker::PhantomData,
        }
    }
}

impl<'d, L, R> Fiber<'d> for Join<'d, L, R>
where
    L: Fiber<'d>,
    R: Fiber<'d>,
{
    type Output = (L::Output, R::Output);

    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
        let (this, cx) = call.into_parts();
        let this = this.project();
        let side = *this.next;
        *this.next = side.other();
        let mut first = true;
        let (left, right) = match side {
            Side::Left => (
                this.left.poll(&mut *cx, &mut first),
                this.right.poll(cx, &mut first),
            ),
            Side::Right => {
                let right = this.right.poll(&mut *cx, &mut first);
                (this.left.poll(cx, &mut first), right)
            }
        };
        let (Some(left), Some(right)) = (left, right) else {
            return Poll::Pending;
        };
        Poll::Ready((left.take(), right.take()))
    }
}