-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
consume_budget.rs
33 lines (29 loc) · 1.03 KB
/
consume_budget.rs
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
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
/// Consumes a unit of budget and returns the execution back to the Tokio
/// runtime *if* the task went out ouf budget.
///
/// The task will only yield if it ran out of its coop budget.
/// It can be used in order to insert optional yield points into long
/// computations that do not use Tokio resources like sockets or semaphores,
/// without redundantly yielding to runtime each time.
#[cfg_attr(docsrs, doc(cfg(feature = "rt")))]
pub async fn consume_budget() {
struct ConsumeBudget {
status: Poll<()>,
}
impl Future for ConsumeBudget {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.status.is_ready() {
return self.status;
}
self.status = crate::coop::poll_proceed(cx).map(|restore| {
restore.made_progress();
});
self.status
}
}
ConsumeBudget { status: Poll::Pending }.await
}