use std::cell::RefCell;
use std::collections::BTreeMap;
use std::sync::Arc;
use crate::Value;
thread_local! {
static AUTO_LITERALS: RefCell<Option<Arc<BTreeMap<String, Value>>>> = const { RefCell::new(None) };
}
pub struct AutoLiteralGuard {
prev: Option<Arc<BTreeMap<String, Value>>>,
}
impl AutoLiteralGuard {
pub fn install(params: &BTreeMap<String, Value>) -> Self {
let next = params
.keys()
.any(|name| name.starts_with("__AUTO_"))
.then(|| Arc::new(params.clone()));
let prev = AUTO_LITERALS.with(|slot| slot.replace(next));
Self { prev }
}
}
impl Drop for AutoLiteralGuard {
fn drop(&mut self) {
let prev = self.prev.take();
AUTO_LITERALS.with(|slot| *slot.borrow_mut() = prev);
}
}
pub fn auto_literal(name: &str) -> Option<Value> {
if !name.starts_with("__AUTO_") {
return None;
}
AUTO_LITERALS.with(|slot| {
slot.borrow()
.as_ref()
.and_then(|map| map.get(name).cloned())
})
}