From bdf7d657a4711bd8b6daa6f22b45d0a7e184ea9d Mon Sep 17 00:00:00 2001 From: Vedran Dobos <19259909+vedran-dobos@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:48:14 +0100 Subject: [PATCH] CSV: a sep= stand-in is never a character the file holds (#1446) The stand-in delimiter for a sep= line that names none is now chosen once over the whole body: a free noncharacter, else any free character. A text that holds every character is refused instead of being split at U+FDD0. Co-Authored-By: Claude Opus 5.5 --- crates/xlsx/src/csv.rs | 48 ++++++++++++++++++++---------- crates/xlsx/src/tests/csv_tests.rs | 22 +++++++++++--- 2 files changed, 50 insertions(+), 20 deletions(-) diff --git a/crates/xlsx/src/csv.rs b/crates/xlsx/src/csv.rs index 474eff091..5e5f86865 100644 --- a/crates/xlsx/src/csv.rs +++ b/crates/xlsx/src/csv.rs @@ -40,23 +40,28 @@ pub(crate) fn sep_line(text: &str, quote: char) -> Option<(Option, usize)> } } -/// [`craft_csv::parse_records`] with a record kept to the grid's [`MAX_COLS`] fields. Without a -/// delimiter each line is one field; without a quote character nothing is quoted. -fn parse_records(text: &str, delim: Option, quote: Option, on_record: impl FnMut(Vec) -> bool) { - // craft-csv always splits and unquotes, so a character the text doesn't hold stands in. - let (delim, quote) = match (delim, quote) { - (Some(d), Some(q)) => (d, q), - _ => { - let [d, q] = unused_chars(text); - (delim.unwrap_or(d), quote.unwrap_or(q)) - } - }; +/// [`craft_csv::parse_records`] with a record kept to the grid's [`MAX_COLS`] fields. +fn parse_records(text: &str, delim: char, quote: char, on_record: impl FnMut(Vec) -> bool) { craft_csv::parse_records(text, delim, quote, MAX_COLS as usize, on_record); } -/// Two Unicode noncharacters (U+FDD0 to U+FDEF, which exchanged text doesn't use) that `text` -/// doesn't hold. A text that holds them all is hostile: it gets the first two, and is split there. -fn unused_chars(text: &str) -> [char; 2] { +/// The delimiter and quote character to read `text` with. craft-csv always splits and unquotes, so +/// for a `sep=` line that names no delimiter (each line is one field) or names the quote (nothing is +/// quoted), a character `text` doesn't hold stands in: a Unicode noncharacter (U+FDD0 to U+FDEF, +/// which exchanged text doesn't use), else any other. A text that holds every character leaves +/// none, and is refused rather than split at one of its own. +fn stand_ins(text: &str, delim: Option, quote: Option) -> Result<(char, char), IoError> { + if let (Some(d), Some(q)) = (delim, quote) { + return Ok((d, q)); + } + let [d, q] = unused_chars(text) + .ok_or_else(|| IoError::Format("the file holds every character, so its fields can't be read without a delimiter".into()))?; + Ok((delim.unwrap_or(d), quote.unwrap_or(q))) +} + +/// Two characters `text` doesn't hold: noncharacters when it leaves two of them free, else the +/// first two free scalar values (a 136 KiB bitset, only for a text holding all 32 noncharacters). +fn unused_chars(text: &str) -> Option<[char; 2]> { const FIRST: u32 = 0xFDD0; let mut used = 0u32; for c in text.chars() { @@ -65,7 +70,17 @@ fn unused_chars(text: &str) -> [char; 2] { } } let mut free = (0..32).filter(|i| used & (1 << i) == 0).filter_map(|i| char::from_u32(FIRST + i)); - [free.next().unwrap_or('\u{FDD0}'), free.next().unwrap_or('\u{FDD1}')] + if let (Some(d), Some(q)) = (free.next(), free.next()) { + return Some([d, q]); + } + let mut all = vec![0u64; 0x11_0000 / 64]; + for c in text.chars() { + if let Some(w) = all.get_mut(c as usize / 64) { + *w |= 1 << (c as u32 % 64); + } + } + let mut free = (0..0x11_0000u32).filter(|&u| all.get(u as usize / 64).is_some_and(|w| w & (1 << (u % 64)) == 0)).filter_map(char::from_u32); + Some([free.next()?, free.next()?]) } /// How many rows and bytes of a text file are read to decide each column's date order. @@ -215,7 +230,7 @@ fn valid_date(sys: DateSystem, year: i64, month: i64, day: i64) -> Option { } /// The first records of the file, bounded by rows and bytes, for date-order inference. -fn sample_records(text: &str, delim: Option, quote: Option) -> Vec> { +fn sample_records(text: &str, delim: char, quote: char) -> Vec> { let mut cut = text.len().min(DATE_SAMPLE_BYTES); while !text.is_char_boundary(cut) { cut -= 1; @@ -325,6 +340,7 @@ pub fn read_csv_with_report(bytes: &[u8], opts: &CsvOptions) -> Result<(Workbook (text.as_str(), Some(delim), Some(quote)) } }; + let (delim, quote) = stand_ins(body, delim, quote)?; let date_columns = if opts.parse_values { infer_date_rules(&sample_records(body, delim, quote), opts.date_system) } else { vec![] }; let mut report = ReadReport::default(); date_warnings(&date_columns, &mut report); diff --git a/crates/xlsx/src/tests/csv_tests.rs b/crates/xlsx/src/tests/csv_tests.rs index 73f3e34af..5642c9971 100644 --- a/crates/xlsx/src/tests/csv_tests.rs +++ b/crates/xlsx/src/tests/csv_tests.rs @@ -493,11 +493,25 @@ fn csv_used_range_limit_is_enforced_while_reading() { } /// `sep=` naming nothing reads through craft-csv with a stand-in delimiter the text doesn't hold -/// (`sep_line_names_the_delimiter` has the usual cases). A text holding every stand-in still opens. +/// (`sep_line_names_the_delimiter` has the usual cases). A text holding every noncharacter still +/// opens whole: another character stands in. Review of #2270: it was split at U+FDD0. #[test] fn sep_line_stand_in_survives_a_text_holding_every_stand_in() { let all: String = (0xFDD0..=0xFDEF).filter_map(char::from_u32).collect(); - let text = format!("sep=\r\nx{all}y\r\n"); - let wb = read_csv(text.as_bytes(), &CsvOptions { delimiter: 0, ..Default::default() }).unwrap(); - assert_eq!(wb.sheet(0).unwrap().value(CellRef::new(0, 0)), Value::text("x"), "split at the first stand-in"); + let text = format!("sep=\r\nx{all}y\r\n\0z\r\n"); + let wb = read_csv(text.as_bytes(), &CsvOptions { delimiter: 0, parse_values: false, ..Default::default() }).unwrap(); + let sh = wb.sheet(0).unwrap(); + assert_eq!(sh.value(CellRef::new(0, 0)), Value::text(format!("x{all}y")), "the whole line is one field"); + assert_eq!(sh.value(CellRef::new(0, 1)), Value::Empty); + assert_eq!(sh.value(CellRef::new(1, 0)), Value::text("\0z")); +} + +/// A text that holds every character leaves nothing to stand in for the missing delimiter: it's +/// refused, not split at one of its own characters. +#[test] +fn sep_line_without_a_free_stand_in_is_refused() { + let all: String = (0..=0x10_FFFF).filter_map(char::from_u32).filter(|c| !matches!(c, '\r' | '\n')).collect(); + let text = format!("sep=\r\n{all}\r\n"); + let opts = CsvOptions { delimiter: 0, parse_values: false, ..Default::default() }; + assert!(matches!(read_csv(text.as_bytes(), &opts), Err(IoError::Format(_)))); }