use super::global_allocation_stats_snapshot;
use core::fmt;
use std::collections::TryReserveError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemoryLimitExceeded {
pub usage: u64,
pub limit: u64,
}
impl fmt::Display for MemoryLimitExceeded {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"memory allocation exceeds limit (usage={}, limit={})",
self.usage, self.limit
)
}
}
impl std::error::Error for MemoryLimitExceeded {}
#[derive(Debug)]
pub enum ReservationError {
LimitExceeded(MemoryLimitExceeded),
CapacityOverflow,
Allocation(TryReserveError),
}
impl fmt::Display for ReservationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::LimitExceeded(error) => error.fmt(f),
Self::CapacityOverflow => f.write_str("memory reservation size overflow"),
Self::Allocation(error) => error.fmt(f),
}
}
}
impl std::error::Error for ReservationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::LimitExceeded(error) => Some(error),
Self::CapacityOverflow => None,
Self::Allocation(error) => Some(error),
}
}
}
pub fn check_allocation(bytes: usize, limit: u64) -> Result<(), MemoryLimitExceeded> {
let live = global_allocation_stats_snapshot().allocated;
let usage = u64::try_from(bytes)
.ok()
.and_then(|bytes| live.checked_add(bytes));
match usage {
Some(usage) if usage <= limit => Ok(()),
usage => Err(MemoryLimitExceeded {
usage: usage.unwrap_or(u64::MAX),
limit,
}),
}
}
pub fn try_reserve_string(
output: &mut String,
additional: usize,
limit: u64,
) -> Result<(), ReservationError> {
if additional <= output.capacity() - output.len() {
return Ok(());
}
let needed = output
.len()
.checked_add(additional)
.ok_or(ReservationError::CapacityOverflow)?;
let growing = needed.max(output.capacity().saturating_mul(2));
let capacity = if check_allocation(growing, limit).is_ok() {
growing
} else {
check_allocation(needed, limit).map_err(ReservationError::LimitExceeded)?;
needed
};
output
.try_reserve_exact(capacity - output.len())
.map_err(ReservationError::Allocation)?;
check_allocation(0, limit).map_err(ReservationError::LimitExceeded)
}