use core::cell::RefCell;
use std::io;
use bstack::{BStack, BStackOwnedSlice, BStackRange};
use crate::BStackRaiiAllocator;
use crate::registry::FileId;
use crate::types::traits::BStackDrop;
use crate::util::io_error;
type TeardownSink = (*const BStack, Vec<(FileId, BStackRange)>);
thread_local! {
static TEARDOWN_SINK: RefCell<Option<TeardownSink>> = const { RefCell::new(None) };
}
struct Sink;
impl Sink {
fn is_active() -> bool {
TEARDOWN_SINK.with(|s| s.borrow().is_some())
}
fn install(stack: *const BStack) -> SinkGuard {
TEARDOWN_SINK.with(|s| *s.borrow_mut() = Some((stack, Vec::new())));
SinkGuard
}
fn collect<A: BStackRaiiAllocator>(allocator: &A, range: BStackRange) -> bool {
TEARDOWN_SINK.with(|s| match s.borrow_mut().as_mut() {
Some((installer, sink)) => {
let foreign = allocator.wal_file_id() != FileId::SELF;
if foreign || allocator.stack() == unsafe { &**installer } {
sink.push((allocator.wal_file_id(), range));
true
} else {
false
}
}
None => false,
})
}
unsafe fn dealloc<A: BStackRaiiAllocator>(allocator: &A, range: BStackRange) -> io::Result<()> {
if Self::collect(allocator, range) {
return Ok(());
}
let owned: BStackOwnedSlice<'_, A> =
unsafe { BStackOwnedSlice::from_raw_range(allocator, range) };
allocator.dealloc(owned).map_err(|e| e.source)
}
}
struct SinkGuard;
impl SinkGuard {
fn take(&self) -> Vec<(FileId, BStackRange)> {
TEARDOWN_SINK
.with(|s| s.borrow_mut().take())
.map(|(_, v)| v)
.unwrap_or_default()
}
}
impl Drop for SinkGuard {
fn drop(&mut self) {
TEARDOWN_SINK.with(|s| *s.borrow_mut() = None);
}
}
thread_local! {
static TEARDOWN_DEPTH: core::cell::Cell<u32> = const { core::cell::Cell::new(0) };
}
const MAX_TEARDOWN_DEPTH: u32 = 500;
pub(crate) struct TeardownDepthGuard;
impl TeardownDepthGuard {
pub(crate) fn enter() -> io::Result<Self> {
let depth = TEARDOWN_DEPTH.with(|c| {
let n = c.get() + 1;
c.set(n);
n
});
if depth > MAX_TEARDOWN_DEPTH {
TEARDOWN_DEPTH.with(|c| c.set(c.get() - 1)); return Err(io_error!(
"teardown recursion too deep (an owned-reference cycle?)"
));
}
Ok(TeardownDepthGuard)
}
}
impl Drop for TeardownDepthGuard {
fn drop(&mut self) {
TEARDOWN_DEPTH.with(|c| c.set(c.get().saturating_sub(1)));
}
}
pub fn wal_teardown<A: BStackRaiiAllocator, T: BStackDrop>(
handle: T,
allocator: &A,
) -> io::Result<()> {
if Sink::is_active() {
return handle.bstack_drop(allocator);
}
if allocator.wal_anchor().is_none() {
return handle.bstack_drop(allocator);
}
let sink_guard = Sink::install(core::ptr::from_ref(allocator.stack()));
let result = handle.bstack_drop(allocator);
let slices = sink_guard.take();
result?;
crate::io_core::commit_frees(allocator, slices)
}
pub unsafe fn dealloc_range<A: BStackRaiiAllocator>(
allocator: &A,
range: BStackRange,
) -> io::Result<()> {
unsafe { Sink::dealloc(allocator, range) }
}