Skip to main content

dope_core/executor/task/
mod.rs

1pub mod batch;
2pub mod group;
3pub mod storage;
4pub mod time;
5pub mod wait;
6
7pub mod future;
8mod race;
9pub use race::Race;
10
11use core::{convert, marker, pin, task::Poll};
12
13use crate::{
14    executor::task::{context::PollCall, storage::slots},
15    signal,
16};
17
18pub mod context;
19
20#[derive(Clone, Copy, Debug)]
21enum Side {
22    Left,
23    Right,
24}
25
26impl Side {
27    const fn other(self) -> Self {
28        match self {
29            Self::Left => Self::Right,
30            Self::Right => Self::Left,
31        }
32    }
33}
34
35#[must_use = "a fiber does nothing unless it is driven"]
36/// A pinned unit of cooperative work admitted by its live owner and driver.
37/// Ready ends polling; the owning task drops this fiber before exposing its output.
38/// [`Task`] retains standalone completion; nested polls share admission and budget.
39pub trait Fiber<'d>: Sized {
40    type Output;
41
42    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output>;
43}
44
45/// A pinned sequence whose owner stops polling after `Ready(None)`.
46/// Each admitted call yields at most one item; [`Task`] drops the child at end.
47#[must_use = "a stream does nothing unless it is driven"]
48pub trait Stream<'d>: Sized {
49    type Item;
50
51    fn poll_next(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Option<Self::Item>>;
52
53    /// True after an item if the next poll would immediately return `Ready(None)` without effects.
54    fn is_final(&self) -> bool {
55        false
56    }
57}
58
59impl<'d, F: Fiber<'d>> Fiber<'d> for pin::Pin<&mut Task<F>> {
60    type Output = F::Output;
61
62    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
63        let (this, context) = call.into_parts();
64        this.get_mut().as_mut().poll(context)
65    }
66}
67
68impl<'d> Fiber<'d> for convert::Infallible {
69    type Output = Self;
70
71    fn poll(call: PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
72        match *call.into_fiber().get_mut() {}
73    }
74}
75
76impl<'d> Fiber<'d> for &mut signal::Wait<'_, 'd> {
77    type Output = Result<(), crate::Errno>;
78
79    fn poll(call: PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
80        let (this, context) = call.into_parts();
81        this.get_mut().poll(context.completion())
82    }
83}
84
85/// One final pinned place that drops its child before releasing the output.
86#[pin_project::pin_project]
87#[repr(transparent)]
88#[must_use = "a task does nothing unless it is driven"]
89pub struct Task<F> {
90    #[pin]
91    state: Option<F>,
92}
93
94impl<F> Task<F> {
95    pub const fn new(fiber: F) -> Self {
96        Self { state: Some(fiber) }
97    }
98
99    pub(crate) fn poll<'d>(
100        self: pin::Pin<&mut Self>,
101        context: &mut context::Context<'_, 'd>,
102    ) -> Poll<F::Output>
103    where
104        F: Fiber<'d>,
105    {
106        Self::poll_slot(self.project().state, context)
107    }
108
109    fn poll_slot<'d>(
110        mut state: pin::Pin<&mut Option<F>>,
111        context: &mut context::Context<'_, 'd>,
112    ) -> Poll<F::Output>
113    where
114        F: Fiber<'d>,
115    {
116        let Some(fiber) = state.as_mut().as_pin_mut() else {
117            return Poll::Pending;
118        };
119        let result = F::poll(PollCall { fiber, context });
120        if result.is_ready() {
121            state.set(None);
122        }
123        result
124    }
125
126    pub(crate) fn poll_next<'d>(
127        self: pin::Pin<&mut Self>,
128        context: &mut context::Context<'_, 'd>,
129    ) -> Poll<Option<F::Item>>
130    where
131        F: Stream<'d>,
132    {
133        let mut state = self.project().state;
134        let Some(fiber) = state.as_mut().as_pin_mut() else {
135            return Poll::Ready(None);
136        };
137        let result = F::poll_next(PollCall { fiber, context });
138        if matches!(result, Poll::Ready(None)) {
139            state.set(None);
140        }
141        result
142    }
143}
144
145#[repr(transparent)]
146#[must_use = "a fiber does nothing unless it is driven"]
147#[derive(Debug)]
148pub struct Ready<T> {
149    output: Option<T>,
150}
151
152impl<T> Unpin for Ready<T> {}
153
154impl<T> Ready<T> {
155    pub const fn new(output: T) -> Self {
156        Self {
157            output: Some(output),
158        }
159    }
160}
161
162impl<'d, T> Fiber<'d> for Ready<T> {
163    type Output = T;
164
165    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
166        let this = call.into_fiber();
167        let Some(output) = this.get_mut().output.take() else {
168            return Poll::Pending;
169        };
170        Poll::Ready(output)
171    }
172}
173
174#[repr(transparent)]
175#[must_use = "a fiber does nothing unless it is driven"]
176#[derive(Debug)]
177pub struct PollFn<'d, F> {
178    f: F,
179    driver: marker::PhantomData<&'d mut &'d ()>,
180}
181
182impl<F> Unpin for PollFn<'_, F> {}
183
184impl<'d, F> PollFn<'d, F> {
185    pub const fn new<T>(
186        mut f: F,
187    ) -> PollFn<'d, impl FnMut(context::raw::Admission<'_, '_, 'd>) -> Poll<T>>
188    where
189        F: FnMut(&mut context::Context<'_, 'd>) -> Poll<T>,
190    {
191        PollFn::admitted(move |admit| f(admit.into_context()))
192    }
193
194    /// Retains the poll's initial admission for one child task or ready group.
195    pub const fn admitted<T>(f: F) -> Self
196    where
197        F: FnMut(context::raw::Admission<'_, '_, 'd>) -> Poll<T>,
198    {
199        Self {
200            f,
201            driver: marker::PhantomData,
202        }
203    }
204}
205
206impl<'d, F, T> Fiber<'d> for PollFn<'d, F>
207where
208    F: FnMut(context::raw::Admission<'_, '_, 'd>) -> Poll<T>,
209{
210    type Output = T;
211
212    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
213        let (this, admit) = call.into_admit();
214        let this = this.get_mut();
215        (this.f)(admit)
216    }
217}
218
219#[pin_project::pin_project]
220#[must_use = "a fiber does nothing unless it is driven"]
221pub struct Join<'d, L, R>
222where
223    L: Fiber<'d>,
224    R: Fiber<'d>,
225{
226    #[pin]
227    left: slots::raw::Entry<L, L::Output>,
228    #[pin]
229    right: slots::raw::Entry<R, R::Output>,
230    next: Side,
231    driver: marker::PhantomData<fn(&'d ()) -> &'d ()>,
232}
233
234impl<'d, L, R> Join<'d, L, R>
235where
236    L: Fiber<'d>,
237    R: Fiber<'d>,
238{
239    pub fn new(left: L, right: R) -> Self {
240        Self {
241            left: slots::raw::Entry::new(left),
242            right: slots::raw::Entry::new(right),
243            next: Side::Left,
244            driver: marker::PhantomData,
245        }
246    }
247}
248
249impl<'d, L, R> Fiber<'d> for Join<'d, L, R>
250where
251    L: Fiber<'d>,
252    R: Fiber<'d>,
253{
254    type Output = (L::Output, R::Output);
255
256    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
257        let (this, cx) = call.into_parts();
258        let this = this.project();
259        let side = *this.next;
260        *this.next = side.other();
261        let mut first = true;
262        let (left, right) = match side {
263            Side::Left => (
264                this.left.poll(&mut *cx, &mut first),
265                this.right.poll(cx, &mut first),
266            ),
267            Side::Right => {
268                let right = this.right.poll(&mut *cx, &mut first);
269                (this.left.poll(cx, &mut first), right)
270            }
271        };
272        let (Some(left), Some(right)) = (left, right) else {
273            return Poll::Pending;
274        };
275        Poll::Ready((left.take(), right.take()))
276    }
277}