Cotton code
884 lines · 35.2 KB · RustRaw
//! Contacts in and out of files (CONTACTS, 28 Nov 2026): vCard (2.1, 3.0 and 4.0) and a Google Contacts CSV read//! into cards, and contacts written back out as vCard 3.0 or 4.0.//!//! Pure: text in, cards out, and cards in, text out. Nothing here touches a database, fetches a URL or decides who is//! who. A card read here goes through the same door as a card from the phone's address book (the phone's//! `contacts.import`, `crates/cotton-ffi/src/phone/contacts_io.rs`), so the same handle rules match it to a person, and//! an import never merges two people by itself.//!//! What is read: the name (`FN`, else `N`, else `ORG`), every number and email with its label, the organisation and//! title, the city of the first address, the birthday, the note, an embedded photo (a `PHOTO` given as a link is never//! fetched), the groups (`CATEGORIES`, an iCloud or 4.0 group card's members, a Google CSV's labels), and the card's//! `UID`. The rest of a card stays in the file.//!//! The things that bite, all handled: folded lines; quoted-printable (2.1 and Android), with its soft line breaks;//! escaped `\,` `\;` `\n`; the 4.0 `tel:` value; Apple's `item1.` groups and `X-ABLabel`; bare 2.1 types (`TEL;CELL:`);//! a byte order mark; CRLF or LF.use serde::{Deserialize, Serialize};/// A number or an address, with the label the file gave it ("Mobile", "Work"), or none.#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]pub struct Labelled {    pub value: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub label: Option<String>,}/// A birthday: month and day always, the year when the file says it.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub struct Birthday {    pub month: u32,    pub day: u32,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub year: Option<i32>,}/// An embedded picture: its type and its bytes as base64 (decoded by the caller).#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Photo {    pub mime: String,    pub base64: String,}/// One contact read from a file, or to write to one.#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]pub struct Card {    /// The file's own id for the card (`UID`), when it has one.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub uid: Option<String>,    pub full_name: String,    /// `organisation` for a card that is a company (4.0 `KIND:org`, Apple's `X-ABShowAs:COMPANY`, or only an `ORG`).    pub organisation: bool,    pub phones: Vec<Labelled>,    pub emails: Vec<Labelled>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub org: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub role_title: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub city: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub birthday: Option<Birthday>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub note: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub photo: Option<Photo>,    pub groups: Vec<String>,}/// AUDIT D: what one file may hold. A file past any of these is refused whole, in one plain line (`over_limits`).pub const FILE_MAX_BYTES: usize = 64 * 1024 * 1024;pub const CARDS_MAX: usize = 50_000;pub const GROUPS_MAX: usize = 200;/// A note's length, in characters.pub const NOTE_MAX_CHARS: usize = 64 * 1024;/// A name, organisation, title, city, number, address, label or group name, in characters.pub const FIELD_MAX_CHARS: usize = 1024;/// Numbers, addresses or groups on one card.pub const VALUES_MAX: usize = 100;/// The plain line a file past `FILE_MAX_BYTES` is refused with, before it is read.pub fn file_too_large() -> String {    "This file is larger than 64 MB. Split it into smaller files and import each one.".to_string()}/// Why a file read whole is too much to import, in one plain line; None when it is within every limit.pub fn over_limits(read: &Read) -> Option<String> {    if read.cards.len() > CARDS_MAX {        return Some(format!("This file holds {} contacts, more than the 50,000 one import takes. Split it into smaller files and import each one.", read.cards.len()));    }    let groups: std::collections::HashSet<&str> = read.cards.iter().flat_map(|c| c.groups.iter().map(String::as_str)).collect();    if groups.len() > GROUPS_MAX {        return Some(format!("This file would make {} groups, more than the 200 one import makes. Remove some labels from the file and try again.", groups.len()));    }    let long = |s: &str| s.chars().count() > FIELD_MAX_CHARS;    for c in &read.cards {        let name = if c.full_name.trim().is_empty() { "one contact".to_string() } else { format!("\u{201c}{}\u{201d}", c.full_name.chars().take(60).collect::<String>()) };        if c.note.as_deref().is_some_and(|n| n.chars().count() > NOTE_MAX_CHARS) {            return Some(format!("In this file, {name} has a note longer than 64 KB. Shorten it and try again."));        }        if c.phones.len() > VALUES_MAX || c.emails.len() > VALUES_MAX || c.groups.len() > VALUES_MAX {            return Some(format!("In this file, {name} has more than 100 numbers, addresses or groups. Fix that contact and try again."));        }        let fields = [Some(c.full_name.as_str()), c.org.as_deref(), c.role_title.as_deref(), c.city.as_deref()].into_iter().flatten();        let values = c.phones.iter().chain(&c.emails).flat_map(|l| [Some(l.value.as_str()), l.label.as_deref()]).flatten();        if fields.chain(values).chain(c.groups.iter().map(String::as_str)).any(long) {            return Some(format!("In this file, {name} has a name, number or label longer than 1,024 characters. Fix that contact and try again."));        }    }    None}/// What a file held: the cards, and how many blocks were passed over (empty, or a group card itself).#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct Read {    pub cards: Vec<Card>,    pub skipped: usize,}// ── vCard in ──────────────────────────────────────────────────────────────/// One property line, unfolded: `group.NAME;params:value`.#[derive(Debug, Clone)]struct Prop {    group: Option<String>,    name: String,    params: Vec<(String, String)>,    value: String,}impl Prop {    /// Every TYPE, lower case: `TYPE=cell,voice`, `TYPE="cell,voice"`, repeated `TYPE=`, and 2.1's bare `CELL`.    fn types(&self) -> Vec<String> {        let mut out = Vec::new();        for (k, v) in &self.params {            if k == "type" || (v.is_empty() && !k.is_empty()) {                let raw = if v.is_empty() { k.as_str() } else { v.as_str() };                for t in raw.trim_matches('"').split(',') {                    let t = t.trim().to_ascii_lowercase();                    if !t.is_empty() {                        out.push(t);                    }                }            }        }        out    }    fn param(&self, name: &str) -> Option<&str> {        self.params.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())    }    fn quoted_printable(&self) -> bool {        self.param("encoding").is_some_and(|e| e.eq_ignore_ascii_case("quoted-printable")) || self.params.iter().any(|(k, v)| v.is_empty() && k == "quoted-printable")    }    fn base64(&self) -> bool {        self.param("encoding").is_some_and(|e| e.eq_ignore_ascii_case("b") || e.eq_ignore_ascii_case("base64")) || self.params.iter().any(|(k, v)| v.is_empty() && k == "base64")    }    /// The value as text: quoted-printable decoded, then vCard escapes undone.    fn text(&self) -> String {        unescape(&self.raw_text())    }    /// The value decoded but not unescaped (for structured values split on `;` first).    fn raw_text(&self) -> String {        if self.quoted_printable() {            decode_qp(&self.value)        } else {            self.value.clone()        }    }}/// Lines unfolded: a line that starts with a space or tab continues the one before; a quoted-printable line ending/// in `=` continues on the next (its soft break).fn unfold(text: &str) -> Vec<String> {    let text = text.strip_prefix('\u{feff}').unwrap_or(text);    let mut lines: Vec<String> = Vec::new();    let mut soft = false;    // AUDIT D: whether the line being built is quoted-printable, decided once its head (up to the first colon) is    // whole. Uppercasing the head on every input line made a long line with no colon (8 million ` a` continuations)    // take time in the square of its length: the import hung.    let mut qp: Option<bool> = None;    for raw in text.split('\n') {        let line = raw.strip_suffix('\r').unwrap_or(raw);        let added = match lines.last_mut() {            Some(last) if soft => {                last.pop(); // the soft break's `=`                last.push_str(line);                line            }            Some(last) if line.starts_with(' ') || line.starts_with('\t') => {                last.push_str(&line[1..]);                &line[1..]            }            _ => {                lines.push(line.to_string());                qp = None;                line            }        };        let last = lines.last().expect("a line");        if qp.is_none() && added.contains(':') {            qp = Some(last.split(':').next().is_some_and(|head| head.to_ascii_uppercase().contains("QUOTED-PRINTABLE")));        }        soft = last.ends_with('=') && qp == Some(true);    }    lines}/// `group.NAME;a=b;c:value`, the colon inside a quoted parameter value not counted.fn parse_line(line: &str) -> Option<Prop> {    let mut in_quote = false;    let mut colon = None;    for (i, ch) in line.char_indices() {        match ch {            '"' => in_quote = !in_quote,            ':' if !in_quote => {                colon = Some(i);                break;            }            _ => {}        }    }    let colon = colon?;    let (head, value) = (&line[..colon], &line[colon + 1..]);    let mut parts = split_unquoted(head, ';').into_iter();    let full = parts.next()?;    let (group, name) = match full.rsplit_once('.') {        Some((g, n)) => (Some(g.to_ascii_lowercase()), n.to_ascii_lowercase()),        None => (None, full.to_ascii_lowercase()),    };    let params = parts        .map(|p| match p.split_once('=') {            Some((k, v)) => (k.trim().to_ascii_lowercase(), v.trim().to_string()),            None => (p.trim().to_ascii_lowercase(), String::new()),        })        .collect();    Some(Prop { group, name, params, value: value.to_string() })}fn split_unquoted(s: &str, sep: char) -> Vec<String> {    let mut out = Vec::new();    let mut cur = String::new();    let mut in_quote = false;    for ch in s.chars() {        if ch == '"' {            in_quote = !in_quote;            cur.push(ch);        } else if ch == sep && !in_quote {            out.push(std::mem::take(&mut cur));        } else {            cur.push(ch);        }    }    out.push(cur);    out}/// A structured value split on unescaped `sep`, each part unescaped.fn split_escaped(s: &str, sep: char) -> Vec<String> {    let mut out = Vec::new();    let mut cur = String::new();    let mut chars = s.chars();    while let Some(ch) = chars.next() {        if ch == '\\' {            cur.push(ch);            if let Some(next) = chars.next() {                cur.push(next);            }        } else if ch == sep {            out.push(unescape(&std::mem::take(&mut cur)));        } else {            cur.push(ch);        }    }    out.push(unescape(&cur));    out}fn unescape(s: &str) -> String {    let mut out = String::with_capacity(s.len());    let mut chars = s.chars();    while let Some(ch) = chars.next() {        if ch == '\\' {            match chars.next() {                Some('n' | 'N') => out.push('\n'),                Some(other) => out.push(other),                None => {}            }        } else {            out.push(ch);        }    }    out}/// `=XX` bytes decoded and read as UTF-8 (Latin-1 when they are not UTF-8).fn decode_qp(s: &str) -> String {    let bytes = s.as_bytes();    let mut out = Vec::with_capacity(bytes.len());    let mut i = 0;    while i < bytes.len() {        if bytes[i] == b'=' && i + 2 < bytes.len() {            if let Some(b) = std::str::from_utf8(&bytes[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok()) {                out.push(b);                i += 3;                continue;            }        }        out.push(bytes[i]);        i += 1;    }    match String::from_utf8(out) {        Ok(text) => text,        Err(e) => e.into_bytes().iter().map(|&b| b as char).collect(),    }}/// Apple's custom label `_$!<Mobile>!$_` read as `Mobile`.fn clean_label(raw: &str) -> String {    raw.trim().trim_start_matches("_$!<").trim_end_matches(">!$_").trim().to_string()}fn label_of(types: &[String], kind: &str) -> Option<String> {    let has = |t: &str| types.iter().any(|x| x == t);    let words = if kind == "tel" {        if has("cell") || has("mobile") {            "Mobile"        } else if has("iphone") {            "iPhone"        } else if has("fax") {            "Fax"        } else if has("pager") {            "Pager"        } else if has("main") {            "Main"        } else if has("work") {            "Work"        } else if has("home") {            "Home"        } else if has("other") {            "Other"        } else {            return None;        }    } else if has("work") {        "Work"    } else if has("home") {        "Home"    } else if has("other") {        "Other"    } else {        return None;    };    Some(words.to_string())}/// A `BDAY`: `1990-05-17`, `19900517`, `--05-17`, `--0517`, with or without a time after `T`.pub fn parse_birthday(raw: &str) -> Option<Birthday> {    let date = raw.trim().split('T').next()?.trim();    let (year, rest) = if let Some(rest) = date.strip_prefix("--") {        (None, rest.replace('-', ""))    } else {        let digits = date.replace('-', "");        // AUDIT D: eight ASCII digits before any cut (`123é456` is eight bytes, and `[..4]` split the é: a panic).        if digits.len() != 8 || !digits.bytes().all(|b| b.is_ascii_digit()) {            return None;        }        (digits[..4].parse::<i32>().ok().filter(|y| *y > 1604), digits[4..].to_string())    };    if rest.len() != 4 || !rest.chars().all(|c| c.is_ascii_digit()) {        return None;    }    let month: u32 = rest[..2].parse().ok()?;    let day: u32 = rest[2..].parse().ok()?;    let days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];    if !(1..=12).contains(&month) || day == 0 || day > days[(month - 1) as usize] {        return None;    }    Some(Birthday { month, day, year })}fn non_empty(s: String) -> Option<String> {    let t = s.trim();    (!t.is_empty()).then(|| t.to_string())}fn push_unique(list: &mut Vec<Labelled>, value: String, label: Option<String>) {    // AUDIT D: a list stops one past VALUES_MAX (the file is then refused, `over_limits`), so this scan stays short: a    // card of a million numbers took a million scans of a growing list.    if list.len() > VALUES_MAX {        return;    }    let value = value.trim().to_string();    if value.is_empty() || list.iter().any(|l| l.value == value) {        return;    }    list.push(Labelled { value, label });}/// A group added to a card once, stopping one past VALUES_MAX as `push_unique` does.fn push_group(groups: &mut Vec<String>, name: &str) {    if groups.len() <= VALUES_MAX && !name.is_empty() && !groups.iter().any(|g| g == name) {        groups.push(name.to_string());    }}/// Every card in a `.vcf` file. Group cards (4.0 `KIND:group`, iCloud's `X-ADDRESSBOOKSERVER-KIND:group`) are not/// contacts: their name becomes a group on each member card named by `UID`.pub fn read_vcf(text: &str) -> Read {    let mut cards: Vec<Card> = Vec::new();    let mut group_cards: Vec<(String, Vec<String>)> = Vec::new();    let mut skipped = 0;    let mut current: Option<Vec<Prop>> = None;    for line in unfold(text) {        if line.trim().is_empty() {            continue;        }        let upper = line.trim().to_ascii_uppercase();        if upper == "BEGIN:VCARD" {            current = Some(Vec::new());            continue;        }        if upper == "END:VCARD" {            if let Some(props) = current.take() {                match card_of(&props) {                    Block::Card(card) => cards.push(card),                    Block::Group(name, members) => {                        group_cards.push((name, members));                        skipped += 1;                    }                    Block::Empty => skipped += 1,                }            }            continue;        }        if let (Some(props), Some(prop)) = (current.as_mut(), parse_line(&line)) {            props.push(prop);        }    }    // AUDIT D: each member found by its uid in one map, not every card against every member.    let mut by_uid: std::collections::HashMap<String, Vec<usize>> = std::collections::HashMap::new();    for (i, card) in cards.iter().enumerate() {        if let Some(uid) = &card.uid {            by_uid.entry(uid.clone()).or_default().push(i);        }    }    for (name, members) in group_cards {        let mut seen = std::collections::HashSet::new();        for m in members {            if !seen.insert(m.clone()) {                continue;            }            for &i in by_uid.get(&m).into_iter().flatten() {                push_group(&mut cards[i].groups, &name);            }        }    }    Read { cards, skipped }}enum Block {    Card(Card),    Group(String, Vec<String>),    Empty,}fn member_uid(raw: &str) -> String {    let raw = raw.trim();    raw.strip_prefix("urn:uuid:").unwrap_or(raw).to_string()}fn card_of(props: &[Prop]) -> Block {    let mut card = Card::default();    let mut fn_name = None;    let mut n_name = None;    let mut kind = None;    let mut members = Vec::new();    let mut org_only_show = false;    // Apple's labels: `item1.X-ABLabel:Office` names `item1.TEL`.    let labels: Vec<(String, String)> = props.iter().filter(|p| p.name == "x-ablabel").filter_map(|p| Some((p.group.clone()?, clean_label(&p.text())))).collect();    let label_for = |p: &Prop, kind: &str| -> Option<String> {        p.group.as_ref().and_then(|g| labels.iter().find(|(lg, _)| lg == g).map(|(_, l)| l.clone())).filter(|l| !l.is_empty()).or_else(|| label_of(&p.types(), kind))    };    for p in props {        match p.name.as_str() {            "fn" => fn_name = non_empty(p.text()),            "n" => {                let parts = split_escaped(&p.raw_text(), ';');                let get = |i: usize| parts.get(i).map(|s| s.trim().to_string()).unwrap_or_default();                let joined = [get(3), get(1), get(2), get(0), get(4)].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" ");                n_name = non_empty(joined);            }            "tel" => {                let value = p.text();                let value = value.strip_prefix("tel:").unwrap_or(&value).to_string();                push_unique(&mut card.phones, value, label_for(p, "tel"));            }            "email" => {                let value = p.text();                let value = value.strip_prefix("mailto:").unwrap_or(&value).to_string();                push_unique(&mut card.emails, value, label_for(p, "email"));            }            "org" => {                if card.org.is_none() {                    card.org = split_escaped(&p.raw_text(), ';').into_iter().next().and_then(non_empty);                }            }            "title" => {                if card.role_title.is_none() {                    card.role_title = non_empty(p.text());                }            }            "role" => {                if card.role_title.is_none() {                    card.role_title = non_empty(p.text());                }            }            "adr" => {                if card.city.is_none() {                    card.city = split_escaped(&p.raw_text(), ';').get(3).cloned().and_then(non_empty);                }            }            "bday" => card.birthday = card.birthday.or_else(|| parse_birthday(&p.text())),            "note" => {                if let Some(note) = non_empty(p.text()) {                    // AUDIT D: appended in place, and no further once past the limit (the file is refused then): a                    // copy of the whole note per NOTE line was quadratic.                    match card.note.as_mut() {                        Some(before) if before.len() > NOTE_MAX_CHARS * 4 => {}                        Some(before) => {                            before.push('\n');                            before.push_str(&note);                        }                        None => card.note = Some(note),                    }                }            }            "photo" if card.photo.is_none() => card.photo = photo_of(p),            "categories" => {                for g in split_escaped(&p.raw_text(), ',') {                    push_group(&mut card.groups, g.trim());                }            }            "uid" => card.uid = non_empty(p.text()),            "kind" | "x-addressbookserver-kind" => kind = Some(p.text().trim().to_ascii_lowercase()),            "member" | "x-addressbookserver-member" => members.push(member_uid(&p.text())),            "x-abshowas" => org_only_show = p.text().trim().eq_ignore_ascii_case("company"),            _ => {}        }    }    if kind.as_deref() == Some("group") {        return match fn_name.or(n_name) {            Some(name) => Block::Group(name, members),            None => Block::Empty,        };    }    card.organisation = matches!(kind.as_deref(), Some("org" | "organization")) || org_only_show || (fn_name.is_none() && n_name.is_none() && card.org.is_some());    let name = if card.organisation { card.org.clone().or(fn_name.clone()).or(n_name.clone()) } else { fn_name.or(n_name).or_else(|| card.org.clone()) };    let name = name.or_else(|| card.emails.first().map(|e| e.value.clone())).or_else(|| card.phones.first().map(|p| p.value.clone()));    match name {        Some(name) => {            card.full_name = name;            Block::Card(card)        }        None => Block::Empty,    }}/// An embedded photo: 3.0 `PHOTO;ENCODING=b;TYPE=JPEG:<base64>`, 4.0 `PHOTO:data:image/jpeg;base64,<base64>`. A link/// (`http…`) is never fetched: no photo.fn photo_of(p: &Prop) -> Option<Photo> {    let value = p.value.trim();    if let Some(data) = value.strip_prefix("data:") {        let (head, body) = data.split_once(',')?;        if !head.to_ascii_lowercase().ends_with(";base64") {            return None;        }        let mime = head[..head.len() - ";base64".len()].trim().to_ascii_lowercase();        let mime = if mime.is_empty() { "image/jpeg".to_string() } else { mime };        return clean_base64(body).map(|base64| Photo { mime, base64 });    }    if !p.base64() {        return None;    }    let ty = p.param("type").or_else(|| p.param("mediatype")).map(|t| t.trim_matches('"').to_ascii_lowercase()).or_else(|| p.params.iter().find(|(k, v)| v.is_empty() && ["jpeg", "jpg", "png", "gif"].contains(&k.as_str())).map(|(k, _)| k.clone()));    let mime = match ty.as_deref() {        Some(t) if t.contains('/') => t.to_string(),        Some("png") => "image/png".to_string(),        Some("gif") => "image/gif".to_string(),        _ => "image/jpeg".to_string(),    };    clean_base64(value).map(|base64| Photo { mime, base64 })}fn clean_base64(s: &str) -> Option<String> {    let cleaned: String = s.chars().filter(|c| !c.is_whitespace()).collect();    (!cleaned.is_empty() && cleaned.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '=' | '-' | '_'))).then_some(cleaned)}// ── Google Contacts CSV in ────────────────────────────────────────────────/// RFC 4180 rows: quoted fields with `""`, commas and newlines inside quotes, CRLF or LF, a byte order mark.pub fn csv_rows(text: &str) -> Vec<Vec<String>> {    let text = text.strip_prefix('\u{feff}').unwrap_or(text);    let mut rows = Vec::new();    let mut row = Vec::new();    let mut field = String::new();    let mut in_quote = false;    let mut chars = text.chars().peekable();    while let Some(ch) = chars.next() {        if in_quote {            if ch == '"' {                if chars.peek() == Some(&'"') {                    field.push('"');                    chars.next();                } else {                    in_quote = false;                }            } else {                field.push(ch);            }            continue;        }        match ch {            '"' => in_quote = true,            ',' => row.push(std::mem::take(&mut field)),            '\r' => {}            '\n' => {                row.push(std::mem::take(&mut field));                if !(row.len() == 1 && row[0].is_empty()) {                    rows.push(std::mem::take(&mut row));                } else {                    row.clear();                }            }            _ => field.push(ch),        }    }    if !field.is_empty() || !row.is_empty() {        row.push(field);        rows.push(row);    }    rows}/// A Google Contacts export (Google CSV, the current and the older column names). Several values in one cell are/// joined by ` ::: `. System labels (`* myContacts`, `* starred`) are not groups. The `Photo` column is a link: never/// fetched.pub fn read_google_csv(text: &str) -> Read {    let rows = csv_rows(text);    let Some((head, body)) = rows.split_first() else { return Read::default() };    let col: Vec<String> = head.iter().map(|h| h.trim().to_ascii_lowercase()).collect();    // AUDIT D: each header found in one map (the first column of a name wins), not by a scan of every column per    // column: a 100,000-column header hung.    let mut at: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();    for (i, c) in col.iter().enumerate() {        at.entry(c.as_str()).or_insert(i);    }    let find = |names: &[&str]| names.iter().find_map(|n| at.get(n).copied());    let first = find(&["first name", "given name"]);    let middle = find(&["middle name", "additional name"]);    let last = find(&["last name", "family name"]);    let prefix = find(&["name prefix"]);    let suffix = find(&["name suffix"]);    let whole = find(&["name"]);    let file_as = find(&["file as"]);    let nickname = find(&["nickname"]);    let org = find(&["organization name", "organization 1 - name"]);    let title = find(&["organization title", "organization 1 - title"]);    let birthday = find(&["birthday"]);    let notes = find(&["notes"]);    let labels = find(&["labels", "group membership"]);    // Numbered columns: `Phone 1 - Value` with `Phone 1 - Label` (or `- Type`), the same for e-mail and address.    let numbered = |kind: &str, part: &str| -> Vec<(usize, usize, Option<usize>)> {        let mut out = Vec::new();        for (i, c) in col.iter().enumerate() {            let Some(rest) = c.strip_prefix(&format!("{kind} ")) else { continue };            let Some((n, tail)) = rest.split_once(" - ") else { continue };            if tail != part {                continue;            }            let label = at.get(format!("{kind} {n} - label").as_str()).or_else(|| at.get(format!("{kind} {n} - type").as_str())).copied();            out.push((n.parse().unwrap_or(0), i, label));        }        out.sort();        out    };    let phones = numbered("phone", "value");    let emails = numbered("e-mail", "value");    let cities = numbered("address", "city");    let mut read = Read::default();    for row in body {        let cell = |i: Option<usize>| i.and_then(|i| row.get(i)).map(|s| s.trim().to_string()).filter(|s| !s.is_empty());        let mut card = Card::default();        let parts = [cell(prefix), cell(first), cell(middle), cell(last), cell(suffix)].into_iter().flatten().collect::<Vec<_>>().join(" ");        card.org = cell(org);        card.role_title = cell(title);        card.birthday = cell(birthday).and_then(|b| parse_birthday(&b));        card.note = cell(notes);        for (_, value, label) in &phones {            let label = cell(*label).map(|l| google_label(&l));            for v in cell(Some(*value)).unwrap_or_default().split(":::") {                push_unique(&mut card.phones, v.to_string(), label.clone());            }        }        for (_, value, label) in &emails {            let label = cell(*label).map(|l| google_label(&l));            for v in cell(Some(*value)).unwrap_or_default().split(":::") {                push_unique(&mut card.emails, v.to_string(), label.clone());            }        }        card.city = cities.iter().find_map(|(_, i, _)| cell(Some(*i)));        for g in cell(labels).unwrap_or_default().split(":::") {            let g = g.trim();            if !g.starts_with('*') {                push_group(&mut card.groups, g);            }        }        let name = non_empty(parts).or_else(|| cell(whole)).or_else(|| cell(file_as)).or_else(|| cell(nickname));        card.organisation = name.is_none() && card.org.is_some();        let name = name.or_else(|| card.org.clone()).or_else(|| card.emails.first().map(|e| e.value.clone())).or_else(|| card.phones.first().map(|p| p.value.clone()));        match name {            Some(name) => {                card.full_name = name;                read.cards.push(card);            }            None => read.skipped += 1,        }    }    read}/// Google's labels (`Mobile`, `* Work`, `Home`) without the star it puts before a primary one.fn google_label(raw: &str) -> String {    raw.trim().trim_start_matches('*').trim().to_string()}// ── vCard out ─────────────────────────────────────────────────────────────/// The vCard versions written.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Version {    V3,    V4,}fn escape(s: &str) -> String {    let mut out = String::with_capacity(s.len());    for ch in s.chars() {        match ch {            '\\' => out.push_str("\\\\"),            ',' => out.push_str("\\,"),            ';' => out.push_str("\\;"),            '\n' => out.push_str("\\n"),            '\r' => {}            other => out.push(other),        }    }    out}/// A line folded at 75 octets, never inside a UTF-8 character; continuation lines start with one space.fn fold(line: &str, out: &mut String) {    let mut width = 0;    for ch in line.chars() {        let len = ch.len_utf8();        if width + len > 75 {            out.push_str("\r\n ");            width = 1;        }        out.push(ch);        width += len;    }    out.push_str("\r\n");}fn type_of(label: Option<&str>, kind: &str) -> Option<&'static str> {    let l = label?.to_ascii_lowercase();    Some(match (kind, l.as_str()) {        ("tel", "mobile" | "cell" | "iphone") => "cell",        ("tel", "fax") => "fax",        ("tel", "pager") => "pager",        ("tel", "main") => "main",        (_, "work") => "work",        (_, "home") => "home",        (_, "other") => "other",        _ => return None,    })}/// Every card as one `.vcf` text, CRLF, folded, in the version asked.pub fn write_vcf(cards: &[Card], version: Version) -> String {    let mut out = String::new();    for card in cards {        let mut lines: Vec<String> = Vec::new();        lines.push("BEGIN:VCARD".into());        lines.push(match version {            Version::V3 => "VERSION:3.0".into(),            Version::V4 => "VERSION:4.0".into(),        });        if version == Version::V4 && card.organisation {            lines.push("KIND:org".into());        }        lines.push(format!("FN:{}", escape(&card.full_name)));        // N: the last word as the family name; an organisation has none.        let n = if card.organisation {            String::from(";;;;")        } else {            match card.full_name.trim().rsplit_once(' ') {                Some((given, family)) => format!("{};{};;;", escape(family), escape(given)),                None => format!("{};;;;", escape(card.full_name.trim())),            }        };        lines.push(format!("N:{n}"));        if version == Version::V3 && card.organisation {            lines.push("X-ABShowAs:COMPANY".into());        }        if let Some(org) = &card.org {            lines.push(format!("ORG:{}", escape(org)));        }        if let Some(title) = &card.role_title {            lines.push(format!("TITLE:{}", escape(title)));        }        for phone in &card.phones {            let ty = type_of(phone.label.as_deref(), "tel");            lines.push(match (version, ty) {                (Version::V4, Some(t)) => format!("TEL;VALUE=uri;TYPE={t}:tel:{}", phone.value.replace(' ', "")),                (Version::V4, None) => format!("TEL;VALUE=uri:tel:{}", phone.value.replace(' ', "")),                (Version::V3, Some(t)) => format!("TEL;TYPE={}:{}", t.to_ascii_uppercase(), escape(&phone.value)),                (Version::V3, None) => format!("TEL:{}", escape(&phone.value)),            });        }        for email in &card.emails {            let ty = type_of(email.label.as_deref(), "email");            lines.push(match (version, ty) {                (Version::V4, Some(t)) => format!("EMAIL;TYPE={t}:{}", escape(&email.value)),                (Version::V3, Some(t)) => format!("EMAIL;TYPE=INTERNET,{}:{}", t.to_ascii_uppercase(), escape(&email.value)),                (Version::V4, None) => format!("EMAIL:{}", escape(&email.value)),                (Version::V3, None) => format!("EMAIL;TYPE=INTERNET:{}", escape(&email.value)),            });        }        if let Some(city) = &card.city {            lines.push(format!("ADR:;;;{};;;", escape(city)));        }        if let Some(b) = card.birthday {            lines.push(match (b.year, version) {                (Some(y), _) => format!("BDAY:{y:04}-{:02}-{:02}", b.month, b.day),                (None, Version::V4) => format!("BDAY:--{:02}{:02}", b.month, b.day),                (None, Version::V3) => format!("BDAY:--{:02}-{:02}", b.month, b.day),            });        }        if let Some(note) = &card.note {            lines.push(format!("NOTE:{}", escape(note)));        }        if !card.groups.is_empty() {            lines.push(format!("CATEGORIES:{}", card.groups.iter().map(|g| escape(g)).collect::<Vec<_>>().join(",")));        }        if let Some(photo) = &card.photo {            lines.push(match version {                Version::V4 => format!("PHOTO:data:{};base64,{}", photo.mime, photo.base64),                Version::V3 => {                    let ty = photo.mime.rsplit('/').next().unwrap_or("jpeg").to_ascii_uppercase();                    format!("PHOTO;ENCODING=b;TYPE={ty}:{}", photo.base64)                }            });        }        if let Some(uid) = &card.uid {            lines.push(format!("UID:{}", escape(uid)));        }        lines.push("END:VCARD".into());        for line in lines {            fold(&line, &mut out);        }    }    out}#[cfg(test)]#[path = "contacts_io_tests.rs"]mod tests;