Skip to main content

crisol_core/data/
csv.rs

1//! CSV and TSV parsing into a typed dataset.
2
3use std::path::Path;
4
5use super::column::Column;
6use super::dataset::Dataset;
7use super::source::{ColumnSchema, DataError, DataSource};
8
9/// CSV options.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11/// # Example
12///
13/// ```
14/// use crisol_core::data::CsvOptions;
15/// ```
16pub struct CsvOptions {
17    /// Field delimiter.
18    pub delimiter: u8,
19    /// Treat the first row as the column names.
20    pub header: bool,
21}
22
23impl Default for CsvOptions {
24    fn default() -> Self {
25        Self {
26            delimiter: b',',
27            header: true,
28        }
29    }
30}
31
32impl CsvOptions {
33    /// Comma-separated.
34    pub fn csv() -> Self {
35        Self::default()
36    }
37
38    /// Tab-separated.
39    pub fn tsv() -> Self {
40        Self {
41            delimiter: b'\t',
42            ..Self::default()
43        }
44    }
45}
46
47/// A parsed CSV/TSV source.
48#[derive(Clone, Debug, PartialEq)]
49/// # Example
50///
51/// ```
52/// use crisol_core::data::CsvSource;
53/// ```
54pub struct CsvSource {
55    name: String,
56    data: Dataset,
57    schema: Vec<ColumnSchema>,
58}
59
60impl CsvSource {
61    /// Parse UTF-8 delimited text.
62    ///
63    /// # Errors
64    /// When the text has no rows or a row has more fields than the header.
65    pub fn parse(name: impl Into<String>, text: &str, options: CsvOptions) -> Result<Self, DataError> {
66        let name = name.into();
67        let data = parse_csv(&name, text.as_bytes(), options)?;
68        let schema = data.columns().iter().map(ColumnSchema::from_column).collect();
69        Ok(Self { name, data, schema })
70    }
71
72    /// Open a file from disk.
73    ///
74    /// # Errors
75    /// When the file cannot be read or parsed.
76    #[cfg(feature = "threads")]
77    pub fn open(path: impl AsRef<Path>) -> Result<Self, DataError> {
78        let path = path.as_ref();
79        let bytes = super::source::read_limited(path)?;
80        let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("data.csv");
81        let options = if name.ends_with(".tsv") || name.ends_with(".tab") {
82            CsvOptions::tsv()
83        } else {
84            CsvOptions::csv()
85        };
86        let data = parse_csv(name, &bytes, options)?;
87        let schema = data.columns().iter().map(ColumnSchema::from_column).collect();
88        Ok(Self {
89            name: name.to_owned(),
90            data,
91            schema,
92        })
93    }
94
95    /// The file name.
96    pub fn name(&self) -> &str {
97        &self.name
98    }
99
100    /// The parsed data.
101    pub fn data(&self) -> &Dataset {
102        &self.data
103    }
104}
105
106impl DataSource for CsvSource {
107    fn schema(&self) -> &[ColumnSchema] {
108        &self.schema
109    }
110
111    fn row_count(&self) -> usize {
112        self.data.row_count()
113    }
114
115    fn read_range(&self, range: std::ops::Range<usize>) -> Result<Dataset, DataError> {
116        super::source::check_range(&range, self.row_count())?;
117        Ok(self.data.slice(range))
118    }
119}
120
121/// Parse bytes as a delimited table, inferring int, float, bool, and text columns.
122///
123/// # Errors
124/// When there is no header and no rows, or a row has more fields than the header.
125/// # Example
126///
127/// ```
128/// use crisol_core::data::parse_csv;
129/// ```
130pub fn parse_csv(name: &str, bytes: &[u8], options: CsvOptions) -> Result<Dataset, DataError> {
131    let text = std::str::from_utf8(bytes).map_err(|error| DataError::Connector(error.to_string()))?;
132    // A byte-order mark would stay glued to the first header name.
133    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
134    let mut rows = parse_rows(text, options.delimiter);
135    if rows.is_empty() {
136        return Ok(Dataset::new().with_name(name));
137    }
138    let headers = if options.header {
139        rows.remove(0)
140    } else {
141        (0..rows.first().map_or(0, Vec::len))
142            .map(|index| format!("column_{index}"))
143            .collect()
144    };
145    if rows.iter().any(|row| row.len() > headers.len()) {
146        return Err(DataError::Connector("a row has more fields than the header".to_owned()));
147    }
148    let mut columns = Vec::with_capacity(headers.len());
149    for (index, header) in headers.iter().enumerate() {
150        let values: Vec<&str> = rows
151            .iter()
152            .map(|row| row.get(index).map_or("", String::as_str))
153            .collect();
154        columns.push(infer_column(header, &values));
155    }
156    let mut dataset = Dataset::from_columns(columns);
157    dataset.set_metadata("source", name);
158    Ok(dataset)
159}
160
161trait NamedDataset {
162    fn with_name(self, name: &str) -> Self;
163}
164
165impl NamedDataset for Dataset {
166    fn with_name(mut self, name: &str) -> Self {
167        self.set_metadata("source", name);
168        self
169    }
170}
171
172fn infer_column(name: &str, values: &[&str]) -> Column {
173    let non_empty: Vec<&str> = values.iter().copied().filter(|value| !value.is_empty()).collect();
174    if non_empty.is_empty() {
175        return Column::text(name, values.to_vec()).with_validity(values.iter().map(|value| !value.is_empty()));
176    }
177    if non_empty
178        .iter()
179        .all(|value| value.eq_ignore_ascii_case("true") || value.eq_ignore_ascii_case("false"))
180    {
181        return Column::bools(
182            name,
183            values
184                .iter()
185                .map(|value| value.eq_ignore_ascii_case("true"))
186                .collect::<Vec<_>>(),
187        )
188        .with_validity(values.iter().map(|value| !value.is_empty()));
189    }
190    if non_empty.iter().all(|value| value.parse::<i64>().is_ok()) {
191        return Column::ints(
192            name,
193            values
194                .iter()
195                .map(|value| value.parse::<i64>().unwrap_or(0))
196                .collect::<Vec<_>>(),
197        )
198        .with_validity(values.iter().map(|value| !value.is_empty()));
199    }
200    if non_empty.iter().all(|value| value.parse::<f64>().is_ok()) {
201        return Column::floats(
202            name,
203            values
204                .iter()
205                .map(|value| value.parse::<f64>().unwrap_or(f64::NAN))
206                .collect::<Vec<_>>(),
207        )
208        .with_validity(values.iter().map(|value| !value.is_empty()));
209    }
210    Column::text(name, values.to_vec()).with_validity(values.iter().map(|value| !value.is_empty()))
211}
212
213fn parse_rows(text: &str, delimiter: u8) -> Vec<Vec<String>> {
214    let delimiter = char::from(delimiter);
215    let mut rows = Vec::new();
216    let mut row = Vec::new();
217    let mut field = String::new();
218    let mut quoted = false;
219    let mut chars = text.chars().peekable();
220    while let Some(character) = chars.next() {
221        if quoted {
222            match character {
223                '"' if chars.peek() == Some(&'"') => {
224                    chars.next();
225                    field.push('"');
226                }
227                '"' => quoted = false,
228                _ => field.push(character),
229            }
230            continue;
231        }
232        match character {
233            '"' if field.is_empty() => quoted = true,
234            character if character == delimiter => row.push(std::mem::take(&mut field)),
235            // A blank line is not a row of one empty field.
236            '\n' if row.is_empty() && field.is_empty() => {}
237            '\n' => {
238                row.push(std::mem::take(&mut field));
239                rows.push(std::mem::take(&mut row));
240            }
241            '\r' => {}
242            _ => field.push(character),
243        }
244    }
245    if !field.is_empty() || !row.is_empty() {
246        row.push(field);
247        rows.push(row);
248    }
249    rows
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255    use crate::data::CellValue;
256
257    #[test]
258    fn csv_infers_types_and_handles_quotes() {
259        let text = "name,voltage,cycle,ok\n\"coil, a\",1.5,2,true\ncoil b,2.0,3,false\n";
260        let source = CsvSource::parse("test.csv", text, CsvOptions::csv()).expect("csv");
261        assert_eq!(source.row_count(), 2);
262        assert_eq!(source.schema()[0].kind, crate::data::ColumnType::Text);
263        assert_eq!(source.schema()[1].kind, crate::data::ColumnType::Float);
264        assert_eq!(source.schema()[2].kind, crate::data::ColumnType::Int);
265        assert_eq!(source.schema()[3].kind, crate::data::ColumnType::Bool);
266        let page = source.read_range(0..2).expect("page");
267        assert_eq!(page.cell(0, 0), CellValue::Text("coil, a"));
268        assert_eq!(page.cell(1, 1), CellValue::Float(2.0));
269    }
270
271    #[test]
272    fn tsv_and_empty_cells() {
273        let source = CsvSource::parse("test.tsv", "a\tb\n1\t\n2\tx\n", CsvOptions::tsv()).expect("tsv");
274        assert_eq!(source.row_count(), 2);
275        assert_eq!(source.data().cell(0, 1), CellValue::Null);
276        assert_eq!(source.data().cell(1, 1), CellValue::Text("x"));
277    }
278}