elfo_core/context/
budget.rs

1#[derive(Clone)]
2pub(crate) struct Budget(u8);
3
4impl Default for Budget {
5    fn default() -> Self {
6        Self(64)
7    }
8}
9
10impl Budget {
11    pub(crate) async fn acquire(&mut self) {
12        if self.0 == 0 {
13            // We should reset the budget before `yield_now()` because
14            // `select! { _ => ctx.recv() .. }` above can lock the branch forever.
15            *self = Self::default();
16            tokio::task::yield_now().await;
17        }
18    }
19
20    pub(crate) fn decrement(&mut self) {
21        // We use a saturating operation here because `try_recv()`
22        // can be called many times without calling `Budget::acquire()`.
23        self.0 = self.0.saturating_sub(1);
24    }
25}