maitake/future/
yield_future.rs

1use core::{
2    future::Future,
3    pin::Pin,
4    task::{Context, Poll},
5};
6
7/// A future that yields to the scheduler one or more times before completing.
8#[derive(Debug)]
9#[must_use = "futures do nothing unless `.await`ed or polled"]
10pub struct Yield {
11    yields: usize,
12}
13
14impl Future for Yield {
15    type Output = ();
16    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
17        let yields = &mut self.as_mut().yields;
18        if *yields == 0 {
19            return Poll::Ready(());
20        }
21        *yields -= 1;
22        cx.waker().wake_by_ref();
23        Poll::Pending
24    }
25}
26
27impl Yield {
28    /// Returns a new future that yields `yields` times before completing.
29    #[inline]
30    pub const fn new(yields: usize) -> Self {
31        Self { yields }
32    }
33}
34
35/// Yield to the scheduler a single time before proceeding.
36#[inline]
37pub fn yield_now() -> Yield {
38    Yield::new(1)
39}