async_executors/iface/
yield_now.rs

1use
2{
3	std::{ future::Future, pin::Pin, task::{ Context, Poll } } ,
4	blanket::blanket,
5};
6
7/// Trait indicating that tasks can yield to the executor. This put's
8/// the current task at the back of the schedulers queue, giving other
9/// tasks a chance to run.
10///
11/// In practice for most executors this just returns a future that will,
12/// the first time it is polled, wake up the waker and then return Pending.
13///
14/// The problem with using the executors native implementation is that they
15/// generally return an opaque future we would have to box.
16//
17#[ blanket( derive(Ref, Mut, Arc, Rc, Box) ) ]
18//
19pub trait YieldNow
20{
21	/// Await this future in order to yield to the executor.
22	//
23	fn yield_now( &self ) -> YieldNowFut
24	{
25		YieldNowFut{ done: false }
26	}
27}
28
29
30
31/// Future returned by [`YieldNow::yield_now`].
32//
33#[must_use = "YieldNowFut doesn't do anything unless polled or awaited."]
34//
35#[ derive( Debug, Copy, Clone ) ]
36//
37pub struct YieldNowFut
38{
39	pub(crate) done: bool,
40}
41
42
43impl Future for YieldNowFut
44{
45	type Output = ();
46
47	fn poll( mut self: Pin<&mut Self>, cx: &mut Context<'_> ) -> Poll<()>
48	{
49		if self.done
50		{
51			return Poll::Ready(());
52		}
53
54		self.done = true;
55		cx.waker().wake_by_ref();
56		Poll::Pending
57	}
58}