namba 0.1.0

A fast, lightweight library for parsing, validating, and formatting phone numbers
Documentation
use crate::PhoneNumber;

/// Semantic relationship between two phone numbers.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Match {
    /// Calling code, national number, and extension agree.
    Exact,
    /// Calling code and national number agree but extensions differ.
    SameNumber,
    /// One national number is a plausible suffix of the other.
    ShortNational,
    /// The phone numbers differ.
    None,
}

/// Options for semantic comparison.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct MatchOptions {
    /// Whether extensions participate in exact matching.
    compare_extensions: bool,
}

impl MatchOptions {
    /// Creates the default comparison policy.
    pub const fn new() -> Self {
        Self {
            compare_extensions: true,
        }
    }

    /// Sets whether extensions participate in exact matching.
    pub const fn with_extensions(mut self, compare: bool) -> Self {
        self.compare_extensions = compare;
        self
    }
}

impl Default for MatchOptions {
    fn default() -> Self {
        Self::new()
    }
}

/// Compares two parsed phone numbers.
pub(crate) fn compare(left: &PhoneNumber, right: &PhoneNumber, options: MatchOptions) -> Match {
    if left.calling_code() == right.calling_code()
        && left.national_number() == right.national_number()
    {
        if !options.compare_extensions || left.extension() == right.extension() {
            Match::Exact
        } else {
            Match::SameNumber
        }
    } else if left.calling_code() == right.calling_code()
        && suffix_match(left.national_number(), right.national_number())
    {
        Match::ShortNational
    } else {
        Match::None
    }
}

fn suffix_match(left: &str, right: &str) -> bool {
    let shortest = left.len().min(right.len());
    shortest >= 7 && (left.ends_with(right) || right.ends_with(left))
}