use std::cell::Cell;
pub const STACK: u64 = 984 * 1024 * 1024 * 1024;
pub(crate) const fn per_level(n: u64) -> u64 {
STACK / n
}
pub(crate) const fn extra(a: u64, b: u64) -> u64 {
per_level(b) - per_level(a)
}
thread_local! {
static USED: Cell<u64> = const { Cell::new(0) };
}
#[must_use = "the level is given back when this is dropped"]
#[derive(Debug)]
pub(crate) struct Level {
cost: u64,
}
impl Drop for Level {
fn drop(&mut self) {
USED.with(|used| used.set(used.get().saturating_sub(self.cost)));
}
}
#[inline]
pub(crate) fn enter(cost: u64) -> Option<Level> {
USED.with(|used| {
let now = used.get().checked_add(cost).filter(|&now| now <= STACK)?;
used.set(now);
Some(Level { cost })
})
}
pub(crate) fn used() -> u64 {
USED.with(Cell::get)
}
pub(crate) fn left() -> u64 {
STACK.saturating_sub(used())
}
#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
const RED_ZONE: usize = 256 * 1024;
#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
const SEGMENT: usize = 4 * 1024 * 1024;
#[inline(always)]
pub(crate) fn stack_address() -> usize {
let marker = 0u8;
std::hint::black_box(&marker) as *const u8 as usize
}
#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
thread_local! {
static LIMIT: Cell<usize> = const { Cell::new(0) };
}
#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
const LIMIT_SPAN: usize = 1 << 30;
#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
#[cold]
fn learn_limit(here: usize) -> usize {
let limit = stacker::remaining_stack().map_or(1, |left| here.saturating_sub(left).max(2));
LIMIT.with(|l| l.set(limit));
limit
}
pub fn can_grow() -> bool {
#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
{
match LIMIT.with(Cell::get) {
0 => learn_limit(stack_address()) != 1,
limit => limit != 1,
}
}
#[cfg(not(all(feature = "stack-growth", not(target_family = "wasm"))))]
{
false
}
}
#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
#[inline]
pub(crate) fn grow_with<R>(f: impl FnOnce() -> R) -> R {
let here = stack_address();
let limit = LIMIT.with(Cell::get);
if limit > 1 && here.wrapping_sub(limit).wrapping_sub(RED_ZONE) < LIMIT_SPAN {
return f();
}
grow_slow(here, limit, f)
}
#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
#[cold]
#[inline(never)]
fn grow_slow<R>(here: usize, limit: usize, f: impl FnOnce() -> R) -> R {
let limit = if limit > 1 && here.wrapping_sub(limit) < LIMIT_SPAN {
limit
} else {
learn_limit(here)
};
if limit == 1 || here.saturating_sub(limit) >= RED_ZONE {
return f();
}
struct Restore(usize);
impl Drop for Restore {
fn drop(&mut self) {
LIMIT.with(|l| l.set(self.0));
}
}
stacker::grow(SEGMENT, move || {
let _restore = Restore(limit);
learn_limit(stack_address());
f()
})
}
#[cfg(all(feature = "stack-growth", not(target_family = "wasm")))]
macro_rules! grow {
($e:expr) => {
$crate::depth::grow_with(|| $e)
};
}
#[cfg(not(all(feature = "stack-growth", not(target_family = "wasm"))))]
macro_rules! grow {
($e:expr) => {
$e
};
}
pub(crate) use grow;
#[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, 300, 1_716, 2_914, 4_642, 9_820, 60_000] {
let cost = per_level(n);
assert_eq!(left() / cost, n);
let levels: Vec<Level> = (0..n).map(|_| enter(cost).expect("fits")).collect();
assert!(enter(cost).is_none(), "{n}");
drop(levels);
assert_eq!(used(), 0);
}
}
#[test]
fn levels_are_given_back_on_unwind() {
let r = std::panic::catch_unwind(|| {
let _a = enter(per_level(10)).unwrap();
let _b = enter(per_level(10)).unwrap();
panic!("unwinds");
});
assert!(r.is_err());
assert_eq!(used(), 0);
}
#[test]
fn growth_is_available_where_the_feature_and_target_allow_it() {
let expected = cfg!(all(feature = "stack-growth", not(target_family = "wasm")));
assert_eq!(can_grow(), expected);
fn down(n: usize) -> usize {
let pad = std::hint::black_box([0u8; 512]);
if n == 0 {
return 1;
}
grow!(down(n - 1)) + usize::from(pad[n % 512])
}
if expected {
let r = std::thread::Builder::new()
.stack_size(2 << 20)
.spawn(|| down(100_000))
.unwrap()
.join()
.unwrap();
assert!(r > 0);
}
}
}