Skip to main content

lumen_dioxus/pickers/
phone_engine.rs

1//! Dependency-free phone number engine behind `PhoneInput`.
2//!
3//! `@santi020k/lumen-core` resolves phone input with `libphonenumber-js/max`: its as-you-type
4//! formatter shapes what the field shows, and its parsed number decides validity, the E.164 value,
5//! and the national format of a complete international number. This module ports the parts of
6//! that library the phone input uses to plain Rust over the same metadata, which
7//! `scripts/generate-dioxus-pickers-phone.mjs` writes to `phone_data.rs`.
8//!
9//! Metadata patterns use a small regular-expression subset. [`pattern`] evaluates it without
10//! backtracking: boolean matches walk the pattern once over sets of reachable input positions, and
11//! the few places that need capture groups run a Pike virtual machine. Both take time linear in the
12//! pattern size for the short inputs a phone number has, and a malformed pattern never panics; it
13//! simply does not match.
14
15// cspell:words Ivoire NANP peekable rfind
16
17use super::phone_data::{CALLING_CODES, COUNTRIES, NON_GEOGRAPHIC, REGIONS};
18
19/// A country the phone input can offer.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21pub struct PhoneInputCountry {
22    /// ISO 3166-1 alpha-2 region code, such as `US`.
23    pub region_code: &'static str,
24    /// International calling code with its leading plus sign, such as `+1`.
25    pub calling_code: &'static str,
26    /// English display name, such as `United States`.
27    pub display_name: &'static str,
28}
29
30impl PhoneInputCountry {
31    /// Every supported country in picker order: English display names in English collation order,
32    /// which is what the React phone input shows with its default locale.
33    pub fn all() -> &'static [PhoneInputCountry] {
34        COUNTRIES
35    }
36
37    /// Finds a country by its region code (case-insensitive, such as `us`) or by a calling code
38    /// (such as `+44`, which resolves to the main region for that code).
39    pub fn find(region_or_calling_code: &str) -> Option<PhoneInputCountry> {
40        let query = region_or_calling_code.trim();
41        let calling_code = query.strip_prefix('+').unwrap_or(query);
42
43        if !calling_code.is_empty() && calling_code.bytes().all(|byte| byte.is_ascii_digit()) {
44            let main_region = regions_for_calling_code(calling_code)?.first()?;
45
46            return country_for_region(main_region);
47        }
48
49        COUNTRIES
50            .iter()
51            .find(|country| country.region_code.eq_ignore_ascii_case(query))
52            .copied()
53    }
54
55    /// The flag emoji built from the region code's regional indicator symbols.
56    pub fn flag(&self) -> String {
57        flag_for_region(self.region_code)
58    }
59
60    /// The label the country picker shows, such as `🇺🇸 United States (+1)`.
61    pub fn picker_label(&self) -> String {
62        format!(
63            "{} {} ({})",
64            self.flag(),
65            self.display_name,
66            self.calling_code
67        )
68    }
69}
70
71/// A parsed phone value.
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub struct PhoneInputNumber {
74    /// The country the number belongs to. International input switches it to the country the
75    /// calling code and number identify; national input keeps the selected country.
76    pub country: PhoneInputCountry,
77    /// The E.164 value, such as `+12015550123`, present only when the number is valid.
78    pub e164: Option<String>,
79    /// Whether the number is a complete, valid number for its country.
80    pub is_valid: bool,
81    /// The text the phone field shows: the as-you-type formatted input, or the national format of
82    /// a valid international number.
83    pub national_number: String,
84}
85
86impl PhoneInputNumber {
87    /// An empty value for `country`.
88    pub fn empty(country: PhoneInputCountry) -> Self {
89        Self {
90            country,
91            e164: None,
92            is_valid: false,
93            national_number: String::new(),
94        }
95    }
96
97    /// Formats and validates `input` for `country`, like `resolveLumenPhoneNumber` in
98    /// `@santi020k/lumen-core`.
99    ///
100    /// National input is formatted as the user types it. Input that starts with `+` is read as an
101    /// international number: the calling code picks the country, and a valid number is shown in
102    /// that country's national format.
103    pub fn resolve(country: PhoneInputCountry, input: &str) -> Self {
104        let normalized = sanitize_phone_input(input);
105
106        if normalized.is_empty() || normalized == "+" {
107            return Self::empty(country);
108        }
109
110        let international = normalized.starts_with('+');
111        let default_region = if international {
112            None
113        } else {
114            region_by_code(country.region_code)
115        };
116
117        let mut typing = AsYouType::new(default_region);
118        let formatted_input = typing.input(&normalized);
119        let parsed = typing.number();
120        let valid = parsed.as_ref().is_some_and(ParsedNumber::is_valid);
121
122        let resolved_country = if international {
123            parsed
124                .as_ref()
125                .and_then(|number| number.region)
126                .and_then(|region| country_for_region(region.code()))
127                .unwrap_or(country)
128        } else {
129            country
130        };
131
132        match parsed.filter(|_| valid) {
133            Some(number) => Self {
134                country: resolved_country,
135                e164: Some(number.e164()),
136                is_valid: true,
137                national_number: if international {
138                    number.format_national()
139                } else {
140                    formatted_input
141                },
142            },
143            None => Self {
144                country: resolved_country,
145                e164: None,
146                is_valid: false,
147                national_number: formatted_input,
148            },
149        }
150    }
151
152    /// The value for read-only presentation, like `formatLumenPhoneNumber`: the E.164 value of a
153    /// valid number, otherwise the editable national text.
154    pub fn display(&self) -> String {
155        match (&self.e164, self.is_valid) {
156            (Some(e164), true) => e164.clone(),
157            _ => self.national_number.clone(),
158        }
159    }
160}
161
162/// Keeps ASCII digits and a leading plus sign, like `sanitizeLumenPhoneInput`.
163pub(crate) fn sanitize_phone_input(input: &str) -> String {
164    let mut normalized = String::new();
165
166    for character in input.chars() {
167        if character.is_ascii_digit() || (character == '+' && normalized.is_empty()) {
168            normalized.push(character);
169        }
170    }
171
172    normalized
173}
174
175/// The flag emoji for a two-letter region code, or an empty string for anything else.
176pub(crate) fn flag_for_region(region: &str) -> String {
177    const REGIONAL_INDICATOR_A: u32 = 0x1F1E6;
178
179    let normalized = region.to_uppercase();
180
181    if normalized.len() != 2 || !normalized.bytes().all(|byte| byte.is_ascii_uppercase()) {
182        return String::new();
183    }
184
185    normalized
186        .bytes()
187        .filter_map(|letter| char::from_u32(REGIONAL_INDICATOR_A + u32::from(letter - b'A')))
188        .collect()
189}
190
191/// Numbering-plan metadata for one region, generated from `libphonenumber-js` metadata.
192pub(crate) struct PhoneRegion(
193    /// ISO 3166-1 alpha-2 region code, or `001` for a non-geographic plan.
194    pub(crate) &'static str,
195    /// Calling code without the plus sign.
196    pub(crate) &'static str,
197    /// Pattern for the international dialing prefix used to call abroad from this region.
198    pub(crate) &'static str,
199    /// Pattern every national significant number matches.
200    pub(crate) &'static str,
201    /// Possible national significant number lengths, ascending.
202    pub(crate) &'static [u8],
203    /// National (trunk) prefix, or empty.
204    pub(crate) &'static str,
205    /// Pattern for the prefix to strip from national input, or empty to strip the national prefix.
206    pub(crate) &'static str,
207    /// Replacement for the national prefix pattern's captures, or empty.
208    pub(crate) &'static str,
209    /// Pattern that identifies this region among regions sharing a calling code, or empty.
210    pub(crate) &'static str,
211    /// Formats, or empty to use the formats of the calling code's main region.
212    pub(crate) &'static [PhoneFormat],
213    /// Number type patterns (fixed line, mobile, toll free, and so on).
214    pub(crate) &'static [&'static str],
215);
216
217/// One way to format national significant numbers, generated from `libphonenumber-js` metadata.
218pub(crate) struct PhoneFormat(
219    /// Pattern of capture groups a complete number must match.
220    pub(crate) &'static str,
221    /// National template, such as `($1) $2-$3`.
222    pub(crate) &'static str,
223    /// Leading-digit patterns for 3, 4, 5, and more typed digits; the last is the most precise.
224    pub(crate) &'static [&'static str],
225    /// National prefix formatting rule, such as `0$1`, or empty.
226    pub(crate) &'static str,
227    /// Whether the national prefix is optional when formatting.
228    pub(crate) bool,
229    /// International template, or empty to reuse the national template.
230    pub(crate) &'static str,
231);
232
233impl PhoneRegion {
234    fn code(&self) -> &'static str {
235        self.0
236    }
237
238    fn calling_code(&self) -> &'static str {
239        self.1
240    }
241
242    fn idd_prefix(&self) -> &'static str {
243        self.2
244    }
245
246    fn national_pattern(&self) -> &'static str {
247        self.3
248    }
249
250    fn possible_lengths(&self) -> &'static [u8] {
251        self.4
252    }
253
254    fn national_prefix(&self) -> &'static str {
255        self.5
256    }
257
258    /// The explicit national prefix pattern, without falling back to the national prefix.
259    fn own_national_prefix_for_parsing(&self) -> &'static str {
260        self.6
261    }
262
263    fn national_prefix_for_parsing(&self) -> &'static str {
264        if self.6.is_empty() { self.5 } else { self.6 }
265    }
266
267    fn national_prefix_transform_rule(&self) -> &'static str {
268        self.7
269    }
270
271    fn leading_digits(&self) -> &'static str {
272        self.8
273    }
274
275    /// Regions sharing a calling code keep their formats in the code's main region.
276    fn formats(&self) -> &'static [PhoneFormat] {
277        if !self.9.is_empty() {
278            return self.9;
279        }
280
281        match regions_for_calling_code(self.calling_code())
282            .and_then(|regions| regions.first())
283            .and_then(|main| region_by_code(main))
284        {
285            Some(main) => main.9,
286            None => &[],
287        }
288    }
289
290    /// `isValid()` from `libphonenumber-js`: the general pattern and at least one type pattern
291    /// match the whole national significant number. Every generated type pattern only matches its
292    /// own possible lengths, which the generator verifies, so lengths need no separate check.
293    fn is_valid_number(&self, national_number: &str) -> bool {
294        pattern::matches_entirely(national_number, self.national_pattern())
295            && (self.10.is_empty()
296                || self
297                    .10
298                    .iter()
299                    .any(|type_pattern| pattern::matches_entirely(national_number, type_pattern)))
300    }
301
302    /// `checkNumberLength()` from `libphonenumber-js` against the general possible lengths.
303    fn check_number_length(&self, national_number: &str) -> NumberLength {
304        let lengths = self.possible_lengths();
305        let actual = national_number.len();
306
307        let (Some(&minimum), Some(&maximum)) = (lengths.first(), lengths.last()) else {
308            return NumberLength::Possible;
309        };
310
311        if usize::from(minimum) == actual {
312            NumberLength::Possible
313        } else if usize::from(minimum) > actual {
314            NumberLength::TooShort
315        } else if usize::from(maximum) < actual {
316            NumberLength::TooLong
317        } else if lengths
318            .iter()
319            .skip(1)
320            .any(|&length| usize::from(length) == actual)
321        {
322            NumberLength::Possible
323        } else {
324            NumberLength::InvalidLength
325        }
326    }
327}
328
329impl PhoneFormat {
330    fn pattern(&self) -> &'static str {
331        self.0
332    }
333
334    fn template(&self) -> &'static str {
335        self.1
336    }
337
338    fn leading_digits(&self) -> &'static [&'static str] {
339        self.2
340    }
341
342    fn national_prefix_formatting_rule(&self) -> &'static str {
343        self.3
344    }
345
346    fn national_prefix_is_optional(&self) -> bool {
347        self.4
348    }
349
350    fn international_template(&self) -> &'static str {
351        if self.5.is_empty() { self.1 } else { self.5 }
352    }
353
354    /// Whether the national prefix formatting rule adds a national prefix rather than only
355    /// wrapping the first group, like `($1)`.
356    fn uses_national_prefix(&self) -> bool {
357        let rule = self.national_prefix_formatting_rule();
358
359        !rule.is_empty() && !matches!(rule, "$1" | "($1" | "$1)" | "($1)")
360    }
361
362    fn national_prefix_is_mandatory(&self) -> bool {
363        self.uses_national_prefix() && !self.national_prefix_is_optional()
364    }
365}
366
367#[derive(Clone, Copy, PartialEq, Eq)]
368enum NumberLength {
369    Possible,
370    TooShort,
371    TooLong,
372    InvalidLength,
373}
374
375fn region_by_code(code: &str) -> Option<&'static PhoneRegion> {
376    REGIONS
377        .binary_search_by(|region| region.code().cmp(code))
378        .ok()
379        .and_then(|index| REGIONS.get(index))
380}
381
382fn country_for_region(code: &str) -> Option<PhoneInputCountry> {
383    COUNTRIES
384        .iter()
385        .find(|country| country.region_code == code)
386        .copied()
387}
388
389/// Geographic regions for a calling code, main region first.
390fn regions_for_calling_code(calling_code: &str) -> Option<&'static [&'static str]> {
391    CALLING_CODES
392        .binary_search_by(|(code, _)| (*code).cmp(calling_code))
393        .ok()
394        .and_then(|index| CALLING_CODES.get(index))
395        .map(|(_, regions)| *regions)
396}
397
398fn non_geographic_plan(calling_code: &str) -> Option<&'static PhoneRegion> {
399    NON_GEOGRAPHIC
400        .binary_search_by(|region| region.calling_code().cmp(calling_code))
401        .ok()
402        .and_then(|index| NON_GEOGRAPHIC.get(index))
403}
404
405/// `selectNumberingPlan(callingCode)`: the main region of a calling code, or its non-geographic
406/// plan.
407fn plan_for_calling_code(calling_code: &str) -> Option<&'static PhoneRegion> {
408    match regions_for_calling_code(calling_code) {
409        Some(regions) => regions.first().and_then(|main| region_by_code(main)),
410        None => non_geographic_plan(calling_code),
411    }
412}
413
414/// The calling code as a static string when it exists, geographic or not.
415fn known_calling_code(calling_code: &str) -> Option<&'static str> {
416    if let Ok(index) = CALLING_CODES.binary_search_by(|(code, _)| (*code).cmp(calling_code)) {
417        return CALLING_CODES.get(index).map(|(code, _)| *code);
418    }
419
420    non_geographic_plan(calling_code).map(PhoneRegion::calling_code)
421}
422
423/// `getCountryByNationalNumber()`: the first region whose leading digits or number types match.
424fn region_by_national_number(
425    national_number: &str,
426    region_codes: &[&str],
427) -> Option<&'static PhoneRegion> {
428    region_codes
429        .iter()
430        .filter_map(|code| region_by_code(code))
431        .find(|region| {
432            if region.leading_digits().is_empty() {
433                region.is_valid_number(national_number)
434            } else {
435                !national_number.is_empty()
436                    && pattern::matches_at_start(national_number, region.leading_digits())
437            }
438        })
439}
440
441/// `getCountryByCallingCode()`.
442fn region_by_calling_code(
443    calling_code: &str,
444    national_number: &str,
445) -> Option<&'static PhoneRegion> {
446    let regions = regions_for_calling_code(calling_code)?;
447
448    if let [only] = regions {
449        return region_by_code(only);
450    }
451
452    region_by_national_number(national_number, regions)
453}
454
455fn same_region(left: Option<&PhoneRegion>, right: Option<&PhoneRegion>) -> bool {
456    match (left, right) {
457        (Some(left), Some(right)) => left.code() == right.code(),
458        (None, None) => true,
459        _ => false,
460    }
461}
462
463fn same_format(left: &PhoneFormat, right: &PhoneFormat) -> bool {
464    std::ptr::eq(left, right)
465}
466
467/// A number `libphonenumber-js` would build from the typed input: `new PhoneNumber(...)`.
468struct ParsedNumber {
469    /// The detected region, if any.
470    region: Option<&'static PhoneRegion>,
471    calling_code: &'static str,
472    national_number: String,
473}
474
475impl ParsedNumber {
476    fn plan(&self) -> Option<&'static PhoneRegion> {
477        self.region
478            .or_else(|| plan_for_calling_code(self.calling_code))
479    }
480
481    fn is_valid(&self) -> bool {
482        self.plan()
483            .is_some_and(|plan| plan.is_valid_number(&self.national_number))
484    }
485
486    fn e164(&self) -> String {
487        format!("+{}{}", self.calling_code, self.national_number)
488    }
489
490    /// `formatNational()`: the first format whose last leading-digit pattern and full pattern
491    /// match, applied with its national prefix formatting rule.
492    fn format_national(&self) -> String {
493        let number = self.national_number.as_str();
494        let Some(plan) = self.plan() else {
495            return number.to_owned();
496        };
497
498        let format = plan.formats().iter().find(|format| {
499            format
500                .leading_digits()
501                .last()
502                .is_none_or(|leading| pattern::matches_at_start(number, leading))
503                && pattern::matches_entirely(number, format.pattern())
504        });
505
506        match format {
507            Some(format) => format_with_pattern(number, format, false, true),
508            None => number.to_owned(),
509        }
510    }
511}
512
513/// `formatNationalNumberUsingFormat()`.
514fn format_with_pattern(
515    number: &str,
516    format: &PhoneFormat,
517    international: bool,
518    with_national_prefix: bool,
519) -> String {
520    let rule = format.national_prefix_formatting_rule();
521    let template = if international {
522        format.international_template().to_owned()
523    } else if with_national_prefix && !rule.is_empty() {
524        replace_first_group_reference(format.template(), rule)
525    } else {
526        format.template().to_owned()
527    };
528
529    let formatted = pattern::replace_first(format.pattern(), number, &template);
530
531    if international {
532        apply_international_separator_style(&formatted)
533    } else {
534        formatted
535    }
536}
537
538/// `template.replace(/(\$\d)/, rule)`: the rule's `$1` stands for the replaced reference.
539fn replace_first_group_reference(template: &str, rule: &str) -> String {
540    let bytes = template.as_bytes();
541    let Some(index) = bytes
542        .windows(2)
543        .position(|pair| pair[0] == b'$' && pair[1].is_ascii_digit())
544    else {
545        return template.to_owned();
546    };
547
548    let reference = &template[index..index + 2];
549    let captures = [Some((index, index + 2)), Some((index, index + 2))];
550
551    format!(
552        "{}{}{}",
553        &template[..index],
554        pattern::expand_replacement(rule, template, &captures),
555        &template[index + reference.len()..]
556    )
557}
558
559/// Characters `libphonenumber-js` treats as phone number punctuation (`VALID_PUNCTUATION`).
560fn is_valid_punctuation(character: char) -> bool {
561    matches!(
562        character,
563        '-' | '\u{2010}'
564            ..='\u{2015}'
565                | '\u{2212}'
566                | '\u{30FC}'
567                | '\u{FF0D}'
568                | '\u{FF0F}'
569                | '/'
570                | '\u{FF0E}'
571                | '.'
572                | ' '
573                | '\u{00A0}'
574                | '\u{00AD}'
575                | '\u{200B}'
576                | '\u{2060}'
577                | '\u{3000}'
578                | '('
579                | ')'
580                | '\u{FF08}'
581                | '\u{FF09}'
582                | '\u{FF3B}'
583                | '\u{FF3D}'
584                | '['
585                | ']'
586                | '~'
587                | '\u{2053}'
588                | '\u{223C}'
589                | '\u{FF5E}'
590    )
591}
592
593/// `applyInternationalSeparatorStyle()`: punctuation runs become single spaces.
594fn apply_international_separator_style(formatted: &str) -> String {
595    let mut output = String::with_capacity(formatted.len());
596    let mut in_punctuation = false;
597
598    for character in formatted.chars() {
599        if is_valid_punctuation(character) {
600            if !in_punctuation {
601                output.push(' ');
602            }
603
604            in_punctuation = true;
605        } else {
606            output.push(character);
607            in_punctuation = false;
608        }
609    }
610
611    output.trim().to_owned()
612}
613
614fn parse_digits(text: &str) -> String {
615    text.chars().filter(char::is_ascii_digit).collect()
616}
617
618/// `NON_ALTERING_FORMAT_REG_EXP`: the template keeps `$1` and only adds punctuation after it.
619fn is_non_altering_template(template: &str) -> bool {
620    template.match_indices("$1").any(|(index, _)| {
621        let mut rest = template[index + 2..].chars().peekable();
622
623        loop {
624            while rest
625                .next_if(|&character| is_valid_punctuation(character))
626                .is_some()
627            {}
628
629            match rest.next() {
630                None => return true,
631                Some('$') => {
632                    if rest.next_if(char::is_ascii_digit).is_none() {
633                        return false;
634                    }
635                }
636                Some(_) => return false,
637            }
638        }
639    })
640}
641
642/// The template pattern `libphonenumber-js` derives from a format pattern for as-you-type
643/// formatting: classes and standalone digits become `\d`.
644fn template_pattern(format_pattern: &str) -> String {
645    // `[...]` without nested brackets becomes `\d`.
646    let mut without_classes = String::with_capacity(format_pattern.len());
647    let mut rest = format_pattern;
648
649    while let Some(start) = rest.find('[') {
650        without_classes.push_str(&rest[..start]);
651
652        let after = &rest[start + 1..];
653
654        match after.find([']', '[']) {
655            Some(end) if after.as_bytes().get(end) == Some(&b']') => {
656                without_classes.push_str("\\d");
657                rest = &after[end + 1..];
658            }
659            _ => {
660                without_classes.push('[');
661                rest = after;
662            }
663        }
664    }
665
666    without_classes.push_str(rest);
667
668    // A digit followed by two characters other than `,` and `}` (so not a quantifier bound).
669    let bytes = without_classes.as_bytes();
670    let mut output = String::with_capacity(bytes.len() + 8);
671
672    for (index, &byte) in bytes.iter().enumerate() {
673        let followed_by_two = matches!(
674            (bytes.get(index + 1), bytes.get(index + 2)),
675            (Some(first), Some(second))
676                if !matches!(first, b',' | b'}') && !matches!(second, b',' | b'}')
677        );
678
679        if byte.is_ascii_digit() && followed_by_two {
680            output.push_str("\\d");
681        } else {
682            output.push(char::from(byte));
683        }
684    }
685
686    output
687}
688
689/// `cutAndStripNonPairedParens()`.
690fn cut_and_strip_non_paired_parens(text: &str, cut_before: usize) -> String {
691    let bytes = text.as_bytes();
692    let cut = if bytes.get(cut_before) == Some(&b')') {
693        cut_before + 1
694    } else {
695        cut_before
696    };
697
698    let kept = &bytes[..cut.min(bytes.len())];
699    let mut dangling = Vec::new();
700
701    for (index, &byte) in kept.iter().enumerate() {
702        if byte == b'(' {
703            dangling.push(index);
704        } else if byte == b')' {
705            dangling.pop();
706        }
707    }
708
709    kept.iter()
710        .enumerate()
711        .filter(|(index, _)| !dangling.contains(index))
712        .map(|(_, &byte)| char::from(byte))
713        .collect()
714}
715
716/// `populateTemplateWithDigits()`: fills `x` placeholders left to right.
717fn populate_template_with_digits(
718    template: &str,
719    position: Option<usize>,
720    digits: &str,
721) -> Option<(String, Option<usize>)> {
722    let mut template = template.to_owned();
723    let mut position = position;
724
725    for digit in digits.chars() {
726        let search_from = position.map_or(0, |position| position + 1);
727
728        if !template
729            .get(search_from..)
730            .is_some_and(|rest| rest.contains(DIGIT_PLACEHOLDER))
731        {
732            return None;
733        }
734
735        let index = template.find(DIGIT_PLACEHOLDER)?;
736
737        template.replace_range(index..=index, digit.encode_utf8(&mut [0; 4]));
738        position = Some(index);
739    }
740
741    Some((template, position))
742}
743
744const DIGIT_PLACEHOLDER: char = 'x';
745
746/// What `extractNationalNumberFromPossiblyIncompleteNumber()` returns.
747struct NationalNumberExtraction {
748    national_number: String,
749    /// The national prefix, or empty when none was detected.
750    national_prefix: String,
751}
752
753/// `extractNationalNumberFromPossiblyIncompleteNumber()`.
754fn extract_national_number_from_possibly_incomplete_number(
755    number: &str,
756    plan: &PhoneRegion,
757) -> NationalNumberExtraction {
758    let prefix_pattern = plan.national_prefix_for_parsing();
759    let unchanged = || NationalNumberExtraction {
760        national_number: number.to_owned(),
761        national_prefix: String::new(),
762    };
763
764    if number.is_empty() || prefix_pattern.is_empty() {
765        return unchanged();
766    }
767
768    let Some(captures) = pattern::captures_at_start(prefix_pattern, number) else {
769        return unchanged();
770    };
771
772    let Some(Some((_, match_end))) = captures.first().copied() else {
773        return unchanged();
774    };
775
776    let group_count = captures.len() - 1;
777    let group_text = |group: usize| {
778        captures
779            .get(group)
780            .copied()
781            .flatten()
782            .and_then(|(start, end)| number.get(start..end))
783    };
784
785    let has_captured_groups =
786        group_count > 0 && group_text(group_count).is_some_and(|text| !text.is_empty());
787    let transform_rule = plan.national_prefix_transform_rule();
788
789    let after_match = number.get(match_end..).unwrap_or_default();
790    let national_number = if !transform_rule.is_empty() && has_captured_groups {
791        format!(
792            "{}{after_match}",
793            pattern::expand_replacement(transform_rule, number, &captures)
794        )
795    } else {
796        after_match.to_owned()
797    };
798
799    let national_prefix = if has_captured_groups {
800        // `number.indexOf(match[1])`, where an unmatched group reads as "undefined".
801        let end = match group_text(1).map(|first| number.find(first)) {
802            Some(Some(position)) => position,
803            _ => number.len().saturating_sub(1),
804        };
805        let possible_national_prefix = number.get(..end).unwrap_or_default();
806
807        let national_prefix = plan.national_prefix();
808
809        if !national_prefix.is_empty() && possible_national_prefix == national_prefix {
810            national_prefix.to_owned()
811        } else {
812            String::new()
813        }
814    } else {
815        number.get(..match_end).unwrap_or_default().to_owned()
816    };
817
818    NationalNumberExtraction {
819        national_number,
820        national_prefix,
821    }
822}
823
824/// `extractNationalNumber()`: strips the national prefix only when the rest is still plausible.
825fn extract_national_number(number: &str, plan: &PhoneRegion) -> String {
826    let extraction = extract_national_number_from_possibly_incomplete_number(number, plan);
827    let national_number = extraction.national_number;
828
829    if national_number == number {
830        return national_number;
831    }
832
833    let national_pattern = plan.national_pattern();
834
835    if pattern::matches_entirely(number, national_pattern)
836        && !pattern::matches_entirely(&national_number, national_pattern)
837    {
838        return number.to_owned();
839    }
840
841    let length_plan = region_by_calling_code(plan.calling_code(), &national_number).unwrap_or(plan);
842
843    if matches!(
844        length_plan.check_number_length(&national_number),
845        NumberLength::TooShort | NumberLength::InvalidLength
846    ) {
847        return number.to_owned();
848    }
849
850    national_number
851}
852
853/// `extractCountryCallingCodeFromInternationalNumberWithoutPlusSign()`.
854fn calling_code_without_plus_sign(number: &str, region: &PhoneRegion) -> Option<&'static str> {
855    let calling_code = region.calling_code();
856    let shorter = number.strip_prefix(calling_code)?;
857    let shorter_national_number = extract_national_number(shorter, region);
858    let national_number = extract_national_number(number, region);
859    let national_pattern = region.national_pattern();
860
861    let better_without_calling_code =
862        !pattern::matches_entirely(&national_number, national_pattern)
863            && pattern::matches_entirely(&shorter_national_number, national_pattern);
864
865    (better_without_calling_code
866        || region.check_number_length(&national_number) == NumberLength::TooLong)
867        .then_some(calling_code)
868}
869
870/// `stripIddPrefix()`: the digits after the region's international dialing prefix.
871fn strip_idd_prefix<'a>(number: &'a str, region: &PhoneRegion) -> Option<&'a str> {
872    let idd_prefix = region.idd_prefix();
873
874    if idd_prefix.is_empty() {
875        return None;
876    }
877
878    let captures = pattern::captures_at_start(idd_prefix, number)?;
879    let (_, end) = captures.first().copied().flatten()?;
880    let rest = number.get(end..)?;
881
882    // Calling codes never start with 0.
883    if rest.starts_with('0') {
884        return None;
885    }
886
887    Some(rest)
888}
889
890/// `extractCountryCallingCode()` for `+digits`: the longest-known calling code of up to three
891/// digits and the rest of the number.
892fn split_calling_code(digits: &str) -> Option<(&'static str, &str)> {
893    if digits.starts_with('0') {
894        return None;
895    }
896
897    (1..=3.min(digits.len())).find_map(|length| {
898        let calling_code = known_calling_code(digits.get(..length)?)?;
899
900        Some((calling_code, digits.get(length..)?))
901    })
902}
903
904/// The typed number's state (`AsYouTypeState`). Empty strings stand for `undefined`.
905#[derive(Default)]
906struct TypingState {
907    international: bool,
908    missing_plus: bool,
909    idd_prefix: String,
910    calling_code: Option<&'static str>,
911    country: Option<&'static PhoneRegion>,
912    digits: String,
913    national_significant_number: String,
914    national_significant_number_is_modified: bool,
915    national_prefix: String,
916    prefix_before_national_significant_number: String,
917}
918
919impl TypingState {
920    fn national_digits(&self) -> String {
921        if !self.international {
922            return self.digits.clone();
923        }
924
925        let skip = self.idd_prefix.len() + self.calling_code.map_or(0, str::len);
926
927        self.digits.get(skip..).unwrap_or_default().to_owned()
928    }
929
930    fn digits_without_international_prefix(&self) -> &str {
931        if self.international && !self.idd_prefix.is_empty() {
932            return self.digits.get(self.idd_prefix.len()..).unwrap_or_default();
933        }
934
935        &self.digits
936    }
937
938    fn reset_national_significant_number(&mut self) {
939        self.national_significant_number = self.national_digits();
940        self.national_significant_number_is_modified = false;
941        self.national_prefix.clear();
942        self.prefix_before_national_significant_number.clear();
943    }
944}
945
946/// `AsYouTypeParser` flags.
947#[derive(Default)]
948struct ParserState {
949    has_selected_numbering_plan: bool,
950    could_possibly_extract_another_national_significant_number: bool,
951    has_extracted_national_significant_number: bool,
952}
953
954/// `AsYouTypeFormatter` state.
955#[derive(Default)]
956struct FormatterState {
957    matching_formats: Vec<&'static PhoneFormat>,
958    chosen_format: Option<&'static PhoneFormat>,
959    template: String,
960    populated_template: String,
961    populated_position: Option<usize>,
962    is_nanp: bool,
963}
964
965/// A port of `AsYouType` from `libphonenumber-js`, fed the whole input at once the way
966/// `resolveLumenPhoneNumber` uses it.
967struct AsYouType {
968    default_country: Option<&'static PhoneRegion>,
969    /// The selected numbering plan (`metadata.numberingPlan`).
970    plan: Option<&'static PhoneRegion>,
971    state: TypingState,
972    parser: ParserState,
973    formatter: FormatterState,
974}
975
976impl AsYouType {
977    fn new(default_country: Option<&'static PhoneRegion>) -> Self {
978        let mut typing = Self {
979            default_country,
980            plan: None,
981            state: TypingState::default(),
982            parser: ParserState::default(),
983            formatter: FormatterState::default(),
984        };
985
986        typing.init_country_and_calling_code(default_country, None);
987
988        typing
989    }
990
991    // State transitions and the callbacks `AsYouType` registers on them.
992
993    fn init_country_and_calling_code(
994        &mut self,
995        country: Option<&'static PhoneRegion>,
996        calling_code: Option<&'static str>,
997    ) {
998        self.state.country = country;
999        self.set_calling_code(calling_code);
1000    }
1001
1002    fn set_calling_code(&mut self, calling_code: Option<&'static str>) {
1003        self.state.calling_code = calling_code;
1004
1005        // `onCallingCodeChange`: select the plan, then reset the formatter and the parser.
1006        self.plan = match (self.state.country, calling_code) {
1007            (Some(country), _) => Some(country),
1008            (None, Some(calling_code)) => plan_for_calling_code(calling_code),
1009            (None, None) => None,
1010        };
1011
1012        self.reset_formatter();
1013
1014        // `AsYouTypeParser.reset()`: a prefix pattern with more than digits and classes may
1015        // match differently once more digits arrive.
1016        let prefix_pattern = self
1017            .plan
1018            .map_or("", PhoneRegion::own_national_prefix_for_parsing);
1019
1020        self.parser.has_selected_numbering_plan = self.plan.is_some();
1021        self.parser
1022            .could_possibly_extract_another_national_significant_number = prefix_pattern
1023            .bytes()
1024            .any(|byte| !matches!(byte, b'0'..=b'9' | b'[' | b']'));
1025    }
1026
1027    fn start_international_number_state(
1028        &mut self,
1029        country: Option<&'static PhoneRegion>,
1030        calling_code: Option<&'static str>,
1031    ) {
1032        self.state.international = true;
1033        self.init_country_and_calling_code(country, calling_code);
1034    }
1035
1036    fn on_national_significant_number_change(&mut self) {
1037        self.determine_the_country_if_needed();
1038        self.reset_formatter();
1039    }
1040
1041    fn determine_the_country_if_needed(&mut self) {
1042        let ambiguous = self
1043            .state
1044            .calling_code
1045            .and_then(regions_for_calling_code)
1046            .is_some_and(|regions| regions.len() > 1);
1047
1048        if self.state.country.is_none() || ambiguous {
1049            let country = if self.state.international {
1050                self.state.calling_code.and_then(|calling_code| {
1051                    region_by_calling_code(calling_code, &self.state.national_significant_number)
1052                })
1053            } else {
1054                None
1055            };
1056
1057            if !same_region(country, self.state.country) {
1058                self.state.country = country;
1059
1060                if country.is_some() {
1061                    self.plan = country;
1062                }
1063            }
1064        }
1065    }
1066
1067    // `AsYouType.input()` and the parser.
1068
1069    fn input(&mut self, text: &str) -> String {
1070        let (digits, has_plus) = match text.strip_prefix('+') {
1071            Some(rest) => (parse_digits(rest), true),
1072            None => (parse_digits(text), false),
1073        };
1074
1075        if has_plus && self.state.digits.is_empty() {
1076            self.start_international_number_state(None, None);
1077
1078            if digits.is_empty() {
1079                return "+".to_owned();
1080            }
1081        }
1082
1083        if digits.is_empty() {
1084            return String::new();
1085        }
1086
1087        self.input_digits(&digits);
1088        self.determine_the_country_if_needed();
1089
1090        if !self.state.national_significant_number.is_empty() {
1091            self.narrow_down_matching_formats();
1092        }
1093
1094        let mut formatted = None;
1095
1096        if self.plan.is_some() {
1097            formatted = self.format(&digits);
1098        }
1099
1100        if formatted.is_none() && self.re_extract_national_significant_number() {
1101            self.determine_the_country_if_needed();
1102
1103            let national_digits = self.state.national_digits();
1104
1105            if !national_digits.is_empty() {
1106                formatted = self.format(&national_digits);
1107            }
1108        }
1109
1110        match formatted.filter(|formatted| !formatted.is_empty()) {
1111            Some(formatted) => self.full_number(&formatted),
1112            None => self.non_formatted_number(),
1113        }
1114    }
1115
1116    fn input_digits(&mut self, next_digits: &str) {
1117        let previous_length = self.state.digits.len();
1118        let has_received_three_leading_digits =
1119            previous_length < 3 && previous_length + next_digits.len() >= 3;
1120
1121        self.state.digits.push_str(next_digits);
1122
1123        if has_received_three_leading_digits {
1124            self.extract_idd_prefix();
1125        }
1126
1127        if self.state.international && self.state.calling_code.is_none() {
1128            if !self.extract_country_calling_code() {
1129                return;
1130            }
1131        } else {
1132            self.state.national_significant_number.push_str(next_digits);
1133        }
1134
1135        if !self.state.international && !self.parser.has_extracted_national_significant_number {
1136            let national_digits = self.state.national_digits();
1137
1138            self.extract_national_significant_number(&national_digits);
1139        }
1140    }
1141
1142    fn extract_country_calling_code(&mut self) -> bool {
1143        let digits = self.state.digits_without_international_prefix().to_owned();
1144
1145        let Some((calling_code, national_number)) = split_calling_code(&digits) else {
1146            return false;
1147        };
1148
1149        let national_number = national_number.to_owned();
1150
1151        self.set_calling_code(Some(calling_code));
1152        self.state.national_significant_number = national_number;
1153
1154        true
1155    }
1156
1157    fn extract_national_significant_number(&mut self, national_digits: &str) -> bool {
1158        if !self.parser.has_selected_numbering_plan {
1159            return false;
1160        }
1161
1162        let Some(plan) = self.plan else {
1163            return false;
1164        };
1165
1166        let extraction =
1167            extract_national_number_from_possibly_incomplete_number(national_digits, plan);
1168
1169        if extraction.national_number == national_digits {
1170            return false;
1171        }
1172
1173        self.on_extracted_national_number(extraction, national_digits);
1174
1175        true
1176    }
1177
1178    fn extract_another_national_significant_number(
1179        &mut self,
1180        national_digits: &str,
1181        previous_national_significant_number: &str,
1182    ) -> bool {
1183        if !self.parser.has_extracted_national_significant_number {
1184            return self.extract_national_significant_number(national_digits);
1185        }
1186
1187        if !self
1188            .parser
1189            .could_possibly_extract_another_national_significant_number
1190        {
1191            return false;
1192        }
1193
1194        let Some(plan) = self.plan else {
1195            return false;
1196        };
1197
1198        let extraction =
1199            extract_national_number_from_possibly_incomplete_number(national_digits, plan);
1200
1201        if extraction.national_number == previous_national_significant_number {
1202            return false;
1203        }
1204
1205        self.on_extracted_national_number(extraction, national_digits);
1206
1207        true
1208    }
1209
1210    fn on_extracted_national_number(
1211        &mut self,
1212        extraction: NationalNumberExtraction,
1213        national_digits: &str,
1214    ) {
1215        let national_number = extraction.national_number;
1216        let mut modified = false;
1217        let mut prefix_before = String::new();
1218
1219        match national_digits.rfind(national_number.as_str()) {
1220            Some(index) if index + national_number.len() == national_digits.len() => {
1221                let prefix = &national_digits[..index];
1222
1223                if !prefix.is_empty() && prefix != extraction.national_prefix {
1224                    prefix.clone_into(&mut prefix_before);
1225                }
1226            }
1227            _ => modified = true,
1228        }
1229
1230        self.state.national_prefix = extraction.national_prefix;
1231        self.state.national_significant_number = national_number;
1232        self.state.national_significant_number_is_modified = modified;
1233        self.state.prefix_before_national_significant_number = prefix_before;
1234        self.parser.has_extracted_national_significant_number = true;
1235        self.on_national_significant_number_change();
1236    }
1237
1238    fn re_extract_national_significant_number(&mut self) -> bool {
1239        let national_digits = self.state.national_digits();
1240        let previous = self.state.national_significant_number.clone();
1241
1242        if self.extract_another_national_significant_number(&national_digits, &previous) {
1243            return true;
1244        }
1245
1246        if self.extract_idd_prefix() || self.fix_missing_plus() {
1247            self.extract_calling_code_and_national_significant_number();
1248
1249            return true;
1250        }
1251
1252        false
1253    }
1254
1255    fn extract_idd_prefix(&mut self) -> bool {
1256        if self.state.international || !self.state.idd_prefix.is_empty() {
1257            return false;
1258        }
1259
1260        let Some(default_country) = self.default_country else {
1261            return false;
1262        };
1263
1264        let Some(rest) = strip_idd_prefix(&self.state.digits, default_country) else {
1265            return false;
1266        };
1267
1268        if rest.len() == self.state.digits.len() {
1269            return false;
1270        }
1271
1272        let idd_length = self.state.digits.len() - rest.len();
1273
1274        self.state.idd_prefix = self
1275            .state
1276            .digits
1277            .get(..idd_length)
1278            .unwrap_or_default()
1279            .to_owned();
1280        self.start_international_number(None, None);
1281
1282        true
1283    }
1284
1285    fn fix_missing_plus(&mut self) -> bool {
1286        if self.state.international {
1287            return false;
1288        }
1289
1290        let Some(region) = self.state.country.or(self.default_country) else {
1291            return false;
1292        };
1293
1294        let Some(calling_code) = calling_code_without_plus_sign(&self.state.digits, region) else {
1295            return false;
1296        };
1297
1298        self.state.missing_plus = true;
1299        self.start_international_number(self.state.country, Some(calling_code));
1300
1301        true
1302    }
1303
1304    fn start_international_number(
1305        &mut self,
1306        country: Option<&'static PhoneRegion>,
1307        calling_code: Option<&'static str>,
1308    ) {
1309        self.start_international_number_state(country, calling_code);
1310
1311        if !self.state.national_significant_number.is_empty() {
1312            self.state.reset_national_significant_number();
1313            self.on_national_significant_number_change();
1314            self.parser.has_extracted_national_significant_number = false;
1315        }
1316    }
1317
1318    fn extract_calling_code_and_national_significant_number(&mut self) {
1319        if self.extract_country_calling_code() {
1320            let national_digits = self.state.national_digits();
1321
1322            self.extract_national_significant_number(&national_digits);
1323        }
1324    }
1325
1326    // Output.
1327
1328    fn international_prefix(&self, spacing: Option<bool>) -> String {
1329        if !self.state.idd_prefix.is_empty() {
1330            if spacing == Some(false) {
1331                return self.state.idd_prefix.clone();
1332            }
1333
1334            return format!("{} ", self.state.idd_prefix);
1335        }
1336
1337        if self.state.missing_plus {
1338            String::new()
1339        } else {
1340            "+".to_owned()
1341        }
1342    }
1343
1344    fn full_number(&self, formatted_national_number: &str) -> String {
1345        if !self.state.international {
1346            return formatted_national_number.to_owned();
1347        }
1348
1349        let text = match self.state.calling_code {
1350            None => self.state.digits_without_international_prefix().to_owned(),
1351            Some(calling_code) if formatted_national_number.is_empty() => calling_code.to_owned(),
1352            Some(calling_code) => format!("{calling_code} {formatted_national_number}"),
1353        };
1354
1355        format!(
1356            "{}{text}",
1357            self.international_prefix(Some(!text.is_empty()))
1358        )
1359    }
1360
1361    fn non_formatted_number(&self) -> String {
1362        let national = if self.state.national_significant_number_is_modified {
1363            self.state.national_digits()
1364        } else {
1365            let prefix = if self
1366                .state
1367                .prefix_before_national_significant_number
1368                .is_empty()
1369            {
1370                &self.state.national_prefix
1371            } else {
1372                &self.state.prefix_before_national_significant_number
1373            };
1374
1375            format!("{prefix}{}", self.state.national_significant_number)
1376        };
1377
1378        self.full_number(&national)
1379    }
1380
1381    /// `AsYouType.getNumber()`.
1382    fn number(&self) -> Option<ParsedNumber> {
1383        let national_number = &self.state.national_significant_number;
1384
1385        if national_number.is_empty() {
1386            return None;
1387        }
1388
1389        let mut country = self.state.country;
1390
1391        if country.is_none() && self.state.calling_code.is_none() {
1392            return None;
1393        }
1394
1395        if let (Some(current), Some(default_country)) = (country, self.default_country)
1396            && current.code() == default_country.code()
1397            && let Some(plan) = self.plan
1398            && let Some(regions) = regions_for_calling_code(plan.calling_code())
1399            && regions.len() > 1
1400            && let Some(exact) = region_by_national_number(national_number, regions)
1401        {
1402            country = Some(exact);
1403        }
1404
1405        let calling_code = match country {
1406            Some(region) => region.calling_code(),
1407            None => self.state.calling_code?,
1408        };
1409
1410        Some(ParsedNumber {
1411            region: country,
1412            calling_code,
1413            national_number: national_number.clone(),
1414        })
1415    }
1416
1417    // The formatter.
1418
1419    fn reset_format(&mut self) {
1420        let formatter = &mut self.formatter;
1421
1422        formatter.chosen_format = None;
1423        formatter.template.clear();
1424        formatter.populated_template.clear();
1425        formatter.populated_position = None;
1426    }
1427
1428    fn reset_formatter(&mut self) {
1429        self.reset_format();
1430
1431        let Some(plan) = self.plan else {
1432            self.formatter.is_nanp = false;
1433            self.formatter.matching_formats.clear();
1434
1435            return;
1436        };
1437
1438        self.formatter.is_nanp = plan.calling_code() == "1";
1439        self.formatter.matching_formats = plan.formats().iter().collect();
1440
1441        if !self.state.national_significant_number.is_empty() {
1442            self.narrow_down_matching_formats();
1443        }
1444    }
1445
1446    fn narrow_down_matching_formats(&mut self) {
1447        let leading_digits = &self.state.national_significant_number;
1448        let pattern_index = leading_digits.len().saturating_sub(3);
1449        let international = self.state.international;
1450        let national_prefix = &self.state.national_prefix;
1451
1452        self.formatter.matching_formats.retain(|format| {
1453            format_suits(format, international, national_prefix)
1454                && format_matches(format, leading_digits, pattern_index)
1455        });
1456
1457        if let Some(chosen) = self.formatter.chosen_format
1458            && !self
1459                .formatter
1460                .matching_formats
1461                .iter()
1462                .any(|format| same_format(format, chosen))
1463        {
1464            self.reset_format();
1465        }
1466    }
1467
1468    fn can_format_complete_number(&self) -> bool {
1469        self.plan.is_some_and(|plan| {
1470            plan.check_number_length(&self.state.national_significant_number)
1471                == NumberLength::Possible
1472        })
1473    }
1474
1475    fn format(&mut self, next_digits: &str) -> Option<String> {
1476        if self.can_format_complete_number() {
1477            for format in self.formatter.matching_formats.clone() {
1478                if let Some(formatted) = self.format_complete_number(format) {
1479                    self.reset_format();
1480                    self.formatter.chosen_format = Some(format);
1481
1482                    let template: String = formatted
1483                        .chars()
1484                        .map(|character| {
1485                            if character.is_ascii_digit() {
1486                                DIGIT_PLACEHOLDER
1487                            } else {
1488                                character
1489                            }
1490                        })
1491                        .collect();
1492
1493                    self.set_national_number_template(template);
1494                    self.formatter.populated_position =
1495                        self.formatter.template.rfind(DIGIT_PLACEHOLDER);
1496                    self.formatter.populated_template.clone_from(&formatted);
1497
1498                    return Some(formatted);
1499                }
1500            }
1501        }
1502
1503        self.format_national_number_with_next_digits(next_digits)
1504    }
1505
1506    fn format_complete_number(&self, format: &PhoneFormat) -> Option<String> {
1507        if !pattern::matches_entirely(&self.state.national_significant_number, format.pattern()) {
1508            return None;
1509        }
1510
1511        if self.should_try_national_prefix_formatting_rule(format)
1512            && let Some(formatted) = self.format_complete_national_number(format, true)
1513        {
1514            return Some(formatted);
1515        }
1516
1517        self.format_complete_national_number(format, false)
1518    }
1519
1520    fn format_complete_national_number(
1521        &self,
1522        format: &PhoneFormat,
1523        use_national_prefix_formatting_rule: bool,
1524    ) -> Option<String> {
1525        let state = &self.state;
1526        let mut formatted = format_with_pattern(
1527            &state.national_significant_number,
1528            format,
1529            state.international,
1530            use_national_prefix_formatting_rule,
1531        );
1532
1533        if !use_national_prefix_formatting_rule {
1534            if !state.national_prefix.is_empty() {
1535                formatted = format!(
1536                    "{}{}{formatted}",
1537                    state.national_prefix,
1538                    self.separator_after_national_prefix(format)
1539                );
1540            } else if !state.prefix_before_national_significant_number.is_empty() {
1541                formatted = format!(
1542                    "{} {formatted}",
1543                    state.prefix_before_national_significant_number
1544                );
1545            }
1546        }
1547
1548        (parse_digits(&formatted) == state.national_digits()).then_some(formatted)
1549    }
1550
1551    fn format_national_number_with_next_digits(&mut self, next_digits: &str) -> Option<String> {
1552        let previous = self.formatter.chosen_format;
1553        let chosen = self.choose_format()?;
1554
1555        if previous.is_some_and(|previous| same_format(previous, chosen)) {
1556            self.format_next_national_number_digits(next_digits)
1557        } else {
1558            let national_digits = self.state.national_digits();
1559
1560            self.format_next_national_number_digits(&national_digits)
1561        }
1562    }
1563
1564    fn choose_format(&mut self) -> Option<&'static PhoneFormat> {
1565        for format in self.formatter.matching_formats.clone() {
1566            if self
1567                .formatter
1568                .chosen_format
1569                .is_some_and(|chosen| same_format(chosen, format))
1570            {
1571                break;
1572            }
1573
1574            let template = if self.state.international {
1575                format.international_template()
1576            } else {
1577                format.template()
1578            };
1579
1580            if !is_non_altering_template(template) {
1581                continue;
1582            }
1583
1584            if !self.create_template_for_format(format) {
1585                self.formatter
1586                    .matching_formats
1587                    .retain(|candidate| !same_format(candidate, format));
1588
1589                continue;
1590            }
1591
1592            self.formatter.chosen_format = Some(format);
1593
1594            break;
1595        }
1596
1597        if self.formatter.chosen_format.is_none() {
1598            self.reset_format();
1599        }
1600
1601        self.formatter.chosen_format
1602    }
1603
1604    fn create_template_for_format(&mut self, format: &PhoneFormat) -> bool {
1605        if format.pattern().contains('|') {
1606            return false;
1607        }
1608
1609        match self.template_for_format(format) {
1610            Some(template) if !template.is_empty() => {
1611                self.set_national_number_template(template);
1612
1613                true
1614            }
1615            _ => false,
1616        }
1617    }
1618
1619    fn template_for_format(&self, format: &PhoneFormat) -> Option<String> {
1620        const LONGEST_DUMMY_NUMBER: &str = "999999999999999";
1621
1622        let state = &self.state;
1623        let pattern = template_pattern(format.pattern());
1624        let dummy_match = pattern::captures(&pattern, LONGEST_DUMMY_NUMBER)?;
1625        let (start, end) = dummy_match.first().copied().flatten()?;
1626        let mut digits = LONGEST_DUMMY_NUMBER.get(start..end)?.to_owned();
1627
1628        if state.national_significant_number.len() > digits.len() {
1629            return None;
1630        }
1631
1632        let national_number_dummy = "9".repeat(state.national_significant_number.len());
1633
1634        if pattern::matches_entirely(&national_number_dummy, &pattern) {
1635            digits = national_number_dummy;
1636        }
1637
1638        let mut number_format = if state.international {
1639            format.international_template().to_owned()
1640        } else {
1641            format.template().to_owned()
1642        };
1643
1644        let mut national_prefix_included = false;
1645
1646        if self.should_try_national_prefix_formatting_rule(format) {
1647            let rule = format.national_prefix_formatting_rule();
1648
1649            if parse_digits(rule) == format!("{}1", state.national_prefix) {
1650                number_format = replace_first_group_reference(&number_format, rule);
1651                national_prefix_included = true;
1652
1653                for _ in 0..state.national_prefix.len() {
1654                    if let Some(index) =
1655                        number_format.find(|character: char| character.is_ascii_digit())
1656                    {
1657                        number_format.replace_range(index..=index, "x");
1658                    }
1659                }
1660            }
1661        }
1662
1663        let mut template =
1664            pattern::replace_first(&pattern, &digits, &number_format).replace('9', "x");
1665
1666        if !national_prefix_included {
1667            let prefix_before = &state.prefix_before_national_significant_number;
1668
1669            if !prefix_before.is_empty() {
1670                template = format!("{} {template}", "x".repeat(prefix_before.len()));
1671            } else if !state.national_prefix.is_empty() {
1672                template = format!(
1673                    "{}{}{template}",
1674                    "x".repeat(state.national_prefix.len()),
1675                    self.separator_after_national_prefix(format)
1676                );
1677            }
1678        }
1679
1680        if state.international {
1681            template = apply_international_separator_style(&template);
1682        }
1683
1684        Some(template)
1685    }
1686
1687    fn set_national_number_template(&mut self, template: String) {
1688        self.formatter.populated_position = None;
1689
1690        self.formatter.template = if self.state.international {
1691            let prefix: String = self
1692                .international_prefix(None)
1693                .chars()
1694                .map(|character| {
1695                    if character.is_ascii_digit() || character == '+' {
1696                        DIGIT_PLACEHOLDER
1697                    } else {
1698                        character
1699                    }
1700                })
1701                .collect();
1702
1703            let calling_code_length = self.state.calling_code.map_or(0, str::len);
1704
1705            format!("{prefix}{} {template}", "x".repeat(calling_code_length))
1706        } else {
1707            template.clone()
1708        };
1709
1710        self.formatter.populated_template = template;
1711    }
1712
1713    fn format_next_national_number_digits(&mut self, digits: &str) -> Option<String> {
1714        let Some((template, position)) = populate_template_with_digits(
1715            &self.formatter.populated_template,
1716            self.formatter.populated_position,
1717            digits,
1718        ) else {
1719            self.reset_format();
1720
1721            return None;
1722        };
1723
1724        let cut_before = position.map_or(0, |position| position + 1);
1725        let formatted = cut_and_strip_non_paired_parens(&template, cut_before);
1726
1727        self.formatter.populated_template = template;
1728        self.formatter.populated_position = position;
1729
1730        Some(formatted)
1731    }
1732
1733    fn should_try_national_prefix_formatting_rule(&self, format: &PhoneFormat) -> bool {
1734        if format.national_prefix_formatting_rule().is_empty() {
1735            return false;
1736        }
1737
1738        let uses_national_prefix = format.uses_national_prefix();
1739
1740        (uses_national_prefix && !self.state.national_prefix.is_empty())
1741            || (!uses_national_prefix && !self.state.international)
1742    }
1743
1744    fn separator_after_national_prefix(&self, format: &PhoneFormat) -> &'static str {
1745        if self.formatter.is_nanp {
1746            return " ";
1747        }
1748
1749        if format
1750            .national_prefix_formatting_rule()
1751            .contains(['-', ' '])
1752        {
1753            " "
1754        } else {
1755            ""
1756        }
1757    }
1758}
1759
1760/// `formatSuits()`: whether a format fits a typed national prefix.
1761fn format_suits(format: &PhoneFormat, international: bool, national_prefix: &str) -> bool {
1762    if !national_prefix.is_empty()
1763        && !format.uses_national_prefix()
1764        && !format.national_prefix_is_optional()
1765    {
1766        return false;
1767    }
1768
1769    !(!international && national_prefix.is_empty() && format.national_prefix_is_mandatory())
1770}
1771
1772/// `formatMatches()`: whether a format's leading digits fit the digits typed so far.
1773fn format_matches(format: &PhoneFormat, leading_digits: &str, pattern_index: usize) -> bool {
1774    let patterns = format.leading_digits();
1775    let Some(last_index) = patterns.len().checked_sub(1) else {
1776        return true;
1777    };
1778
1779    let Some(leading_pattern) = patterns.get(pattern_index.min(last_index)) else {
1780        return true;
1781    };
1782
1783    if leading_digits.len() < 3 {
1784        return pattern::partial::matches(leading_pattern, leading_digits);
1785    }
1786
1787    pattern::matches_at_start(leading_digits, leading_pattern)
1788}
1789
1790/// Linear-time matching for the regular-expression subset in phone metadata: literals, `\d`,
1791/// classes with ranges, groups, alternation, `$`, and `?`, `*`, `+`, `{n}`, `{n,}`, `{n,m}`.
1792mod pattern {
1793    /// Longest input the position-set matcher evaluates. Generated metadata patterns match at most
1794    /// 40 characters, so longer input never matches entirely and is truncated for prefix matches.
1795    const MAX_INPUT: usize = 63;
1796
1797    /// Fuel for one match: each atom evaluation costs one unit. Generated patterns need a few
1798    /// thousand at most; the cap only bounds work on malformed patterns.
1799    const FUEL: u32 = 1_000_000;
1800
1801    /// Mandatory repetitions after which a position set has settled: positions only move
1802    /// forward through the `MAX_INPUT + 1` places, so two passes over them (128) always suffice.
1803    const MAX_SETTLING_ITERATIONS: u32 = 128;
1804
1805    /// Deepest group nesting accepted.
1806    const MAX_DEPTH: u32 = 64;
1807
1808    /// Largest compiled program the capture matcher accepts.
1809    const MAX_PROGRAM: usize = 20_000;
1810
1811    /// The pattern is outside the supported subset.
1812    #[derive(Debug)]
1813    struct Malformed;
1814
1815    type Parsed<T> = Result<T, Malformed>;
1816
1817    /// A set of ASCII bytes.
1818    #[derive(Clone, Copy, Default)]
1819    struct ByteSet(u128);
1820
1821    impl ByteSet {
1822        fn digits() -> Self {
1823            let mut set = Self::default();
1824
1825            set.insert_range(b'0', b'9');
1826
1827            set
1828        }
1829
1830        fn single(byte: u8) -> Self {
1831            let mut set = Self::default();
1832
1833            set.insert_range(byte, byte);
1834
1835            set
1836        }
1837
1838        fn insert_range(&mut self, first: u8, last: u8) {
1839            for byte in first..=last.min(127) {
1840                self.0 |= 1 << byte;
1841            }
1842        }
1843
1844        fn contains(self, byte: u8) -> bool {
1845            byte < 128 && ((self.0 >> byte) & 1) == 1
1846        }
1847    }
1848
1849    fn parse_number(pattern: &[u8], position: &mut usize) -> Parsed<u32> {
1850        let start = *position;
1851        let mut value: u32 = 0;
1852
1853        while let Some(&byte) = pattern.get(*position).filter(|byte| byte.is_ascii_digit()) {
1854            value = value
1855                .checked_mul(10)
1856                .and_then(|value| value.checked_add(u32::from(byte - b'0')))
1857                .ok_or(Malformed)?;
1858            *position += 1;
1859        }
1860
1861        if *position == start {
1862            return Err(Malformed);
1863        }
1864
1865        Ok(value)
1866    }
1867
1868    /// Parses a quantifier at `position`: `(minimum, maximum, lazy)`, or `None` without one.
1869    fn parse_quantifier(
1870        pattern: &[u8],
1871        position: &mut usize,
1872    ) -> Parsed<Option<(u32, Option<u32>, bool)>> {
1873        let bounds = match pattern.get(*position) {
1874            Some(b'?') => (0, Some(1)),
1875            Some(b'*') => (0, None),
1876            Some(b'+') => (1, None),
1877            Some(b'{') => {
1878                *position += 1;
1879
1880                let minimum = parse_number(pattern, position)?;
1881                let maximum = if pattern.get(*position) == Some(&b',') {
1882                    *position += 1;
1883
1884                    if pattern.get(*position) == Some(&b'}') {
1885                        None
1886                    } else {
1887                        Some(parse_number(pattern, position)?)
1888                    }
1889                } else {
1890                    Some(minimum)
1891                };
1892
1893                if pattern.get(*position) != Some(&b'}')
1894                    || maximum.is_some_and(|maximum| maximum < minimum)
1895                {
1896                    return Err(Malformed);
1897                }
1898
1899                (minimum, maximum)
1900            }
1901            _ => return Ok(None),
1902        };
1903
1904        *position += 1;
1905
1906        let lazy = pattern.get(*position) == Some(&b'?');
1907
1908        if lazy {
1909            *position += 1;
1910        }
1911
1912        Ok(Some((bounds.0, bounds.1, lazy)))
1913    }
1914
1915    /// Parses `[...]` starting at the opening bracket.
1916    fn parse_class(pattern: &[u8], position: &mut usize) -> Parsed<ByteSet> {
1917        *position += 1;
1918
1919        let negated = pattern.get(*position) == Some(&b'^');
1920
1921        if negated {
1922            *position += 1;
1923        }
1924
1925        let mut set = ByteSet::default();
1926
1927        loop {
1928            let byte = *pattern.get(*position).ok_or(Malformed)?;
1929
1930            if byte == b']' {
1931                *position += 1;
1932
1933                break;
1934            }
1935
1936            let start = if byte == b'\\' {
1937                let escaped = *pattern.get(*position + 1).ok_or(Malformed)?;
1938
1939                *position += 2;
1940
1941                if escaped == b'd' {
1942                    set.0 |= ByteSet::digits().0;
1943
1944                    continue;
1945                }
1946
1947                if escaped.is_ascii_alphanumeric() {
1948                    return Err(Malformed);
1949                }
1950
1951                escaped
1952            } else {
1953                *position += 1;
1954
1955                byte
1956            };
1957
1958            if pattern.get(*position) == Some(&b'-')
1959                && pattern.get(*position + 1).is_some_and(|&next| next != b']')
1960            {
1961                let end = *pattern.get(*position + 1).ok_or(Malformed)?;
1962
1963                if end == b'\\' || end < start {
1964                    return Err(Malformed);
1965                }
1966
1967                set.insert_range(start, end);
1968                *position += 2;
1969            } else {
1970                set.insert_range(start, start);
1971            }
1972        }
1973
1974        if negated {
1975            set.0 = !set.0;
1976        }
1977
1978        Ok(set)
1979    }
1980
1981    /// Parses an escape outside a class, starting at the backslash.
1982    fn parse_escape(pattern: &[u8], position: &mut usize) -> Parsed<ByteSet> {
1983        let escaped = *pattern.get(*position + 1).ok_or(Malformed)?;
1984
1985        *position += 2;
1986
1987        match escaped {
1988            b'd' => Ok(ByteSet::digits()),
1989            byte if byte.is_ascii_punctuation() => Ok(ByteSet::single(byte)),
1990            _ => Err(Malformed),
1991        }
1992    }
1993
1994    /// Evaluates a pattern over sets of input positions: bit `i` means "matched up to `i`".
1995    struct PositionSets<'a> {
1996        pattern: &'a [u8],
1997        position: usize,
1998        input: &'a [u8],
1999        digit_masks: [u64; 10],
2000        end_mask: u64,
2001        fuel: u32,
2002    }
2003
2004    impl<'a> PositionSets<'a> {
2005        fn new(pattern: &'a str, input: &'a [u8], at_end: bool) -> Self {
2006            let mut digit_masks = [0; 10];
2007
2008            for (index, byte) in input.iter().enumerate() {
2009                if let Some(mask) = byte
2010                    .checked_sub(b'0')
2011                    .and_then(|digit| digit_masks.get_mut(usize::from(digit)))
2012                {
2013                    *mask |= 1 << index;
2014                }
2015            }
2016
2017            Self {
2018                pattern: pattern.as_bytes(),
2019                position: 0,
2020                input,
2021                digit_masks,
2022                end_mask: if at_end { 1 << input.len() } else { 0 },
2023                fuel: FUEL,
2024            }
2025        }
2026
2027        /// The end positions of a whole-pattern match that starts at position 0.
2028        fn ends(mut self) -> Parsed<u64> {
2029            let ends = self.alternation(1, 0)?;
2030
2031            if self.position == self.pattern.len() {
2032                Ok(ends)
2033            } else {
2034                Err(Malformed)
2035            }
2036        }
2037
2038        fn peek(&self) -> Option<u8> {
2039            self.pattern.get(self.position).copied()
2040        }
2041
2042        fn mask(&self, set: ByteSet) -> u64 {
2043            let mut mask = 0;
2044
2045            for (digit, &digit_mask) in (b'0'..=b'9').zip(&self.digit_masks) {
2046                if set.contains(digit) {
2047                    mask |= digit_mask;
2048                }
2049            }
2050
2051            for (index, &byte) in self.input.iter().enumerate() {
2052                if !byte.is_ascii_digit() && set.contains(byte) {
2053                    mask |= 1 << index;
2054                }
2055            }
2056
2057            mask
2058        }
2059
2060        fn alternation(&mut self, starts: u64, depth: u32) -> Parsed<u64> {
2061            if depth > MAX_DEPTH {
2062                return Err(Malformed);
2063            }
2064
2065            let mut ends = self.sequence(starts, depth)?;
2066
2067            while self.peek() == Some(b'|') {
2068                self.position += 1;
2069                ends |= self.sequence(starts, depth)?;
2070            }
2071
2072            Ok(ends)
2073        }
2074
2075        fn sequence(&mut self, starts: u64, depth: u32) -> Parsed<u64> {
2076            let mut current = starts;
2077
2078            while let Some(byte) = self.peek() {
2079                if byte == b'|' || byte == b')' {
2080                    break;
2081                }
2082
2083                current = self.quantified(current, depth)?;
2084            }
2085
2086            Ok(current)
2087        }
2088
2089        fn quantified(&mut self, starts: u64, depth: u32) -> Parsed<u64> {
2090            let atom_start = self.position;
2091            let once = self.atom(starts, depth)?;
2092            let atom_end = self.position;
2093
2094            let Some((minimum, maximum, _lazy)) =
2095                parse_quantifier(self.pattern, &mut self.position)?
2096            else {
2097                return Ok(once);
2098            };
2099
2100            let after = self.position;
2101            let ends = self.repeat(
2102                starts,
2103                once,
2104                (atom_start, atom_end),
2105                (minimum, maximum),
2106                depth,
2107            )?;
2108
2109            self.position = after;
2110
2111            Ok(ends)
2112        }
2113
2114        /// The union of `atom^k(starts)` for `minimum <= k <= maximum`.
2115        fn repeat(
2116            &mut self,
2117            starts: u64,
2118            once: u64,
2119            atom: (usize, usize),
2120            (minimum, maximum): (u32, Option<u32>),
2121            depth: u32,
2122        ) -> Parsed<u64> {
2123            // Mandatory iterations. Position sets only move forward, so they settle or empty out
2124            // within a few dozen steps; stop there instead of iterating a huge minimum.
2125            let mut current = starts;
2126
2127            for iteration in 1..=minimum {
2128                let next = if iteration == 1 {
2129                    once
2130                } else {
2131                    self.reevaluate(atom, current, depth)?
2132                };
2133
2134                let settled = next == current;
2135
2136                current = next;
2137
2138                if current == 0 || settled || iteration > MAX_SETTLING_ITERATIONS {
2139                    break;
2140                }
2141            }
2142
2143            // Optional iterations: only newly reached positions can reach anything new.
2144            let mut reached = current;
2145            let mut frontier = current;
2146            let mut iteration = minimum;
2147
2148            while maximum.is_none_or(|maximum| iteration < maximum) && frontier != 0 {
2149                let next = if iteration == 0 {
2150                    once
2151                } else {
2152                    self.reevaluate(atom, frontier, depth)?
2153                } & !reached;
2154
2155                reached |= next;
2156                frontier = next;
2157                iteration += 1;
2158            }
2159
2160            Ok(reached)
2161        }
2162
2163        fn reevaluate(
2164            &mut self,
2165            (start, end): (usize, usize),
2166            starts: u64,
2167            depth: u32,
2168        ) -> Parsed<u64> {
2169            if starts == 0 {
2170                return Ok(0);
2171            }
2172
2173            self.position = start;
2174
2175            let ends = self.atom(starts, depth)?;
2176
2177            if self.position == end {
2178                Ok(ends)
2179            } else {
2180                Err(Malformed)
2181            }
2182        }
2183
2184        fn atom(&mut self, starts: u64, depth: u32) -> Parsed<u64> {
2185            self.fuel = self.fuel.checked_sub(1).ok_or(Malformed)?;
2186
2187            let byte = self.peek().ok_or(Malformed)?;
2188
2189            match byte {
2190                b'(' => {
2191                    self.position += 1;
2192
2193                    if self.pattern.get(self.position) == Some(&b'?') {
2194                        if self.pattern.get(self.position + 1) != Some(&b':') {
2195                            return Err(Malformed);
2196                        }
2197
2198                        self.position += 2;
2199                    }
2200
2201                    let ends = self.alternation(starts, depth + 1)?;
2202
2203                    if self.peek() != Some(b')') {
2204                        return Err(Malformed);
2205                    }
2206
2207                    self.position += 1;
2208
2209                    Ok(ends)
2210                }
2211                b'[' => {
2212                    let set = parse_class(self.pattern, &mut self.position)?;
2213
2214                    Ok((starts & self.mask(set)) << 1)
2215                }
2216                b'\\' => {
2217                    let set = parse_escape(self.pattern, &mut self.position)?;
2218
2219                    Ok((starts & self.mask(set)) << 1)
2220                }
2221                b'$' => {
2222                    self.position += 1;
2223
2224                    Ok(starts & self.end_mask)
2225                }
2226                b')' | b'|' | b'?' | b'*' | b'+' | b'{' | b'}' | b']' | b'^' | b'.' => {
2227                    Err(Malformed)
2228                }
2229                _ => {
2230                    self.position += 1;
2231
2232                    Ok((starts & self.mask(ByteSet::single(byte))) << 1)
2233                }
2234            }
2235        }
2236    }
2237
2238    /// `^(?:pattern)$`: whether the pattern matches the whole input.
2239    pub(super) fn matches_entirely(input: &str, pattern: &str) -> bool {
2240        let input = input.as_bytes();
2241
2242        if input.len() > MAX_INPUT {
2243            return false;
2244        }
2245
2246        PositionSets::new(pattern, input, true)
2247            .ends()
2248            .is_ok_and(|ends| ends & (1 << input.len()) != 0)
2249    }
2250
2251    /// `^(?:pattern)`: whether the pattern matches a prefix of the input.
2252    pub(super) fn matches_at_start(input: &str, pattern: &str) -> bool {
2253        let input = input.as_bytes();
2254        let truncated = input.len() > MAX_INPUT;
2255        let input = input.get(..MAX_INPUT).unwrap_or(input);
2256
2257        PositionSets::new(pattern, input, !truncated)
2258            .ends()
2259            .is_ok_and(|ends| ends != 0)
2260    }
2261
2262    /// Capture group spans, group 0 being the whole match. Unmatched groups are `None`.
2263    pub(super) type Captures = Vec<Option<(usize, usize)>>;
2264
2265    #[derive(Clone, Copy)]
2266    enum Instruction {
2267        Byte(ByteSet),
2268        Split(usize, usize),
2269        Jump(usize),
2270        Save(usize),
2271        End,
2272        Match,
2273    }
2274
2275    fn relocate(fragment: &[Instruction], base: usize) -> impl Iterator<Item = Instruction> + '_ {
2276        fragment.iter().map(move |instruction| match *instruction {
2277            Instruction::Split(first, second) => Instruction::Split(first + base, second + base),
2278            Instruction::Jump(target) => Instruction::Jump(target + base),
2279            other => other,
2280        })
2281    }
2282
2283    /// Compiles a pattern into Pike VM fragments. Jump targets are relative to the fragment, and a
2284    /// target equal to the fragment length means "continue after the fragment".
2285    struct Compiler<'a> {
2286        pattern: &'a [u8],
2287        position: usize,
2288        groups: usize,
2289    }
2290
2291    impl Compiler<'_> {
2292        fn peek(&self) -> Option<u8> {
2293            self.pattern.get(self.position).copied()
2294        }
2295
2296        fn check_size(fragment: &[Instruction]) -> Parsed<()> {
2297            if fragment.len() > MAX_PROGRAM {
2298                Err(Malformed)
2299            } else {
2300                Ok(())
2301            }
2302        }
2303
2304        fn alternation(&mut self, depth: u32) -> Parsed<Vec<Instruction>> {
2305            if depth > MAX_DEPTH {
2306                return Err(Malformed);
2307            }
2308
2309            let mut branches = vec![self.sequence(depth)?];
2310
2311            while self.peek() == Some(b'|') {
2312                self.position += 1;
2313                branches.push(self.sequence(depth)?);
2314            }
2315
2316            let mut fragment = branches.pop().ok_or(Malformed)?;
2317
2318            // Fold from the right so earlier branches keep priority.
2319            while let Some(branch) = branches.pop() {
2320                let mut combined = Vec::with_capacity(branch.len() + fragment.len() + 2);
2321                let second = branch.len() + 2;
2322                let end = second + fragment.len();
2323
2324                combined.push(Instruction::Split(1, second));
2325                combined.extend(relocate(&branch, 1));
2326                combined.push(Instruction::Jump(end));
2327                combined.extend(relocate(&fragment, second));
2328
2329                Self::check_size(&combined)?;
2330                fragment = combined;
2331            }
2332
2333            Ok(fragment)
2334        }
2335
2336        fn sequence(&mut self, depth: u32) -> Parsed<Vec<Instruction>> {
2337            let mut fragment = Vec::new();
2338
2339            while let Some(byte) = self.peek() {
2340                if byte == b'|' || byte == b')' {
2341                    break;
2342                }
2343
2344                let piece = self.quantified(depth)?;
2345                let base = fragment.len();
2346
2347                fragment.extend(relocate(&piece, base));
2348                Self::check_size(&fragment)?;
2349            }
2350
2351            Ok(fragment)
2352        }
2353
2354        fn quantified(&mut self, depth: u32) -> Parsed<Vec<Instruction>> {
2355            let atom = self.atom(depth)?;
2356
2357            let Some((minimum, maximum, lazy)) =
2358                parse_quantifier(self.pattern, &mut self.position)?
2359            else {
2360                return Ok(atom);
2361            };
2362
2363            let mut fragment = Vec::new();
2364
2365            for _ in 0..minimum {
2366                let base = fragment.len();
2367
2368                fragment.extend(relocate(&atom, base));
2369                Self::check_size(&fragment)?;
2370            }
2371
2372            let optional = match maximum {
2373                // `atom*`: Split(body, out); body; Jump(split).
2374                None => {
2375                    let mut star = Vec::with_capacity(atom.len() + 2);
2376                    let out = atom.len() + 2;
2377
2378                    star.push(if lazy {
2379                        Instruction::Split(out, 1)
2380                    } else {
2381                        Instruction::Split(1, out)
2382                    });
2383                    star.extend(relocate(&atom, 1));
2384                    star.push(Instruction::Jump(0));
2385                    star
2386                }
2387                // Nested optional copies: (atom (atom (atom)?)?)?
2388                Some(maximum) => {
2389                    let mut nested: Vec<Instruction> = Vec::new();
2390
2391                    for _ in minimum..maximum {
2392                        let mut copy = Vec::with_capacity(atom.len() + nested.len() + 1);
2393                        let out = atom.len() + nested.len() + 1;
2394
2395                        copy.push(if lazy {
2396                            Instruction::Split(out, 1)
2397                        } else {
2398                            Instruction::Split(1, out)
2399                        });
2400                        copy.extend(relocate(&atom, 1));
2401                        copy.extend(relocate(&nested, atom.len() + 1));
2402                        Self::check_size(&copy)?;
2403                        nested = copy;
2404                    }
2405
2406                    nested
2407                }
2408            };
2409
2410            let base = fragment.len();
2411
2412            fragment.extend(relocate(&optional, base));
2413            Self::check_size(&fragment)?;
2414
2415            Ok(fragment)
2416        }
2417
2418        fn atom(&mut self, depth: u32) -> Parsed<Vec<Instruction>> {
2419            let byte = self.peek().ok_or(Malformed)?;
2420
2421            match byte {
2422                b'(' => {
2423                    self.position += 1;
2424
2425                    let capture = if self.peek() == Some(b'?') {
2426                        if self.pattern.get(self.position + 1) != Some(&b':') {
2427                            return Err(Malformed);
2428                        }
2429
2430                        self.position += 2;
2431
2432                        None
2433                    } else {
2434                        self.groups += 1;
2435
2436                        Some(self.groups)
2437                    };
2438
2439                    let body = self.alternation(depth + 1)?;
2440
2441                    if self.peek() != Some(b')') {
2442                        return Err(Malformed);
2443                    }
2444
2445                    self.position += 1;
2446
2447                    Ok(match capture {
2448                        Some(group) => {
2449                            let mut fragment = Vec::with_capacity(body.len() + 2);
2450
2451                            fragment.push(Instruction::Save(group * 2));
2452                            fragment.extend(relocate(&body, 1));
2453                            fragment.push(Instruction::Save(group * 2 + 1));
2454                            fragment
2455                        }
2456                        None => body,
2457                    })
2458                }
2459                b'[' => Ok(vec![Instruction::Byte(parse_class(
2460                    self.pattern,
2461                    &mut self.position,
2462                )?)]),
2463                b'\\' => Ok(vec![Instruction::Byte(parse_escape(
2464                    self.pattern,
2465                    &mut self.position,
2466                )?)]),
2467                b'$' => {
2468                    self.position += 1;
2469
2470                    Ok(vec![Instruction::End])
2471                }
2472                b')' | b'|' | b'?' | b'*' | b'+' | b'{' | b'}' | b']' | b'^' | b'.' => {
2473                    Err(Malformed)
2474                }
2475                _ => {
2476                    self.position += 1;
2477
2478                    Ok(vec![Instruction::Byte(ByteSet::single(byte))])
2479                }
2480            }
2481        }
2482    }
2483
2484    /// Compiles `Save(0) pattern Save(1) Match` and returns it with its capture-group count.
2485    fn compile(pattern: &str) -> Parsed<(Vec<Instruction>, usize)> {
2486        let mut compiler = Compiler {
2487            pattern: pattern.as_bytes(),
2488            position: 0,
2489            groups: 0,
2490        };
2491
2492        let body = compiler.alternation(0)?;
2493
2494        if compiler.position != compiler.pattern.len() {
2495            return Err(Malformed);
2496        }
2497
2498        let mut program = Vec::with_capacity(body.len() + 3);
2499
2500        program.push(Instruction::Save(0));
2501        program.extend(relocate(&body, 1));
2502        program.push(Instruction::Save(1));
2503        program.push(Instruction::Match);
2504
2505        Ok((program, compiler.groups))
2506    }
2507
2508    const UNSET: usize = usize::MAX;
2509
2510    struct Thread {
2511        program_counter: usize,
2512        slots: Vec<usize>,
2513    }
2514
2515    /// Threads at one input position, in priority order, with a visited set for deduplication.
2516    struct ThreadList {
2517        threads: Vec<Thread>,
2518        visited: Vec<bool>,
2519    }
2520
2521    impl ThreadList {
2522        fn new(size: usize) -> Self {
2523            Self {
2524                threads: Vec::new(),
2525                visited: vec![false; size],
2526            }
2527        }
2528
2529        fn clear(&mut self) {
2530            self.threads.clear();
2531            self.visited.fill(false);
2532        }
2533    }
2534
2535    enum Frame {
2536        Visit(usize),
2537        Restore(usize, usize),
2538    }
2539
2540    /// Follows the empty transitions from `start` in priority order and queues the threads that
2541    /// wait on input or match.
2542    fn add_thread(
2543        list: &mut ThreadList,
2544        program: &[Instruction],
2545        start: usize,
2546        (position, length): (usize, usize),
2547        slots: &[usize],
2548    ) {
2549        let mut slots = slots.to_vec();
2550        let mut stack = vec![Frame::Visit(start)];
2551
2552        while let Some(frame) = stack.pop() {
2553            let program_counter = match frame {
2554                Frame::Restore(slot, value) => {
2555                    if let Some(entry) = slots.get_mut(slot) {
2556                        *entry = value;
2557                    }
2558
2559                    continue;
2560                }
2561                Frame::Visit(program_counter) => program_counter,
2562            };
2563
2564            let (Some(instruction), Some(visited)) = (
2565                program.get(program_counter),
2566                list.visited.get_mut(program_counter),
2567            ) else {
2568                continue;
2569            };
2570
2571            if *visited {
2572                continue;
2573            }
2574
2575            *visited = true;
2576
2577            match *instruction {
2578                Instruction::Jump(target) => stack.push(Frame::Visit(target)),
2579                Instruction::Split(first, second) => {
2580                    stack.push(Frame::Visit(second));
2581                    stack.push(Frame::Visit(first));
2582                }
2583                Instruction::Save(slot) => {
2584                    if let Some(entry) = slots.get_mut(slot) {
2585                        stack.push(Frame::Restore(slot, *entry));
2586                        *entry = position;
2587                    }
2588
2589                    stack.push(Frame::Visit(program_counter + 1));
2590                }
2591                Instruction::End => {
2592                    if position == length {
2593                        stack.push(Frame::Visit(program_counter + 1));
2594                    }
2595                }
2596                Instruction::Byte(_) | Instruction::Match => list.threads.push(Thread {
2597                    program_counter,
2598                    slots: slots.clone(),
2599                }),
2600            }
2601        }
2602    }
2603
2604    /// Runs a Pike VM with JavaScript's leftmost-first priorities. `anchored` only tries a match
2605    /// starting at position 0.
2606    fn run(pattern: &str, input: &str, anchored: bool) -> Option<Captures> {
2607        let (program, groups) = compile(pattern).ok()?;
2608        let input = input.as_bytes();
2609        let length = input.len();
2610        let empty_slots = vec![UNSET; (groups + 1) * 2];
2611        let mut current = ThreadList::new(program.len());
2612        let mut next = ThreadList::new(program.len());
2613        let mut matched: Option<Vec<usize>> = None;
2614
2615        for position in 0..=length {
2616            if matched.is_none() && (position == 0 || !anchored) {
2617                add_thread(&mut current, &program, 0, (position, length), &empty_slots);
2618            }
2619
2620            if current.threads.is_empty() {
2621                break;
2622            }
2623
2624            for thread in &current.threads {
2625                match program.get(thread.program_counter) {
2626                    Some(Instruction::Byte(set)) => {
2627                        if input.get(position).is_some_and(|&byte| set.contains(byte)) {
2628                            add_thread(
2629                                &mut next,
2630                                &program,
2631                                thread.program_counter + 1,
2632                                (position + 1, length),
2633                                &thread.slots,
2634                            );
2635                        }
2636                    }
2637                    Some(Instruction::Match) => {
2638                        matched = Some(thread.slots.clone());
2639
2640                        break;
2641                    }
2642                    _ => {}
2643                }
2644            }
2645
2646            std::mem::swap(&mut current, &mut next);
2647            next.clear();
2648        }
2649
2650        let slots = matched?;
2651
2652        Some(
2653            slots
2654                .chunks(2)
2655                .map(|pair| match *pair {
2656                    [start, end] if start != UNSET && end != UNSET && start <= end => {
2657                        Some((start, end))
2658                    }
2659                    _ => None,
2660                })
2661                .collect(),
2662        )
2663    }
2664
2665    /// `/^(?:pattern)/.exec(input)`: the leftmost-first match at the start of the input.
2666    pub(super) fn captures_at_start(pattern: &str, input: &str) -> Option<Captures> {
2667        run(pattern, input, true)
2668    }
2669
2670    /// `input.match(new RegExp(pattern))`: the leftmost-first match anywhere in the input.
2671    pub(super) fn captures(pattern: &str, input: &str) -> Option<Captures> {
2672        run(pattern, input, false)
2673    }
2674
2675    /// `input.replace(new RegExp(pattern), replacement)`: replaces the first match. Malformed
2676    /// patterns and input without a match come back unchanged.
2677    pub(super) fn replace_first(pattern: &str, input: &str, replacement: &str) -> String {
2678        let Some(found) = captures(pattern, input) else {
2679            return input.to_owned();
2680        };
2681
2682        let Some(Some((start, end))) = found.first().copied() else {
2683            return input.to_owned();
2684        };
2685
2686        format!(
2687            "{}{}{}",
2688            input.get(..start).unwrap_or_default(),
2689            expand_replacement(replacement, input, &found),
2690            input.get(end..).unwrap_or_default()
2691        )
2692    }
2693
2694    /// JavaScript's `GetSubstitution`: `$$`, `$&`, `` $` ``, `$'`, and `$1`-`$99`.
2695    pub(super) fn expand_replacement(
2696        replacement: &str,
2697        input: &str,
2698        found: &[Option<(usize, usize)>],
2699    ) -> String {
2700        let group_count = found.len().saturating_sub(1);
2701        let text = |group: usize| {
2702            found
2703                .get(group)
2704                .copied()
2705                .flatten()
2706                .and_then(|(start, end)| input.get(start..end))
2707                .unwrap_or_default()
2708        };
2709
2710        let (match_start, match_end) = found.first().copied().flatten().unwrap_or((0, 0));
2711        let bytes = replacement.as_bytes();
2712        let mut output = String::with_capacity(replacement.len() + input.len());
2713        let mut index = 0;
2714
2715        while let Some(&byte) = bytes.get(index) {
2716            if byte != b'$' {
2717                let character_end = (index + 1..=bytes.len())
2718                    .find(|&end| replacement.is_char_boundary(end))
2719                    .unwrap_or(bytes.len());
2720
2721                output.push_str(&replacement[index..character_end]);
2722                index = character_end;
2723
2724                continue;
2725            }
2726
2727            let digit = |offset: usize| {
2728                bytes
2729                    .get(index + offset)
2730                    .filter(|byte| byte.is_ascii_digit())
2731                    .map(|byte| usize::from(byte - b'0'))
2732            };
2733
2734            match bytes.get(index + 1) {
2735                Some(b'$') => {
2736                    output.push('$');
2737                    index += 2;
2738                }
2739                Some(b'&') => {
2740                    output.push_str(text(0));
2741                    index += 2;
2742                }
2743                Some(b'`') => {
2744                    output.push_str(input.get(..match_start).unwrap_or_default());
2745                    index += 2;
2746                }
2747                Some(b'\'') => {
2748                    output.push_str(input.get(match_end..).unwrap_or_default());
2749                    index += 2;
2750                }
2751                _ => match (digit(1), digit(2)) {
2752                    (Some(tens), Some(ones)) if (1..=group_count).contains(&(tens * 10 + ones)) => {
2753                        output.push_str(text(tens * 10 + ones));
2754                        index += 3;
2755                    }
2756                    (Some(group), _) if (1..=group_count).contains(&group) => {
2757                        output.push_str(text(group));
2758                        index += 2;
2759                    }
2760                    _ => {
2761                        output.push('$');
2762                        index += 1;
2763                    }
2764                },
2765            }
2766        }
2767
2768        output
2769    }
2770
2771    /// The partial matcher `libphonenumber-js` uses for leading-digit patterns while fewer than
2772    /// three national digits are typed (`AsYouTypeFormatter.PatternMatcher`). It accepts digits
2773    /// that could still grow into a match and tolerates extra digits, and it reads `\d` as two
2774    /// literal characters, exactly like the original.
2775    pub(super) mod partial {
2776        enum Node {
2777            Character(u8),
2778            Sequence(Vec<Node>),
2779            Either(Vec<Node>),
2780            OneOf(Vec<u8>),
2781        }
2782
2783        enum Outcome {
2784            Match(usize),
2785            Partial,
2786            Overflow,
2787        }
2788
2789        struct Context {
2790            or: bool,
2791            one_of_set: bool,
2792            instructions: Vec<Node>,
2793            branches: Option<Vec<Node>>,
2794        }
2795
2796        impl Context {
2797            fn or(branches: Option<Vec<Node>>) -> Self {
2798                Self {
2799                    or: true,
2800                    one_of_set: false,
2801                    instructions: Vec::new(),
2802                    branches,
2803                }
2804            }
2805        }
2806
2807        const OPERATORS: [&str; 5] = ["|", "(?:", ")", "[", "]"];
2808
2809        fn expand(mut nodes: Vec<Node>) -> Node {
2810            if nodes.len() == 1
2811                && let Some(node) = nodes.pop()
2812            {
2813                return node;
2814            }
2815
2816            Node::Sequence(nodes)
2817        }
2818
2819        fn add_characters(context: &mut Context, text: &str) -> Option<()> {
2820            if text.bytes().any(|byte| b"()[]?:|".contains(&byte)) {
2821                return None;
2822            }
2823
2824            context
2825                .instructions
2826                .extend(text.bytes().map(Node::Character));
2827
2828            Some(())
2829        }
2830
2831        fn one_of_set(text: &str) -> Option<Vec<u8>> {
2832            let bytes = text.as_bytes();
2833            let mut values = Vec::new();
2834
2835            for (index, &byte) in bytes.iter().enumerate() {
2836                if byte == b'-' {
2837                    if index == 0 || index + 1 == bytes.len() {
2838                        return None;
2839                    }
2840
2841                    let first = bytes.get(index - 1)?.checked_add(1)?;
2842                    let last = bytes.get(index + 1)?.checked_sub(1)?;
2843
2844                    values.extend(first..=last);
2845                } else {
2846                    values.push(byte);
2847                }
2848            }
2849
2850            Some(values)
2851        }
2852
2853        /// `PatternParser.parse()`.
2854        fn parse(pattern: &str) -> Option<Node> {
2855            let mut contexts = vec![Context::or(None)];
2856            let mut rest = pattern;
2857
2858            if rest.is_empty() {
2859                return None;
2860            }
2861
2862            loop {
2863                let found = OPERATORS
2864                    .iter()
2865                    .filter_map(|operator| rest.find(operator).map(|index| (index, *operator)))
2866                    .min_by_key(|(index, _)| *index);
2867
2868                let Some((index, operator)) = found else {
2869                    add_characters(contexts.last_mut()?, rest)?;
2870
2871                    break;
2872                };
2873
2874                let before = &rest[..index];
2875                let after = &rest[index + operator.len()..];
2876
2877                match operator {
2878                    "(?:" => {
2879                        if !before.is_empty() {
2880                            add_characters(contexts.last_mut()?, before)?;
2881                        }
2882
2883                        contexts.push(Context::or(Some(Vec::new())));
2884                    }
2885                    ")" => {
2886                        if !contexts.last()?.or {
2887                            return None;
2888                        }
2889
2890                        if !before.is_empty() {
2891                            add_characters(contexts.last_mut()?, before)?;
2892                        }
2893
2894                        let context = contexts.pop()?;
2895
2896                        if context.instructions.is_empty() {
2897                            return None;
2898                        }
2899
2900                        let mut branches = context.branches?;
2901
2902                        branches.push(expand(context.instructions));
2903                        contexts
2904                            .last_mut()?
2905                            .instructions
2906                            .push(Node::Either(branches));
2907                    }
2908                    "|" => {
2909                        let depth = contexts.len();
2910                        let context = contexts.last_mut()?;
2911
2912                        if !context.or {
2913                            return None;
2914                        }
2915
2916                        if !before.is_empty() {
2917                            add_characters(context, before)?;
2918                        }
2919
2920                        if context.branches.is_none() {
2921                            if depth != 1 {
2922                                return None;
2923                            }
2924
2925                            context.branches = Some(Vec::new());
2926                        }
2927
2928                        let instructions = std::mem::take(&mut context.instructions);
2929
2930                        context.branches.as_mut()?.push(expand(instructions));
2931                    }
2932                    "[" => {
2933                        if !before.is_empty() {
2934                            add_characters(contexts.last_mut()?, before)?;
2935                        }
2936
2937                        contexts.push(Context {
2938                            or: false,
2939                            one_of_set: true,
2940                            instructions: Vec::new(),
2941                            branches: None,
2942                        });
2943                    }
2944                    _ => {
2945                        if !contexts.last()?.one_of_set {
2946                            return None;
2947                        }
2948
2949                        contexts.pop();
2950                        contexts
2951                            .last_mut()?
2952                            .instructions
2953                            .push(Node::OneOf(one_of_set(before)?));
2954                    }
2955                }
2956
2957                if after.is_empty() {
2958                    break;
2959                }
2960
2961                rest = after;
2962            }
2963
2964            if contexts.len() != 1 {
2965                return None;
2966            }
2967
2968            let root = contexts.pop()?;
2969
2970            if let Some(mut branches) = root.branches {
2971                branches.push(expand(root.instructions));
2972
2973                return Some(Node::Either(branches));
2974            }
2975
2976            if root.instructions.is_empty() {
2977                return None;
2978            }
2979
2980            Some(expand(root.instructions))
2981        }
2982
2983        /// `match()` from `AsYouTypeFormatter.PatternMatcher`.
2984        fn match_node(characters: &[u8], node: &Node, last: bool) -> Option<Outcome> {
2985            match node {
2986                Node::Character(character) => match characters {
2987                    [] => Some(Outcome::Partial),
2988                    [only] if only == character => Some(Outcome::Match(1)),
2989                    [first, ..] if first == character => Some(if last {
2990                        Outcome::Overflow
2991                    } else {
2992                        Outcome::Match(1)
2993                    }),
2994                    _ => None,
2995                },
2996                Node::Sequence(nodes) => {
2997                    let mut rest = characters;
2998
2999                    for (index, node) in nodes.iter().enumerate() {
3000                        let is_last = index + 1 == nodes.len();
3001
3002                        match match_node(rest, node, last && is_last)? {
3003                            Outcome::Overflow => return Some(Outcome::Overflow),
3004                            Outcome::Partial => return Some(Outcome::Partial),
3005                            Outcome::Match(length) => {
3006                                rest = rest.get(length..).unwrap_or_default();
3007
3008                                if rest.is_empty() {
3009                                    return Some(if is_last {
3010                                        Outcome::Match(characters.len())
3011                                    } else {
3012                                        Outcome::Partial
3013                                    });
3014                                }
3015                            }
3016                        }
3017                    }
3018
3019                    if last {
3020                        return Some(Outcome::Overflow);
3021                    }
3022
3023                    Some(Outcome::Match(characters.len() - rest.len()))
3024                }
3025                Node::Either(branches) => {
3026                    let mut partial = false;
3027
3028                    for branch in branches {
3029                        match match_node(characters, branch, last) {
3030                            Some(Outcome::Overflow) => return Some(Outcome::Overflow),
3031                            Some(Outcome::Match(length)) => return Some(Outcome::Match(length)),
3032                            Some(Outcome::Partial) => partial = true,
3033                            None => {}
3034                        }
3035                    }
3036
3037                    partial.then_some(Outcome::Partial)
3038                }
3039                Node::OneOf(values) => {
3040                    let first = characters.first()?;
3041
3042                    let outcome = if characters.len() > 1 && last {
3043                        Outcome::Overflow
3044                    } else {
3045                        Outcome::Match(1)
3046                    };
3047
3048                    values.contains(first).then_some(outcome)
3049                }
3050            }
3051        }
3052
3053        /// `new PatternMatcher(pattern).match(digits, { allowOverflow: true }) !== undefined`. A
3054        /// pattern the parser rejects counts as a match, as in `libphonenumber-js`.
3055        pub(in super::super) fn matches(pattern: &str, digits: &str) -> bool {
3056            if digits.is_empty() {
3057                return true;
3058            }
3059
3060            match parse(pattern) {
3061                Some(tree) => match_node(digits.as_bytes(), &tree, true).is_some(),
3062                None => true,
3063            }
3064        }
3065    }
3066}
3067
3068#[cfg(test)]
3069mod tests {
3070    use std::time::{Duration, Instant};
3071
3072    use super::pattern::{self, partial};
3073    use super::*;
3074
3075    fn country(region_code: &str) -> PhoneInputCountry {
3076        PhoneInputCountry::find(region_code)
3077            .unwrap_or_else(|| panic!("missing country {region_code}"))
3078    }
3079
3080    /// `(selected region, input, resolved region, national text, E.164)` from libphonenumber-js
3081    /// 1.13.17 (`AsYouType`, `getNumber`, `formatNational`) run through the same steps as
3082    /// `resolveLumenPhoneNumber`. A number is valid exactly when it has an E.164 value.
3083    const LIBPHONENUMBER_VECTORS: &[(&str, &str, &str, &str, Option<&str>)] = &[
3084        (
3085            "US",
3086            "2015550123",
3087            "US",
3088            "(201) 555-0123",
3089            Some("+12015550123"),
3090        ),
3091        (
3092            "US",
3093            "(201) 555-0123",
3094            "US",
3095            "(201) 555-0123",
3096            Some("+12015550123"),
3097        ),
3098        (
3099            "US",
3100            "1 201 555 0123",
3101            "US",
3102            "1 (201) 555-0123",
3103            Some("+12015550123"),
3104        ),
3105        (
3106            "US",
3107            "6135550123",
3108            "US",
3109            "(613) 555-0123",
3110            Some("+16135550123"),
3111        ),
3112        (
3113            "CA",
3114            "4165550123",
3115            "CA",
3116            "(416) 555-0123",
3117            Some("+14165550123"),
3118        ),
3119        (
3120            "GB",
3121            "020 7946 0018",
3122            "GB",
3123            "020 7946 0018",
3124            Some("+442079460018"),
3125        ),
3126        (
3127            "GB",
3128            "2079460018",
3129            "GB",
3130            "2079460018",
3131            Some("+442079460018"),
3132        ),
3133        (
3134            "GB",
3135            "07400 123456",
3136            "GB",
3137            "07400 123456",
3138            Some("+447400123456"),
3139        ),
3140        ("DE", "030 123456", "DE", "030 123456", Some("+4930123456")),
3141        (
3142            "DE",
3143            "015112345678",
3144            "DE",
3145            "01511 2345678",
3146            Some("+4915112345678"),
3147        ),
3148        (
3149            "FR",
3150            "01 23 45 67 89",
3151            "FR",
3152            "01 23 45 67 89",
3153            Some("+33123456789"),
3154        ),
3155        ("FR", "612345678", "FR", "612345678", Some("+33612345678")),
3156        (
3157            "ES",
3158            "612 34 56 78",
3159            "ES",
3160            "612 34 56 78",
3161            Some("+34612345678"),
3162        ),
3163        (
3164            "IT",
3165            "312 345 6789",
3166            "IT",
3167            "312 345 6789",
3168            Some("+393123456789"),
3169        ),
3170        (
3171            "IT",
3172            "06 1234 5678",
3173            "IT",
3174            "06 1234 5678",
3175            Some("+390612345678"),
3176        ),
3177        (
3178            "CO",
3179            "300 123 4567",
3180            "CO",
3181            "300 1234567",
3182            Some("+573001234567"),
3183        ),
3184        (
3185            "CO",
3186            "601 2345678",
3187            "CO",
3188            "(601) 2345678",
3189            Some("+576012345678"),
3190        ),
3191        (
3192            "MX",
3193            "55 1234 5678",
3194            "MX",
3195            "55 1234 5678",
3196            Some("+525512345678"),
3197        ),
3198        (
3199            "BR",
3200            "11 98765-4321",
3201            "BR",
3202            "(11) 98765-4321",
3203            Some("+5511987654321"),
3204        ),
3205        (
3206            "BR",
3207            "(11) 3456-7890",
3208            "BR",
3209            "(11) 3456-7890",
3210            Some("+551134567890"),
3211        ),
3212        (
3213            "IN",
3214            "98765 43210",
3215            "IN",
3216            "98765 43210",
3217            Some("+919876543210"),
3218        ),
3219        (
3220            "JP",
3221            "03-1234-5678",
3222            "JP",
3223            "03-1234-5678",
3224            Some("+81312345678"),
3225        ),
3226        (
3227            "JP",
3228            "090-1234-5678",
3229            "JP",
3230            "090-1234-5678",
3231            Some("+819012345678"),
3232        ),
3233        (
3234            "AU",
3235            "0412 345 678",
3236            "AU",
3237            "0412 345 678",
3238            Some("+61412345678"),
3239        ),
3240        (
3241            "AU",
3242            "02 9876 5432",
3243            "AU",
3244            "(02) 9876 5432",
3245            Some("+61298765432"),
3246        ),
3247        (
3248            "AR",
3249            "011 15-2345-6789",
3250            "AR",
3251            "011 15-2345-6789",
3252            Some("+5491123456789"),
3253        ),
3254        (
3255            "US",
3256            "+1 201 555 0123",
3257            "US",
3258            "(201) 555-0123",
3259            Some("+12015550123"),
3260        ),
3261        (
3262            "US",
3263            "+1 613 555 0123",
3264            "CA",
3265            "(613) 555-0123",
3266            Some("+16135550123"),
3267        ),
3268        (
3269            "US",
3270            "+1 787 234 5678",
3271            "PR",
3272            "(787) 234-5678",
3273            Some("+17872345678"),
3274        ),
3275        (
3276            "GB",
3277            "+1 268 464 1234",
3278            "AG",
3279            "(268) 464-1234",
3280            Some("+12684641234"),
3281        ),
3282        (
3283            "US",
3284            "+44 20 7946 0018",
3285            "GB",
3286            "020 7946 0018",
3287            Some("+442079460018"),
3288        ),
3289        (
3290            "US",
3291            "+44 1481 256789",
3292            "GG",
3293            "01481 256789",
3294            Some("+441481256789"),
3295        ),
3296        (
3297            "US",
3298            "+44 7797 123456",
3299            "JE",
3300            "07797 123456",
3301            Some("+447797123456"),
3302        ),
3303        ("US", "+44 1624 456789", "IM", "+44 1624 456789", None),
3304        (
3305            "US",
3306            "+44 1624 756789",
3307            "IM",
3308            "01624 756789",
3309            Some("+441624756789"),
3310        ),
3311        (
3312            "IM",
3313            "01624 756789",
3314            "IM",
3315            "01624 756789",
3316            Some("+441624756789"),
3317        ),
3318        (
3319            "US",
3320            "+49 30 123456",
3321            "DE",
3322            "030 123456",
3323            Some("+4930123456"),
3324        ),
3325        (
3326            "US",
3327            "+33 1 23 45 67 89",
3328            "FR",
3329            "01 23 45 67 89",
3330            Some("+33123456789"),
3331        ),
3332        (
3333            "US",
3334            "+81 3 1234 5678",
3335            "JP",
3336            "03-1234-5678",
3337            Some("+81312345678"),
3338        ),
3339        (
3340            "US",
3341            "+61 412 345 678",
3342            "AU",
3343            "0412 345 678",
3344            Some("+61412345678"),
3345        ),
3346        (
3347            "US",
3348            "+55 11 98765 4321",
3349            "BR",
3350            "(11) 98765-4321",
3351            Some("+5511987654321"),
3352        ),
3353        (
3354            "US",
3355            "+52 55 1234 5678",
3356            "MX",
3357            "55 1234 5678",
3358            Some("+525512345678"),
3359        ),
3360        (
3361            "US",
3362            "+57 300 1234567",
3363            "CO",
3364            "300 1234567",
3365            Some("+573001234567"),
3366        ),
3367        (
3368            "US",
3369            "+91 98765 43210",
3370            "IN",
3371            "098765 43210",
3372            Some("+919876543210"),
3373        ),
3374        (
3375            "US",
3376            "+34 612 34 56 78",
3377            "ES",
3378            "612 34 56 78",
3379            Some("+34612345678"),
3380        ),
3381        (
3382            "US",
3383            "+39 06 1234 5678",
3384            "IT",
3385            "06 1234 5678",
3386            Some("+390612345678"),
3387        ),
3388        (
3389            "US",
3390            "+54 9 11 2345 6789",
3391            "AR",
3392            "011 15-2345-6789",
3393            Some("+5491123456789"),
3394        ),
3395        (
3396            "US",
3397            "+44 (0) 20 7946 0018",
3398            "GB",
3399            "020 7946 0018",
3400            Some("+442079460018"),
3401        ),
3402        (
3403            "US",
3404            "+800 1234 5678",
3405            "US",
3406            "1234 5678",
3407            Some("+80012345678"),
3408        ),
3409        (
3410            "US",
3411            "011 44 20 7946 0018",
3412            "US",
3413            "011 44 20 7946 0018",
3414            Some("+442079460018"),
3415        ),
3416        (
3417            "GB",
3418            "00 33 1 23 45 67 89",
3419            "GB",
3420            "00 33 1 23 45 67 89",
3421            Some("+33123456789"),
3422        ),
3423        (
3424            "GB",
3425            "442079460018",
3426            "GB",
3427            "44 20 7946 0018",
3428            Some("+442079460018"),
3429        ),
3430        ("US", "2", "US", "2", None),
3431        ("US", "201", "US", "(201)", None),
3432        ("US", "2015", "US", "(201) 5", None),
3433        ("US", "201555", "US", "(201) 555", None),
3434        ("CA", "416555", "CA", "(416) 555", None),
3435        ("GB", "0207", "GB", "020 7", None),
3436        ("GB", "07400 12", "GB", "07400 12", None),
3437        ("DE", "0301", "DE", "030 1", None),
3438        ("FR", "0612", "FR", "06 12", None),
3439        ("ES", "6123", "ES", "612 3", None),
3440        ("IT", "31234", "IT", "312 34", None),
3441        ("CO", "30012", "CO", "300 12", None),
3442        ("MX", "551234", "MX", "55 1234", None),
3443        ("BR", "119876", "BR", "(11) 9876", None),
3444        ("IN", "98765", "IN", "98765", None),
3445        ("JP", "0312", "JP", "03-12", None),
3446        ("AU", "04123", "AU", "0412 3", None),
3447        ("US", "+44 20", "US", "+44 20", None),
3448        ("US", "+1", "US", "+1", None),
3449        ("US", "+12", "US", "+1 2", None),
3450        ("US", "2115550123", "US", "(211) 555-0123", None),
3451        ("US", "20155501234", "US", "20155501234", None),
3452        ("GB", "0000000000", "GB", "0000000000", None),
3453        ("DE", "1", "DE", "1", None),
3454        ("US", "+999 123", "US", "+999123", None),
3455        (
3456            "US",
3457            "tel: +1 (201) 555-0123",
3458            "US",
3459            "(201) 555-0123",
3460            Some("+12015550123"),
3461        ),
3462        (
3463            "US",
3464            "call 201.555.0123 now",
3465            "US",
3466            "(201) 555-0123",
3467            Some("+12015550123"),
3468        ),
3469        (
3470            "FR",
3471            "a0b1c2d3e4f5g6h7i8j9",
3472            "FR",
3473            "01 23 45 67 89",
3474            Some("+33123456789"),
3475        ),
3476        ("US", "abc", "US", "", None),
3477        ("US", "+", "US", "", None),
3478        ("US", "", "US", "", None),
3479        ("US", " + ", "US", "", None),
3480        ("US", "1+2", "US", "1 2", None),
3481    ];
3482
3483    #[test]
3484    fn resolve_matches_libphonenumber() {
3485        for &(selected, input, region, national, e164) in LIBPHONENUMBER_VECTORS {
3486            let resolved = PhoneInputNumber::resolve(country(selected), input);
3487
3488            assert_eq!(
3489                (
3490                    resolved.country.region_code,
3491                    resolved.national_number.as_str(),
3492                    resolved.e164.as_deref(),
3493                    resolved.is_valid,
3494                ),
3495                (region, national, e164, e164.is_some()),
3496                "{selected} {input:?}"
3497            );
3498        }
3499    }
3500
3501    #[test]
3502    fn empty_input_resolves_to_an_empty_value() {
3503        for input in ["", "+", " + ", "abc", "++", "-()"] {
3504            assert_eq!(
3505                PhoneInputNumber::resolve(country("GB"), input),
3506                PhoneInputNumber::empty(country("GB")),
3507                "{input:?}"
3508            );
3509        }
3510    }
3511
3512    #[test]
3513    fn display_prefers_e164_for_valid_numbers() {
3514        assert_eq!(
3515            PhoneInputNumber::resolve(country("US"), "2015550123").display(),
3516            "+12015550123"
3517        );
3518        assert_eq!(
3519            PhoneInputNumber::resolve(country("US"), "201555").display(),
3520            "(201) 555"
3521        );
3522        assert_eq!(PhoneInputNumber::empty(country("US")).display(), "");
3523    }
3524
3525    #[test]
3526    fn resolving_the_displayed_text_is_stable() {
3527        // The field shows `national_number` and resolves it again on the next edit. Non-geographic
3528        // numbers such as +800 keep the selected country, like the React input, so they are skipped.
3529        for &(selected, input, _, _, _) in LIBPHONENUMBER_VECTORS {
3530            let first = PhoneInputNumber::resolve(country(selected), input);
3531            let second = PhoneInputNumber::resolve(first.country, &first.national_number);
3532            let same_plan = first
3533                .e164
3534                .as_deref()
3535                .is_some_and(|e164| e164.starts_with(first.country.calling_code));
3536
3537            if same_plan {
3538                assert_eq!(second.e164, first.e164, "{selected} {input:?}");
3539            }
3540        }
3541    }
3542
3543    #[test]
3544    fn input_that_breaks_libphonenumber_does_not_panic() {
3545        // libphonenumber-js throws a TypeError for these; the engine keeps the typed digits.
3546        let resolved = PhoneInputNumber::resolve(country("WS"), "06");
3547
3548        assert!(!resolved.is_valid);
3549        assert_eq!(resolved.e164, None);
3550        assert_eq!(resolved.national_number, "0 6");
3551    }
3552
3553    #[test]
3554    fn sanitize_keeps_ascii_digits_and_one_leading_plus() {
3555        let cases = [
3556            (" +1 (201) 555-0123 ", "+12015550123"),
3557            ("1+2", "12"),
3558            ("++1", "+1"),
3559            ("a+1", "+1"),
3560            ("tel:+44-20", "+4420"),
3561            ("\u{FF11}\u{FF12}3", "3"),
3562            ("\u{0661}2", "2"),
3563            ("", ""),
3564            ("+", "+"),
3565        ];
3566
3567        for (input, expected) in cases {
3568            assert_eq!(sanitize_phone_input(input), expected, "{input:?}");
3569        }
3570    }
3571
3572    #[test]
3573    fn flags_and_picker_labels() {
3574        assert_eq!(country("US").flag(), "\u{1F1FA}\u{1F1F8}");
3575        assert_eq!(flag_for_region("gb"), "\u{1F1EC}\u{1F1E7}");
3576        assert_eq!(flag_for_region("001"), "");
3577        assert_eq!(flag_for_region("USA"), "");
3578        assert_eq!(flag_for_region(""), "");
3579        assert_eq!(
3580            country("US").picker_label(),
3581            "\u{1F1FA}\u{1F1F8} United States (+1)"
3582        );
3583        assert_eq!(
3584            country("CI").picker_label(),
3585            "\u{1F1E8}\u{1F1EE} C\u{F4}te d\u{2019}Ivoire (+225)"
3586        );
3587    }
3588
3589    #[test]
3590    fn all_lists_every_region_in_english_collation_order() {
3591        let countries = PhoneInputCountry::all();
3592        let codes: Vec<&str> = countries
3593            .iter()
3594            .map(|country| country.region_code)
3595            .collect();
3596        let position = |code: &str| codes.iter().position(|candidate| *candidate == code);
3597
3598        assert_eq!(countries.len(), 245);
3599        assert_eq!(codes.first(), Some(&"AF"));
3600        assert_eq!(codes.get(1), Some(&"AX"));
3601        assert_eq!(codes.last(), Some(&"ZW"));
3602        assert!(position("CR") < position("CI"));
3603        assert!(position("CI") < position("HR"));
3604        assert!(position("CU") < position("CW"));
3605
3606        for country in countries {
3607            let region = region_by_code(country.region_code)
3608                .unwrap_or_else(|| panic!("missing metadata for {}", country.region_code));
3609
3610            assert_eq!(country.calling_code, format!("+{}", region.calling_code()));
3611            assert_ne!(country.display_name, "");
3612            assert_eq!(PhoneInputCountry::find(country.region_code), Some(*country));
3613        }
3614    }
3615
3616    #[test]
3617    fn metadata_tables_are_sorted_for_binary_search() {
3618        assert!(
3619            REGIONS
3620                .windows(2)
3621                .all(|pair| pair[0].code() < pair[1].code())
3622        );
3623        assert!(
3624            NON_GEOGRAPHIC
3625                .windows(2)
3626                .all(|pair| pair[0].calling_code() < pair[1].calling_code())
3627        );
3628        assert!(CALLING_CODES.windows(2).all(|pair| pair[0].0 < pair[1].0));
3629        assert_eq!(REGIONS.len(), COUNTRIES.len());
3630
3631        for (calling_code, regions) in CALLING_CODES {
3632            for region in *regions {
3633                assert_eq!(
3634                    region_by_code(region).map(PhoneRegion::calling_code),
3635                    Some(*calling_code)
3636                );
3637            }
3638        }
3639    }
3640
3641    #[test]
3642    fn find_accepts_region_codes_and_calling_codes() {
3643        assert_eq!(
3644            PhoneInputCountry::find("us").map(|country| country.region_code),
3645            Some("US")
3646        );
3647        assert_eq!(
3648            PhoneInputCountry::find(" GB ").map(|country| country.region_code),
3649            Some("GB")
3650        );
3651        assert_eq!(
3652            PhoneInputCountry::find("+44").map(|country| country.region_code),
3653            Some("GB")
3654        );
3655        assert_eq!(
3656            PhoneInputCountry::find("44").map(|country| country.region_code),
3657            Some("GB")
3658        );
3659        assert_eq!(
3660            PhoneInputCountry::find("+1").map(|country| country.region_code),
3661            Some("US")
3662        );
3663        assert_eq!(
3664            PhoneInputCountry::find("+7").map(|country| country.region_code),
3665            Some("RU")
3666        );
3667        assert_eq!(PhoneInputCountry::find("+800"), None);
3668        assert_eq!(PhoneInputCountry::find("+999"), None);
3669        assert_eq!(PhoneInputCountry::find("XX"), None);
3670        assert_eq!(PhoneInputCountry::find(""), None);
3671        assert_eq!(PhoneInputCountry::find("+"), None);
3672    }
3673
3674    #[test]
3675    fn matcher_distinguishes_full_and_prefix_matches() {
3676        assert!(pattern::matches_entirely("123", r"\d{3}"));
3677        assert!(!pattern::matches_entirely("1234", r"\d{3}"));
3678        assert!(pattern::matches_at_start("1234", r"\d{3}"));
3679        assert!(!pattern::matches_at_start("12", r"\d{3}"));
3680        assert!(pattern::matches_entirely("", ""));
3681        assert!(!pattern::matches_entirely("1", ""));
3682    }
3683
3684    #[test]
3685    fn matcher_supports_classes_alternation_and_quantifiers() {
3686        assert!(pattern::matches_entirely("6", "[2-46-9]"));
3687        assert!(!pattern::matches_entirely("5", "[2-46-9]"));
3688        assert!(pattern::matches_entirely("7", r"[\d]"));
3689        assert!(pattern::matches_entirely("2", r"2|3\d"));
3690        assert!(pattern::matches_entirely("34", r"2|3\d"));
3691        assert!(!pattern::matches_entirely("3", r"2|3\d"));
3692        assert!(pattern::matches_entirely("1212", "(?:12){2,3}"));
3693        assert!(pattern::matches_entirely("121212", "(?:12){2,3}"));
3694        assert!(!pattern::matches_entirely("12", "(?:12){2,3}"));
3695        assert!(!pattern::matches_entirely("12121212", "(?:12){2,3}"));
3696        assert!(pattern::matches_entirely("2", "1?2"));
3697        assert!(pattern::matches_entirely("12", "1?2"));
3698        assert!(pattern::matches_entirely("", r"\d*"));
3699        assert!(pattern::matches_entirely("123456", r"\d*"));
3700        assert!(!pattern::matches_entirely("", r"\d+"));
3701        assert!(pattern::matches_entirely("12345", r"\d{2,}"));
3702        assert!(!pattern::matches_entirely("1", r"\d{2,}"));
3703        assert!(pattern::matches_entirely("a.b", r"a\.b"));
3704        assert!(!pattern::matches_entirely("axb", r"a\.b"));
3705    }
3706
3707    #[test]
3708    fn matcher_end_anchor_needs_the_real_end() {
3709        let prefix_for_parsing = r"([457]\d{6})$|1";
3710
3711        assert!(pattern::matches_at_start("4234567", prefix_for_parsing));
3712        assert!(pattern::matches_at_start("1234567", prefix_for_parsing));
3713        assert!(!pattern::matches_at_start("42345678", prefix_for_parsing));
3714
3715        // Long input is truncated for prefix matches, but `$` still needs the real end.
3716        let long_input = "4".repeat(100);
3717
3718        assert!(pattern::matches_at_start(&long_input, r"\d{3}"));
3719        assert!(!pattern::matches_at_start(&long_input, r"\d{3}$"));
3720        assert!(!pattern::matches_entirely(&long_input, r"\d*"));
3721    }
3722
3723    #[test]
3724    fn malformed_patterns_never_match() {
3725        for malformed in [
3726            "(12", "12)", "[1-", r"\q", "{3}", "1{3,2}", "(?=1)", "^1", ".", "1**", "a]",
3727        ] {
3728            assert!(!pattern::matches_entirely("12", malformed), "{malformed:?}");
3729            assert!(!pattern::matches_at_start("12", malformed), "{malformed:?}");
3730            assert!(
3731                pattern::captures_at_start(malformed, "12").is_none(),
3732                "{malformed:?}"
3733            );
3734            assert_eq!(
3735                pattern::replace_first(malformed, "12", "x"),
3736                "12",
3737                "{malformed:?}"
3738            );
3739        }
3740    }
3741
3742    #[test]
3743    fn captures_follow_javascript_priorities() {
3744        let spans = |pattern: &str, input: &str| pattern::captures_at_start(pattern, input);
3745
3746        // Leftmost-first: the first alternative wins even when a later one is longer.
3747        assert_eq!(spans("1|12", "123"), Some(vec![Some((0, 1))]));
3748        assert_eq!(
3749            spans(r"(\d{1,3})(\d+)", "12345"),
3750            Some(vec![Some((0, 5)), Some((0, 3)), Some((3, 5))])
3751        );
3752        assert_eq!(
3753            spans(r"(\d{1,3}?)(\d+)", "12345"),
3754            Some(vec![Some((0, 5)), Some((0, 1)), Some((1, 5))])
3755        );
3756        assert_eq!(spans("(1)?2", "2"), Some(vec![Some((0, 1)), None]));
3757        assert_eq!(spans("0|180020", "1800201234"), Some(vec![Some((0, 6))]));
3758        assert_eq!(spans("2", "12"), None);
3759        assert_eq!(pattern::captures("2", "12"), Some(vec![Some((1, 2))]));
3760    }
3761
3762    #[test]
3763    fn replacement_follows_javascript_substitution() {
3764        assert_eq!(
3765            pattern::replace_first(r"(\d{3})(\d{4})", "5550123", "$1-$2"),
3766            "555-0123"
3767        );
3768        assert_eq!(
3769            pattern::replace_first(r"(\d{3})", "12345", "[$1]"),
3770            "[123]45"
3771        );
3772        assert_eq!(
3773            pattern::replace_first("3", "12345", "<$&$`$'$$>"),
3774            "12<31245$>45"
3775        );
3776        assert_eq!(pattern::replace_first("(1)", "12", "$2$9"), "$2$92");
3777        assert_eq!(pattern::replace_first("(1)", "12", "$01"), "12");
3778        assert_eq!(pattern::replace_first("9", "12", "x"), "12");
3779    }
3780
3781    #[test]
3782    fn partial_leading_digit_matcher_mirrors_libphonenumber() {
3783        assert!(partial::matches("[2-9]", "2"));
3784        assert!(!partial::matches("[2-9]", "1"));
3785        assert!(partial::matches("21|3", "2"));
3786        assert!(partial::matches("800", "80"));
3787        assert!(!partial::matches("800", "81"));
3788        assert!(partial::matches("8", "89"));
3789        assert!(partial::matches("1(?:38|5[23])", "15"));
3790        assert!(!partial::matches("1(?:38|5[23])", "16"));
3791        // `\d` is read as two literal characters, exactly like libphonenumber-js.
3792        assert!(!partial::matches(r"\d", "5"));
3793        // Patterns its parser rejects count as matches.
3794        assert!(partial::matches("1?", "5"));
3795    }
3796
3797    #[test]
3798    fn template_patterns_replace_classes_and_standalone_digits() {
3799        assert_eq!(template_pattern(r"(\d{3})(\d{3,4})"), r"(\d{3})(\d{3,4})");
3800        assert_eq!(
3801            template_pattern(r"([2-9]\d{2})(\d{4})"),
3802            r"(\d\d{2})(\d{4})"
3803        );
3804        assert_eq!(
3805            template_pattern(r"(9)(\d{4})(\d{10,12})"),
3806            r"(\d)(\d{4})(\d{10,12})"
3807        );
3808    }
3809
3810    #[test]
3811    fn adversarial_input_returns_quickly() {
3812        let limit = Duration::from_secs(10);
3813        let inputs = [
3814            "1".repeat(100_000),
3815            format!("+{}", "4".repeat(100_000)),
3816            "+1".repeat(50_000),
3817            "+".repeat(100_000),
3818            format!("{}2015550123", "+ -".repeat(30_000)),
3819            "0".repeat(100_000),
3820        ];
3821
3822        for input in &inputs {
3823            for region in ["US", "GB", "AR", "BR", "WS"] {
3824                let started = Instant::now();
3825                let resolved = PhoneInputNumber::resolve(country(region), input);
3826
3827                assert!(
3828                    started.elapsed() < limit,
3829                    "{region} took {:?}",
3830                    started.elapsed()
3831                );
3832                assert!(resolved.national_number.len() <= input.len() * 2);
3833            }
3834        }
3835
3836        assert!(PhoneInputNumber::resolve(country("US"), &inputs[4]).is_valid);
3837    }
3838
3839    #[test]
3840    fn adversarial_patterns_stay_bounded() {
3841        let started = Instant::now();
3842        let deep = format!("{}1{}", "(?:".repeat(1_000), ")".repeat(1_000));
3843
3844        assert!(!pattern::matches_entirely("1", &deep));
3845        assert!(pattern::captures_at_start(&deep, "1").is_none());
3846        assert!(!pattern::matches_entirely("1", "1{999999999}"));
3847        assert!(!pattern::matches_entirely("1", "(?:1?){999999999}1{2}"));
3848        assert!(pattern::matches_entirely("11", "(?:1?){999999999}"));
3849        assert!(pattern::captures_at_start("(?:1?){999999999}", "1").is_none());
3850        assert!(started.elapsed() < Duration::from_secs(10));
3851    }
3852}