namba 0.1.0

A fast, lightweight library for parsing, validating, and formatting phone numbers
Documentation
mod binary;
mod schema;

use std::{collections::HashMap, sync::LazyLock};

pub(crate) use schema::{FormatRule, Plan, Rule, ShortPlan};

const PLAN_BYTES: &[u8] = include_bytes!("plans/artifacts/numbers.bin");
const SHORT_PLAN_BYTES: &[u8] = include_bytes!("plans/artifacts/short_numbers.bin");

static ALL: LazyLock<Box<[Plan]>> =
    LazyLock::new(|| decode::<Vec<_>>(PLAN_BYTES, binary::PLAN_TAG).into_boxed_slice());
static SHORT: LazyLock<Box<[ShortPlan]>> =
    LazyLock::new(|| decode::<Vec<_>>(SHORT_PLAN_BYTES, binary::SHORT_PLAN_TAG).into_boxed_slice());

fn decode<T: serde::de::DeserializeOwned>(bytes: &[u8], tag: u8) -> T {
    assert!(
        bytes.starts_with(binary::MAGIC) && bytes.get(binary::MAGIC.len()) == Some(&tag),
        "invalid Namba plan header"
    );
    postcard::from_bytes(&bytes[binary::MAGIC.len() + 1..])
        .expect("generated Namba plans must decode")
}

static BY_REGION: LazyLock<HashMap<&'static str, usize>> = LazyLock::new(|| {
    ALL.iter()
        .enumerate()
        .map(|(index, plan)| (plan.region.as_str(), index))
        .collect()
});

static SHORT_BY_REGION: LazyLock<HashMap<&'static str, usize>> = LazyLock::new(|| {
    SHORT
        .iter()
        .enumerate()
        .map(|(index, plan)| (plan.region.as_str(), index))
        .collect()
});

static BY_CALLING_CODE: LazyLock<HashMap<u16, Box<[usize]>>> = LazyLock::new(|| {
    let mut index: HashMap<u16, Vec<usize>> = HashMap::new();
    for (position, plan) in ALL.iter().enumerate() {
        let entries = index.entry(plan.calling_code).or_default();
        if plan.primary {
            entries.insert(0, position);
        } else {
            entries.push(position);
        }
    }
    index
        .into_iter()
        .map(|(code, entries)| (code, entries.into_boxed_slice()))
        .collect()
});

static REGIONS_BY_CALLING_CODE: LazyLock<HashMap<u16, Box<[crate::Region]>>> =
    LazyLock::new(|| {
        BY_CALLING_CODE
            .iter()
            .map(|(code, indexes)| {
                let regions = indexes
                    .iter()
                    .filter_map(|index| crate::Region::try_from(ALL[*index].region.as_str()).ok())
                    .collect::<Vec<_>>()
                    .into_boxed_slice();
                (*code, regions)
            })
            .collect()
    });

pub(crate) fn by_region(region: &str) -> Option<&'static Plan> {
    BY_REGION.get(region).map(|index| &ALL[*index])
}

pub(crate) fn by_calling_code(calling_code: u16) -> impl Iterator<Item = &'static Plan> + Clone {
    BY_CALLING_CODE
        .get(&calling_code)
        .into_iter()
        .flatten()
        .map(|index| &ALL[*index])
}

pub(crate) fn regions(calling_code: u16) -> &'static [crate::Region] {
    REGIONS_BY_CALLING_CODE
        .get(&calling_code)
        .map_or(&[], AsRef::as_ref)
}

pub(crate) fn primary(calling_code: u16) -> Option<&'static Plan> {
    by_calling_code(calling_code).next()
}

pub(crate) fn calling_code(region: &str) -> Option<u16> {
    by_region(region).map(|plan| plan.calling_code)
}

pub(crate) fn short(region: &str) -> Option<&'static ShortPlan> {
    SHORT_BY_REGION.get(region).map(|index| &SHORT[*index])
}

impl Rule {
    pub(crate) fn matches(&'static self, value: &str) -> bool {
        (self.possible_lengths.is_empty() || self.contains_length(value.len()))
            && crate::pattern::full_match(&self.pattern, value)
    }

    pub(crate) fn contains_length(&self, length: usize) -> bool {
        contains(&self.possible_lengths, length)
    }

    pub(crate) fn contains_local_length(&self, length: usize) -> bool {
        contains(&self.local_only_lengths, length)
    }
}

fn contains(lengths: &[u8], length: usize) -> bool {
    u8::try_from(length).is_ok_and(|length| lengths.contains(&length))
}

#[cfg(test)]
pub(crate) fn all() -> &'static [Plan] {
    &ALL
}

#[cfg(test)]
pub(crate) fn all_short() -> &'static [ShortPlan] {
    &SHORT
}