Skip to main content

lib_jsl_file_io/
csv.rs

1//! Delimited text tables (CSV, RFC 4180).
2//!
3//! Fields may be quoted with `"`, and quoted fields may contain the delimiter, line breaks and
4//! doubled quotes (`""` for a literal `"`). Records end with LF or CRLF; a trailing line break is
5//! optional. Writing quotes exactly the fields that need it.
6//!
7//! See the book entry [Data files](https://jwkunz.github.io/lib_jsl/book/foundations/data-files.html#csv).
8
9use lib_jsl_core::ErrorsJSL;
10use std::path::Path;
11
12/// A parsed table: an optional header row and the records, all as strings.
13#[derive(Debug, Clone, PartialEq, Eq, Default)]
14pub struct CsvTable {
15    pub header: Option<Vec<String>>,
16    pub rows: Vec<Vec<String>>,
17}
18
19impl CsvTable {
20    /// The index of the column named `name` in the header.
21    pub fn column_index(&self, name: &str) -> Option<usize> {
22        self.header.as_ref()?.iter().position(|h| h == name)
23    }
24
25    /// Column `index` parsed as numbers (empty fields become NaN).
26    pub fn column_f64(&self, index: usize) -> Result<Vec<f64>, ErrorsJSL> {
27        self.rows.iter().map(|row| parse_number(row.get(index).map(String::as_str).unwrap_or(""))).collect()
28    }
29
30    /// The whole table parsed as numbers, row-major (empty fields become NaN). Every row must
31    /// have the same number of fields.
32    pub fn to_f64_rows(&self) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
33        let width = self.rows.first().map_or(0, |r| r.len());
34        self.rows
35            .iter()
36            .map(|row| {
37                if row.len() != width {
38                    return Err(ErrorsJSL::IncompatibleArraySizes((row.len(), width)));
39                }
40                row.iter().map(|f| parse_number(f)).collect()
41            })
42            .collect()
43    }
44}
45
46fn parse_number(field: &str) -> Result<f64, ErrorsJSL> {
47    let t = field.trim();
48    if t.is_empty() {
49        return Ok(f64::NAN);
50    }
51    t.parse::<f64>().map_err(|_| ErrorsJSL::RuntimeError("A CSV field is not a number."))
52}
53
54/// Parses delimited text. With `has_header` the first record becomes the header.
55pub fn parse_csv(text: &str, delimiter: char, has_header: bool) -> Result<CsvTable, ErrorsJSL> {
56    if delimiter == '"' || delimiter == '\n' || delimiter == '\r' {
57        return Err(ErrorsJSL::InvalidInputRange("The delimiter cannot be a quote or a line break."));
58    }
59    let mut records: Vec<Vec<String>> = Vec::new();
60    let mut record = Vec::new();
61    let mut field = String::new();
62    let mut chars = text.chars().peekable();
63    let mut in_quotes = false;
64    let mut field_started = false;
65    while let Some(c) = chars.next() {
66        if in_quotes {
67            if c == '"' {
68                if chars.peek() == Some(&'"') {
69                    field.push('"');
70                    chars.next();
71                } else {
72                    in_quotes = false;
73                }
74            } else {
75                field.push(c);
76            }
77            continue;
78        }
79        match c {
80            '"' if field.is_empty() && !field_started => {
81                in_quotes = true;
82                field_started = true;
83            }
84            '"' => return Err(ErrorsJSL::RuntimeError("A quote appears inside an unquoted CSV field.")),
85            c if c == delimiter => {
86                record.push(std::mem::take(&mut field));
87                field_started = false;
88            }
89            '\r' if chars.peek() == Some(&'\n') => {}
90            '\n' | '\r' => {
91                record.push(std::mem::take(&mut field));
92                records.push(std::mem::take(&mut record));
93                field_started = false;
94            }
95            c => {
96                field.push(c);
97                field_started = true;
98            }
99        }
100    }
101    if in_quotes {
102        return Err(ErrorsJSL::RuntimeError("Unterminated quoted CSV field."));
103    }
104    if field_started || !field.is_empty() || !record.is_empty() {
105        record.push(field);
106        records.push(record);
107    }
108    let header = if has_header && !records.is_empty() { Some(records.remove(0)) } else { None };
109    Ok(CsvTable { header, rows: records })
110}
111
112// ANCHOR: write_field
113fn write_field(out: &mut String, field: &str, delimiter: char) {
114    if field.contains(delimiter) || field.contains('"') || field.contains('\n') || field.contains('\r') || field.starts_with(' ') || field.ends_with(' ') {
115        out.push('"');
116        out.push_str(&field.replace('"', "\"\""));
117        out.push('"');
118    } else {
119        out.push_str(field);
120    }
121}
122// ANCHOR_END: write_field
123
124/// Formats a table as delimited text with LF line endings.
125pub fn format_csv(table: &CsvTable, delimiter: char) -> String {
126    let mut out = String::new();
127    for record in table.header.iter().chain(&table.rows) {
128        for (i, field) in record.iter().enumerate() {
129            if i > 0 {
130                out.push(delimiter);
131            }
132            write_field(&mut out, field, delimiter);
133        }
134        out.push('\n');
135    }
136    out
137}
138
139/// Formats numeric rows (with an optional header); numbers use Rust's shortest round-trip
140/// representation, so parsing the text back recovers them exactly.
141pub fn format_csv_f64(header: Option<&[&str]>, rows: &[Vec<f64>], delimiter: char) -> String {
142    let table = CsvTable {
143        header: header.map(|h| h.iter().map(|s| s.to_string()).collect()),
144        rows: rows.iter().map(|r| r.iter().map(|v| if v.is_nan() { String::new() } else { format!("{v:?}") }).collect()).collect(),
145    };
146    format_csv(&table, delimiter)
147}
148
149/// Reads a delimited text file.
150pub fn read_csv_file(path: impl AsRef<Path>, delimiter: char, has_header: bool) -> Result<CsvTable, ErrorsJSL> {
151    let text = std::fs::read_to_string(path).map_err(|_| ErrorsJSL::RuntimeError("Could not read the CSV file."))?;
152    parse_csv(text.strip_prefix('\u{feff}').unwrap_or(&text), delimiter, has_header)
153}
154
155/// Writes a delimited text file.
156pub fn write_csv_file(path: impl AsRef<Path>, table: &CsvTable, delimiter: char) -> Result<(), ErrorsJSL> {
157    std::fs::write(path, format_csv(table, delimiter)).map_err(|_| ErrorsJSL::RuntimeError("Could not write the CSV file."))
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn parses_quoting_line_endings_and_headers() {
166        let text = "name,value,note\r\n\"Smith, J\",3.5,\"said \"\"hi\"\"\"\nplain,-1e3,\"two\nlines\"\nempty,,\n";
167        let t = parse_csv(text, ',', true).unwrap();
168        assert_eq!(t.header.as_deref(), Some(&["name".to_string(), "value".into(), "note".into()][..]));
169        assert_eq!(t.rows[0], vec!["Smith, J", "3.5", "said \"hi\""]);
170        assert_eq!(t.rows[1][2], "two\nlines");
171        assert_eq!(t.rows[2], vec!["empty", "", ""]);
172        let values = t.column_f64(t.column_index("value").unwrap()).unwrap();
173        assert_eq!(&values[..2], &[3.5, -1000.0]);
174        assert!(values[2].is_nan());
175        // No trailing newline, other delimiters, and a quoted empty field.
176        let t = parse_csv("1;2\n\"\";4", ';', false).unwrap();
177        assert_eq!(t.rows, vec![vec!["1", "2"], vec!["", "4"]]);
178        assert!(parse_csv("a,\"open", ',', false).is_err() && parse_csv("a,b\"c", ',', false).is_err());
179        assert!(t.to_f64_rows().is_ok() && parse_csv("1,2\n3", ',', false).unwrap().to_f64_rows().is_err());
180    }
181
182    #[test]
183    fn writing_round_trips_strings_and_numbers_exactly() {
184        let table = CsvTable {
185            header: Some(vec!["a".into(), "b c".into()]),
186            rows: vec![vec!["x,y".into(), "q\"uote".into()], vec![" padded ".into(), "multi\nline".into()]],
187        };
188        assert_eq!(parse_csv(&format_csv(&table, ','), ',', true).unwrap(), table);
189        let rows = vec![vec![0.1, -2.5e-300, f64::MAX], vec![1.0 / 3.0, f64::NAN, -0.0]];
190        let parsed = parse_csv(&format_csv_f64(Some(&["p", "q", "r"]), &rows, '\t'), '\t', true).unwrap().to_f64_rows().unwrap();
191        for (a, b) in parsed.iter().flatten().zip(rows.iter().flatten()) {
192            assert!(a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan()));
193        }
194    }
195}