CSV Diff — Rust source
Diff two CSVs by a key column: rows added, removed and changed, with the differing columns named. Quoted cells with commas, quotes and newlines are handled. Runs locally with a shareable link.
This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! csv-diff — key-based row diff of two RFC-4180 CSVs. Rust port (canonical TS:
//! `src/lib/csv-diff.ts`; Go twin: `cli/csv-diff`). No external crates: the
//! RFC-4180 parser mirrors the TS loop (quoted cells with embedded commas,
//! quotes and newlines; CR dropped; a trailing field without a newline still
//! completes its row) and blank single-cell rows are dropped as trailing
//! noise. Strict per-side validation — empty CSV, duplicate columns, ragged
//! rows ("Left: row 2 has 3 cells, expected 4"), duplicate keys — then a
//! key-based diff over the sorted key union: added/removed rows and changed
//! rows whose differing column names come out sorted. Errors travel in
//! `DiffResult.error` (`None` mirrors TS `null` on success).
/// One RFC-4180 parser pass mirroring the TS loop: lenient quotes, CR
/// dropped, a trailing field without a newline still completes its row.
pub fn csv_to_rows(csv: &str) -> Vec<Vec<String>> {
let mut rows: Vec<Vec<String>> = Vec::new();
let mut field = String::new();
let mut row: Vec<String> = Vec::new();
let mut in_q = false;
let chars: Vec<char> = csv.chars().collect();
let n = chars.len();
let mut i = 0;
while i < n {
let ch = chars[i];
if in_q {
if ch == '"' {
if i + 1 < n && chars[i + 1] == '"' {
field.push('"');
i += 1;
} else {
in_q = false;
}
} else {
field.push(ch);
}
} else if ch == '"' {
in_q = true;
} else if ch == ',' {
row.push(std::mem::take(&mut field));
} else if ch == '\n' {
row.push(std::mem::take(&mut field));
rows.push(std::mem::take(&mut row));
} else if ch != '\r' {
field.push(ch);
}
i += 1;
}
if !field.is_empty() || !row.is_empty() {
row.push(field);
rows.push(row);
}
rows
}
/// Blank single-cell rows are trailing noise to a diff, not data.
fn parse_csv(text: &str) -> Vec<Vec<String>> {
csv_to_rows(text)
.into_iter()
.filter(|r| !(r.len() == 1 && r[0].is_empty()))
.collect()
}
/// A record as name→value pairs in header order (the before/after payload).
type Record = Vec<(String, String)>;
fn cell(rec: &Record, name: &str) -> &str {
&rec.iter().find(|(n, _)| n == name).unwrap().1
}
/// Strict per-side validation → (header, records) or the pinned error string.
fn to_records(rows: &[Vec<String>], label: &str) -> Result<(Vec<String>, Vec<Record>), String> {
if rows.is_empty() {
return Err(format!("{label}: empty CSV"));
}
let header = rows[0].clone();
let mut seen: std::collections::HashSet<&String> = std::collections::HashSet::new();
for name in &header {
if !seen.insert(name) {
return Err(format!("{label}: duplicate column \"{name}\""));
}
}
let mut records = Vec::new();
for (i, row) in rows.iter().enumerate().skip(1) {
if row.len() != header.len() {
return Err(format!(
"{label}: row {} has {} cells, expected {}",
i + 1,
row.len(),
header.len()
));
}
records.push(header.iter().cloned().zip(row.iter().cloned()).collect());
}
Ok((header, records))
}
pub struct RowDiff {
pub key: String,
pub kind: &'static str, // "added" | "removed" | "changed"
pub columns: Vec<String>, // differing names, sorted (changed only)
pub before: Option<Record>, // removed/changed
pub after: Option<Record>, // added/changed
}
pub struct DiffResult {
pub rows: Vec<RowDiff>,
pub same: bool,
pub error: Option<String>, // None mirrors TS null (success)
}
/// Diff two CSVs by key column (`None` → the first header column).
pub fn csv_diff(left_raw: &str, right_raw: &str, key_column: Option<&str>) -> DiffResult {
if left_raw.trim().is_empty() || right_raw.trim().is_empty() {
return DiffResult { rows: vec![], same: false, error: Some("Both inputs are required".into()) };
}
let run = || -> Result<DiffResult, String> {
let (lheader, lrecs) = to_records(&parse_csv(left_raw), "Left")?;
let (rheader, rrecs) = to_records(&parse_csv(right_raw), "Right")?;
let key = key_column.unwrap_or(&lheader[0]).to_string();
if !lheader.contains(&key) {
return Err(format!("Left: no key column \"{key}\""));
}
if !rheader.contains(&key) {
return Err(format!("Right: no key column \"{key}\""));
}
if lheader != rheader {
return Err(format!(
"Headers differ: left [{}] vs right [{}]",
lheader.join(", "),
rheader.join(", ")
));
}
let index = |records: &[Record], label: &str| -> Result<std::collections::BTreeMap<String, Record>, String> {
let mut by = std::collections::BTreeMap::new();
for rec in records {
let k = cell(rec, &key).to_string();
if by.contains_key(&k) {
return Err(format!("{label}: duplicate key \"{k}\""));
}
by.insert(k, rec.clone());
}
Ok(by)
};
let left_by = index(&lrecs, "Left")?;
let right_by = index(&rrecs, "Right")?;
let mut rows = Vec::new();
// BTreeSet = sorted, deduplicated union of both key sets.
let union: std::collections::BTreeSet<&String> =
left_by.keys().chain(right_by.keys()).collect();
for k in union {
let l = left_by.get(k);
let r = right_by.get(k);
match (l, r) {
(None, Some(r)) => rows.push(RowDiff {
key: k.clone(), kind: "added", columns: vec![], before: None, after: Some(r.clone()),
}),
(Some(l), None) => rows.push(RowDiff {
key: k.clone(), kind: "removed", columns: vec![], before: Some(l.clone()), after: None,
}),
(Some(l), Some(r)) => {
let mut columns: Vec<String> = Vec::new();
for name in &lheader {
if name != &key && cell(l, name) != cell(r, name) {
columns.push(name.clone());
}
}
columns.sort();
if !columns.is_empty() {
rows.push(RowDiff {
key: k.clone(), kind: "changed", columns,
before: Some(l.clone()), after: Some(r.clone()),
});
}
}
(None, None) => unreachable!(),
}
}
let same = rows.is_empty();
Ok(DiffResult { rows, same, error: None })
};
match run() {
Ok(r) => r,
Err(e) => DiffResult { rows: vec![], same: false, error: Some(e) },
}
}
// Example:
// let r = csv_diff("id,name\n1,Ada\n2,Bob", "id,name\n1,Ada\n2,Robert\n3,New", None);
// assert!(!r.same);
// assert_eq!(r.rows[0].kind, "changed");
// assert_eq!(r.rows[0].columns, ["name"]);
// assert_eq!(r.rows[1].kind, "added");
Also available in 12 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →