use core::{fmt, ops::Range};
use crate::{PhoneNumber, Region};
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Confidence {
Valid,
Possible,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct FindOptions {
default_region: Option<Region>,
max_results: usize,
include_possible: bool,
}
impl FindOptions {
pub const fn new() -> Self {
Self {
default_region: None,
max_results: 32,
include_possible: false,
}
}
pub const fn with_default_region(mut self, region: Region) -> Self {
self.default_region = Some(region);
self
}
pub const fn with_max_results(mut self, max_results: usize) -> Self {
self.max_results = max_results;
self
}
pub const fn with_possible(mut self, include: bool) -> Self {
self.include_possible = include;
self
}
}
impl Default for FindOptions {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone, Eq, PartialEq)]
pub struct FoundNumber<'a> {
range: Range<usize>,
source: &'a str,
number: PhoneNumber,
confidence: Confidence,
}
impl<'a> FoundNumber<'a> {
pub fn range(&self) -> Range<usize> {
self.range.clone()
}
pub const fn source(&self) -> &'a str {
self.source
}
pub const fn number(&self) -> &PhoneNumber {
&self.number
}
pub const fn confidence(&self) -> Confidence {
self.confidence
}
}
impl fmt::Debug for FoundNumber<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FoundNumber")
.field("range", &self.range)
.field("source", &"**redacted**")
.field("number", &self.number)
.field("confidence", &self.confidence)
.finish()
}
}
pub struct FoundNumbers<'a> {
text: &'a str,
options: FindOptions,
cursor: usize,
yielded: usize,
}
impl<'a> FoundNumbers<'a> {
pub const fn new(text: &'a str, options: FindOptions) -> Self {
Self {
text,
options,
cursor: 0,
yielded: 0,
}
}
}
impl<'a> Iterator for FoundNumbers<'a> {
type Item = FoundNumber<'a>;
fn next(&mut self) -> Option<Self::Item> {
while self.cursor < self.text.len() && self.yielded < self.options.max_results {
let start = next_candidate_start(self.text, self.cursor)?;
let (end, truncated) = candidate_end(self.text, start);
if truncated {
self.cursor = skip_candidate(self.text, end);
continue;
}
self.cursor = if end > start {
end
} else {
start + self.text[start..].chars().next().map_or(1, char::len_utf8)
};
let source = self.text[start..end]
.trim_end()
.trim_end_matches(['.', ',', ';', ':']);
let end = start + source.len();
let parsed = match self.options.default_region {
Some(region) => crate::parse_in(region, source),
None => crate::parse(source),
};
if let Ok(number) = parsed {
let valid = crate::assessment::is_valid(&number);
let possible = matches!(
crate::assessment::possibility(&number),
crate::Possibility::Possible | crate::Possibility::LocalOnly
);
if valid || (self.options.include_possible && possible) {
self.yielded += 1;
return Some(FoundNumber {
range: start..end,
source,
confidence: if valid {
Confidence::Valid
} else {
Confidence::Possible
},
number,
});
}
}
}
None
}
}
impl std::iter::FusedIterator for FoundNumbers<'_> {}
fn next_candidate_start(text: &str, from: usize) -> Option<usize> {
text[from..]
.char_indices()
.find(|(_, character)| {
crate::parse::is_plus_sign(*character)
|| crate::parse::decimal_digit(*character).is_some()
})
.map(|(offset, _)| from + offset)
}
fn candidate_end(text: &str, start: usize) -> (usize, bool) {
const MAX_CANDIDATE_BYTES: usize = 128;
let mut end = start;
let mut digits = 0;
for (offset, character) in text[start..].char_indices() {
if crate::parse::decimal_digit(character).is_some() {
digits += 1;
}
if character.is_ascii_alphabetic()
&& digits >= 7
&& text[start..start + offset]
.chars()
.next_back()
.is_some_and(char::is_whitespace)
&& !starts_with_extension(&text[start + offset..])
{
break;
}
if !is_candidate_character(character) {
break;
}
if offset + character.len_utf8() > MAX_CANDIDATE_BYTES {
return (end, true);
}
end = start + offset + character.len_utf8();
}
(end, false)
}
fn skip_candidate(text: &str, from: usize) -> usize {
text[from..]
.char_indices()
.find(|(_, character)| !is_candidate_character(*character))
.map_or(text.len(), |(offset, _)| from + offset)
}
fn is_candidate_character(character: char) -> bool {
character.is_ascii_alphabetic()
|| crate::parse::decimal_digit(character).is_some()
|| crate::parse::is_plus_sign(character)
|| matches!(character, '-' | '(' | ')' | '.' | ' ' | '#' | ';' | '=')
}
fn starts_with_extension(text: &str) -> bool {
text.get(..3)
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("ext"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn candidate_limit_counts_utf8_bytes() {
let text = "реп".repeat(100);
let (end, truncated) = candidate_end(&text, 0);
assert!(truncated);
assert!(end <= 128);
assert!(text.is_char_boundary(end));
}
#[test]
fn oversized_candidates_do_not_yield_valid_suffixes() {
let text = format!("{}6502530000, +44 20 7946 0018", "1".repeat(130));
let found = FoundNumbers::new(&text, FindOptions::default())
.next()
.expect("number after oversized candidate");
assert_eq!(found.source(), "+44 20 7946 0018");
}
}