namba 0.1.0

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

use crate::{Error, ErrorKind, Region, Result};

/// A region-scoped short number such as an emergency or service code.
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct ShortNumber {
    region: Region,
    digits: Box<str>,
}

impl ShortNumber {
    /// Parses a short number without treating it as a global E.164 number.
    ///
    /// Input is limited to 32 UTF-8 bytes and 10 digits.
    pub fn parse(region: Region, input: &str) -> Result<Self> {
        if input.len() > 32 {
            return Err(Error::new(ErrorKind::TooLong));
        }
        let mut digits = String::new();
        for character in input.chars() {
            if let Some(digit) = crate::parse::decimal_digit(character) {
                digits.push(char::from(b'0' + digit));
            } else if !matches!(character, ' ' | '-' | '(' | ')') {
                return Err(Error::new(ErrorKind::NotANumber));
            }
        }
        if digits.len() < 2 {
            return Err(Error::new(ErrorKind::TooShort));
        }
        if digits.len() > 10 {
            return Err(Error::new(ErrorKind::TooLong));
        }
        Ok(Self {
            region,
            digits: digits.into_boxed_str(),
        })
    }

    /// Returns the region in which the short number is interpreted.
    pub const fn region(&self) -> Region {
        self.region
    }

    /// Returns the normalized short digits.
    pub fn digits(&self) -> &str {
        &self.digits
    }

    /// Returns the number's relationship to an emergency code.
    pub fn emergency_match(&self) -> EmergencyMatch {
        let Some(plan) = crate::plans::short(self.region.as_str()) else {
            return EmergencyMatch::None;
        };
        // Brazil, Chile, and Nicaragua require an exact emergency code.
        if plan.emergency.matches(&self.digits) {
            EmergencyMatch::Exact
        } else if !matches!(self.region.as_str(), "BR" | "CL" | "NI")
            && crate::pattern::prefix_match(&plan.emergency.pattern, &self.digits)
        {
            EmergencyMatch::Connects
        } else {
            EmergencyMatch::None
        }
    }

    /// Returns whether the digits match a valid short-code pattern.
    pub fn is_valid(&self) -> bool {
        crate::plans::short(self.region.as_str()).is_some_and(|plan| {
            plan.general.matches(&self.digits) && plan.short_code.matches(&self.digits)
        })
    }

    /// Returns whether the length is plausible for a short number in the region.
    pub fn is_possible(&self) -> bool {
        crate::plans::short(self.region.as_str()).is_some_and(|plan| {
            plan.general.possible_lengths.is_empty()
                || plan.general.contains_length(self.digits.len())
        })
    }

    /// Returns whether the short number is specific to a carrier.
    pub fn is_carrier_specific(&self) -> bool {
        crate::plans::short(self.region.as_str())
            .is_some_and(|plan| plan.carrier_specific.matches(&self.digits))
    }

    /// Returns whether the short code identifies an SMS service.
    pub fn is_sms_service(&self) -> bool {
        crate::plans::short(self.region.as_str())
            .is_some_and(|plan| plan.sms_services.matches(&self.digits))
    }
}

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

/// Relationship between short digits and an emergency service code.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum EmergencyMatch {
    /// The digits exactly match an emergency code.
    Exact,
    /// The digits start with an emergency code and can connect in this region.
    Connects,
    /// The digits do not match an emergency code.
    None,
}