use std::{
collections::HashMap,
sync::{Arc, Mutex, OnceLock},
};
use crate::{ansi::Style, errors::RegistryError};
static REGISTRY: OnceLock<Mutex<HashMap<String, Arc<Style>>>> = OnceLock::new();
pub fn insert_style(name: impl Into<String>, style: Style) {
REGISTRY
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.unwrap()
.insert(name.into(), Arc::new(style));
}
pub fn set_prefix(name: impl Into<String>, prefix: impl Into<String>) -> Result<(), RegistryError> {
let name = name.into();
let prefix = prefix.into();
let mut map = REGISTRY
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.unwrap();
if let Some(style) = map.get_mut(&name) {
let s = Arc::make_mut(style);
s.prefix = Some(prefix);
Ok(())
} else {
Err(RegistryError::UnknownStyle(name))
}
}
pub(crate) fn search_registry(query: impl Into<String>) -> Result<Arc<Style>, RegistryError> {
let map = REGISTRY
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.unwrap();
let query = query.into();
match map.get(&query) {
Some(style) => Ok(Arc::clone(style)),
None => Err(RegistryError::UnknownStyle(query)),
}
}