use std::cell::Cell;
use std::sync::{Mutex, OnceLock, PoisonError};
thread_local! {
static END: Cell<Option<usize>> = const { Cell::new(None) };
}
pub fn set_end(end: Option<usize>) {
END.set(end);
}
#[must_use]
pub fn left() -> Option<usize> {
let marker = 0_u8;
let here = std::ptr::from_ref(&marker).addr();
END.get().and_then(|end| here.checked_sub(end))
}
pub fn with_room<R: Send>(need: usize, work: impl FnOnce() -> R + Send) -> R {
if !always_apart() && left().is_none_or(|left| left >= need) {
return work();
}
let slot = Mutex::new(Some(work));
let take = || {
slot.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
.expect("the work runs once")
};
std::thread::scope(|scope| {
let started = std::thread::Builder::new()
.name("pltrs-deep".to_owned())
.stack_size(need)
.spawn_scoped(scope, || take()());
match started {
Ok(thread) => thread
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
Err(_) => take()(),
}
})
}
fn always_apart() -> bool {
static APART: OnceLock<bool> = OnceLock::new();
*APART.get_or_init(|| std::env::var_os("PLTRS_DEEP_WORK_APART").is_some())
}
#[cfg(test)]
mod tests {
use super::*;
fn runs_on(left: usize, need: usize) -> Option<String> {
let marker = 0_u8;
set_end(Some(std::ptr::from_ref(&marker).addr() - left));
let name = with_room(need, || std::thread::current().name().map(str::to_owned));
set_end(None);
name
}
#[test]
fn work_runs_here_while_the_stack_has_room() {
let here = std::thread::current().name().map(str::to_owned);
assert_eq!(runs_on(1 << 20, 64 << 10), here);
assert_eq!(left(), None, "an unknown end");
assert_eq!(with_room(usize::MAX, || 7), 7, "runs here without an end");
}
#[test]
fn work_runs_on_a_stack_of_its_own_where_the_stack_is_short() {
assert_eq!(runs_on(16 << 10, 64 << 10).as_deref(), Some("pltrs-deep"));
}
#[test]
fn the_work_gets_the_stack_it_needs() {
fn deep(depth: usize) -> usize {
let frame = std::hint::black_box([1_u8; 1024]);
if depth == 0 {
return usize::from(frame[0]);
}
deep(depth - 1) + usize::from(frame[1])
}
let marker = 0_u8;
set_end(Some(std::ptr::from_ref(&marker).addr() - (8 << 10)));
assert_eq!(with_room(4 << 20, || deep(500)), 501);
set_end(None);
}
#[test]
fn a_panic_of_the_work_unwinds_from_the_caller() {
let marker = 0_u8;
set_end(Some(std::ptr::from_ref(&marker).addr() - (16 << 10)));
let caught = std::panic::catch_unwind(|| {
with_room(64 << 10, || std::panic::panic_any::<u32>(42));
});
set_end(None);
let payload = caught.expect_err("the panic reaches the caller");
assert_eq!(payload.downcast_ref::<u32>(), Some(&42));
}
#[test]
fn a_stack_other_than_the_threads_has_no_room_known() {
set_end(Some(usize::MAX));
assert_eq!(left(), None);
set_end(None);
}
}