Skip to main content

memory_budget/
lease.rs

1//! RAII lease returned by [`MemoryBudget::lease`](crate::MemoryBudget::lease).
2
3use std::sync::Arc;
4
5use crate::budget::BudgetState;
6
7/// Active short-term reservation against the budget.
8///
9/// While alive, the effective per-cache target is reduced by
10/// `bytes()`. The reduction is released when the guard is dropped.
11///
12/// Issued by [`MemoryBudget::lease`](crate::MemoryBudget::lease).
13/// The guard owns the shared accounting state until release, even when the
14/// public budget handle has been dropped. It never releases a reservation
15/// merely because work moved to another task or queue.
16#[must_use = "dropping the LeaseGuard immediately releases the lease"]
17pub struct LeaseGuard {
18    bytes: u64,
19    state: Arc<BudgetState>,
20}
21
22impl LeaseGuard {
23    pub(crate) fn new(bytes: u64, state: Arc<BudgetState>) -> Self {
24        Self { bytes, state }
25    }
26
27    /// Bytes reserved by this guard.
28    #[must_use]
29    pub fn bytes(&self) -> u64 {
30        self.bytes
31    }
32}
33
34impl Drop for LeaseGuard {
35    fn drop(&mut self) {
36        self.state.release_lease(self.bytes);
37    }
38}