//! Phone numbers as people write them: `+31 6 1234 5678`, `06-12345678`, //! `0031612345678`. Dialled as written (digits and a leading `+`); matched //! on their last nine digits, which is the subscriber's number with the //! country and trunk prefixes off in every numbering plan that matters //! here, so a caller's `+31612345678` finds the contact saved as //! `06 12345678`. use alloc::string::String; /// How many trailing digits two numbers must share to be the same. const SIGNIFICANT: usize = 9; /// The number as a modem dials it: its digits, a leading `+`, and `*` /// and `#` (service codes); `None` when nothing dialable is left. pub fn dialable(written: &str) -> Option { let mut out = String::new(); let written = written.trim(); // `+31 (0)6 …`: the trunk zero in brackets is not dialled after a // country code. let written = match written.starts_with('+') { true => written.replacen("(0)", "", 1), false => written.into(), }; for c in written.chars() { match c { '+' if out.is_empty() => out.push('+'), '0'..='9' | '*' | '#' => out.push(c), ' ' | '-' | '.' | '(' | ')' | '/' => {} _ => return None, } } out.chars().any(|c| c.is_ascii_digit()).then_some(out) } fn digits(n: &str) -> impl DoubleEndedIterator + '_ { n.bytes().filter(u8::is_ascii_digit) } /// Whether `a` and `b` are the same number, however each was written: /// their last nine digits agree, or, when either is shorter (a short /// service number), all of them. pub fn same(a: &str, b: &str) -> bool { let (na, nb) = (digits(a).count(), digits(b).count()); if na == 0 || nb == 0 { return false; } if na < SIGNIFICANT || nb < SIGNIFICANT { return na == nb && digits(a).eq(digits(b)); } digits(a) .rev() .take(SIGNIFICANT) .eq(digits(b).rev().take(SIGNIFICANT)) }