use std::cell::Cell;
use std::marker::PhantomData;
use std::rc::Rc;
thread_local! {
static PLACING_SET_CALLS: Cell<bool> = const { Cell::new(true) };
}
pub struct SetPlacementScope {
previous: bool,
thread: PhantomData<Rc<()>>,
}
impl SetPlacementScope {
#[must_use]
pub fn stored_definition() -> Self {
Self::enter(false)
}
#[must_use]
pub fn compiled_source() -> Self {
Self::enter(true)
}
fn enter(placing: bool) -> Self {
Self {
previous: PLACING_SET_CALLS.replace(placing),
thread: PhantomData,
}
}
}
impl Drop for SetPlacementScope {
fn drop(&mut self) {
PLACING_SET_CALLS.set(self.previous);
}
}
pub fn placing_set_calls() -> bool {
PLACING_SET_CALLS.get()
}
#[cfg(test)]
mod tests {
use super::{placing_set_calls, SetPlacementScope};
#[test]
fn stored_definitions_place_no_set_returning_call_until_their_scope_ends() {
assert!(placing_set_calls());
let stored = SetPlacementScope::stored_definition();
assert!(!placing_set_calls());
{
let _source = SetPlacementScope::compiled_source();
assert!(placing_set_calls());
{
let _nested = SetPlacementScope::stored_definition();
assert!(!placing_set_calls());
}
assert!(placing_set_calls());
}
assert!(!placing_set_calls());
drop(stored);
assert!(placing_set_calls());
}
}