use crate::error::DecodeError;
pub const DEFAULT_ALLOC_FACTOR: usize = 16;
pub const DEFAULT_MIN_ALLOC_BYTES: usize = 64 << 10;
pub const DEFAULT_MAX_ALLOC_BYTES: usize = 4 * crate::frame::DEFAULT_MAX_FRAME;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limits {
alloc_factor: usize,
min_alloc_bytes: usize,
max_alloc_bytes: usize,
}
impl Default for Limits {
fn default() -> Self {
Limits {
alloc_factor: DEFAULT_ALLOC_FACTOR,
min_alloc_bytes: DEFAULT_MIN_ALLOC_BYTES,
max_alloc_bytes: DEFAULT_MAX_ALLOC_BYTES,
}
}
}
impl Limits {
pub const UNLIMITED: Limits = Limits {
alloc_factor: usize::MAX,
min_alloc_bytes: usize::MAX,
max_alloc_bytes: usize::MAX,
};
#[must_use]
pub fn with_alloc_factor(mut self, factor: usize) -> Limits {
self.alloc_factor = factor;
self
}
#[must_use]
pub fn with_min_alloc_bytes(mut self, bytes: usize) -> Limits {
self.min_alloc_bytes = bytes;
self
}
#[must_use]
pub fn with_max_alloc_bytes(mut self, bytes: usize) -> Limits {
self.max_alloc_bytes = bytes;
self
}
#[must_use]
pub fn alloc_bytes_for(&self, input_len: usize) -> usize {
input_len
.saturating_mul(self.alloc_factor)
.max(self.min_alloc_bytes)
.min(self.max_alloc_bytes)
}
#[must_use]
pub fn budget(&self, input_len: usize) -> Budget {
Budget::new(self.alloc_bytes_for(input_len))
}
}
#[derive(Debug)]
pub struct Budget {
limit: usize,
used: usize,
}
impl Budget {
#[must_use]
pub fn new(max_alloc_bytes: usize) -> Budget {
Budget {
limit: max_alloc_bytes,
used: 0,
}
}
#[must_use]
pub fn limit(&self) -> usize {
self.limit
}
#[must_use]
pub fn used(&self) -> usize {
self.used
}
pub fn charge(&mut self, bytes: usize) -> Result<(), DecodeError> {
let used = self.used.saturating_add(bytes);
self.check(used)?;
self.used = used;
Ok(())
}
pub fn release(&mut self, bytes: usize) {
self.used = self.used.saturating_sub(bytes);
}
#[inline]
pub fn push<T>(&mut self, items: &mut Vec<T>, value: T) -> Result<(), DecodeError> {
if items.len() == items.capacity() {
self.grow_for(items)?;
}
items.push(value);
Ok(())
}
#[inline(never)]
fn grow_for<T>(&mut self, items: &mut Vec<T>) -> Result<(), DecodeError> {
let elem = size_of::<T>();
if elem == 0 {
return Ok(());
}
let old = items.capacity();
let target = if old == 0 {
first_capacity(elem)
} else {
old.saturating_mul(2)
};
let old_bytes = old.saturating_mul(elem);
let new_bytes = target.saturating_mul(elem);
self.grow(old_bytes, new_bytes)?;
items.try_reserve_exact(target - items.len()).map_err(|_| {
DecodeError::AllocationFailed {
bytes: new_bytes,
limit: self.limit,
}
})?;
self.settle(new_bytes, items.capacity().saturating_mul(elem))
}
#[inline]
pub fn progress(&self, before: usize, after: usize) -> Result<(), DecodeError> {
if after >= before {
return Err(DecodeError::NoProgress);
}
Ok(())
}
fn grow(&mut self, old_bytes: usize, new_bytes: usize) -> Result<(), DecodeError> {
let peak = self.used.saturating_add(new_bytes);
self.check(peak)?;
self.used = peak.saturating_sub(old_bytes);
Ok(())
}
fn settle(&mut self, charged: usize, actual: usize) -> Result<(), DecodeError> {
if actual == charged {
return Ok(());
}
let used = self.used.saturating_add(actual).saturating_sub(charged);
self.check(used)?;
self.used = used;
Ok(())
}
fn check(&self, wanted: usize) -> Result<(), DecodeError> {
if wanted > self.limit {
return Err(DecodeError::AllocationLimit {
limit: self.limit,
wanted,
});
}
Ok(())
}
}
const fn first_capacity(elem: usize) -> usize {
if elem == 1 {
8
} else if elem <= 1024 {
4
} else {
1
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn budget_scales_with_input_and_respects_floor_and_ceiling() {
let limits = Limits::default();
assert_eq!(limits.alloc_bytes_for(1 << 20), 16 << 20);
assert_eq!(limits.alloc_bytes_for(16), DEFAULT_MIN_ALLOC_BYTES);
assert_eq!(
limits.alloc_bytes_for(crate::frame::DEFAULT_MAX_FRAME),
DEFAULT_MAX_ALLOC_BYTES
);
let capped = limits.with_max_alloc_bytes(1 << 20);
assert_eq!(capped.alloc_bytes_for(64 << 20), 1 << 20);
assert_eq!(
limits
.with_max_alloc_bytes(usize::MAX)
.alloc_bytes_for(usize::MAX),
usize::MAX
);
assert_eq!(Limits::UNLIMITED.alloc_bytes_for(0), usize::MAX);
}
#[test]
fn push_stops_at_the_limit_rather_than_allocating_past_it() {
let mut budget = Budget::new(32);
let mut items: Vec<u64> = Vec::new();
for i in 0..4u64 {
budget.push(&mut items, i).expect("within budget");
}
assert_eq!(items.len(), 4);
assert_eq!(budget.used(), 32);
assert!(matches!(
budget.push(&mut items, 4),
Err(DecodeError::AllocationLimit { limit: 32, .. })
));
assert_eq!(items.len(), 4);
assert_eq!(items.capacity(), 4);
}
#[test]
fn growth_transient_is_charged_not_amortized() {
let mut budget = Budget::new(64);
let mut items: Vec<u64> = Vec::new();
for i in 0..4u64 {
budget.push(&mut items, i).expect("within budget");
}
assert!(budget.push(&mut items, 4).is_err());
}
#[test]
fn zero_sized_elements_never_charge() {
let mut budget = Budget::new(0);
let mut items: Vec<()> = Vec::new();
for _ in 0..1000 {
budget
.push(&mut items, ())
.expect("no allocation to charge");
}
assert_eq!(budget.used(), 0);
}
#[test]
fn progress_rejects_a_zero_width_element() {
let budget = Budget::new(0);
assert_eq!(budget.progress(10, 9), Ok(()));
assert_eq!(budget.progress(10, 10), Err(DecodeError::NoProgress));
}
#[test]
fn charge_and_release_are_symmetric() {
let mut budget = Budget::new(100);
budget.charge(60).expect("fits");
assert!(budget.charge(60).is_err());
budget.release(60);
assert_eq!(budget.used(), 0);
budget.release(1); assert_eq!(budget.used(), 0);
}
}