Cotton code
218 lines · 13.7 KB · RustRaw
//! Every card and row invented.use super::*;const V3: &str = "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Apple Inc.//iPhone OS 17.0//EN\r\nN:Menon;Asha;;;\r\nFN:Asha Menon\r\nORG:Invented Labs;Research\r\nTITLE:Engineer\r\nitem1.TEL;type=pref:+91 98765 00001\r\nitem1.X-ABLabel:_$!<Mobile>!$_\r\nTEL;type=WORK;type=VOICE:+91 22 0000 0002\r\nitem2.TEL:+1 555 555 0100\r\nitem2.X-ABLabel:Studio\r\nEMAIL;type=INTERNET;type=HOME;type=pref:asha@example.com\r\nEMAIL;type=INTERNET;type=WORK:asha@work.example\r\nADR;type=HOME:;;12 Invented Road;Pune;MH;411001;India\r\nBDAY:1990-05-17\r\nNOTE:Met at the\\, invented\\nconference\r\nCATEGORIES:Family,Book club\r\nPHOTO;ENCODING=b;TYPE=JPEG:/9j/4AAQSkZJRgABAQ\r\n AAAQABAAD/2wBD\r\nUID:card-1\r\nEND:VCARD\r\n";#[test]fn reads_a_3_0_card_whole() {    let read = read_vcf(V3);    assert_eq!(read.cards.len(), 1);    let c = &read.cards[0];    assert_eq!(c.full_name, "Asha Menon");    assert!(!c.organisation);    assert_eq!(c.phones, vec![        Labelled { value: "+91 98765 00001".into(), label: Some("Mobile".into()) },        Labelled { value: "+91 22 0000 0002".into(), label: Some("Work".into()) },        Labelled { value: "+1 555 555 0100".into(), label: Some("Studio".into()) },    ]);    assert_eq!(c.emails.iter().map(|e| (e.value.as_str(), e.label.as_deref())).collect::<Vec<_>>(), vec![("asha@example.com", Some("Home")), ("asha@work.example", Some("Work"))]);    assert_eq!(c.org.as_deref(), Some("Invented Labs"));    assert_eq!(c.role_title.as_deref(), Some("Engineer"));    assert_eq!(c.city.as_deref(), Some("Pune"));    assert_eq!(c.birthday, Some(Birthday { month: 5, day: 17, year: Some(1990) }));    assert_eq!(c.note.as_deref(), Some("Met at the, invented\nconference"));    assert_eq!(c.groups, vec!["Family".to_string(), "Book club".to_string()]);    assert_eq!(c.photo, Some(Photo { mime: "image/jpeg".into(), base64: "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD".into() }));    assert_eq!(c.uid.as_deref(), Some("card-1"));}#[test]fn reads_4_0_tel_uris_data_photos_kinds_and_dates_without_a_year() {    let text = "BEGIN:VCARD\nVERSION:4.0\nFN:Ravi Shah\nTEL;VALUE=uri;TYPE=\"cell,voice\":tel:+91-98765-00003\nEMAIL;TYPE=work:ravi@example.org\nBDAY:--0229\nPHOTO:data:image/png;base64,iVBORw0KGgo=\nEND:VCARD\nBEGIN:VCARD\nVERSION:4.0\nKIND:org\nFN:Invented Bakery\nORG:Invented Bakery\nTEL:tel:+91 20 0000 0004\nEND:VCARD\n";    let read = read_vcf(text);    assert_eq!(read.cards.len(), 2);    assert_eq!(read.cards[0].phones, vec![Labelled { value: "+91-98765-00003".into(), label: Some("Mobile".into()) }]);    assert_eq!(read.cards[0].birthday, Some(Birthday { month: 2, day: 29, year: None }));    assert_eq!(read.cards[0].photo.as_ref().map(|p| p.mime.as_str()), Some("image/png"));    assert!(read.cards[1].organisation);    assert_eq!(read.cards[1].full_name, "Invented Bakery");}#[test]fn reads_android_2_1_quoted_printable_with_soft_breaks_and_bare_types() {    // "राम" in UTF-8, split by a soft break.    let text = "BEGIN:VCARD\r\nVERSION:2.1\r\nN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:;=E0=A4=B0=E0=A4=BE=\r\n=E0=A4=AE;;;\r\nFN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:=E0=A4=B0=E0=A4=BE=E0=A4=AE\r\nTEL;CELL:+919876500005\r\nTEL;HOME;VOICE:020 0000 0006\r\nEND:VCARD\r\n";    let read = read_vcf(text);    let c = &read.cards[0];    assert_eq!(c.full_name, "राम");    assert_eq!(c.phones[0], Labelled { value: "+919876500005".into(), label: Some("Mobile".into()) });    assert_eq!(c.phones[1].label.as_deref(), Some("Home"));}#[test]fn turns_a_group_card_into_a_group_on_its_members_and_never_a_contact() {    let text = "BEGIN:VCARD\nVERSION:3.0\nFN:Dev Nair\nUID:dev\nEND:VCARD\nBEGIN:VCARD\nVERSION:3.0\nFN:Meera Iyer\nUID:meera\nEND:VCARD\nBEGIN:VCARD\nVERSION:3.0\nX-ADDRESSBOOKSERVER-KIND:group\nFN:Badminton\nX-ADDRESSBOOKSERVER-MEMBER:urn:uuid:dev\nEND:VCARD\n";    let read = read_vcf(text);    assert_eq!(read.cards.len(), 2);    assert_eq!(read.skipped, 1);    assert_eq!(read.cards[0].groups, vec!["Badminton".to_string()]);    assert!(read.cards[1].groups.is_empty());}#[test]fn names_a_card_from_n_then_org_then_a_handle_and_passes_over_an_empty_one() {    let text = "BEGIN:VCARD\nVERSION:3.0\nN:Iyer;Meera;;Dr.;\nEND:VCARD\nBEGIN:VCARD\nVERSION:3.0\nORG:Invented Clinic\nEND:VCARD\nBEGIN:VCARD\nVERSION:3.0\nEMAIL:only@example.net\nEND:VCARD\nBEGIN:VCARD\nVERSION:3.0\nEND:VCARD\n";    let read = read_vcf(text);    assert_eq!(read.cards.iter().map(|c| c.full_name.as_str()).collect::<Vec<_>>(), vec!["Dr. Meera Iyer", "Invented Clinic", "only@example.net"]);    assert!(read.cards[1].organisation);    assert_eq!(read.skipped, 1);}#[test]fn never_takes_a_photo_given_as_a_link() {    let text = "BEGIN:VCARD\nVERSION:3.0\nFN:Link Photo\nPHOTO;VALUE=uri:https://example.com/face.jpg\nEND:VCARD\n";    assert_eq!(read_vcf(text).cards[0].photo, None);}#[test]fn birthdays_in_every_shape_and_impossible_dates_refused() {    assert_eq!(parse_birthday("19900517"), Some(Birthday { month: 5, day: 17, year: Some(1990) }));    assert_eq!(parse_birthday("1990-05-17T00:00:00Z"), Some(Birthday { month: 5, day: 17, year: Some(1990) }));    assert_eq!(parse_birthday("--05-17"), Some(Birthday { month: 5, day: 17, year: None }));    assert_eq!(parse_birthday("1604-05-17"), Some(Birthday { month: 5, day: 17, year: None }), "Apple's no-year year");    assert_eq!(parse_birthday("2001-02-30"), None);    assert_eq!(parse_birthday("someday"), None);}const GOOGLE: &str = "\u{feff}First Name,Middle Name,Last Name,Name Prefix,Name Suffix,Nickname,File As,Organization Name,Organization Title,Birthday,Notes,Photo,Labels,E-mail 1 - Label,E-mail 1 - Value,E-mail 2 - Label,E-mail 2 - Value,Phone 1 - Label,Phone 1 - Value,Phone 2 - Label,Phone 2 - Value,Address 1 - Label,Address 1 - City\r\nAsha,,Menon,,,,,Invented Labs,Engineer,1990-05-17,\"Line one\nline \"\"two\"\"\",https://example.com/p.jpg,* myContacts ::: Family ::: Book club,* Home,asha@example.com,Work,asha@work.example,Mobile,+91 98765 00001 ::: +91 98765 00007,Work,+91 22 0000 0002,Home,Pune\r\n,,,,,,,Invented Bakery,,,,,* myContacts,,,,,Work,+91 20 0000 0004,,,,\r\n,,,,,,,,,,,,* myContacts,,,,,,,,,,\r\n";#[test]fn reads_a_google_csv() {    let read = read_google_csv(GOOGLE);    assert_eq!(read.cards.len(), 2);    assert_eq!(read.skipped, 1);    let a = &read.cards[0];    assert_eq!(a.full_name, "Asha Menon");    assert_eq!(a.phones.iter().map(|p| (p.value.as_str(), p.label.as_deref())).collect::<Vec<_>>(), vec![("+91 98765 00001", Some("Mobile")), ("+91 98765 00007", Some("Mobile")), ("+91 22 0000 0002", Some("Work"))]);    assert_eq!(a.emails[0], Labelled { value: "asha@example.com".into(), label: Some("Home".into()) });    assert_eq!(a.groups, vec!["Family".to_string(), "Book club".to_string()]);    assert_eq!(a.note.as_deref(), Some("Line one\nline \"two\""));    assert_eq!(a.city.as_deref(), Some("Pune"));    assert_eq!(a.photo, None, "a link is never fetched");    assert!(read.cards[1].organisation);    assert_eq!(read.cards[1].full_name, "Invented Bakery");}#[test]fn reads_the_older_google_columns() {    let text = "Name,Given Name,Family Name,Group Membership,E-mail 1 - Type,E-mail 1 - Value,Phone 1 - Type,Phone 1 - Value,Organization 1 - Name\nDev Nair,Dev,Nair,* My Contacts ::: Work,* Work,dev@example.org,Mobile,+91 98765 00008,Invented Co\n";    let read = read_google_csv(text);    let c = &read.cards[0];    assert_eq!(c.full_name, "Dev Nair");    assert_eq!(c.groups, vec!["Work".to_string()]);    assert_eq!(c.emails[0].label.as_deref(), Some("Work"));    assert_eq!(c.org.as_deref(), Some("Invented Co"));}#[test]fn writes_4_0_and_3_0_that_read_back_the_same() {    let card = read_vcf(V3).cards.remove(0);    for version in [Version::V4, Version::V3] {        let text = write_vcf(std::slice::from_ref(&card), version);        assert!(text.lines().all(|l| l.len() <= 76), "folded at 75 octets");        assert!(text.ends_with("END:VCARD\r\n"));        let back = read_vcf(&text).cards.remove(0);        assert_eq!(back.full_name, card.full_name);        assert_eq!(back.phones.iter().map(|p| p.value.replace([' ', '-'], "")).collect::<Vec<_>>(), card.phones.iter().map(|p| p.value.replace([' ', '-'], "")).collect::<Vec<_>>());        assert_eq!(back.phones[0].label.as_deref(), Some("Mobile"));        assert_eq!(back.emails, card.emails);        assert_eq!(back.org, card.org);        assert_eq!(back.role_title, card.role_title);        assert_eq!(back.city, card.city);        assert_eq!(back.birthday, card.birthday);        assert_eq!(back.note, card.note);        assert_eq!(back.groups, card.groups);        assert_eq!(back.photo, card.photo);        assert_eq!(back.uid, card.uid);    }}#[test]fn writes_an_organisation_as_one_and_folds_long_utf8_lines_whole() {    let org = Card { full_name: "Invented Bakery".into(), organisation: true, org: Some("Invented Bakery".into()), note: Some("राम ".repeat(40)), ..Card::default() };    let v4 = write_vcf(std::slice::from_ref(&org), Version::V4);    assert!(v4.contains("KIND:org\r\n"));    let back = read_vcf(&v4).cards.remove(0);    assert!(back.organisation);    assert_eq!(back.note, org.note.clone().map(|n| n.trim().to_string()));    let v3 = write_vcf(std::slice::from_ref(&org), Version::V3);    assert!(v3.contains("X-ABShowAs:COMPANY"));    assert!(read_vcf(&v3).cards[0].organisation);    let no_year = Card { full_name: "No Year".into(), birthday: Some(Birthday { month: 2, day: 29, year: None }), ..Card::default() };    assert_eq!(read_vcf(&write_vcf(std::slice::from_ref(&no_year), Version::V3)).cards[0].birthday, no_year.birthday);    assert_eq!(read_vcf(&write_vcf(std::slice::from_ref(&no_year), Version::V4)).cards[0].birthday, no_year.birthday);}// AUDIT D: a file past what one import takes is refused whole, in one plain line naming what is too much.#[test]fn a_file_past_the_limits_is_refused_in_one_plain_line() {    let card = |name: &str| Card { full_name: name.into(), ..Card::default() };    assert_eq!(over_limits(&Read { cards: vec![card("Asha")], skipped: 0 }), None);    let many = Read { cards: (0..=CARDS_MAX).map(|i| card(&format!("P{i}"))).collect(), skipped: 0 };    assert!(over_limits(&many).unwrap().starts_with("This file holds 50001 contacts"));    let groups = Read { cards: (0..=GROUPS_MAX).map(|i| Card { groups: vec![format!("G{i}")], ..card("x") }).collect(), skipped: 0 };    assert!(over_limits(&groups).unwrap().contains("201 groups"));    let note = Read { cards: vec![Card { note: Some("n".repeat(NOTE_MAX_CHARS + 1)), ..card("Long Note") }], skipped: 0 };    assert_eq!(over_limits(&note).unwrap(), "In this file, \u{201c}Long Note\u{201d} has a note longer than 64 KB. Shorten it and try again.");    let phones = Read { cards: vec![Card { phones: (0..=VALUES_MAX).map(|i| Labelled { value: format!("+91{i}"), label: None }).collect(), ..card("Many") }], skipped: 0 };    assert!(over_limits(&phones).unwrap().contains("more than 100 numbers"));    let name = Read { cards: vec![card(&"a".repeat(FIELD_MAX_CHARS + 1))], skipped: 0 };    assert!(over_limits(&name).unwrap().contains("longer than 1,024 characters"));}// AUDIT D: hostile files. A line with no colon folded on and on reads in time that grows with its length, not its// square (it hung); a birthday with a non-ASCII digit is no birthday, never a panic.#[test]fn a_hostile_file_neither_hangs_nor_panics() {    let mut long = String::from("BEGIN:VCARD\r\nVERSION:3.0\r\nX");    long.push_str(&"\r\n a".repeat(400_000));    long.push_str("\r\nFN:Still Read\r\nEND:VCARD\r\n");    let started = std::time::Instant::now();    let read = read_vcf(&long);    assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());    assert_eq!(read.cards[0].full_name, "Still Read");    assert_eq!(parse_birthday("123é456"), None);    // AUDIT D: the other slow paths, each read in time that grows with the file: a million numbers and NOTE lines on    // one card, a group card of 100,000 members over 20,000 cards, a 100,000-column CSV header, a CSV cell of a    // million labels. A card past VALUES_MAX stops one past it, and the file is refused (`over_limits`).    let started = std::time::Instant::now();    let mut card = String::from("BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Many\r\n");    for i in 0..200_000 {        card.push_str(&format!("TEL:+9198{i:08}\r\nNOTE:n{i}\r\n"));    }    card.push_str("CATEGORIES:");    card.push_str(&(0..200_000).map(|i| format!("g{i}")).collect::<Vec<_>>().join(","));    card.push_str("\r\nEND:VCARD\r\n");    let read = read_vcf(&card);    assert_eq!((read.cards[0].phones.len(), read.cards[0].groups.len()), (VALUES_MAX + 1, VALUES_MAX + 1));    assert!(over_limits(&read).is_some());    let mut members = String::new();    for i in 0..20_000 {        members.push_str(&format!("BEGIN:VCARD\r\nVERSION:3.0\r\nFN:P{i}\r\nUID:u{i}\r\nEND:VCARD\r\n"));    }    members.push_str("BEGIN:VCARD\r\nVERSION:4.0\r\nKIND:group\r\nFN:Big\r\n");    for i in 0..100_000 {        members.push_str(&format!("MEMBER:urn:uuid:u{}\r\n", i % 20_000));    }    members.push_str("END:VCARD\r\n");    let read = read_vcf(&members);    assert!(read.cards.iter().all(|c| c.groups == vec!["Big".to_string()]), "every member in the group once");    let header = (0..100_000).map(|i| format!("Phone {i} - Value")).collect::<Vec<_>>().join(",");    let labels = (0..1_000_000).map(|i| format!("L{i}")).collect::<Vec<_>>().join(" ::: ");    let read = read_google_csv(&format!("First Name,Labels,{header}\nDev,\"{labels}\"\n"));    assert_eq!(read.cards[0].groups.len(), VALUES_MAX + 1);    assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed());    assert!(read_vcf("BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Odd Day\r\nBDAY:123é456\r\nEND:VCARD\r\n").cards[0].birthday.is_none());}