use std::cell::{Cell, RefCell};
use std::sync::mpsc::{Receiver, Sender};
pub(crate) struct ParkGate {
reached: Sender<()>,
release: Receiver<()>,
}
pub(crate) fn park_gate() -> (ParkGate, Receiver<()>, Sender<()>) {
let (reached_tx, reached_rx) = std::sync::mpsc::channel();
let (release_tx, release_rx) = std::sync::mpsc::channel();
(
ParkGate {
reached: reached_tx,
release: release_rx,
},
reached_rx,
release_tx,
)
}
thread_local! {
static PARK_AFTER_REAP: RefCell<Option<ParkGate>> = const { RefCell::new(None) };
static PANIC_AFTER_RELOCK: Cell<bool> = const { Cell::new(false) };
static ROOT_TEARDOWNS: Cell<Option<u32>> = const { Cell::new(None) };
}
pub(crate) fn record_root_teardowns() -> RootTeardownRecorder {
ROOT_TEARDOWNS.with(|c| c.set(Some(0)));
RootTeardownRecorder(())
}
#[must_use = "recording stops as soon as the recorder is dropped"]
pub(crate) struct RootTeardownRecorder(());
impl RootTeardownRecorder {
pub(crate) fn count(&self) -> u32 {
ROOT_TEARDOWNS.with(|c| c.get().expect("the recorder is live"))
}
}
impl Drop for RootTeardownRecorder {
fn drop(&mut self) {
ROOT_TEARDOWNS.with(|c| c.set(None));
}
}
pub(super) fn note_root_teardown() {
ROOT_TEARDOWNS.with(|c| {
if let Some(n) = c.get() {
c.set(Some(n + 1));
}
});
}
#[must_use = "dropping this immediately disarms the force; bind it for the probe's duration"]
pub(crate) struct Forced(fn());
impl Drop for Forced {
fn drop(&mut self) {
(self.0)();
}
}
pub(crate) fn park_after_reap_recorded_on(gate: ParkGate) -> Forced {
PARK_AFTER_REAP.with(|p| *p.borrow_mut() = Some(gate));
Forced(|| PARK_AFTER_REAP.with(|p| *p.borrow_mut() = None))
}
pub(super) fn park_after_reap_recorded() {
if let Some(gate) = PARK_AFTER_REAP.with(|p| p.borrow_mut().take()) {
_ = gate.reached.send(());
_ = gate.release.recv();
}
}
pub(crate) fn panic_after_relock_once() -> Forced {
PANIC_AFTER_RELOCK.with(|f| f.set(true));
Forced(|| PANIC_AFTER_RELOCK.with(|f| f.set(false)))
}
pub(super) fn panic_after_relock_if_armed() {
if PANIC_AFTER_RELOCK.with(Cell::take) {
panic!("forced panic just after the holder's relock (test seam)");
}
}
#[cfg(unix)]
type ContendedHook = Box<dyn Fn() + Send>;
#[cfg(unix)]
static ON_LOCK_CONTENDED: std::sync::Mutex<Option<ContendedHook>> = std::sync::Mutex::new(None);
#[cfg(unix)]
#[must_use = "dropping this immediately disarms the hook; bind it for the probe's duration"]
pub(crate) struct ContendedArmed(());
#[cfg(unix)]
impl Drop for ContendedArmed {
fn drop(&mut self) {
*ON_LOCK_CONTENDED
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = None;
}
}
#[cfg(unix)]
pub(crate) fn on_lock_contended(hook: impl Fn() + Send + 'static) -> ContendedArmed {
*ON_LOCK_CONTENDED
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Box::new(hook));
ContendedArmed(())
}
pub(super) fn lock_contended() {
#[cfg(unix)]
if let Some(hook) = ON_LOCK_CONTENDED
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_ref()
{
hook();
}
}