use std::cell::RefCell;
use std::collections::BTreeMap;
use crate::Diagnostic;
use crate::Error;
use crate::kv::Key;
use crate::kv::Value;
use crate::kv::Visitor;
thread_local! {
static THREAD_LOCAL_MAP: RefCell<BTreeMap<String, String>> = const { RefCell::new(BTreeMap::new()) };
}
#[derive(Default, Debug, Clone, Copy)]
#[non_exhaustive]
pub struct ThreadLocalDiagnostic {}
impl ThreadLocalDiagnostic {
pub fn insert<K, V>(key: K, value: V)
where
K: Into<String>,
V: Into<String>,
{
THREAD_LOCAL_MAP.with(|map| {
map.borrow_mut().insert(key.into(), value.into());
});
}
pub fn remove(key: &str) {
THREAD_LOCAL_MAP.with(|map| {
map.borrow_mut().remove(key);
});
}
}
impl Diagnostic for ThreadLocalDiagnostic {
fn visit(&self, visitor: &mut dyn Visitor) -> Result<(), Error> {
THREAD_LOCAL_MAP.with(|map| {
let map = map.borrow();
for (key, value) in map.iter() {
let key = Key::new_ref(key.as_str());
let value = Value::from(value);
visitor.visit(key, value)?;
}
Ok(())
})
}
}