use std::collections::HashMap;
use std::sync::{Arc, Mutex};
pub use trilean_json_shape_pattern::{Pattern, PatternError, json_quote};
static SHARED: Mutex<Option<HashMap<String, Compiled>>> = Mutex::new(None);
pub type Compiled = Result<Arc<Pattern>, PatternError>;
#[cfg(test)]
static COMPILATIONS: Mutex<Option<HashMap<String, usize>>> = Mutex::new(None);
#[cfg(test)]
pub fn compilations_of(source: &str) -> usize {
COMPILATIONS.lock().map_or(0, |counts| {
counts
.as_ref()
.and_then(|counts| counts.get(source).copied())
.unwrap_or(0)
})
}
pub fn shared(source: &str) -> Compiled {
let mut shared = SHARED
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
shared
.get_or_insert_with(HashMap::new)
.entry(source.to_owned())
.or_insert_with(|| {
#[cfg(test)]
if let Ok(mut counts) = COMPILATIONS.lock() {
*counts
.get_or_insert_with(HashMap::new)
.entry(source.to_owned())
.or_insert(0) += 1;
}
Pattern::new(source).map(Arc::new)
})
.clone()
}