use super::phone_data::{CALLING_CODES, COUNTRIES, NON_GEOGRAPHIC, REGIONS};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PhoneInputCountry {
pub region_code: &'static str,
pub calling_code: &'static str,
pub display_name: &'static str,
}
impl PhoneInputCountry {
pub fn all() -> &'static [PhoneInputCountry] {
COUNTRIES
}
pub fn find(region_or_calling_code: &str) -> Option<PhoneInputCountry> {
let query = region_or_calling_code.trim();
let calling_code = query.strip_prefix('+').unwrap_or(query);
if !calling_code.is_empty() && calling_code.bytes().all(|byte| byte.is_ascii_digit()) {
let main_region = regions_for_calling_code(calling_code)?.first()?;
return country_for_region(main_region);
}
COUNTRIES
.iter()
.find(|country| country.region_code.eq_ignore_ascii_case(query))
.copied()
}
pub fn flag(&self) -> String {
flag_for_region(self.region_code)
}
pub fn picker_label(&self) -> String {
format!(
"{} {} ({})",
self.flag(),
self.display_name,
self.calling_code
)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PhoneInputNumber {
pub country: PhoneInputCountry,
pub e164: Option<String>,
pub is_valid: bool,
pub national_number: String,
}
impl PhoneInputNumber {
pub fn empty(country: PhoneInputCountry) -> Self {
Self {
country,
e164: None,
is_valid: false,
national_number: String::new(),
}
}
pub fn resolve(country: PhoneInputCountry, input: &str) -> Self {
let normalized = sanitize_phone_input(input);
if normalized.is_empty() || normalized == "+" {
return Self::empty(country);
}
let international = normalized.starts_with('+');
let default_region = if international {
None
} else {
region_by_code(country.region_code)
};
let mut typing = AsYouType::new(default_region);
let formatted_input = typing.input(&normalized);
let parsed = typing.number();
let valid = parsed.as_ref().is_some_and(ParsedNumber::is_valid);
let resolved_country = if international {
parsed
.as_ref()
.and_then(|number| number.region)
.and_then(|region| country_for_region(region.code()))
.unwrap_or(country)
} else {
country
};
match parsed.filter(|_| valid) {
Some(number) => Self {
country: resolved_country,
e164: Some(number.e164()),
is_valid: true,
national_number: if international {
number.format_national()
} else {
formatted_input
},
},
None => Self {
country: resolved_country,
e164: None,
is_valid: false,
national_number: formatted_input,
},
}
}
pub fn display(&self) -> String {
match (&self.e164, self.is_valid) {
(Some(e164), true) => e164.clone(),
_ => self.national_number.clone(),
}
}
}
pub(crate) fn sanitize_phone_input(input: &str) -> String {
let mut normalized = String::new();
for character in input.chars() {
if character.is_ascii_digit() || (character == '+' && normalized.is_empty()) {
normalized.push(character);
}
}
normalized
}
pub(crate) fn flag_for_region(region: &str) -> String {
const REGIONAL_INDICATOR_A: u32 = 0x1F1E6;
let normalized = region.to_uppercase();
if normalized.len() != 2 || !normalized.bytes().all(|byte| byte.is_ascii_uppercase()) {
return String::new();
}
normalized
.bytes()
.filter_map(|letter| char::from_u32(REGIONAL_INDICATOR_A + u32::from(letter - b'A')))
.collect()
}
pub(crate) struct PhoneRegion(
pub(crate) &'static str,
pub(crate) &'static str,
pub(crate) &'static str,
pub(crate) &'static str,
pub(crate) &'static [u8],
pub(crate) &'static str,
pub(crate) &'static str,
pub(crate) &'static str,
pub(crate) &'static str,
pub(crate) &'static [PhoneFormat],
pub(crate) &'static [&'static str],
);
pub(crate) struct PhoneFormat(
pub(crate) &'static str,
pub(crate) &'static str,
pub(crate) &'static [&'static str],
pub(crate) &'static str,
pub(crate) bool,
pub(crate) &'static str,
);
impl PhoneRegion {
fn code(&self) -> &'static str {
self.0
}
fn calling_code(&self) -> &'static str {
self.1
}
fn idd_prefix(&self) -> &'static str {
self.2
}
fn national_pattern(&self) -> &'static str {
self.3
}
fn possible_lengths(&self) -> &'static [u8] {
self.4
}
fn national_prefix(&self) -> &'static str {
self.5
}
fn own_national_prefix_for_parsing(&self) -> &'static str {
self.6
}
fn national_prefix_for_parsing(&self) -> &'static str {
if self.6.is_empty() { self.5 } else { self.6 }
}
fn national_prefix_transform_rule(&self) -> &'static str {
self.7
}
fn leading_digits(&self) -> &'static str {
self.8
}
fn formats(&self) -> &'static [PhoneFormat] {
if !self.9.is_empty() {
return self.9;
}
match regions_for_calling_code(self.calling_code())
.and_then(|regions| regions.first())
.and_then(|main| region_by_code(main))
{
Some(main) => main.9,
None => &[],
}
}
fn is_valid_number(&self, national_number: &str) -> bool {
pattern::matches_entirely(national_number, self.national_pattern())
&& (self.10.is_empty()
|| self
.10
.iter()
.any(|type_pattern| pattern::matches_entirely(national_number, type_pattern)))
}
fn check_number_length(&self, national_number: &str) -> NumberLength {
let lengths = self.possible_lengths();
let actual = national_number.len();
let (Some(&minimum), Some(&maximum)) = (lengths.first(), lengths.last()) else {
return NumberLength::Possible;
};
if usize::from(minimum) == actual {
NumberLength::Possible
} else if usize::from(minimum) > actual {
NumberLength::TooShort
} else if usize::from(maximum) < actual {
NumberLength::TooLong
} else if lengths
.iter()
.skip(1)
.any(|&length| usize::from(length) == actual)
{
NumberLength::Possible
} else {
NumberLength::InvalidLength
}
}
}
impl PhoneFormat {
fn pattern(&self) -> &'static str {
self.0
}
fn template(&self) -> &'static str {
self.1
}
fn leading_digits(&self) -> &'static [&'static str] {
self.2
}
fn national_prefix_formatting_rule(&self) -> &'static str {
self.3
}
fn national_prefix_is_optional(&self) -> bool {
self.4
}
fn international_template(&self) -> &'static str {
if self.5.is_empty() { self.1 } else { self.5 }
}
fn uses_national_prefix(&self) -> bool {
let rule = self.national_prefix_formatting_rule();
!rule.is_empty() && !matches!(rule, "$1" | "($1" | "$1)" | "($1)")
}
fn national_prefix_is_mandatory(&self) -> bool {
self.uses_national_prefix() && !self.national_prefix_is_optional()
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum NumberLength {
Possible,
TooShort,
TooLong,
InvalidLength,
}
fn region_by_code(code: &str) -> Option<&'static PhoneRegion> {
REGIONS
.binary_search_by(|region| region.code().cmp(code))
.ok()
.and_then(|index| REGIONS.get(index))
}
fn country_for_region(code: &str) -> Option<PhoneInputCountry> {
COUNTRIES
.iter()
.find(|country| country.region_code == code)
.copied()
}
fn regions_for_calling_code(calling_code: &str) -> Option<&'static [&'static str]> {
CALLING_CODES
.binary_search_by(|(code, _)| (*code).cmp(calling_code))
.ok()
.and_then(|index| CALLING_CODES.get(index))
.map(|(_, regions)| *regions)
}
fn non_geographic_plan(calling_code: &str) -> Option<&'static PhoneRegion> {
NON_GEOGRAPHIC
.binary_search_by(|region| region.calling_code().cmp(calling_code))
.ok()
.and_then(|index| NON_GEOGRAPHIC.get(index))
}
fn plan_for_calling_code(calling_code: &str) -> Option<&'static PhoneRegion> {
match regions_for_calling_code(calling_code) {
Some(regions) => regions.first().and_then(|main| region_by_code(main)),
None => non_geographic_plan(calling_code),
}
}
fn known_calling_code(calling_code: &str) -> Option<&'static str> {
if let Ok(index) = CALLING_CODES.binary_search_by(|(code, _)| (*code).cmp(calling_code)) {
return CALLING_CODES.get(index).map(|(code, _)| *code);
}
non_geographic_plan(calling_code).map(PhoneRegion::calling_code)
}
fn region_by_national_number(
national_number: &str,
region_codes: &[&str],
) -> Option<&'static PhoneRegion> {
region_codes
.iter()
.filter_map(|code| region_by_code(code))
.find(|region| {
if region.leading_digits().is_empty() {
region.is_valid_number(national_number)
} else {
!national_number.is_empty()
&& pattern::matches_at_start(national_number, region.leading_digits())
}
})
}
fn region_by_calling_code(
calling_code: &str,
national_number: &str,
) -> Option<&'static PhoneRegion> {
let regions = regions_for_calling_code(calling_code)?;
if let [only] = regions {
return region_by_code(only);
}
region_by_national_number(national_number, regions)
}
fn same_region(left: Option<&PhoneRegion>, right: Option<&PhoneRegion>) -> bool {
match (left, right) {
(Some(left), Some(right)) => left.code() == right.code(),
(None, None) => true,
_ => false,
}
}
fn same_format(left: &PhoneFormat, right: &PhoneFormat) -> bool {
std::ptr::eq(left, right)
}
struct ParsedNumber {
region: Option<&'static PhoneRegion>,
calling_code: &'static str,
national_number: String,
}
impl ParsedNumber {
fn plan(&self) -> Option<&'static PhoneRegion> {
self.region
.or_else(|| plan_for_calling_code(self.calling_code))
}
fn is_valid(&self) -> bool {
self.plan()
.is_some_and(|plan| plan.is_valid_number(&self.national_number))
}
fn e164(&self) -> String {
format!("+{}{}", self.calling_code, self.national_number)
}
fn format_national(&self) -> String {
let number = self.national_number.as_str();
let Some(plan) = self.plan() else {
return number.to_owned();
};
let format = plan.formats().iter().find(|format| {
format
.leading_digits()
.last()
.is_none_or(|leading| pattern::matches_at_start(number, leading))
&& pattern::matches_entirely(number, format.pattern())
});
match format {
Some(format) => format_with_pattern(number, format, false, true),
None => number.to_owned(),
}
}
}
fn format_with_pattern(
number: &str,
format: &PhoneFormat,
international: bool,
with_national_prefix: bool,
) -> String {
let rule = format.national_prefix_formatting_rule();
let template = if international {
format.international_template().to_owned()
} else if with_national_prefix && !rule.is_empty() {
replace_first_group_reference(format.template(), rule)
} else {
format.template().to_owned()
};
let formatted = pattern::replace_first(format.pattern(), number, &template);
if international {
apply_international_separator_style(&formatted)
} else {
formatted
}
}
fn replace_first_group_reference(template: &str, rule: &str) -> String {
let bytes = template.as_bytes();
let Some(index) = bytes
.windows(2)
.position(|pair| pair[0] == b'$' && pair[1].is_ascii_digit())
else {
return template.to_owned();
};
let reference = &template[index..index + 2];
let captures = [Some((index, index + 2)), Some((index, index + 2))];
format!(
"{}{}{}",
&template[..index],
pattern::expand_replacement(rule, template, &captures),
&template[index + reference.len()..]
)
}
fn is_valid_punctuation(character: char) -> bool {
matches!(
character,
'-' | '\u{2010}'
..='\u{2015}'
| '\u{2212}'
| '\u{30FC}'
| '\u{FF0D}'
| '\u{FF0F}'
| '/'
| '\u{FF0E}'
| '.'
| ' '
| '\u{00A0}'
| '\u{00AD}'
| '\u{200B}'
| '\u{2060}'
| '\u{3000}'
| '('
| ')'
| '\u{FF08}'
| '\u{FF09}'
| '\u{FF3B}'
| '\u{FF3D}'
| '['
| ']'
| '~'
| '\u{2053}'
| '\u{223C}'
| '\u{FF5E}'
)
}
fn apply_international_separator_style(formatted: &str) -> String {
let mut output = String::with_capacity(formatted.len());
let mut in_punctuation = false;
for character in formatted.chars() {
if is_valid_punctuation(character) {
if !in_punctuation {
output.push(' ');
}
in_punctuation = true;
} else {
output.push(character);
in_punctuation = false;
}
}
output.trim().to_owned()
}
fn parse_digits(text: &str) -> String {
text.chars().filter(char::is_ascii_digit).collect()
}
fn is_non_altering_template(template: &str) -> bool {
template.match_indices("$1").any(|(index, _)| {
let mut rest = template[index + 2..].chars().peekable();
loop {
while rest
.next_if(|&character| is_valid_punctuation(character))
.is_some()
{}
match rest.next() {
None => return true,
Some('$') => {
if rest.next_if(char::is_ascii_digit).is_none() {
return false;
}
}
Some(_) => return false,
}
}
})
}
fn template_pattern(format_pattern: &str) -> String {
let mut without_classes = String::with_capacity(format_pattern.len());
let mut rest = format_pattern;
while let Some(start) = rest.find('[') {
without_classes.push_str(&rest[..start]);
let after = &rest[start + 1..];
match after.find([']', '[']) {
Some(end) if after.as_bytes().get(end) == Some(&b']') => {
without_classes.push_str("\\d");
rest = &after[end + 1..];
}
_ => {
without_classes.push('[');
rest = after;
}
}
}
without_classes.push_str(rest);
let bytes = without_classes.as_bytes();
let mut output = String::with_capacity(bytes.len() + 8);
for (index, &byte) in bytes.iter().enumerate() {
let followed_by_two = matches!(
(bytes.get(index + 1), bytes.get(index + 2)),
(Some(first), Some(second))
if !matches!(first, b',' | b'}') && !matches!(second, b',' | b'}')
);
if byte.is_ascii_digit() && followed_by_two {
output.push_str("\\d");
} else {
output.push(char::from(byte));
}
}
output
}
fn cut_and_strip_non_paired_parens(text: &str, cut_before: usize) -> String {
let bytes = text.as_bytes();
let cut = if bytes.get(cut_before) == Some(&b')') {
cut_before + 1
} else {
cut_before
};
let kept = &bytes[..cut.min(bytes.len())];
let mut dangling = Vec::new();
for (index, &byte) in kept.iter().enumerate() {
if byte == b'(' {
dangling.push(index);
} else if byte == b')' {
dangling.pop();
}
}
kept.iter()
.enumerate()
.filter(|(index, _)| !dangling.contains(index))
.map(|(_, &byte)| char::from(byte))
.collect()
}
fn populate_template_with_digits(
template: &str,
position: Option<usize>,
digits: &str,
) -> Option<(String, Option<usize>)> {
let mut template = template.to_owned();
let mut position = position;
for digit in digits.chars() {
let search_from = position.map_or(0, |position| position + 1);
if !template
.get(search_from..)
.is_some_and(|rest| rest.contains(DIGIT_PLACEHOLDER))
{
return None;
}
let index = template.find(DIGIT_PLACEHOLDER)?;
template.replace_range(index..=index, digit.encode_utf8(&mut [0; 4]));
position = Some(index);
}
Some((template, position))
}
const DIGIT_PLACEHOLDER: char = 'x';
struct NationalNumberExtraction {
national_number: String,
national_prefix: String,
}
fn extract_national_number_from_possibly_incomplete_number(
number: &str,
plan: &PhoneRegion,
) -> NationalNumberExtraction {
let prefix_pattern = plan.national_prefix_for_parsing();
let unchanged = || NationalNumberExtraction {
national_number: number.to_owned(),
national_prefix: String::new(),
};
if number.is_empty() || prefix_pattern.is_empty() {
return unchanged();
}
let Some(captures) = pattern::captures_at_start(prefix_pattern, number) else {
return unchanged();
};
let Some(Some((_, match_end))) = captures.first().copied() else {
return unchanged();
};
let group_count = captures.len() - 1;
let group_text = |group: usize| {
captures
.get(group)
.copied()
.flatten()
.and_then(|(start, end)| number.get(start..end))
};
let has_captured_groups =
group_count > 0 && group_text(group_count).is_some_and(|text| !text.is_empty());
let transform_rule = plan.national_prefix_transform_rule();
let after_match = number.get(match_end..).unwrap_or_default();
let national_number = if !transform_rule.is_empty() && has_captured_groups {
format!(
"{}{after_match}",
pattern::expand_replacement(transform_rule, number, &captures)
)
} else {
after_match.to_owned()
};
let national_prefix = if has_captured_groups {
let end = match group_text(1).map(|first| number.find(first)) {
Some(Some(position)) => position,
_ => number.len().saturating_sub(1),
};
let possible_national_prefix = number.get(..end).unwrap_or_default();
let national_prefix = plan.national_prefix();
if !national_prefix.is_empty() && possible_national_prefix == national_prefix {
national_prefix.to_owned()
} else {
String::new()
}
} else {
number.get(..match_end).unwrap_or_default().to_owned()
};
NationalNumberExtraction {
national_number,
national_prefix,
}
}
fn extract_national_number(number: &str, plan: &PhoneRegion) -> String {
let extraction = extract_national_number_from_possibly_incomplete_number(number, plan);
let national_number = extraction.national_number;
if national_number == number {
return national_number;
}
let national_pattern = plan.national_pattern();
if pattern::matches_entirely(number, national_pattern)
&& !pattern::matches_entirely(&national_number, national_pattern)
{
return number.to_owned();
}
let length_plan = region_by_calling_code(plan.calling_code(), &national_number).unwrap_or(plan);
if matches!(
length_plan.check_number_length(&national_number),
NumberLength::TooShort | NumberLength::InvalidLength
) {
return number.to_owned();
}
national_number
}
fn calling_code_without_plus_sign(number: &str, region: &PhoneRegion) -> Option<&'static str> {
let calling_code = region.calling_code();
let shorter = number.strip_prefix(calling_code)?;
let shorter_national_number = extract_national_number(shorter, region);
let national_number = extract_national_number(number, region);
let national_pattern = region.national_pattern();
let better_without_calling_code =
!pattern::matches_entirely(&national_number, national_pattern)
&& pattern::matches_entirely(&shorter_national_number, national_pattern);
(better_without_calling_code
|| region.check_number_length(&national_number) == NumberLength::TooLong)
.then_some(calling_code)
}
fn strip_idd_prefix<'a>(number: &'a str, region: &PhoneRegion) -> Option<&'a str> {
let idd_prefix = region.idd_prefix();
if idd_prefix.is_empty() {
return None;
}
let captures = pattern::captures_at_start(idd_prefix, number)?;
let (_, end) = captures.first().copied().flatten()?;
let rest = number.get(end..)?;
if rest.starts_with('0') {
return None;
}
Some(rest)
}
fn split_calling_code(digits: &str) -> Option<(&'static str, &str)> {
if digits.starts_with('0') {
return None;
}
(1..=3.min(digits.len())).find_map(|length| {
let calling_code = known_calling_code(digits.get(..length)?)?;
Some((calling_code, digits.get(length..)?))
})
}
#[derive(Default)]
struct TypingState {
international: bool,
missing_plus: bool,
idd_prefix: String,
calling_code: Option<&'static str>,
country: Option<&'static PhoneRegion>,
digits: String,
national_significant_number: String,
national_significant_number_is_modified: bool,
national_prefix: String,
prefix_before_national_significant_number: String,
}
impl TypingState {
fn national_digits(&self) -> String {
if !self.international {
return self.digits.clone();
}
let skip = self.idd_prefix.len() + self.calling_code.map_or(0, str::len);
self.digits.get(skip..).unwrap_or_default().to_owned()
}
fn digits_without_international_prefix(&self) -> &str {
if self.international && !self.idd_prefix.is_empty() {
return self.digits.get(self.idd_prefix.len()..).unwrap_or_default();
}
&self.digits
}
fn reset_national_significant_number(&mut self) {
self.national_significant_number = self.national_digits();
self.national_significant_number_is_modified = false;
self.national_prefix.clear();
self.prefix_before_national_significant_number.clear();
}
}
#[derive(Default)]
struct ParserState {
has_selected_numbering_plan: bool,
could_possibly_extract_another_national_significant_number: bool,
has_extracted_national_significant_number: bool,
}
#[derive(Default)]
struct FormatterState {
matching_formats: Vec<&'static PhoneFormat>,
chosen_format: Option<&'static PhoneFormat>,
template: String,
populated_template: String,
populated_position: Option<usize>,
is_nanp: bool,
}
struct AsYouType {
default_country: Option<&'static PhoneRegion>,
plan: Option<&'static PhoneRegion>,
state: TypingState,
parser: ParserState,
formatter: FormatterState,
}
impl AsYouType {
fn new(default_country: Option<&'static PhoneRegion>) -> Self {
let mut typing = Self {
default_country,
plan: None,
state: TypingState::default(),
parser: ParserState::default(),
formatter: FormatterState::default(),
};
typing.init_country_and_calling_code(default_country, None);
typing
}
fn init_country_and_calling_code(
&mut self,
country: Option<&'static PhoneRegion>,
calling_code: Option<&'static str>,
) {
self.state.country = country;
self.set_calling_code(calling_code);
}
fn set_calling_code(&mut self, calling_code: Option<&'static str>) {
self.state.calling_code = calling_code;
self.plan = match (self.state.country, calling_code) {
(Some(country), _) => Some(country),
(None, Some(calling_code)) => plan_for_calling_code(calling_code),
(None, None) => None,
};
self.reset_formatter();
let prefix_pattern = self
.plan
.map_or("", PhoneRegion::own_national_prefix_for_parsing);
self.parser.has_selected_numbering_plan = self.plan.is_some();
self.parser
.could_possibly_extract_another_national_significant_number = prefix_pattern
.bytes()
.any(|byte| !matches!(byte, b'0'..=b'9' | b'[' | b']'));
}
fn start_international_number_state(
&mut self,
country: Option<&'static PhoneRegion>,
calling_code: Option<&'static str>,
) {
self.state.international = true;
self.init_country_and_calling_code(country, calling_code);
}
fn on_national_significant_number_change(&mut self) {
self.determine_the_country_if_needed();
self.reset_formatter();
}
fn determine_the_country_if_needed(&mut self) {
let ambiguous = self
.state
.calling_code
.and_then(regions_for_calling_code)
.is_some_and(|regions| regions.len() > 1);
if self.state.country.is_none() || ambiguous {
let country = if self.state.international {
self.state.calling_code.and_then(|calling_code| {
region_by_calling_code(calling_code, &self.state.national_significant_number)
})
} else {
None
};
if !same_region(country, self.state.country) {
self.state.country = country;
if country.is_some() {
self.plan = country;
}
}
}
}
fn input(&mut self, text: &str) -> String {
let (digits, has_plus) = match text.strip_prefix('+') {
Some(rest) => (parse_digits(rest), true),
None => (parse_digits(text), false),
};
if has_plus && self.state.digits.is_empty() {
self.start_international_number_state(None, None);
if digits.is_empty() {
return "+".to_owned();
}
}
if digits.is_empty() {
return String::new();
}
self.input_digits(&digits);
self.determine_the_country_if_needed();
if !self.state.national_significant_number.is_empty() {
self.narrow_down_matching_formats();
}
let mut formatted = None;
if self.plan.is_some() {
formatted = self.format(&digits);
}
if formatted.is_none() && self.re_extract_national_significant_number() {
self.determine_the_country_if_needed();
let national_digits = self.state.national_digits();
if !national_digits.is_empty() {
formatted = self.format(&national_digits);
}
}
match formatted.filter(|formatted| !formatted.is_empty()) {
Some(formatted) => self.full_number(&formatted),
None => self.non_formatted_number(),
}
}
fn input_digits(&mut self, next_digits: &str) {
let previous_length = self.state.digits.len();
let has_received_three_leading_digits =
previous_length < 3 && previous_length + next_digits.len() >= 3;
self.state.digits.push_str(next_digits);
if has_received_three_leading_digits {
self.extract_idd_prefix();
}
if self.state.international && self.state.calling_code.is_none() {
if !self.extract_country_calling_code() {
return;
}
} else {
self.state.national_significant_number.push_str(next_digits);
}
if !self.state.international && !self.parser.has_extracted_national_significant_number {
let national_digits = self.state.national_digits();
self.extract_national_significant_number(&national_digits);
}
}
fn extract_country_calling_code(&mut self) -> bool {
let digits = self.state.digits_without_international_prefix().to_owned();
let Some((calling_code, national_number)) = split_calling_code(&digits) else {
return false;
};
let national_number = national_number.to_owned();
self.set_calling_code(Some(calling_code));
self.state.national_significant_number = national_number;
true
}
fn extract_national_significant_number(&mut self, national_digits: &str) -> bool {
if !self.parser.has_selected_numbering_plan {
return false;
}
let Some(plan) = self.plan else {
return false;
};
let extraction =
extract_national_number_from_possibly_incomplete_number(national_digits, plan);
if extraction.national_number == national_digits {
return false;
}
self.on_extracted_national_number(extraction, national_digits);
true
}
fn extract_another_national_significant_number(
&mut self,
national_digits: &str,
previous_national_significant_number: &str,
) -> bool {
if !self.parser.has_extracted_national_significant_number {
return self.extract_national_significant_number(national_digits);
}
if !self
.parser
.could_possibly_extract_another_national_significant_number
{
return false;
}
let Some(plan) = self.plan else {
return false;
};
let extraction =
extract_national_number_from_possibly_incomplete_number(national_digits, plan);
if extraction.national_number == previous_national_significant_number {
return false;
}
self.on_extracted_national_number(extraction, national_digits);
true
}
fn on_extracted_national_number(
&mut self,
extraction: NationalNumberExtraction,
national_digits: &str,
) {
let national_number = extraction.national_number;
let mut modified = false;
let mut prefix_before = String::new();
match national_digits.rfind(national_number.as_str()) {
Some(index) if index + national_number.len() == national_digits.len() => {
let prefix = &national_digits[..index];
if !prefix.is_empty() && prefix != extraction.national_prefix {
prefix.clone_into(&mut prefix_before);
}
}
_ => modified = true,
}
self.state.national_prefix = extraction.national_prefix;
self.state.national_significant_number = national_number;
self.state.national_significant_number_is_modified = modified;
self.state.prefix_before_national_significant_number = prefix_before;
self.parser.has_extracted_national_significant_number = true;
self.on_national_significant_number_change();
}
fn re_extract_national_significant_number(&mut self) -> bool {
let national_digits = self.state.national_digits();
let previous = self.state.national_significant_number.clone();
if self.extract_another_national_significant_number(&national_digits, &previous) {
return true;
}
if self.extract_idd_prefix() || self.fix_missing_plus() {
self.extract_calling_code_and_national_significant_number();
return true;
}
false
}
fn extract_idd_prefix(&mut self) -> bool {
if self.state.international || !self.state.idd_prefix.is_empty() {
return false;
}
let Some(default_country) = self.default_country else {
return false;
};
let Some(rest) = strip_idd_prefix(&self.state.digits, default_country) else {
return false;
};
if rest.len() == self.state.digits.len() {
return false;
}
let idd_length = self.state.digits.len() - rest.len();
self.state.idd_prefix = self
.state
.digits
.get(..idd_length)
.unwrap_or_default()
.to_owned();
self.start_international_number(None, None);
true
}
fn fix_missing_plus(&mut self) -> bool {
if self.state.international {
return false;
}
let Some(region) = self.state.country.or(self.default_country) else {
return false;
};
let Some(calling_code) = calling_code_without_plus_sign(&self.state.digits, region) else {
return false;
};
self.state.missing_plus = true;
self.start_international_number(self.state.country, Some(calling_code));
true
}
fn start_international_number(
&mut self,
country: Option<&'static PhoneRegion>,
calling_code: Option<&'static str>,
) {
self.start_international_number_state(country, calling_code);
if !self.state.national_significant_number.is_empty() {
self.state.reset_national_significant_number();
self.on_national_significant_number_change();
self.parser.has_extracted_national_significant_number = false;
}
}
fn extract_calling_code_and_national_significant_number(&mut self) {
if self.extract_country_calling_code() {
let national_digits = self.state.national_digits();
self.extract_national_significant_number(&national_digits);
}
}
fn international_prefix(&self, spacing: Option<bool>) -> String {
if !self.state.idd_prefix.is_empty() {
if spacing == Some(false) {
return self.state.idd_prefix.clone();
}
return format!("{} ", self.state.idd_prefix);
}
if self.state.missing_plus {
String::new()
} else {
"+".to_owned()
}
}
fn full_number(&self, formatted_national_number: &str) -> String {
if !self.state.international {
return formatted_national_number.to_owned();
}
let text = match self.state.calling_code {
None => self.state.digits_without_international_prefix().to_owned(),
Some(calling_code) if formatted_national_number.is_empty() => calling_code.to_owned(),
Some(calling_code) => format!("{calling_code} {formatted_national_number}"),
};
format!(
"{}{text}",
self.international_prefix(Some(!text.is_empty()))
)
}
fn non_formatted_number(&self) -> String {
let national = if self.state.national_significant_number_is_modified {
self.state.national_digits()
} else {
let prefix = if self
.state
.prefix_before_national_significant_number
.is_empty()
{
&self.state.national_prefix
} else {
&self.state.prefix_before_national_significant_number
};
format!("{prefix}{}", self.state.national_significant_number)
};
self.full_number(&national)
}
fn number(&self) -> Option<ParsedNumber> {
let national_number = &self.state.national_significant_number;
if national_number.is_empty() {
return None;
}
let mut country = self.state.country;
if country.is_none() && self.state.calling_code.is_none() {
return None;
}
if let (Some(current), Some(default_country)) = (country, self.default_country)
&& current.code() == default_country.code()
&& let Some(plan) = self.plan
&& let Some(regions) = regions_for_calling_code(plan.calling_code())
&& regions.len() > 1
&& let Some(exact) = region_by_national_number(national_number, regions)
{
country = Some(exact);
}
let calling_code = match country {
Some(region) => region.calling_code(),
None => self.state.calling_code?,
};
Some(ParsedNumber {
region: country,
calling_code,
national_number: national_number.clone(),
})
}
fn reset_format(&mut self) {
let formatter = &mut self.formatter;
formatter.chosen_format = None;
formatter.template.clear();
formatter.populated_template.clear();
formatter.populated_position = None;
}
fn reset_formatter(&mut self) {
self.reset_format();
let Some(plan) = self.plan else {
self.formatter.is_nanp = false;
self.formatter.matching_formats.clear();
return;
};
self.formatter.is_nanp = plan.calling_code() == "1";
self.formatter.matching_formats = plan.formats().iter().collect();
if !self.state.national_significant_number.is_empty() {
self.narrow_down_matching_formats();
}
}
fn narrow_down_matching_formats(&mut self) {
let leading_digits = &self.state.national_significant_number;
let pattern_index = leading_digits.len().saturating_sub(3);
let international = self.state.international;
let national_prefix = &self.state.national_prefix;
self.formatter.matching_formats.retain(|format| {
format_suits(format, international, national_prefix)
&& format_matches(format, leading_digits, pattern_index)
});
if let Some(chosen) = self.formatter.chosen_format
&& !self
.formatter
.matching_formats
.iter()
.any(|format| same_format(format, chosen))
{
self.reset_format();
}
}
fn can_format_complete_number(&self) -> bool {
self.plan.is_some_and(|plan| {
plan.check_number_length(&self.state.national_significant_number)
== NumberLength::Possible
})
}
fn format(&mut self, next_digits: &str) -> Option<String> {
if self.can_format_complete_number() {
for format in self.formatter.matching_formats.clone() {
if let Some(formatted) = self.format_complete_number(format) {
self.reset_format();
self.formatter.chosen_format = Some(format);
let template: String = formatted
.chars()
.map(|character| {
if character.is_ascii_digit() {
DIGIT_PLACEHOLDER
} else {
character
}
})
.collect();
self.set_national_number_template(template);
self.formatter.populated_position =
self.formatter.template.rfind(DIGIT_PLACEHOLDER);
self.formatter.populated_template.clone_from(&formatted);
return Some(formatted);
}
}
}
self.format_national_number_with_next_digits(next_digits)
}
fn format_complete_number(&self, format: &PhoneFormat) -> Option<String> {
if !pattern::matches_entirely(&self.state.national_significant_number, format.pattern()) {
return None;
}
if self.should_try_national_prefix_formatting_rule(format)
&& let Some(formatted) = self.format_complete_national_number(format, true)
{
return Some(formatted);
}
self.format_complete_national_number(format, false)
}
fn format_complete_national_number(
&self,
format: &PhoneFormat,
use_national_prefix_formatting_rule: bool,
) -> Option<String> {
let state = &self.state;
let mut formatted = format_with_pattern(
&state.national_significant_number,
format,
state.international,
use_national_prefix_formatting_rule,
);
if !use_national_prefix_formatting_rule {
if !state.national_prefix.is_empty() {
formatted = format!(
"{}{}{formatted}",
state.national_prefix,
self.separator_after_national_prefix(format)
);
} else if !state.prefix_before_national_significant_number.is_empty() {
formatted = format!(
"{} {formatted}",
state.prefix_before_national_significant_number
);
}
}
(parse_digits(&formatted) == state.national_digits()).then_some(formatted)
}
fn format_national_number_with_next_digits(&mut self, next_digits: &str) -> Option<String> {
let previous = self.formatter.chosen_format;
let chosen = self.choose_format()?;
if previous.is_some_and(|previous| same_format(previous, chosen)) {
self.format_next_national_number_digits(next_digits)
} else {
let national_digits = self.state.national_digits();
self.format_next_national_number_digits(&national_digits)
}
}
fn choose_format(&mut self) -> Option<&'static PhoneFormat> {
for format in self.formatter.matching_formats.clone() {
if self
.formatter
.chosen_format
.is_some_and(|chosen| same_format(chosen, format))
{
break;
}
let template = if self.state.international {
format.international_template()
} else {
format.template()
};
if !is_non_altering_template(template) {
continue;
}
if !self.create_template_for_format(format) {
self.formatter
.matching_formats
.retain(|candidate| !same_format(candidate, format));
continue;
}
self.formatter.chosen_format = Some(format);
break;
}
if self.formatter.chosen_format.is_none() {
self.reset_format();
}
self.formatter.chosen_format
}
fn create_template_for_format(&mut self, format: &PhoneFormat) -> bool {
if format.pattern().contains('|') {
return false;
}
match self.template_for_format(format) {
Some(template) if !template.is_empty() => {
self.set_national_number_template(template);
true
}
_ => false,
}
}
fn template_for_format(&self, format: &PhoneFormat) -> Option<String> {
const LONGEST_DUMMY_NUMBER: &str = "999999999999999";
let state = &self.state;
let pattern = template_pattern(format.pattern());
let dummy_match = pattern::captures(&pattern, LONGEST_DUMMY_NUMBER)?;
let (start, end) = dummy_match.first().copied().flatten()?;
let mut digits = LONGEST_DUMMY_NUMBER.get(start..end)?.to_owned();
if state.national_significant_number.len() > digits.len() {
return None;
}
let national_number_dummy = "9".repeat(state.national_significant_number.len());
if pattern::matches_entirely(&national_number_dummy, &pattern) {
digits = national_number_dummy;
}
let mut number_format = if state.international {
format.international_template().to_owned()
} else {
format.template().to_owned()
};
let mut national_prefix_included = false;
if self.should_try_national_prefix_formatting_rule(format) {
let rule = format.national_prefix_formatting_rule();
if parse_digits(rule) == format!("{}1", state.national_prefix) {
number_format = replace_first_group_reference(&number_format, rule);
national_prefix_included = true;
for _ in 0..state.national_prefix.len() {
if let Some(index) =
number_format.find(|character: char| character.is_ascii_digit())
{
number_format.replace_range(index..=index, "x");
}
}
}
}
let mut template =
pattern::replace_first(&pattern, &digits, &number_format).replace('9', "x");
if !national_prefix_included {
let prefix_before = &state.prefix_before_national_significant_number;
if !prefix_before.is_empty() {
template = format!("{} {template}", "x".repeat(prefix_before.len()));
} else if !state.national_prefix.is_empty() {
template = format!(
"{}{}{template}",
"x".repeat(state.national_prefix.len()),
self.separator_after_national_prefix(format)
);
}
}
if state.international {
template = apply_international_separator_style(&template);
}
Some(template)
}
fn set_national_number_template(&mut self, template: String) {
self.formatter.populated_position = None;
self.formatter.template = if self.state.international {
let prefix: String = self
.international_prefix(None)
.chars()
.map(|character| {
if character.is_ascii_digit() || character == '+' {
DIGIT_PLACEHOLDER
} else {
character
}
})
.collect();
let calling_code_length = self.state.calling_code.map_or(0, str::len);
format!("{prefix}{} {template}", "x".repeat(calling_code_length))
} else {
template.clone()
};
self.formatter.populated_template = template;
}
fn format_next_national_number_digits(&mut self, digits: &str) -> Option<String> {
let Some((template, position)) = populate_template_with_digits(
&self.formatter.populated_template,
self.formatter.populated_position,
digits,
) else {
self.reset_format();
return None;
};
let cut_before = position.map_or(0, |position| position + 1);
let formatted = cut_and_strip_non_paired_parens(&template, cut_before);
self.formatter.populated_template = template;
self.formatter.populated_position = position;
Some(formatted)
}
fn should_try_national_prefix_formatting_rule(&self, format: &PhoneFormat) -> bool {
if format.national_prefix_formatting_rule().is_empty() {
return false;
}
let uses_national_prefix = format.uses_national_prefix();
(uses_national_prefix && !self.state.national_prefix.is_empty())
|| (!uses_national_prefix && !self.state.international)
}
fn separator_after_national_prefix(&self, format: &PhoneFormat) -> &'static str {
if self.formatter.is_nanp {
return " ";
}
if format
.national_prefix_formatting_rule()
.contains(['-', ' '])
{
" "
} else {
""
}
}
}
fn format_suits(format: &PhoneFormat, international: bool, national_prefix: &str) -> bool {
if !national_prefix.is_empty()
&& !format.uses_national_prefix()
&& !format.national_prefix_is_optional()
{
return false;
}
!(!international && national_prefix.is_empty() && format.national_prefix_is_mandatory())
}
fn format_matches(format: &PhoneFormat, leading_digits: &str, pattern_index: usize) -> bool {
let patterns = format.leading_digits();
let Some(last_index) = patterns.len().checked_sub(1) else {
return true;
};
let Some(leading_pattern) = patterns.get(pattern_index.min(last_index)) else {
return true;
};
if leading_digits.len() < 3 {
return pattern::partial::matches(leading_pattern, leading_digits);
}
pattern::matches_at_start(leading_digits, leading_pattern)
}
mod pattern {
const MAX_INPUT: usize = 63;
const FUEL: u32 = 1_000_000;
const MAX_SETTLING_ITERATIONS: u32 = 128;
const MAX_DEPTH: u32 = 64;
const MAX_PROGRAM: usize = 20_000;
#[derive(Debug)]
struct Malformed;
type Parsed<T> = Result<T, Malformed>;
#[derive(Clone, Copy, Default)]
struct ByteSet(u128);
impl ByteSet {
fn digits() -> Self {
let mut set = Self::default();
set.insert_range(b'0', b'9');
set
}
fn single(byte: u8) -> Self {
let mut set = Self::default();
set.insert_range(byte, byte);
set
}
fn insert_range(&mut self, first: u8, last: u8) {
for byte in first..=last.min(127) {
self.0 |= 1 << byte;
}
}
fn contains(self, byte: u8) -> bool {
byte < 128 && ((self.0 >> byte) & 1) == 1
}
}
fn parse_number(pattern: &[u8], position: &mut usize) -> Parsed<u32> {
let start = *position;
let mut value: u32 = 0;
while let Some(&byte) = pattern.get(*position).filter(|byte| byte.is_ascii_digit()) {
value = value
.checked_mul(10)
.and_then(|value| value.checked_add(u32::from(byte - b'0')))
.ok_or(Malformed)?;
*position += 1;
}
if *position == start {
return Err(Malformed);
}
Ok(value)
}
fn parse_quantifier(
pattern: &[u8],
position: &mut usize,
) -> Parsed<Option<(u32, Option<u32>, bool)>> {
let bounds = match pattern.get(*position) {
Some(b'?') => (0, Some(1)),
Some(b'*') => (0, None),
Some(b'+') => (1, None),
Some(b'{') => {
*position += 1;
let minimum = parse_number(pattern, position)?;
let maximum = if pattern.get(*position) == Some(&b',') {
*position += 1;
if pattern.get(*position) == Some(&b'}') {
None
} else {
Some(parse_number(pattern, position)?)
}
} else {
Some(minimum)
};
if pattern.get(*position) != Some(&b'}')
|| maximum.is_some_and(|maximum| maximum < minimum)
{
return Err(Malformed);
}
(minimum, maximum)
}
_ => return Ok(None),
};
*position += 1;
let lazy = pattern.get(*position) == Some(&b'?');
if lazy {
*position += 1;
}
Ok(Some((bounds.0, bounds.1, lazy)))
}
fn parse_class(pattern: &[u8], position: &mut usize) -> Parsed<ByteSet> {
*position += 1;
let negated = pattern.get(*position) == Some(&b'^');
if negated {
*position += 1;
}
let mut set = ByteSet::default();
loop {
let byte = *pattern.get(*position).ok_or(Malformed)?;
if byte == b']' {
*position += 1;
break;
}
let start = if byte == b'\\' {
let escaped = *pattern.get(*position + 1).ok_or(Malformed)?;
*position += 2;
if escaped == b'd' {
set.0 |= ByteSet::digits().0;
continue;
}
if escaped.is_ascii_alphanumeric() {
return Err(Malformed);
}
escaped
} else {
*position += 1;
byte
};
if pattern.get(*position) == Some(&b'-')
&& pattern.get(*position + 1).is_some_and(|&next| next != b']')
{
let end = *pattern.get(*position + 1).ok_or(Malformed)?;
if end == b'\\' || end < start {
return Err(Malformed);
}
set.insert_range(start, end);
*position += 2;
} else {
set.insert_range(start, start);
}
}
if negated {
set.0 = !set.0;
}
Ok(set)
}
fn parse_escape(pattern: &[u8], position: &mut usize) -> Parsed<ByteSet> {
let escaped = *pattern.get(*position + 1).ok_or(Malformed)?;
*position += 2;
match escaped {
b'd' => Ok(ByteSet::digits()),
byte if byte.is_ascii_punctuation() => Ok(ByteSet::single(byte)),
_ => Err(Malformed),
}
}
struct PositionSets<'a> {
pattern: &'a [u8],
position: usize,
input: &'a [u8],
digit_masks: [u64; 10],
end_mask: u64,
fuel: u32,
}
impl<'a> PositionSets<'a> {
fn new(pattern: &'a str, input: &'a [u8], at_end: bool) -> Self {
let mut digit_masks = [0; 10];
for (index, byte) in input.iter().enumerate() {
if let Some(mask) = byte
.checked_sub(b'0')
.and_then(|digit| digit_masks.get_mut(usize::from(digit)))
{
*mask |= 1 << index;
}
}
Self {
pattern: pattern.as_bytes(),
position: 0,
input,
digit_masks,
end_mask: if at_end { 1 << input.len() } else { 0 },
fuel: FUEL,
}
}
fn ends(mut self) -> Parsed<u64> {
let ends = self.alternation(1, 0)?;
if self.position == self.pattern.len() {
Ok(ends)
} else {
Err(Malformed)
}
}
fn peek(&self) -> Option<u8> {
self.pattern.get(self.position).copied()
}
fn mask(&self, set: ByteSet) -> u64 {
let mut mask = 0;
for (digit, &digit_mask) in (b'0'..=b'9').zip(&self.digit_masks) {
if set.contains(digit) {
mask |= digit_mask;
}
}
for (index, &byte) in self.input.iter().enumerate() {
if !byte.is_ascii_digit() && set.contains(byte) {
mask |= 1 << index;
}
}
mask
}
fn alternation(&mut self, starts: u64, depth: u32) -> Parsed<u64> {
if depth > MAX_DEPTH {
return Err(Malformed);
}
let mut ends = self.sequence(starts, depth)?;
while self.peek() == Some(b'|') {
self.position += 1;
ends |= self.sequence(starts, depth)?;
}
Ok(ends)
}
fn sequence(&mut self, starts: u64, depth: u32) -> Parsed<u64> {
let mut current = starts;
while let Some(byte) = self.peek() {
if byte == b'|' || byte == b')' {
break;
}
current = self.quantified(current, depth)?;
}
Ok(current)
}
fn quantified(&mut self, starts: u64, depth: u32) -> Parsed<u64> {
let atom_start = self.position;
let once = self.atom(starts, depth)?;
let atom_end = self.position;
let Some((minimum, maximum, _lazy)) =
parse_quantifier(self.pattern, &mut self.position)?
else {
return Ok(once);
};
let after = self.position;
let ends = self.repeat(
starts,
once,
(atom_start, atom_end),
(minimum, maximum),
depth,
)?;
self.position = after;
Ok(ends)
}
fn repeat(
&mut self,
starts: u64,
once: u64,
atom: (usize, usize),
(minimum, maximum): (u32, Option<u32>),
depth: u32,
) -> Parsed<u64> {
let mut current = starts;
for iteration in 1..=minimum {
let next = if iteration == 1 {
once
} else {
self.reevaluate(atom, current, depth)?
};
let settled = next == current;
current = next;
if current == 0 || settled || iteration > MAX_SETTLING_ITERATIONS {
break;
}
}
let mut reached = current;
let mut frontier = current;
let mut iteration = minimum;
while maximum.is_none_or(|maximum| iteration < maximum) && frontier != 0 {
let next = if iteration == 0 {
once
} else {
self.reevaluate(atom, frontier, depth)?
} & !reached;
reached |= next;
frontier = next;
iteration += 1;
}
Ok(reached)
}
fn reevaluate(
&mut self,
(start, end): (usize, usize),
starts: u64,
depth: u32,
) -> Parsed<u64> {
if starts == 0 {
return Ok(0);
}
self.position = start;
let ends = self.atom(starts, depth)?;
if self.position == end {
Ok(ends)
} else {
Err(Malformed)
}
}
fn atom(&mut self, starts: u64, depth: u32) -> Parsed<u64> {
self.fuel = self.fuel.checked_sub(1).ok_or(Malformed)?;
let byte = self.peek().ok_or(Malformed)?;
match byte {
b'(' => {
self.position += 1;
if self.pattern.get(self.position) == Some(&b'?') {
if self.pattern.get(self.position + 1) != Some(&b':') {
return Err(Malformed);
}
self.position += 2;
}
let ends = self.alternation(starts, depth + 1)?;
if self.peek() != Some(b')') {
return Err(Malformed);
}
self.position += 1;
Ok(ends)
}
b'[' => {
let set = parse_class(self.pattern, &mut self.position)?;
Ok((starts & self.mask(set)) << 1)
}
b'\\' => {
let set = parse_escape(self.pattern, &mut self.position)?;
Ok((starts & self.mask(set)) << 1)
}
b'$' => {
self.position += 1;
Ok(starts & self.end_mask)
}
b')' | b'|' | b'?' | b'*' | b'+' | b'{' | b'}' | b']' | b'^' | b'.' => {
Err(Malformed)
}
_ => {
self.position += 1;
Ok((starts & self.mask(ByteSet::single(byte))) << 1)
}
}
}
}
pub(super) fn matches_entirely(input: &str, pattern: &str) -> bool {
let input = input.as_bytes();
if input.len() > MAX_INPUT {
return false;
}
PositionSets::new(pattern, input, true)
.ends()
.is_ok_and(|ends| ends & (1 << input.len()) != 0)
}
pub(super) fn matches_at_start(input: &str, pattern: &str) -> bool {
let input = input.as_bytes();
let truncated = input.len() > MAX_INPUT;
let input = input.get(..MAX_INPUT).unwrap_or(input);
PositionSets::new(pattern, input, !truncated)
.ends()
.is_ok_and(|ends| ends != 0)
}
pub(super) type Captures = Vec<Option<(usize, usize)>>;
#[derive(Clone, Copy)]
enum Instruction {
Byte(ByteSet),
Split(usize, usize),
Jump(usize),
Save(usize),
End,
Match,
}
fn relocate(fragment: &[Instruction], base: usize) -> impl Iterator<Item = Instruction> + '_ {
fragment.iter().map(move |instruction| match *instruction {
Instruction::Split(first, second) => Instruction::Split(first + base, second + base),
Instruction::Jump(target) => Instruction::Jump(target + base),
other => other,
})
}
struct Compiler<'a> {
pattern: &'a [u8],
position: usize,
groups: usize,
}
impl Compiler<'_> {
fn peek(&self) -> Option<u8> {
self.pattern.get(self.position).copied()
}
fn check_size(fragment: &[Instruction]) -> Parsed<()> {
if fragment.len() > MAX_PROGRAM {
Err(Malformed)
} else {
Ok(())
}
}
fn alternation(&mut self, depth: u32) -> Parsed<Vec<Instruction>> {
if depth > MAX_DEPTH {
return Err(Malformed);
}
let mut branches = vec![self.sequence(depth)?];
while self.peek() == Some(b'|') {
self.position += 1;
branches.push(self.sequence(depth)?);
}
let mut fragment = branches.pop().ok_or(Malformed)?;
while let Some(branch) = branches.pop() {
let mut combined = Vec::with_capacity(branch.len() + fragment.len() + 2);
let second = branch.len() + 2;
let end = second + fragment.len();
combined.push(Instruction::Split(1, second));
combined.extend(relocate(&branch, 1));
combined.push(Instruction::Jump(end));
combined.extend(relocate(&fragment, second));
Self::check_size(&combined)?;
fragment = combined;
}
Ok(fragment)
}
fn sequence(&mut self, depth: u32) -> Parsed<Vec<Instruction>> {
let mut fragment = Vec::new();
while let Some(byte) = self.peek() {
if byte == b'|' || byte == b')' {
break;
}
let piece = self.quantified(depth)?;
let base = fragment.len();
fragment.extend(relocate(&piece, base));
Self::check_size(&fragment)?;
}
Ok(fragment)
}
fn quantified(&mut self, depth: u32) -> Parsed<Vec<Instruction>> {
let atom = self.atom(depth)?;
let Some((minimum, maximum, lazy)) =
parse_quantifier(self.pattern, &mut self.position)?
else {
return Ok(atom);
};
let mut fragment = Vec::new();
for _ in 0..minimum {
let base = fragment.len();
fragment.extend(relocate(&atom, base));
Self::check_size(&fragment)?;
}
let optional = match maximum {
None => {
let mut star = Vec::with_capacity(atom.len() + 2);
let out = atom.len() + 2;
star.push(if lazy {
Instruction::Split(out, 1)
} else {
Instruction::Split(1, out)
});
star.extend(relocate(&atom, 1));
star.push(Instruction::Jump(0));
star
}
Some(maximum) => {
let mut nested: Vec<Instruction> = Vec::new();
for _ in minimum..maximum {
let mut copy = Vec::with_capacity(atom.len() + nested.len() + 1);
let out = atom.len() + nested.len() + 1;
copy.push(if lazy {
Instruction::Split(out, 1)
} else {
Instruction::Split(1, out)
});
copy.extend(relocate(&atom, 1));
copy.extend(relocate(&nested, atom.len() + 1));
Self::check_size(©)?;
nested = copy;
}
nested
}
};
let base = fragment.len();
fragment.extend(relocate(&optional, base));
Self::check_size(&fragment)?;
Ok(fragment)
}
fn atom(&mut self, depth: u32) -> Parsed<Vec<Instruction>> {
let byte = self.peek().ok_or(Malformed)?;
match byte {
b'(' => {
self.position += 1;
let capture = if self.peek() == Some(b'?') {
if self.pattern.get(self.position + 1) != Some(&b':') {
return Err(Malformed);
}
self.position += 2;
None
} else {
self.groups += 1;
Some(self.groups)
};
let body = self.alternation(depth + 1)?;
if self.peek() != Some(b')') {
return Err(Malformed);
}
self.position += 1;
Ok(match capture {
Some(group) => {
let mut fragment = Vec::with_capacity(body.len() + 2);
fragment.push(Instruction::Save(group * 2));
fragment.extend(relocate(&body, 1));
fragment.push(Instruction::Save(group * 2 + 1));
fragment
}
None => body,
})
}
b'[' => Ok(vec![Instruction::Byte(parse_class(
self.pattern,
&mut self.position,
)?)]),
b'\\' => Ok(vec![Instruction::Byte(parse_escape(
self.pattern,
&mut self.position,
)?)]),
b'$' => {
self.position += 1;
Ok(vec![Instruction::End])
}
b')' | b'|' | b'?' | b'*' | b'+' | b'{' | b'}' | b']' | b'^' | b'.' => {
Err(Malformed)
}
_ => {
self.position += 1;
Ok(vec![Instruction::Byte(ByteSet::single(byte))])
}
}
}
}
fn compile(pattern: &str) -> Parsed<(Vec<Instruction>, usize)> {
let mut compiler = Compiler {
pattern: pattern.as_bytes(),
position: 0,
groups: 0,
};
let body = compiler.alternation(0)?;
if compiler.position != compiler.pattern.len() {
return Err(Malformed);
}
let mut program = Vec::with_capacity(body.len() + 3);
program.push(Instruction::Save(0));
program.extend(relocate(&body, 1));
program.push(Instruction::Save(1));
program.push(Instruction::Match);
Ok((program, compiler.groups))
}
const UNSET: usize = usize::MAX;
struct Thread {
program_counter: usize,
slots: Vec<usize>,
}
struct ThreadList {
threads: Vec<Thread>,
visited: Vec<bool>,
}
impl ThreadList {
fn new(size: usize) -> Self {
Self {
threads: Vec::new(),
visited: vec![false; size],
}
}
fn clear(&mut self) {
self.threads.clear();
self.visited.fill(false);
}
}
enum Frame {
Visit(usize),
Restore(usize, usize),
}
fn add_thread(
list: &mut ThreadList,
program: &[Instruction],
start: usize,
(position, length): (usize, usize),
slots: &[usize],
) {
let mut slots = slots.to_vec();
let mut stack = vec![Frame::Visit(start)];
while let Some(frame) = stack.pop() {
let program_counter = match frame {
Frame::Restore(slot, value) => {
if let Some(entry) = slots.get_mut(slot) {
*entry = value;
}
continue;
}
Frame::Visit(program_counter) => program_counter,
};
let (Some(instruction), Some(visited)) = (
program.get(program_counter),
list.visited.get_mut(program_counter),
) else {
continue;
};
if *visited {
continue;
}
*visited = true;
match *instruction {
Instruction::Jump(target) => stack.push(Frame::Visit(target)),
Instruction::Split(first, second) => {
stack.push(Frame::Visit(second));
stack.push(Frame::Visit(first));
}
Instruction::Save(slot) => {
if let Some(entry) = slots.get_mut(slot) {
stack.push(Frame::Restore(slot, *entry));
*entry = position;
}
stack.push(Frame::Visit(program_counter + 1));
}
Instruction::End => {
if position == length {
stack.push(Frame::Visit(program_counter + 1));
}
}
Instruction::Byte(_) | Instruction::Match => list.threads.push(Thread {
program_counter,
slots: slots.clone(),
}),
}
}
}
fn run(pattern: &str, input: &str, anchored: bool) -> Option<Captures> {
let (program, groups) = compile(pattern).ok()?;
let input = input.as_bytes();
let length = input.len();
let empty_slots = vec![UNSET; (groups + 1) * 2];
let mut current = ThreadList::new(program.len());
let mut next = ThreadList::new(program.len());
let mut matched: Option<Vec<usize>> = None;
for position in 0..=length {
if matched.is_none() && (position == 0 || !anchored) {
add_thread(&mut current, &program, 0, (position, length), &empty_slots);
}
if current.threads.is_empty() {
break;
}
for thread in ¤t.threads {
match program.get(thread.program_counter) {
Some(Instruction::Byte(set)) => {
if input.get(position).is_some_and(|&byte| set.contains(byte)) {
add_thread(
&mut next,
&program,
thread.program_counter + 1,
(position + 1, length),
&thread.slots,
);
}
}
Some(Instruction::Match) => {
matched = Some(thread.slots.clone());
break;
}
_ => {}
}
}
std::mem::swap(&mut current, &mut next);
next.clear();
}
let slots = matched?;
Some(
slots
.chunks(2)
.map(|pair| match *pair {
[start, end] if start != UNSET && end != UNSET && start <= end => {
Some((start, end))
}
_ => None,
})
.collect(),
)
}
pub(super) fn captures_at_start(pattern: &str, input: &str) -> Option<Captures> {
run(pattern, input, true)
}
pub(super) fn captures(pattern: &str, input: &str) -> Option<Captures> {
run(pattern, input, false)
}
pub(super) fn replace_first(pattern: &str, input: &str, replacement: &str) -> String {
let Some(found) = captures(pattern, input) else {
return input.to_owned();
};
let Some(Some((start, end))) = found.first().copied() else {
return input.to_owned();
};
format!(
"{}{}{}",
input.get(..start).unwrap_or_default(),
expand_replacement(replacement, input, &found),
input.get(end..).unwrap_or_default()
)
}
pub(super) fn expand_replacement(
replacement: &str,
input: &str,
found: &[Option<(usize, usize)>],
) -> String {
let group_count = found.len().saturating_sub(1);
let text = |group: usize| {
found
.get(group)
.copied()
.flatten()
.and_then(|(start, end)| input.get(start..end))
.unwrap_or_default()
};
let (match_start, match_end) = found.first().copied().flatten().unwrap_or((0, 0));
let bytes = replacement.as_bytes();
let mut output = String::with_capacity(replacement.len() + input.len());
let mut index = 0;
while let Some(&byte) = bytes.get(index) {
if byte != b'$' {
let character_end = (index + 1..=bytes.len())
.find(|&end| replacement.is_char_boundary(end))
.unwrap_or(bytes.len());
output.push_str(&replacement[index..character_end]);
index = character_end;
continue;
}
let digit = |offset: usize| {
bytes
.get(index + offset)
.filter(|byte| byte.is_ascii_digit())
.map(|byte| usize::from(byte - b'0'))
};
match bytes.get(index + 1) {
Some(b'$') => {
output.push('$');
index += 2;
}
Some(b'&') => {
output.push_str(text(0));
index += 2;
}
Some(b'`') => {
output.push_str(input.get(..match_start).unwrap_or_default());
index += 2;
}
Some(b'\'') => {
output.push_str(input.get(match_end..).unwrap_or_default());
index += 2;
}
_ => match (digit(1), digit(2)) {
(Some(tens), Some(ones)) if (1..=group_count).contains(&(tens * 10 + ones)) => {
output.push_str(text(tens * 10 + ones));
index += 3;
}
(Some(group), _) if (1..=group_count).contains(&group) => {
output.push_str(text(group));
index += 2;
}
_ => {
output.push('$');
index += 1;
}
},
}
}
output
}
pub(super) mod partial {
enum Node {
Character(u8),
Sequence(Vec<Node>),
Either(Vec<Node>),
OneOf(Vec<u8>),
}
enum Outcome {
Match(usize),
Partial,
Overflow,
}
struct Context {
or: bool,
one_of_set: bool,
instructions: Vec<Node>,
branches: Option<Vec<Node>>,
}
impl Context {
fn or(branches: Option<Vec<Node>>) -> Self {
Self {
or: true,
one_of_set: false,
instructions: Vec::new(),
branches,
}
}
}
const OPERATORS: [&str; 5] = ["|", "(?:", ")", "[", "]"];
fn expand(mut nodes: Vec<Node>) -> Node {
if nodes.len() == 1
&& let Some(node) = nodes.pop()
{
return node;
}
Node::Sequence(nodes)
}
fn add_characters(context: &mut Context, text: &str) -> Option<()> {
if text.bytes().any(|byte| b"()[]?:|".contains(&byte)) {
return None;
}
context
.instructions
.extend(text.bytes().map(Node::Character));
Some(())
}
fn one_of_set(text: &str) -> Option<Vec<u8>> {
let bytes = text.as_bytes();
let mut values = Vec::new();
for (index, &byte) in bytes.iter().enumerate() {
if byte == b'-' {
if index == 0 || index + 1 == bytes.len() {
return None;
}
let first = bytes.get(index - 1)?.checked_add(1)?;
let last = bytes.get(index + 1)?.checked_sub(1)?;
values.extend(first..=last);
} else {
values.push(byte);
}
}
Some(values)
}
fn parse(pattern: &str) -> Option<Node> {
let mut contexts = vec![Context::or(None)];
let mut rest = pattern;
if rest.is_empty() {
return None;
}
loop {
let found = OPERATORS
.iter()
.filter_map(|operator| rest.find(operator).map(|index| (index, *operator)))
.min_by_key(|(index, _)| *index);
let Some((index, operator)) = found else {
add_characters(contexts.last_mut()?, rest)?;
break;
};
let before = &rest[..index];
let after = &rest[index + operator.len()..];
match operator {
"(?:" => {
if !before.is_empty() {
add_characters(contexts.last_mut()?, before)?;
}
contexts.push(Context::or(Some(Vec::new())));
}
")" => {
if !contexts.last()?.or {
return None;
}
if !before.is_empty() {
add_characters(contexts.last_mut()?, before)?;
}
let context = contexts.pop()?;
if context.instructions.is_empty() {
return None;
}
let mut branches = context.branches?;
branches.push(expand(context.instructions));
contexts
.last_mut()?
.instructions
.push(Node::Either(branches));
}
"|" => {
let depth = contexts.len();
let context = contexts.last_mut()?;
if !context.or {
return None;
}
if !before.is_empty() {
add_characters(context, before)?;
}
if context.branches.is_none() {
if depth != 1 {
return None;
}
context.branches = Some(Vec::new());
}
let instructions = std::mem::take(&mut context.instructions);
context.branches.as_mut()?.push(expand(instructions));
}
"[" => {
if !before.is_empty() {
add_characters(contexts.last_mut()?, before)?;
}
contexts.push(Context {
or: false,
one_of_set: true,
instructions: Vec::new(),
branches: None,
});
}
_ => {
if !contexts.last()?.one_of_set {
return None;
}
contexts.pop();
contexts
.last_mut()?
.instructions
.push(Node::OneOf(one_of_set(before)?));
}
}
if after.is_empty() {
break;
}
rest = after;
}
if contexts.len() != 1 {
return None;
}
let root = contexts.pop()?;
if let Some(mut branches) = root.branches {
branches.push(expand(root.instructions));
return Some(Node::Either(branches));
}
if root.instructions.is_empty() {
return None;
}
Some(expand(root.instructions))
}
fn match_node(characters: &[u8], node: &Node, last: bool) -> Option<Outcome> {
match node {
Node::Character(character) => match characters {
[] => Some(Outcome::Partial),
[only] if only == character => Some(Outcome::Match(1)),
[first, ..] if first == character => Some(if last {
Outcome::Overflow
} else {
Outcome::Match(1)
}),
_ => None,
},
Node::Sequence(nodes) => {
let mut rest = characters;
for (index, node) in nodes.iter().enumerate() {
let is_last = index + 1 == nodes.len();
match match_node(rest, node, last && is_last)? {
Outcome::Overflow => return Some(Outcome::Overflow),
Outcome::Partial => return Some(Outcome::Partial),
Outcome::Match(length) => {
rest = rest.get(length..).unwrap_or_default();
if rest.is_empty() {
return Some(if is_last {
Outcome::Match(characters.len())
} else {
Outcome::Partial
});
}
}
}
}
if last {
return Some(Outcome::Overflow);
}
Some(Outcome::Match(characters.len() - rest.len()))
}
Node::Either(branches) => {
let mut partial = false;
for branch in branches {
match match_node(characters, branch, last) {
Some(Outcome::Overflow) => return Some(Outcome::Overflow),
Some(Outcome::Match(length)) => return Some(Outcome::Match(length)),
Some(Outcome::Partial) => partial = true,
None => {}
}
}
partial.then_some(Outcome::Partial)
}
Node::OneOf(values) => {
let first = characters.first()?;
let outcome = if characters.len() > 1 && last {
Outcome::Overflow
} else {
Outcome::Match(1)
};
values.contains(first).then_some(outcome)
}
}
}
pub(in super::super) fn matches(pattern: &str, digits: &str) -> bool {
if digits.is_empty() {
return true;
}
match parse(pattern) {
Some(tree) => match_node(digits.as_bytes(), &tree, true).is_some(),
None => true,
}
}
}
}
#[cfg(test)]
mod tests {
use std::time::{Duration, Instant};
use super::pattern::{self, partial};
use super::*;
fn country(region_code: &str) -> PhoneInputCountry {
PhoneInputCountry::find(region_code)
.unwrap_or_else(|| panic!("missing country {region_code}"))
}
const LIBPHONENUMBER_VECTORS: &[(&str, &str, &str, &str, Option<&str>)] = &[
(
"US",
"2015550123",
"US",
"(201) 555-0123",
Some("+12015550123"),
),
(
"US",
"(201) 555-0123",
"US",
"(201) 555-0123",
Some("+12015550123"),
),
(
"US",
"1 201 555 0123",
"US",
"1 (201) 555-0123",
Some("+12015550123"),
),
(
"US",
"6135550123",
"US",
"(613) 555-0123",
Some("+16135550123"),
),
(
"CA",
"4165550123",
"CA",
"(416) 555-0123",
Some("+14165550123"),
),
(
"GB",
"020 7946 0018",
"GB",
"020 7946 0018",
Some("+442079460018"),
),
(
"GB",
"2079460018",
"GB",
"2079460018",
Some("+442079460018"),
),
(
"GB",
"07400 123456",
"GB",
"07400 123456",
Some("+447400123456"),
),
("DE", "030 123456", "DE", "030 123456", Some("+4930123456")),
(
"DE",
"015112345678",
"DE",
"01511 2345678",
Some("+4915112345678"),
),
(
"FR",
"01 23 45 67 89",
"FR",
"01 23 45 67 89",
Some("+33123456789"),
),
("FR", "612345678", "FR", "612345678", Some("+33612345678")),
(
"ES",
"612 34 56 78",
"ES",
"612 34 56 78",
Some("+34612345678"),
),
(
"IT",
"312 345 6789",
"IT",
"312 345 6789",
Some("+393123456789"),
),
(
"IT",
"06 1234 5678",
"IT",
"06 1234 5678",
Some("+390612345678"),
),
(
"CO",
"300 123 4567",
"CO",
"300 1234567",
Some("+573001234567"),
),
(
"CO",
"601 2345678",
"CO",
"(601) 2345678",
Some("+576012345678"),
),
(
"MX",
"55 1234 5678",
"MX",
"55 1234 5678",
Some("+525512345678"),
),
(
"BR",
"11 98765-4321",
"BR",
"(11) 98765-4321",
Some("+5511987654321"),
),
(
"BR",
"(11) 3456-7890",
"BR",
"(11) 3456-7890",
Some("+551134567890"),
),
(
"IN",
"98765 43210",
"IN",
"98765 43210",
Some("+919876543210"),
),
(
"JP",
"03-1234-5678",
"JP",
"03-1234-5678",
Some("+81312345678"),
),
(
"JP",
"090-1234-5678",
"JP",
"090-1234-5678",
Some("+819012345678"),
),
(
"AU",
"0412 345 678",
"AU",
"0412 345 678",
Some("+61412345678"),
),
(
"AU",
"02 9876 5432",
"AU",
"(02) 9876 5432",
Some("+61298765432"),
),
(
"AR",
"011 15-2345-6789",
"AR",
"011 15-2345-6789",
Some("+5491123456789"),
),
(
"US",
"+1 201 555 0123",
"US",
"(201) 555-0123",
Some("+12015550123"),
),
(
"US",
"+1 613 555 0123",
"CA",
"(613) 555-0123",
Some("+16135550123"),
),
(
"US",
"+1 787 234 5678",
"PR",
"(787) 234-5678",
Some("+17872345678"),
),
(
"GB",
"+1 268 464 1234",
"AG",
"(268) 464-1234",
Some("+12684641234"),
),
(
"US",
"+44 20 7946 0018",
"GB",
"020 7946 0018",
Some("+442079460018"),
),
(
"US",
"+44 1481 256789",
"GG",
"01481 256789",
Some("+441481256789"),
),
(
"US",
"+44 7797 123456",
"JE",
"07797 123456",
Some("+447797123456"),
),
("US", "+44 1624 456789", "IM", "+44 1624 456789", None),
(
"US",
"+44 1624 756789",
"IM",
"01624 756789",
Some("+441624756789"),
),
(
"IM",
"01624 756789",
"IM",
"01624 756789",
Some("+441624756789"),
),
(
"US",
"+49 30 123456",
"DE",
"030 123456",
Some("+4930123456"),
),
(
"US",
"+33 1 23 45 67 89",
"FR",
"01 23 45 67 89",
Some("+33123456789"),
),
(
"US",
"+81 3 1234 5678",
"JP",
"03-1234-5678",
Some("+81312345678"),
),
(
"US",
"+61 412 345 678",
"AU",
"0412 345 678",
Some("+61412345678"),
),
(
"US",
"+55 11 98765 4321",
"BR",
"(11) 98765-4321",
Some("+5511987654321"),
),
(
"US",
"+52 55 1234 5678",
"MX",
"55 1234 5678",
Some("+525512345678"),
),
(
"US",
"+57 300 1234567",
"CO",
"300 1234567",
Some("+573001234567"),
),
(
"US",
"+91 98765 43210",
"IN",
"098765 43210",
Some("+919876543210"),
),
(
"US",
"+34 612 34 56 78",
"ES",
"612 34 56 78",
Some("+34612345678"),
),
(
"US",
"+39 06 1234 5678",
"IT",
"06 1234 5678",
Some("+390612345678"),
),
(
"US",
"+54 9 11 2345 6789",
"AR",
"011 15-2345-6789",
Some("+5491123456789"),
),
(
"US",
"+44 (0) 20 7946 0018",
"GB",
"020 7946 0018",
Some("+442079460018"),
),
(
"US",
"+800 1234 5678",
"US",
"1234 5678",
Some("+80012345678"),
),
(
"US",
"011 44 20 7946 0018",
"US",
"011 44 20 7946 0018",
Some("+442079460018"),
),
(
"GB",
"00 33 1 23 45 67 89",
"GB",
"00 33 1 23 45 67 89",
Some("+33123456789"),
),
(
"GB",
"442079460018",
"GB",
"44 20 7946 0018",
Some("+442079460018"),
),
("US", "2", "US", "2", None),
("US", "201", "US", "(201)", None),
("US", "2015", "US", "(201) 5", None),
("US", "201555", "US", "(201) 555", None),
("CA", "416555", "CA", "(416) 555", None),
("GB", "0207", "GB", "020 7", None),
("GB", "07400 12", "GB", "07400 12", None),
("DE", "0301", "DE", "030 1", None),
("FR", "0612", "FR", "06 12", None),
("ES", "6123", "ES", "612 3", None),
("IT", "31234", "IT", "312 34", None),
("CO", "30012", "CO", "300 12", None),
("MX", "551234", "MX", "55 1234", None),
("BR", "119876", "BR", "(11) 9876", None),
("IN", "98765", "IN", "98765", None),
("JP", "0312", "JP", "03-12", None),
("AU", "04123", "AU", "0412 3", None),
("US", "+44 20", "US", "+44 20", None),
("US", "+1", "US", "+1", None),
("US", "+12", "US", "+1 2", None),
("US", "2115550123", "US", "(211) 555-0123", None),
("US", "20155501234", "US", "20155501234", None),
("GB", "0000000000", "GB", "0000000000", None),
("DE", "1", "DE", "1", None),
("US", "+999 123", "US", "+999123", None),
(
"US",
"tel: +1 (201) 555-0123",
"US",
"(201) 555-0123",
Some("+12015550123"),
),
(
"US",
"call 201.555.0123 now",
"US",
"(201) 555-0123",
Some("+12015550123"),
),
(
"FR",
"a0b1c2d3e4f5g6h7i8j9",
"FR",
"01 23 45 67 89",
Some("+33123456789"),
),
("US", "abc", "US", "", None),
("US", "+", "US", "", None),
("US", "", "US", "", None),
("US", " + ", "US", "", None),
("US", "1+2", "US", "1 2", None),
];
#[test]
fn resolve_matches_libphonenumber() {
for &(selected, input, region, national, e164) in LIBPHONENUMBER_VECTORS {
let resolved = PhoneInputNumber::resolve(country(selected), input);
assert_eq!(
(
resolved.country.region_code,
resolved.national_number.as_str(),
resolved.e164.as_deref(),
resolved.is_valid,
),
(region, national, e164, e164.is_some()),
"{selected} {input:?}"
);
}
}
#[test]
fn empty_input_resolves_to_an_empty_value() {
for input in ["", "+", " + ", "abc", "++", "-()"] {
assert_eq!(
PhoneInputNumber::resolve(country("GB"), input),
PhoneInputNumber::empty(country("GB")),
"{input:?}"
);
}
}
#[test]
fn display_prefers_e164_for_valid_numbers() {
assert_eq!(
PhoneInputNumber::resolve(country("US"), "2015550123").display(),
"+12015550123"
);
assert_eq!(
PhoneInputNumber::resolve(country("US"), "201555").display(),
"(201) 555"
);
assert_eq!(PhoneInputNumber::empty(country("US")).display(), "");
}
#[test]
fn resolving_the_displayed_text_is_stable() {
for &(selected, input, _, _, _) in LIBPHONENUMBER_VECTORS {
let first = PhoneInputNumber::resolve(country(selected), input);
let second = PhoneInputNumber::resolve(first.country, &first.national_number);
let same_plan = first
.e164
.as_deref()
.is_some_and(|e164| e164.starts_with(first.country.calling_code));
if same_plan {
assert_eq!(second.e164, first.e164, "{selected} {input:?}");
}
}
}
#[test]
fn input_that_breaks_libphonenumber_does_not_panic() {
let resolved = PhoneInputNumber::resolve(country("WS"), "06");
assert!(!resolved.is_valid);
assert_eq!(resolved.e164, None);
assert_eq!(resolved.national_number, "0 6");
}
#[test]
fn sanitize_keeps_ascii_digits_and_one_leading_plus() {
let cases = [
(" +1 (201) 555-0123 ", "+12015550123"),
("1+2", "12"),
("++1", "+1"),
("a+1", "+1"),
("tel:+44-20", "+4420"),
("\u{FF11}\u{FF12}3", "3"),
("\u{0661}2", "2"),
("", ""),
("+", "+"),
];
for (input, expected) in cases {
assert_eq!(sanitize_phone_input(input), expected, "{input:?}");
}
}
#[test]
fn flags_and_picker_labels() {
assert_eq!(country("US").flag(), "\u{1F1FA}\u{1F1F8}");
assert_eq!(flag_for_region("gb"), "\u{1F1EC}\u{1F1E7}");
assert_eq!(flag_for_region("001"), "");
assert_eq!(flag_for_region("USA"), "");
assert_eq!(flag_for_region(""), "");
assert_eq!(
country("US").picker_label(),
"\u{1F1FA}\u{1F1F8} United States (+1)"
);
assert_eq!(
country("CI").picker_label(),
"\u{1F1E8}\u{1F1EE} C\u{F4}te d\u{2019}Ivoire (+225)"
);
}
#[test]
fn all_lists_every_region_in_english_collation_order() {
let countries = PhoneInputCountry::all();
let codes: Vec<&str> = countries
.iter()
.map(|country| country.region_code)
.collect();
let position = |code: &str| codes.iter().position(|candidate| *candidate == code);
assert_eq!(countries.len(), 245);
assert_eq!(codes.first(), Some(&"AF"));
assert_eq!(codes.get(1), Some(&"AX"));
assert_eq!(codes.last(), Some(&"ZW"));
assert!(position("CR") < position("CI"));
assert!(position("CI") < position("HR"));
assert!(position("CU") < position("CW"));
for country in countries {
let region = region_by_code(country.region_code)
.unwrap_or_else(|| panic!("missing metadata for {}", country.region_code));
assert_eq!(country.calling_code, format!("+{}", region.calling_code()));
assert_ne!(country.display_name, "");
assert_eq!(PhoneInputCountry::find(country.region_code), Some(*country));
}
}
#[test]
fn metadata_tables_are_sorted_for_binary_search() {
assert!(
REGIONS
.windows(2)
.all(|pair| pair[0].code() < pair[1].code())
);
assert!(
NON_GEOGRAPHIC
.windows(2)
.all(|pair| pair[0].calling_code() < pair[1].calling_code())
);
assert!(CALLING_CODES.windows(2).all(|pair| pair[0].0 < pair[1].0));
assert_eq!(REGIONS.len(), COUNTRIES.len());
for (calling_code, regions) in CALLING_CODES {
for region in *regions {
assert_eq!(
region_by_code(region).map(PhoneRegion::calling_code),
Some(*calling_code)
);
}
}
}
#[test]
fn find_accepts_region_codes_and_calling_codes() {
assert_eq!(
PhoneInputCountry::find("us").map(|country| country.region_code),
Some("US")
);
assert_eq!(
PhoneInputCountry::find(" GB ").map(|country| country.region_code),
Some("GB")
);
assert_eq!(
PhoneInputCountry::find("+44").map(|country| country.region_code),
Some("GB")
);
assert_eq!(
PhoneInputCountry::find("44").map(|country| country.region_code),
Some("GB")
);
assert_eq!(
PhoneInputCountry::find("+1").map(|country| country.region_code),
Some("US")
);
assert_eq!(
PhoneInputCountry::find("+7").map(|country| country.region_code),
Some("RU")
);
assert_eq!(PhoneInputCountry::find("+800"), None);
assert_eq!(PhoneInputCountry::find("+999"), None);
assert_eq!(PhoneInputCountry::find("XX"), None);
assert_eq!(PhoneInputCountry::find(""), None);
assert_eq!(PhoneInputCountry::find("+"), None);
}
#[test]
fn matcher_distinguishes_full_and_prefix_matches() {
assert!(pattern::matches_entirely("123", r"\d{3}"));
assert!(!pattern::matches_entirely("1234", r"\d{3}"));
assert!(pattern::matches_at_start("1234", r"\d{3}"));
assert!(!pattern::matches_at_start("12", r"\d{3}"));
assert!(pattern::matches_entirely("", ""));
assert!(!pattern::matches_entirely("1", ""));
}
#[test]
fn matcher_supports_classes_alternation_and_quantifiers() {
assert!(pattern::matches_entirely("6", "[2-46-9]"));
assert!(!pattern::matches_entirely("5", "[2-46-9]"));
assert!(pattern::matches_entirely("7", r"[\d]"));
assert!(pattern::matches_entirely("2", r"2|3\d"));
assert!(pattern::matches_entirely("34", r"2|3\d"));
assert!(!pattern::matches_entirely("3", r"2|3\d"));
assert!(pattern::matches_entirely("1212", "(?:12){2,3}"));
assert!(pattern::matches_entirely("121212", "(?:12){2,3}"));
assert!(!pattern::matches_entirely("12", "(?:12){2,3}"));
assert!(!pattern::matches_entirely("12121212", "(?:12){2,3}"));
assert!(pattern::matches_entirely("2", "1?2"));
assert!(pattern::matches_entirely("12", "1?2"));
assert!(pattern::matches_entirely("", r"\d*"));
assert!(pattern::matches_entirely("123456", r"\d*"));
assert!(!pattern::matches_entirely("", r"\d+"));
assert!(pattern::matches_entirely("12345", r"\d{2,}"));
assert!(!pattern::matches_entirely("1", r"\d{2,}"));
assert!(pattern::matches_entirely("a.b", r"a\.b"));
assert!(!pattern::matches_entirely("axb", r"a\.b"));
}
#[test]
fn matcher_end_anchor_needs_the_real_end() {
let prefix_for_parsing = r"([457]\d{6})$|1";
assert!(pattern::matches_at_start("4234567", prefix_for_parsing));
assert!(pattern::matches_at_start("1234567", prefix_for_parsing));
assert!(!pattern::matches_at_start("42345678", prefix_for_parsing));
let long_input = "4".repeat(100);
assert!(pattern::matches_at_start(&long_input, r"\d{3}"));
assert!(!pattern::matches_at_start(&long_input, r"\d{3}$"));
assert!(!pattern::matches_entirely(&long_input, r"\d*"));
}
#[test]
fn malformed_patterns_never_match() {
for malformed in [
"(12", "12)", "[1-", r"\q", "{3}", "1{3,2}", "(?=1)", "^1", ".", "1**", "a]",
] {
assert!(!pattern::matches_entirely("12", malformed), "{malformed:?}");
assert!(!pattern::matches_at_start("12", malformed), "{malformed:?}");
assert!(
pattern::captures_at_start(malformed, "12").is_none(),
"{malformed:?}"
);
assert_eq!(
pattern::replace_first(malformed, "12", "x"),
"12",
"{malformed:?}"
);
}
}
#[test]
fn captures_follow_javascript_priorities() {
let spans = |pattern: &str, input: &str| pattern::captures_at_start(pattern, input);
assert_eq!(spans("1|12", "123"), Some(vec![Some((0, 1))]));
assert_eq!(
spans(r"(\d{1,3})(\d+)", "12345"),
Some(vec![Some((0, 5)), Some((0, 3)), Some((3, 5))])
);
assert_eq!(
spans(r"(\d{1,3}?)(\d+)", "12345"),
Some(vec![Some((0, 5)), Some((0, 1)), Some((1, 5))])
);
assert_eq!(spans("(1)?2", "2"), Some(vec![Some((0, 1)), None]));
assert_eq!(spans("0|180020", "1800201234"), Some(vec![Some((0, 6))]));
assert_eq!(spans("2", "12"), None);
assert_eq!(pattern::captures("2", "12"), Some(vec![Some((1, 2))]));
}
#[test]
fn replacement_follows_javascript_substitution() {
assert_eq!(
pattern::replace_first(r"(\d{3})(\d{4})", "5550123", "$1-$2"),
"555-0123"
);
assert_eq!(
pattern::replace_first(r"(\d{3})", "12345", "[$1]"),
"[123]45"
);
assert_eq!(
pattern::replace_first("3", "12345", "<$&$`$'$$>"),
"12<31245$>45"
);
assert_eq!(pattern::replace_first("(1)", "12", "$2$9"), "$2$92");
assert_eq!(pattern::replace_first("(1)", "12", "$01"), "12");
assert_eq!(pattern::replace_first("9", "12", "x"), "12");
}
#[test]
fn partial_leading_digit_matcher_mirrors_libphonenumber() {
assert!(partial::matches("[2-9]", "2"));
assert!(!partial::matches("[2-9]", "1"));
assert!(partial::matches("21|3", "2"));
assert!(partial::matches("800", "80"));
assert!(!partial::matches("800", "81"));
assert!(partial::matches("8", "89"));
assert!(partial::matches("1(?:38|5[23])", "15"));
assert!(!partial::matches("1(?:38|5[23])", "16"));
assert!(!partial::matches(r"\d", "5"));
assert!(partial::matches("1?", "5"));
}
#[test]
fn template_patterns_replace_classes_and_standalone_digits() {
assert_eq!(template_pattern(r"(\d{3})(\d{3,4})"), r"(\d{3})(\d{3,4})");
assert_eq!(
template_pattern(r"([2-9]\d{2})(\d{4})"),
r"(\d\d{2})(\d{4})"
);
assert_eq!(
template_pattern(r"(9)(\d{4})(\d{10,12})"),
r"(\d)(\d{4})(\d{10,12})"
);
}
#[test]
fn adversarial_input_returns_quickly() {
let limit = Duration::from_secs(10);
let inputs = [
"1".repeat(100_000),
format!("+{}", "4".repeat(100_000)),
"+1".repeat(50_000),
"+".repeat(100_000),
format!("{}2015550123", "+ -".repeat(30_000)),
"0".repeat(100_000),
];
for input in &inputs {
for region in ["US", "GB", "AR", "BR", "WS"] {
let started = Instant::now();
let resolved = PhoneInputNumber::resolve(country(region), input);
assert!(
started.elapsed() < limit,
"{region} took {:?}",
started.elapsed()
);
assert!(resolved.national_number.len() <= input.len() * 2);
}
}
assert!(PhoneInputNumber::resolve(country("US"), &inputs[4]).is_valid);
}
#[test]
fn adversarial_patterns_stay_bounded() {
let started = Instant::now();
let deep = format!("{}1{}", "(?:".repeat(1_000), ")".repeat(1_000));
assert!(!pattern::matches_entirely("1", &deep));
assert!(pattern::captures_at_start(&deep, "1").is_none());
assert!(!pattern::matches_entirely("1", "1{999999999}"));
assert!(!pattern::matches_entirely("1", "(?:1?){999999999}1{2}"));
assert!(pattern::matches_entirely("11", "(?:1?){999999999}"));
assert!(pattern::captures_at_start("(?:1?){999999999}", "1").is_none());
assert!(started.elapsed() < Duration::from_secs(10));
}
}