use std::ptr;
use rquickjs::allocator::{Allocator, RustAllocator};
use crate::execution::{Interrupt, StopReason};
const HEADER: usize = 8;
const ALIGN: usize = 8;
pub(super) struct HeapLimit {
used: usize,
limit: usize,
interrupt: Interrupt,
}
impl HeapLimit {
pub(super) fn new(limit: usize, interrupt: Interrupt) -> Self {
Self {
used: 0,
limit,
interrupt,
}
}
fn cost(size: usize) -> Option<usize> {
size.checked_next_multiple_of(ALIGN)?.checked_add(HEADER)
}
fn reserve(&mut self, cost: Option<usize>) -> bool {
match cost.and_then(|cost| self.used.checked_add(cost)) {
Some(used) if used <= self.limit => true,
_ => {
self.interrupt.stop(StopReason::Heap);
false
}
}
}
unsafe fn held(block: *mut u8) -> usize {
unsafe { RustAllocator::usable_size(block) + HEADER }
}
}
unsafe impl Allocator for HeapLimit {
fn alloc(&mut self, size: usize) -> *mut u8 {
if !self.reserve(Self::cost(size)) {
return ptr::null_mut();
}
let block = RustAllocator.alloc(size);
if !block.is_null() {
self.used += unsafe { Self::held(block) };
}
block
}
fn calloc(&mut self, count: usize, size: usize) -> *mut u8 {
let Some(total) = count.checked_mul(size) else {
return ptr::null_mut();
};
if !self.reserve(Self::cost(total)) {
return ptr::null_mut();
}
let block = RustAllocator.calloc(count, size);
if !block.is_null() {
self.used += unsafe { Self::held(block) };
}
block
}
unsafe fn dealloc(&mut self, block: *mut u8) {
unsafe {
self.used -= Self::held(block);
RustAllocator.dealloc(block);
}
}
unsafe fn realloc(&mut self, block: *mut u8, new_size: usize) -> *mut u8 {
if block.is_null() {
return self.alloc(new_size);
}
let old = unsafe { Self::held(block) };
let grows = Self::cost(new_size).map(|cost| cost.saturating_sub(old));
if !self.reserve(grows) {
return ptr::null_mut();
}
let moved = unsafe { RustAllocator.realloc(block, new_size) };
if !moved.is_null() {
self.used = self.used - old + unsafe { Self::held(moved) };
}
moved
}
unsafe fn usable_size(block: *mut u8) -> usize {
unsafe { RustAllocator::usable_size(block) }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn allocations_past_the_limit_are_refused_and_recorded() {
let interrupt = Interrupt::default();
let mut heap = HeapLimit::new(1024, interrupt.clone());
let first = heap.alloc(500);
assert!(!first.is_null());
assert_eq!(heap.used, 512);
assert!(interrupt.stopped().is_none());
assert!(heap.alloc(512).is_null());
assert_eq!(interrupt.stopped(), Some(StopReason::Heap));
assert!(heap.calloc(usize::MAX, 2).is_null());
unsafe {
let grown = heap.realloc(first, 900);
assert!(!grown.is_null());
assert_eq!(heap.used, 912);
assert!(heap.realloc(grown, 2000).is_null());
let shrunk = heap.realloc(grown, 8);
assert_eq!(heap.used, 16);
heap.dealloc(shrunk);
}
assert_eq!(heap.used, 0);
}
}