use core::fmt;
use crate::{Format, PhoneNumber, Region};
const MAX_INPUT_DIGITS: usize = 15;
const MAX_EDITABLE_INPUT_BYTES: usize = 256;
#[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 {
pub const fn new(region: Region) -> Self {
Self {
region,
input: String::new(),
output: String::new(),
}
}
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
}
pub fn clear(&mut self) {
self.input.clear();
self.output.clear();
}
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));
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct FormattedEdit {
text: String,
cursor: usize,
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 {
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,
}
}
pub fn text(&self) -> &str {
&self.text
}
pub const fn cursor(&self) -> usize {
self.cursor
}
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()
})
}