namba 0.1.0

A fast, lightweight library for parsing, validating, and formatting phone numbers
Documentation
use std::{
    collections::HashMap,
    sync::{LazyLock, RwLock},
};

use regex::Regex;

// Bundled plans own every key, so caller input cannot grow these caches.
static FULL_PATTERNS: LazyLock<RwLock<HashMap<&'static str, Regex>>> =
    LazyLock::new(|| RwLock::new(HashMap::new()));
static PREFIX_PATTERNS: LazyLock<RwLock<HashMap<&'static str, Regex>>> =
    LazyLock::new(|| RwLock::new(HashMap::new()));

pub(crate) fn full_match(pattern: &'static str, value: &str) -> bool {
    compiled(&FULL_PATTERNS, pattern, |pattern| {
        format!("^(?:{pattern})$")
    })
    .is_some_and(|expression| expression.is_match(value))
}

pub(crate) fn prefix_match(pattern: &'static str, value: &str) -> bool {
    compiled(&PREFIX_PATTERNS, pattern, |pattern| {
        format!("^(?:{pattern})")
    })
    .is_some_and(|expression| expression.is_match(value))
}

pub(crate) fn full_expression(pattern: &'static str) -> Option<Regex> {
    compiled(&FULL_PATTERNS, pattern, |pattern| {
        format!("^(?:{pattern})$")
    })
}

pub(crate) fn prefix_expression(pattern: &'static str) -> Option<Regex> {
    compiled(&PREFIX_PATTERNS, pattern, |pattern| {
        format!("^(?:{pattern})")
    })
}

fn compiled(
    cache: &RwLock<HashMap<&'static str, Regex>>,
    pattern: &'static str,
    source: impl FnOnce(&str) -> String,
) -> Option<Regex> {
    if pattern.is_empty() {
        return None;
    }
    let entries = cache
        .read()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if let Some(expression) = entries.get(pattern) {
        return Some(expression.clone());
    }
    drop(entries);

    let expression = Regex::new(&source(pattern)).expect("generated patterns must compile");
    cache
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .entry(pattern)
        .or_insert_with(|| expression.clone());
    Some(expression)
}