1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use core::fmt;
use core::future::Future;
use core::pin::Pin;
use core::task::{Context, Poll};

#[cfg(doc)]
use super::YieldProgress;

/// The minimum, executor-agnostic yield operation.
/// **This may be unsuitable for some applications.**
///
/// This function is provided as a convenience for constructing a [`YieldProgress`] where no more
/// specific yield implementation is required. It does not itself interact with the
/// [`YieldProgress`] system.
///
/// # Caveat
///
/// This function implements yielding by returning a [`Future`] which will:
///
/// 1. The first time it is polled, immediately [wake] and return [`Poll::Pending`].
/// 2. The second time it is polled, return [`Poll::Ready`].
///
/// This might be inadequate if the executor's scheduling policy:
///
/// * Distinguishes intentional yielding.
///   For example, in Tokio 1.\*, you should use [`tokio::task::yield_now()`] instead.
/// * Is not fair among tasks, so some amount of delay is required to successfully yield to other
///   tasks.
/// * Is not fair between tasks and something else.
///   For example, if the executor is implemented inside some event loop but itself loops through
///   Rust async tasks as long as any of the tasks have [woken][wake], then something additional is
///   needed to yield to the higher level.
///
/// [wake]: core::task::Waker::wake()
/// [`tokio::task::yield_now()`]: https://docs.rs/tokio/1/tokio/task/fn.yield_now.html
pub fn basic_yield_now() -> impl Future<Output = ()> + fmt::Debug + Send + 'static {
    BasicYieldNow { state: State::New }
}

#[derive(Debug)]
struct BasicYieldNow {
    state: State,
}

#[derive(Clone, Copy, Debug)]
enum State {
    New,
    Ready,
    Used,
}
impl Future for BasicYieldNow {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let state = &mut self.get_mut().state;
        match *state {
            State::New => {
                *state = State::Ready;
                cx.waker().wake_by_ref();
                Poll::Pending
            }
            State::Ready => {
                *state = State::Used;
                Poll::Ready(())
            }
            State::Used => panic!("future polled after completion"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn yield_smoke_test() {
        basic_yield_now().await;
    }
}