use std::cell::Cell;
thread_local! {
static APPLYING_REPLICATED: Cell<bool> = const { Cell::new(false) };
}
pub struct ReplicatedApplyGuard {
prev: bool,
}
impl ReplicatedApplyGuard {
#[must_use = "ReplicatedApplyGuard is RAII — drop it at scope end"]
pub fn enter() -> Self {
let prev = APPLYING_REPLICATED.with(Cell::get);
APPLYING_REPLICATED.with(|c| c.set(true));
Self { prev }
}
}
impl Drop for ReplicatedApplyGuard {
fn drop(&mut self) {
APPLYING_REPLICATED.with(|c| c.set(self.prev));
}
}
pub(crate) fn is_applying_replicated() -> bool {
APPLYING_REPLICATED.with(Cell::get)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_is_off() {
assert!(!is_applying_replicated());
}
#[test]
fn guard_sets_then_clears() {
assert!(!is_applying_replicated());
{
let _g = ReplicatedApplyGuard::enter();
assert!(is_applying_replicated());
}
assert!(!is_applying_replicated());
}
#[test]
fn guard_nests_correctly() {
let _outer = ReplicatedApplyGuard::enter();
assert!(is_applying_replicated());
{
let _inner = ReplicatedApplyGuard::enter();
assert!(is_applying_replicated());
}
assert!(is_applying_replicated());
}
}