use std::sync::Mutex;
use std::sync::MutexGuard;
use crate::resource::ResourceLimit;
use crate::resource::ResourceQuantity;
#[derive(Debug)]
pub(in crate::resource::budget) struct ManagedResourcePoolInner<R, Q>
where
Q: ResourceQuantity,
{
pub(in crate::resource::budget) limit: ResourceLimit<R, Q>,
available: Mutex<Q>,
}
impl<R, Q> ManagedResourcePoolInner<R, Q>
where
Q: ResourceQuantity,
{
#[must_use]
#[inline]
pub(in crate::resource::budget) fn new(limit: ResourceLimit<R, Q>) -> Self {
let available = limit.maximum();
Self {
limit,
available: Mutex::new(available),
}
}
#[inline]
pub(in crate::resource::budget) fn lock_available(&self) -> MutexGuard<'_, Q> {
self.available.lock().unwrap_or_else(|error| error.into_inner())
}
pub(in crate::resource::budget) fn release(&self, amount: Q) {
let capacity = self.limit.maximum();
let mut available = self.lock_available();
*available = match available.checked_add(amount) {
Some(next) if next <= capacity => next,
_ => capacity,
};
}
}