use std::cell::Cell;
#[cfg_attr(not(test), allow(dead_code))]
pub const fn per_level(n: u64) -> u64 {
crate::depth::per_level(n)
}
pub const FIXED_STACK: u64 = 3 * 512 * 1024;
thread_local! {
static FIXED_USED: Cell<u64> = const { Cell::new(0) };
}
#[must_use = "the level is given back when this is dropped"]
#[derive(Debug)]
pub struct Level {
_node: crate::depth::Level,
rust: u64,
}
impl Drop for Level {
fn drop(&mut self) {
FIXED_USED.with(|used| used.set(used.get().saturating_sub(self.rust)));
}
}
#[inline]
pub fn enter(node: u64, rust: u64) -> Option<Level> {
let rust = if can_grow() { 0 } else { rust };
let fits = FIXED_USED.with(|used| {
let now = used.get().checked_add(rust).filter(|&r| r <= FIXED_STACK)?;
used.set(now);
Some(())
});
fits?;
match crate::depth::enter(node) {
Some(level) => Some(Level { _node: level, rust }),
None => {
FIXED_USED.with(|used| used.set(used.get().saturating_sub(rust)));
None
}
}
}
#[inline]
pub fn can_grow() -> bool {
crate::depth::can_grow()
}
#[inline]
pub fn grow<R>(f: impl FnOnce() -> R) -> R {
crate::depth::grow!(f())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_shape_of_n_levels_fits_and_one_more_does_not() {
for n in [1, 2, 3, 818, 1_328, 4_096, 60_000] {
let cost = per_level(n);
let levels: Vec<Level> = (0..n).map(|_| enter(cost, 0).expect("fits")).collect();
assert!(enter(cost, 0).is_none(), "{n}");
drop(levels);
assert_eq!(crate::depth::used(), 0);
assert_eq!(FIXED_USED.with(Cell::get), 0);
}
}
}