namba 0.1.0

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

/// A Namba operation result.
pub type Result<T> = core::result::Result<T, Error>;

/// Stable category for a failed operation.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ErrorKind {
    /// The input did not contain a phone number.
    NotANumber,
    /// The input contains a regional number but no default region.
    MissingRegion,
    /// Namba does not support the region.
    UnsupportedRegion,
    /// Namba does not support the calling code.
    UnsupportedCallingCode,
    /// The number is too short to interpret.
    TooShort,
    /// The number exceeds supported bounds.
    TooLong,
    /// Strict parsing rejected non-canonical input.
    NotCanonical,
}

/// A phone number error that omits input values.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Error {
    kind: ErrorKind,
}

impl Error {
    pub(crate) const fn new(kind: ErrorKind) -> Self {
        Self { kind }
    }

    /// Returns the stable error category.
    pub const fn kind(self) -> ErrorKind {
        self.kind
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let message = match self.kind {
            ErrorKind::NotANumber => "input is not a phone number",
            ErrorKind::MissingRegion => "a default region is required",
            ErrorKind::UnsupportedRegion => "unsupported region",
            ErrorKind::UnsupportedCallingCode => "unsupported calling code",
            ErrorKind::TooShort => "phone number is too short",
            ErrorKind::TooLong => "phone number is too long",
            ErrorKind::NotCanonical => "phone number is not in canonical E.164 or RFC 3966 form",
        };
        f.write_str(message)
    }
}

impl std::error::Error for Error {}