namba 0.1.0

A fast, lightweight library for parsing, validating, and formatting phone numbers
Documentation
use core::{fmt, hash::Hash, str::FromStr};

use crate::{Assessment, Format, Formatted, Region};

/// An E.164 country calling code.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct CallingCode(u16);

impl CallingCode {
    /// Returns the numeric calling code without a leading plus sign.
    pub const fn value(self) -> u16 {
        self.0
    }
}

/// A phone extension, preserving leading zeroes.
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Extension(Box<str>);

impl Extension {
    pub(crate) fn new(value: String) -> Self {
        Self(value.into_boxed_str())
    }

    /// Returns the extension digits.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for Extension {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Debug for Extension {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Extension(**redacted**)")
    }
}

/// A structurally parsed global phone number.
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct PhoneNumber {
    pub(crate) calling_code: u16,
    pub(crate) national: Box<str>,
    pub(crate) extension: Option<Extension>,
}

impl PhoneNumber {
    /// Returns the E.164 calling code.
    pub fn calling_code(&self) -> CallingCode {
        CallingCode(self.calling_code)
    }

    /// Returns the national significant number.
    pub fn national_number(&self) -> &str {
        &self.national
    }

    /// Returns the extension, if present.
    pub fn extension(&self) -> Option<&Extension> {
        self.extension.as_ref()
    }

    /// Returns the most specific region that the bundled plans identify.
    pub fn region(&self) -> Option<Region> {
        let plan = crate::assessment::resolve(self)?;
        let region = Region::try_from(plan.region.as_str()).ok()?;
        (crate::assessment::classify(plan, &self.national) != crate::NumberKind::Unknown)
            .then_some(region)
    }

    /// Assesses length, validity, service category, regions, and dialing policy.
    pub fn assess(&self) -> Assessment {
        Assessment::new(self)
    }

    /// Returns whether this number is valid specifically for `region`.
    pub fn is_valid_for(&self, region: Region) -> bool {
        crate::assessment::is_valid_for(self, region)
    }

    /// Formats the number explicitly.
    pub fn format(&self, format: Format) -> Formatted<'_> {
        Formatted::new(self, format)
    }

    /// Compares two numbers using phone number semantics.
    pub fn match_with(&self, other: &Self) -> crate::Match {
        crate::matching::compare(self, other, crate::MatchOptions::default())
    }

    /// Compares two numbers using explicit matching policy.
    pub fn match_with_options(&self, other: &Self, options: crate::MatchOptions) -> crate::Match {
        crate::matching::compare(self, other, options)
    }
}

impl FromStr for PhoneNumber {
    type Err = crate::Error;

    fn from_str(value: &str) -> crate::Result<Self> {
        crate::parse(value)
    }
}

impl fmt::Debug for PhoneNumber {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PhoneNumber")
            .field("calling_code", &self.calling_code())
            .field("value", &"**redacted**")
            .field("has_extension", &self.extension().is_some())
            .finish()
    }
}

/// A parsed number with explicitly retained source text.
#[derive(Clone, Eq, PartialEq)]
pub struct ParsedNumber {
    number: PhoneNumber,
    source: Box<str>,
    default_region: Option<Region>,
}

impl fmt::Debug for ParsedNumber {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ParsedNumber")
            .field("number", &self.number)
            .field("source", &"**redacted**")
            .field("default_region", &self.default_region)
            .finish()
    }
}

impl ParsedNumber {
    /// Parses an international number while retaining its original text.
    pub fn parse(source: impl Into<String>) -> crate::Result<Self> {
        Self::parse_with(source.into(), None)
    }

    /// Parses a regional number while retaining its original text.
    pub fn parse_in(region: Region, source: impl Into<String>) -> crate::Result<Self> {
        Self::parse_with(source.into(), Some(region))
    }

    fn parse_with(source: String, default_region: Option<Region>) -> crate::Result<Self> {
        let number = match default_region {
            Some(region) => crate::parse_in(region, &source)?,
            None => crate::parse(&source)?,
        };
        Ok(Self {
            number,
            source: source.into_boxed_str(),
            default_region,
        })
    }

    /// Returns the interpreted number.
    pub const fn number(&self) -> &PhoneNumber {
        &self.number
    }

    /// Returns the sensitive source text that the caller chose to retain.
    pub fn source(&self) -> &str {
        &self.source
    }

    /// Returns the default region supplied for parsing.
    pub const fn default_region(&self) -> Option<Region> {
        self.default_region
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for PhoneNumber {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.format(Format::Rfc3966).to_string())
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for PhoneNumber {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
        crate::parse_strict(&value).map_err(serde::de::Error::custom)
    }
}