Skip to main content

farben_core/
registry.rs

1use std::{
2    collections::HashMap,
3    sync::{Mutex, OnceLock},
4};
5
6use crate::ansi::Style;
7use crate::errors::LexError;
8
9static REGISTRY: OnceLock<Mutex<HashMap<String, Style>>> = OnceLock::new();
10
11pub fn insert_style(name: impl Into<String>, style: Style) {
12    REGISTRY
13        .get_or_init(|| Mutex::new(HashMap::new()))
14        .lock()
15        .unwrap()
16        .insert(name.into(), style);
17}
18
19pub(crate) fn search_registry(query: impl Into<String>) -> Result<Style, LexError> {
20    let map = REGISTRY
21        .get_or_init(|| Mutex::new(HashMap::new()))
22        .lock()
23        .unwrap();
24    let query = query.into();
25    match map.get(&query) {
26        Some(style) => Ok(style.clone()),
27        None => Err(LexError::InvalidTag(query)),
28    }
29}
30
31#[macro_export]
32macro_rules! style {
33    ($name:expr, $markup:expr) => {
34        farben_core::registry::insert_style(
35            $name,
36            farben_core::ansi::Style::parse($markup).unwrap(),
37        );
38    };
39}