dope_core/executor/task/
race.rs1use core::task;
2use o3::base::Either;
3
4use crate::{
5 executor::task::context,
6 executor::task::{Fiber, Side},
7};
8
9#[pin_project::pin_project]
10#[must_use = "a fiber does nothing unless it is driven"]
11#[derive(Debug)]
15pub struct Race<L, R> {
16 #[pin]
17 left: L,
18 #[pin]
19 right: R,
20 resume: Side,
21}
22
23impl<L, R> Race<L, R> {
24 pub const fn new(left: L, right: R) -> Self {
25 Self {
26 left,
27 right,
28 resume: Side::Left,
29 }
30 }
31}
32
33impl<'d, L, R> Fiber<'d> for Race<L, R>
34where
35 L: Fiber<'d>,
36 R: Fiber<'d>,
37{
38 type Output = Either<L::Output, R::Output>;
39
40 fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> task::Poll<Self::Output> {
41 use core::task::Poll;
42
43 let (this, context) = call.into_parts();
44 let this = this.project();
45 match *this.resume {
46 Side::Left => {
47 if let Poll::Ready(output) = L::poll(context::PollCall {
48 fiber: this.left,
49 context: &mut *context,
50 }) {
51 return Poll::Ready(Either::Left(output));
52 }
53 *this.resume = Side::Right;
54 let context::Continue::Permit(_permit) = context.try_continue() else {
55 return Poll::Pending;
56 };
57 match R::poll(context::PollCall {
58 fiber: this.right,
59 context,
60 }) {
61 Poll::Ready(output) => Poll::Ready(Either::Right(output)),
62 Poll::Pending => {
63 *this.resume = Side::Left;
64 Poll::Pending
65 }
66 }
67 }
68 Side::Right => {
69 if let Poll::Ready(output) = R::poll(context::PollCall {
70 fiber: this.right,
71 context: &mut *context,
72 }) {
73 return Poll::Ready(Either::Right(output));
74 }
75 *this.resume = Side::Left;
76 let context::Continue::Permit(_permit) = context.try_continue() else {
77 return Poll::Pending;
78 };
79 match L::poll(context::PollCall {
80 fiber: this.left,
81 context,
82 }) {
83 Poll::Ready(output) => Poll::Ready(Either::Left(output)),
84 Poll::Pending => Poll::Pending,
85 }
86 }
87 }
88 }
89}
90
91const _: () = {
92 assert!(core::mem::size_of::<Race<(), ()>>() == core::mem::size_of::<Side>());
93 assert!(core::mem::size_of::<Option<Race<(), ()>>>() == core::mem::size_of::<Race<(), ()>>());
94};