use core::fmt;
use crate::ByteCount;
#[must_use = "a byte budget has no effect unless it is retained and updated"]
#[derive(Debug, Eq, PartialEq)]
pub struct ByteBudget {
limit: ByteCount,
used: ByteCount,
}
impl ByteBudget {
pub const fn new(limit: ByteCount) -> Self {
Self { limit, used: ByteCount::ZERO }
}
#[must_use]
pub const fn limit(&self) -> ByteCount {
self.limit
}
#[must_use]
pub const fn used(&self) -> ByteCount {
self.used
}
#[must_use]
pub const fn available(&self) -> ByteCount {
ByteCount::new(self.limit.get() - self.used.get())
}
#[must_use]
pub const fn can_reserve(&self, amount: ByteCount) -> bool {
amount.get() <= self.available().get()
}
#[must_use]
pub const fn is_exhausted(&self) -> bool {
self.used.get() == self.limit.get()
}
pub fn try_reserve(
&mut self,
amount: ByteCount,
) -> Result<(), CapacityExceeded> {
let available = self.available();
if self.can_reserve(amount) {
self.used = ByteCount::new(self.used.get() + amount.get());
Ok(())
} else {
Err(CapacityExceeded { requested: amount, available })
}
}
pub fn release(&mut self, amount: ByteCount) -> Result<(), OverRelease> {
if amount.get() > self.used.get() {
return Err(OverRelease { released: amount, used: self.used });
}
self.used = ByteCount::new(self.used.get() - amount.get());
Ok(())
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CapacityExceeded {
requested: ByteCount,
available: ByteCount,
}
impl CapacityExceeded {
#[must_use]
pub const fn requested(&self) -> ByteCount {
self.requested
}
#[must_use]
pub const fn available(&self) -> ByteCount {
self.available
}
}
impl fmt::Display for CapacityExceeded {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"requested {} bytes, but only {} bytes are available",
self.requested.get(),
self.available.get()
)
}
}
impl core::error::Error for CapacityExceeded {}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct OverRelease {
released: ByteCount,
used: ByteCount,
}
impl OverRelease {
#[must_use]
pub const fn released(&self) -> ByteCount {
self.released
}
#[must_use]
pub const fn used(&self) -> ByteCount {
self.used
}
}
impl fmt::Display for OverRelease {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"cannot release {} bytes when {} bytes are used",
self.released.get(),
self.used.get()
)
}
}
impl core::error::Error for OverRelease {}