craft-csv: add conservative short-row fallback to sniff_csv_delimiter

This commit is contained in:
AlPaka1234 committed 2026-11-24 07:38:10 +00:00
1 parent 724c8b5440
commit ee8e7a1683
2 files changed
+86 -12

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ mapping a SYLK sheet onto a document are the caller's work.
|---|---|
| `decode_text(bytes)` | UTF-8 and UTF-16 byte order marks; without one, valid UTF-8 is kept; other bytes are Windows-1256 when they read as Arabic, else Windows-1252 |
| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a sample of the first 65,536 characters (empty or whitespace-only quoted records are blank); when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon |
| `sniff_csv_delimiter(text, quote)` | same scan as `sniff_delimiter`, but for `.csv`-named text prefers comma when comma has coherent quoted fields and separates every sampled record with text, or separates the first such record while neither tab nor semicolon coherently separates every sampled record |
| `sniff_csv_delimiter(text, quote)` | same scan as `sniff_delimiter`, but for `.csv`-named text prefers comma when comma coherently separates every sampled record with text; when no candidate coherently separates every sampled record, falls back to a coherent candidate whose header and at least one later record share a positive delimiter count with strictly more than half of the sampled records having 1 to that many delimiters (preferring comma, then tab over semicolon), or else comma if comma coherently separates the first sampled record with text |
| `parse_records(text, delim, quote, max_fields, on_record)` | records of fields, one callback per record (return `false` to stop); CR, LF and CRLF line ends; quoted fields with doubled quotes and line breaks; a quote in the middle of a field is text |
| `records(text, delim, quote, max_records, max_fields)` | the same, collected |
| `push_field(out, field, delim)`, `field_len(field, delim)` | one field as written, quoted only when it holds the delimiter, a quote or a line break; its exact length, to enforce a size cap before writing |
+85 -11
View File
@@ -53,9 +53,15 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 {
/// separates the sampled records.
///
/// Uses the same bounded character sample, quote-boundary coherence rules and fallback ranking
/// as [`sniff_delimiter`], except that when comma has coherent quoted fields it is chosen if
/// it separates every sampled record with text, or if it separates the first such record and
/// neither tab nor semicolon coherently separates every sampled record with text.
/// as [`sniff_delimiter`], with two `.csv`-specific rules:
/// - When comma has coherent quoted fields and separates every sampled record with text, comma
/// wins even if tab or semicolon also separates them.
/// - When no candidate coherently separates every sampled record with text, a coherent candidate
/// whose first record and at least one later record share the same positive delimiter count
/// (and where strictly more than half of the sampled records with text contain between one and
/// that many delimiters) is chosen — preferring comma, then the most matching records, higher
/// header count and total, then tab over semicolon. If none matches, comma still wins when it
/// has coherent quoted fields and separates the first sampled record with text.
pub fn sniff_csv_delimiter(text: &str, quote: char) -> u8 {
sniff_delimiter_inner(text, quote, true)
}
@@ -116,19 +122,52 @@ fn separates_coherently(scan: &DelimiterScan) -> bool {
scan.coherent && scan.counts.iter().min().is_some_and(|&min| min > 0)
}
fn csv_prefers_comma([tab, comma, semi]: &[DelimiterScan; 3]) -> bool {
if !comma.coherent || comma.counts.is_empty() {
return false;
/// Scores a coherent candidate whose first record and at least one later record share the same
/// positive delimiter count, and where strictly more than half of the sampled records with text
/// contain between one and that many delimiters (allowing occasional short rows).
fn header_short_row_score(scan: &DelimiterScan) -> Option<(usize, usize, usize)> {
if !scan.coherent {
return None;
}
if comma.counts.iter().min().is_some_and(|&min| min > 0) {
return true;
let &header = scan.counts.first()?;
if header == 0 {
return None;
}
comma.counts.first().is_some_and(|&first| first > 0) && !separates_coherently(tab) && !separates_coherently(semi)
let exact_matches = scan.counts.iter().filter(|&&count| count == header).count();
let in_range = scan.counts.iter().filter(|&&count| (1..=header).contains(&count)).count();
if exact_matches < 2 || in_range * 2 <= scan.counts.len() {
return None;
}
Some((exact_matches, header, scan.counts.iter().sum()))
}
fn pick_csv_delimiter(scans: &[DelimiterScan; 3]) -> Option<u8> {
let [tab, comma, semi] = scans;
if separates_coherently(comma) {
return Some(b',');
}
if separates_coherently(tab) || separates_coherently(semi) {
return None;
}
if header_short_row_score(comma).is_some() {
return Some(b',');
}
if let Some((delimiter, _)) = [tab, semi]
.into_iter()
.filter_map(|scan| header_short_row_score(scan).map(|score| (scan.delimiter, score)))
.reduce(|best, candidate| if candidate.1 > best.1 { candidate } else { best })
{
return Some(delimiter);
}
if comma.coherent && comma.counts.first().is_some_and(|&first| first > 0) {
return Some(b',');
}
None
}
fn pick_delimiter(scans: [DelimiterScan; 3], prefer_comma: bool) -> u8 {
if prefer_comma && csv_prefers_comma(&scans) {
return b',';
if prefer_comma && let Some(delimiter) = pick_csv_delimiter(&scans) {
return delimiter;
}
let with_text = scans.each_ref().map(|scan| (scan.delimiter, scan.counts.as_slice(), scan.coherent));
// Records of delimiters alone have no quotes, so they are coherent.
@@ -587,6 +626,41 @@ mod tests {
assert_eq!(sniff_csv_delimiter(&format!("{};7\n", ";\n".repeat(40_000)), '"'), b';');
}
#[test]
fn csv_delimiter_sniffing_handles_short_rows_conservatively() {
// Tab- and semicolon-delimited CSVs with a short row recover when the header and a later
// full row agree across a majority of sampled records.
for (text, expected) in [
("Name\tCity\nAda\nGrace\tParis\n", b'\t'),
("Name;City\nAda\nGrace;Paris\n", b';'),
("Name\tCity\tRole\nAda\nGrace\tParis\tLead\n", b'\t'),
("Name;City;Role\nAda\nGrace;Paris;Lead\n", b';'),
("Name\tCity\nAda\tLondon\nGrace\n", b'\t'),
("Name;City\nAda;London\nGrace\n", b';'),
("Last, First\tCity\nAda\nGrace\tParis\n", b'\t'),
("Last, First;City\nAda\nGrace;Paris\n", b';'),
("\"\"\nName\tCity\nAda\nGrace\tParis\n", b'\t'),
("\"Name\"\t\"City;Region\"\nAda;X\nGrace\tParis;Y\n", b'\t'),
] {
assert_eq!(sniff_csv_delimiter(text, '"'), expected, "{text:?}");
}
// Comma preference and conservative single-column fallbacks stay comma.
for text in [
"Name,Note;Tag\nAda\nGrace,Hello;2\n",
"Name,Note\tTag\nAda\nGrace,Hello\t2\n",
"\"Name\",\"Note;Tag\"\nAda;Team\n",
"alpha;beta\r\ngamma\r\n",
"alpha\tbeta\r\ngamma\r\n",
"alpha;beta\r\ngamma\r\ndelta\r\n",
"Notes\r\nalpha;beta\r\ngamma;delta\r\n",
"a;b\nc\nd\ne;f\n",
"Title: a;b\nline\nx;y;z\nline\nc;d\n",
] {
assert_eq!(sniff_csv_delimiter(text, '"'), b',', "{text:?}");
}
}
#[test]
fn parser_stops_collecting_fields_at_the_cap() {
let (max, extra) = (16_384usize, 50);