use std::cell::RefCell;
use textlane_core::Allocator;
use crate::read_retained_memory;
thread_local! {
static SPARE: RefCell<Option<Allocator>> = const { RefCell::new(None) };
}
pub(crate) fn with_allocator<R>(run: impl FnOnce(&Allocator) -> R) -> R {
let mut alloc = SPARE.with_borrow_mut(Option::take).unwrap_or_default();
let result = run(&alloc);
alloc.reset();
if alloc.allocated_bytes() <= read_retained_memory() {
SPARE.with_borrow_mut(|spare| *spare = Some(alloc));
}
result
}
#[cfg(test)]
pub(crate) fn read_spare_bytes() -> Option<usize> {
SPARE.with_borrow(|spare| spare.as_ref().map(Allocator::allocated_bytes))
}