namba 0.1.0

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

use crate::{PhoneNumber, Region};

/// Confidence in a phone number found in text.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Confidence {
    /// The candidate matches a bundled numbering plan.
    Valid,
    /// The candidate has a plausible length but no valid numbering pattern.
    Possible,
}

/// Bounds and policy for extracting numbers from text.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct FindOptions {
    /// Region used for candidates without a calling code.
    default_region: Option<Region>,
    /// Maximum results returned from one input.
    max_results: usize,
    /// Whether to return candidates that are only possible.
    include_possible: bool,
}

impl FindOptions {
    /// Creates the default extraction policy.
    pub const fn new() -> Self {
        Self {
            default_region: None,
            max_results: 32,
            include_possible: false,
        }
    }

    /// Uses `region` for candidates without a calling code.
    pub const fn with_default_region(mut self, region: Region) -> Self {
        self.default_region = Some(region);
        self
    }

    /// Sets the maximum number of returned results.
    pub const fn with_max_results(mut self, max_results: usize) -> Self {
        self.max_results = max_results;
        self
    }

    /// Includes candidates with a plausible length but no valid pattern.
    pub const fn with_possible(mut self, include: bool) -> Self {
        self.include_possible = include;
        self
    }
}

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

/// A phone number and its byte range in source text.
#[derive(Clone, Eq, PartialEq)]
pub struct FoundNumber<'a> {
    /// Byte range occupied by the source candidate.
    range: Range<usize>,
    /// Source text for the candidate.
    source: &'a str,
    /// The interpreted number.
    number: PhoneNumber,
    /// The extraction confidence.
    confidence: Confidence,
}

impl<'a> FoundNumber<'a> {
    /// Returns the byte range occupied by the source candidate.
    pub fn range(&self) -> Range<usize> {
        self.range.clone()
    }

    /// Returns the source text for the candidate.
    pub const fn source(&self) -> &'a str {
        self.source
    }

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

    /// Returns the extraction confidence.
    pub const fn confidence(&self) -> Confidence {
        self.confidence
    }
}

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

/// Lazy, bounded phone number extraction from text.
pub struct FoundNumbers<'a> {
    text: &'a str,
    options: FindOptions,
    cursor: usize,
    yielded: usize,
}

impl<'a> FoundNumbers<'a> {
    /// Creates a bounded iterator over phone number candidates in `text`.
    ///
    /// The iterator examines at most 128 UTF-8 bytes for each candidate.
    pub const fn new(text: &'a str, options: FindOptions) -> Self {
        Self {
            text,
            options,
            cursor: 0,
            yielded: 0,
        }
    }
}

impl<'a> Iterator for FoundNumbers<'a> {
    type Item = FoundNumber<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        while self.cursor < self.text.len() && self.yielded < self.options.max_results {
            let start = next_candidate_start(self.text, self.cursor)?;
            let (end, truncated) = candidate_end(self.text, start);
            if truncated {
                self.cursor = skip_candidate(self.text, end);
                continue;
            }
            self.cursor = if end > start {
                end
            } else {
                start + self.text[start..].chars().next().map_or(1, char::len_utf8)
            };
            let source = self.text[start..end]
                .trim_end()
                .trim_end_matches(['.', ',', ';', ':']);
            let end = start + source.len();
            let parsed = match self.options.default_region {
                Some(region) => crate::parse_in(region, source),
                None => crate::parse(source),
            };
            if let Ok(number) = parsed {
                let valid = crate::assessment::is_valid(&number);
                let possible = matches!(
                    crate::assessment::possibility(&number),
                    crate::Possibility::Possible | crate::Possibility::LocalOnly
                );
                if valid || (self.options.include_possible && possible) {
                    self.yielded += 1;
                    return Some(FoundNumber {
                        range: start..end,
                        source,
                        confidence: if valid {
                            Confidence::Valid
                        } else {
                            Confidence::Possible
                        },
                        number,
                    });
                }
            }
        }
        None
    }
}

impl std::iter::FusedIterator for FoundNumbers<'_> {}

fn next_candidate_start(text: &str, from: usize) -> Option<usize> {
    text[from..]
        .char_indices()
        .find(|(_, character)| {
            crate::parse::is_plus_sign(*character)
                || crate::parse::decimal_digit(*character).is_some()
        })
        .map(|(offset, _)| from + offset)
}

fn candidate_end(text: &str, start: usize) -> (usize, bool) {
    const MAX_CANDIDATE_BYTES: usize = 128;
    let mut end = start;
    let mut digits = 0;
    for (offset, character) in text[start..].char_indices() {
        if crate::parse::decimal_digit(character).is_some() {
            digits += 1;
        }
        if character.is_ascii_alphabetic()
            && digits >= 7
            && text[start..start + offset]
                .chars()
                .next_back()
                .is_some_and(char::is_whitespace)
            && !starts_with_extension(&text[start + offset..])
        {
            break;
        }
        if !is_candidate_character(character) {
            break;
        }
        if offset + character.len_utf8() > MAX_CANDIDATE_BYTES {
            return (end, true);
        }
        end = start + offset + character.len_utf8();
    }
    (end, false)
}

fn skip_candidate(text: &str, from: usize) -> usize {
    text[from..]
        .char_indices()
        .find(|(_, character)| !is_candidate_character(*character))
        .map_or(text.len(), |(offset, _)| from + offset)
}

fn is_candidate_character(character: char) -> bool {
    character.is_ascii_alphabetic()
        || crate::parse::decimal_digit(character).is_some()
        || crate::parse::is_plus_sign(character)
        || matches!(character, '-' | '(' | ')' | '.' | ' ' | '#' | ';' | '=')
}

fn starts_with_extension(text: &str) -> bool {
    text.get(..3)
        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("ext"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn candidate_limit_counts_utf8_bytes() {
        let text = "реп".repeat(100);
        let (end, truncated) = candidate_end(&text, 0);
        assert!(truncated);
        assert!(end <= 128);
        assert!(text.is_char_boundary(end));
    }

    #[test]
    fn oversized_candidates_do_not_yield_valid_suffixes() {
        let text = format!("{}6502530000, +44 20 7946 0018", "1".repeat(130));
        let found = FoundNumbers::new(&text, FindOptions::default())
            .next()
            .expect("number after oversized candidate");
        assert_eq!(found.source(), "+44 20 7946 0018");
    }
}