use core::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct YieldNow(pub bool);
impl Future for YieldNow {
type Output = ();
#[inline]
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.0 {
Poll::Ready(())
} else {
self.0 = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
#[inline(always)]
pub const fn yield_now() -> YieldNow {
YieldNow(false)
}
#[cfg(test)]
mod tests {
use core::task::Waker;
use super::*;
#[test]
fn test_yield_now() {
let mut y = yield_now();
let waker = Waker::noop();
let mut cx = Context::from_waker(waker);
assert_eq!(Pin::new(&mut y).poll(&mut cx), Poll::Pending);
assert_eq!(Pin::new(&mut y).poll(&mut cx), Poll::Ready(()));
assert_eq!(Pin::new(&mut y).poll(&mut cx), Poll::Ready(()));
assert_eq!(YieldNow::default(), yield_now());
}
}