namba 0.1.0

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

use crate::{Format, PhoneNumber, Region};

const MAX_INPUT_DIGITS: usize = 15;
const MAX_EDITABLE_INPUT_BYTES: usize = 256;

/// Append-only phone number formatting for text fields.
#[derive(Clone)]
pub struct AsYouType {
    region: Region,
    input: String,
    output: String,
}

impl fmt::Debug for AsYouType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AsYouType")
            .field("region", &self.region)
            .field(
                "digits",
                &self.input.bytes().filter(u8::is_ascii_digit).count(),
            )
            .finish_non_exhaustive()
    }
}

impl AsYouType {
    /// Creates an empty formatter for a region.
    pub const fn new(region: Region) -> Self {
        Self {
            region,
            input: String::new(),
            output: String::new(),
        }
    }

    /// Appends a supported character and returns the formatted input.
    /// The formatter ignores other characters and characters after 15 digits.
    pub fn push(&mut self, character: char) -> &str {
        if let Some(digit) = crate::parse::decimal_digit(character) {
            let digits = self.input.bytes().filter(u8::is_ascii_digit).count();
            if digits < MAX_INPUT_DIGITS {
                self.input.push(char::from(b'0' + digit));
                self.reformat();
            }
        } else if crate::parse::is_plus_sign(character) && self.input.is_empty() {
            self.input.push('+');
            self.reformat();
        }
        &self.output
    }

    /// Clears all input and retained formatting state.
    pub fn clear(&mut self) {
        self.input.clear();
        self.output.clear();
    }

    /// Returns the normalized input entered so far.
    pub fn raw_input(&self) -> &str {
        &self.input
    }

    fn reformat(&mut self) {
        let format = if self.input.starts_with('+') {
            Format::International
        } else {
            Format::National
        };
        self.output = crate::parse_in(self.region, &self.input)
            .map(|number| number.format(format).to_string())
            .unwrap_or_else(|_| group_digits(&self.input));
    }
}

/// Result of formatting editable input with cursor preservation.
#[derive(Clone, Eq, PartialEq)]
pub struct FormattedEdit {
    /// Newly formatted text.
    text: String,
    /// Cursor byte offset in `text`.
    cursor: usize,
    /// Fully parsed number, when the text is complete enough.
    number: Option<PhoneNumber>,
}

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

impl FormattedEdit {
    /// Reformats edited text and maps a cursor by digit position.
    /// The formatter ignores input after the first 256 bytes. It stops at a
    /// UTF-8 boundary.
    pub fn new(region: Region, text: &str, cursor: usize) -> Self {
        let text = bounded_prefix(text, MAX_EDITABLE_INPUT_BYTES);
        let cursor = cursor.min(text.len());
        let digit_cursor = text
            .char_indices()
            .take_while(|(index, _)| *index < cursor)
            .map(|(_, character)| character)
            .filter(|character| crate::parse::decimal_digit(*character).is_some())
            .count();
        let number = crate::parse_in(region, text).ok();
        let format = if text
            .trim_start()
            .chars()
            .next()
            .is_some_and(crate::parse::is_plus_sign)
        {
            Format::International
        } else {
            Format::National
        };
        let formatted = number
            .as_ref()
            .map(|number| number.format(format).to_string())
            .unwrap_or_else(|| group_digits(text));
        let cursor = cursor_after_digits(&formatted, digit_cursor);
        Self {
            text: formatted,
            cursor,
            number,
        }
    }

    /// Returns the formatted text.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the cursor byte offset in the formatted text.
    pub const fn cursor(&self) -> usize {
        self.cursor
    }

    /// Returns the parsed number when the text contains a complete number.
    pub const fn number(&self) -> Option<&PhoneNumber> {
        self.number.as_ref()
    }
}

fn bounded_prefix(input: &str, max_bytes: usize) -> &str {
    if input.len() <= max_bytes {
        return input;
    }
    let mut end = max_bytes;
    while !input.is_char_boundary(end) {
        end -= 1;
    }
    &input[..end]
}

fn group_digits(input: &str) -> String {
    let mut output = String::new();
    let mut digits = 0;
    for character in input.chars() {
        let character = if let Some(digit) = crate::parse::decimal_digit(character) {
            if digits == MAX_INPUT_DIGITS {
                break;
            }
            digits += 1;
            char::from(b'0' + digit)
        } else if crate::parse::is_plus_sign(character) && output.is_empty() {
            '+'
        } else {
            continue;
        };
        if digits > 1 && (digits - 1).is_multiple_of(3) {
            output.push(' ');
        }
        output.push(character);
    }
    output
}

fn cursor_after_digits(text: &str, digits: usize) -> usize {
    if digits == 0 {
        return 0;
    }
    text.char_indices()
        .filter(|(_, c)| c.is_ascii_digit())
        .nth(digits.saturating_sub(1))
        .map_or(text.len(), |(index, character)| {
            index + character.len_utf8()
        })
}