embedded_runtime/spin.rs
1//! A future to spin once to give up a timeslice
2
3use core::{
4 future::Future,
5 pin::Pin,
6 task::{Context, Poll},
7};
8
9/// A future that can be polled once before it becomes ready; useful to cooperatively give up a timeslice to the
10/// runtime/other pending futures
11///
12/// # Behaviour
13/// Polling this future will immediately wake the waker again and yield, making room for other futures to execute. This
14/// is useful for e.g. running intensive loops or similar inside a future.
15#[derive(Debug, Default)]
16pub struct SpinFuture {
17 /// Whether the future has been polled already or not
18 polled: bool,
19}
20impl SpinFuture {
21 /// Creates a new spin future
22 ///
23 /// # Note
24 /// This future should usually not be constructed directly, use [`spin_once`] instead.
25 pub const fn new() -> Self {
26 Self { polled: false }
27 }
28}
29impl Future for SpinFuture {
30 type Output = ();
31
32 fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
33 if !self.polled {
34 // Mark the future as polled so that it returns ready the next time
35 self.polled = true;
36 cx.waker().wake_by_ref();
37 Poll::Pending
38 } else {
39 // The future has been polled, so it's ready now
40 Poll::Ready(())
41 }
42 }
43}
44
45/// A function that can be awaited once before it returns; useful to cooperatively give up a timeslice to the
46/// runtime/other pending futures
47///
48/// # Behaviour
49/// Awaiting this function will immediately wake the waker again and yield, making room for other futures to execute.
50/// This is useful for e.g. running intensive loops or similar inside a future.
51pub async fn spin_once() {
52 SpinFuture::new().await
53}