Cotton code
161 lines · 7.3 KB · RustRaw
//! Canonical phone normalization shared by import, People, and schema moves.//!//! A number written with its country code (a leading `+` or `00`) is parsed//! by `phonenumber`, the libphonenumber port, and kept as its E.164 digits —//! so the trunk 0 a person writes after the code goes: "+91 098765 43210",//! "+91 98765 43210" and "0091 98765 43210" are one number, 919876543210, and//! "+44 (0)20 7946 0958" is 442079460958. A number written without one has//! no default country to guess from: it stays its digits as typed and matches//! only exactly, because a WRONG country files someone's messages under a//! contact that is not theirs.use crate::js;/// The presentation characters `normalizePhone` strips: JS `[\s\-().]`.////// `\s` is ECMAScript's class, not Rust's — a number pasted with a BOM in it/// normalises on one side and not on the other otherwise.pub fn is_presentation(ch: char) -> bool {    js::is_js_whitespace(ch) || matches!(ch, '-' | '(' | ')' | '.')}pub fn strip_presentation(raw: &str) -> String {    raw.chars().filter(|ch| !is_presentation(*ch)).collect()}/// `^[0-9]{8,15}$` — ASCII digits only. JS `\d` without the `u` flag is/// `[0-9]`, so an Arabic-Indic numeral is NOT a phone number on either side.fn is_canonical(digits: &str) -> bool {    (8..=15).contains(&digits.len()) && digits.bytes().all(|b| b.is_ascii_digit())}/// Canonical form used everywhere in the platform: digits only, no leading `+`.////// Presentation characters go FIRST, then one leading `+` (or `00`, the/// international prefix nearly everywhere) says the country code follows./// Such a number is E.164 through `phonenumber` (which drops a trunk 0 only/// where the rest is a number of that country, and keeps Italy's leading 0);/// one it cannot parse (no country has the code) keeps its digits, as one/// without a code does. Either/// way the result is 8–15 ASCII digits or `None`.pub fn normalize_phone(raw: &str) -> Option<String> {    let stripped = strip_presentation(raw);    // Exactly one leading `+` — `"++91…"` is not a number.    let international = stripped.strip_prefix('+').or_else(|| stripped.strip_prefix("00"));    if let Some(e164) = international.and_then(e164_digits) {        return Some(e164);    }    let digits = stripped.strip_prefix('+').unwrap_or(&stripped);    if is_canonical(digits) {        Some(digits.to_string())    } else {        None    }}/// The E.164 digits of a number WRITTEN with its country code (a leading `+`/// or `00`) that some country's code leads, whether or not libphonenumber/// holds the rest valid: the writer said the country, so it is not guessed/// (a range newer than the metadata, a test range like +1 555 01xx). `None`/// for a number written without a code, or one no country's code leads.pub fn written_international(raw: &str) -> Option<String> {    let stripped = strip_presentation(raw);    stripped.strip_prefix('+').or_else(|| stripped.strip_prefix("00")).and_then(e164_digits)}/// The E.164 digits of a number whose country code leads `international`, or/// `None` when no country has that code or the result is not 8–15 digits.fn e164_digits(international: &str) -> Option<String> {    if international.is_empty() || !international.bytes().all(|b| b.is_ascii_digit()) {        return None;    }    let number = phonenumber::parse(None, format!("+{international}")).ok()?;    let e164 = number.format().mode(phonenumber::Mode::E164).to_string();    let e164 = e164.strip_prefix('+')?;    is_canonical(e164).then(|| e164.to_string())}/// A country to read a number without a code in: the owner's own number's/// (architect, 22 Oct 2026 — "no default country" forbids a compiled one,/// not one the owner's data states). See `phone_fold::region_hint`.pub use phonenumber::country::Id as Region;/// The country of a canonical number, when libphonenumber holds it valid.pub fn region_of(canonical: &str) -> Option<Region> {    if !is_canonical(canonical) {        return None;    }    let number = phonenumber::parse(None, format!("+{canonical}")).ok()?;    phonenumber::is_valid(&number).then(|| number.country().id()).flatten()}/// [`normalize_phone`], with a number written WITHOUT a code read in/// `region` — "098765 43210" and "98765 43210" in India are 919876543210 —/// where the result is a valid number of that country. Anything else is/// [`normalize_phone`]'s, so a number with a code, one the region does not/// hold, and every number when there is no region are as before.pub fn normalize_phone_in(raw: &str, region: Option<Region>) -> Option<String> {    let base = normalize_phone(raw)?;    let stripped = strip_presentation(raw);    let Some(region) = region.filter(|_| !stripped.starts_with('+') && !stripped.starts_with("00")) else {        return Some(base);    };    Some(in_region(&base, region).unwrap_or(base))}/// Digits read as a national number of `region`, as E.164 digits, when valid.fn in_region(digits: &str, region: Region) -> Option<String> {    let number = phonenumber::parse(Some(region), digits).ok()?;    if !phonenumber::is_valid(&number) {        return None;    }    let e164 = number.format().mode(phonenumber::Mode::E164).to_string();    let e164 = e164.strip_prefix('+')?;    is_canonical(e164).then(|| e164.to_string())}/// The form a STORED number takes in `region` (see [`normalize_phone_in`]),/// or `None` when it is already that form or the region does not hold it.pub fn refold_stored_phone_in(stored: &str, region: Region) -> Option<String> {    in_region(stored, region).filter(|e164| e164 != stored)}/// The new canonical form of a number STORED by the earlier normaliser/// (digits, no `+`, a trunk 0 kept after the code), or `None` when it is/// already canonical. What was stored lost its `+`, so the digits are read as/// carrying their country code only where the folded number is one/// libphonenumber holds valid — "9109876543210" becomes 919876543210, while a/// national number that merely starts like a code ("3105550143") is left./// A leading `00` is the international prefix, as [`normalize_phone`] reads it.pub fn refold_stored_phone(stored: &str) -> Option<String> {    if let Some(normal) = normalize_phone(stored).filter(|normal| normal != stored) {        return Some(normal);    }    if !is_canonical(stored) {        return None;    }    let number = phonenumber::parse(None, format!("+{stored}")).ok()?;    if !phonenumber::is_valid(&number) {        return None;    }    let e164 = number.format().mode(phonenumber::Mode::E164).to_string();    let e164 = e164.strip_prefix('+')?;    (e164 != stored && is_canonical(e164)).then(|| e164.to_string())}/// A canonical number (what [`normalize_phone`] returns) as a person reads/// it — its `+`, the country code, and the national number grouped the way/// that country writes it ("+44 20 7946 0958", "+91 98765 43210") — or `None`/// when its leading digits are no country's code (a number stored without/// one), which is then said as written.pub fn international_words(canonical: &str) -> Option<String> {    if canonical.is_empty() || !canonical.bytes().all(|b| b.is_ascii_digit()) {        return None;    }    let number = phonenumber::parse(None, format!("+{canonical}")).ok()?;    Some(number.format().mode(phonenumber::Mode::International).to_string())}#[cfg(test)]#[path = "phone_tests.rs"]mod tests;