[statement] Parsing: strict CSV, amount and date fields, decoding; no bank until real samples arrive
This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
//! A strict CSV reader (RFC 4180 with a chosen delimiter). Every irregularity is an error with its line
|
||||
//! number; a row is either returned whole or the file is refused.
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
/// Longest row accepted, in bytes.
|
||||
pub const MAX_ROW: usize = 64 * 1024;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Dialect {
|
||||
pub delimiter: char,
|
||||
/// The last row must end with a line break: a file cut mid-row is then always an error.
|
||||
pub final_newline: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error, Serialize)]
|
||||
pub enum CsvError {
|
||||
#[error("a quote inside a field that is not quoted")]
|
||||
BareQuote,
|
||||
#[error("a quoted field is never closed")]
|
||||
UnterminatedQuote,
|
||||
#[error("text after a closing quote")]
|
||||
TextAfterQuote,
|
||||
#[error("{found} fields where the header has {expected}")]
|
||||
Ragged { expected: usize, found: usize },
|
||||
#[error("the row is longer than {MAX_ROW} bytes")]
|
||||
RowTooLong,
|
||||
#[error("the file does not end with a line break; it may be cut short")]
|
||||
MissingFinalNewline,
|
||||
#[error("a carriage return without a line feed")]
|
||||
LoneCarriageReturn,
|
||||
}
|
||||
|
||||
/// One row and the line it starts on (1-based).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Row {
|
||||
pub line: usize,
|
||||
pub fields: Vec<String>,
|
||||
}
|
||||
|
||||
/// Reads every row. All rows must have as many fields as the first. Blank lines are refused too (a bank
|
||||
/// parser that expects them, e.g. between a preamble and the table, splits the text first).
|
||||
pub fn read(text: &str, dialect: Dialect) -> Result<Vec<Row>, (usize, CsvError)> {
|
||||
let mut rows: Vec<Row> = Vec::new();
|
||||
let mut chars = text.chars().peekable();
|
||||
let mut line = 1usize;
|
||||
let mut row_start_line = 1usize;
|
||||
let mut row_bytes = 0usize;
|
||||
let mut fields: Vec<String> = Vec::new();
|
||||
let mut field = String::new();
|
||||
let mut in_quotes = false;
|
||||
let mut was_quoted = false; // the current field was quoted and has been closed
|
||||
let mut field_started = false;
|
||||
let mut ended_with_newline = false;
|
||||
|
||||
let finish_row = |rows: &mut Vec<Row>, fields: &mut Vec<String>, start: usize| -> Result<(), (usize, CsvError)> {
|
||||
let row = std::mem::take(fields);
|
||||
if let Some(first) = rows.first() {
|
||||
if row.len() != first.fields.len() {
|
||||
return Err((start, CsvError::Ragged { expected: first.fields.len(), found: row.len() }));
|
||||
}
|
||||
}
|
||||
rows.push(Row { line: start, fields: row });
|
||||
Ok(())
|
||||
};
|
||||
|
||||
while let Some(c) = chars.next() {
|
||||
row_bytes += c.len_utf8();
|
||||
if row_bytes > MAX_ROW {
|
||||
return Err((row_start_line, CsvError::RowTooLong));
|
||||
}
|
||||
ended_with_newline = false;
|
||||
if in_quotes {
|
||||
match c {
|
||||
'"' if chars.peek() == Some(&'"') => {
|
||||
chars.next();
|
||||
field.push('"');
|
||||
}
|
||||
'"' => {
|
||||
in_quotes = false;
|
||||
was_quoted = true;
|
||||
}
|
||||
'\n' => {
|
||||
line += 1;
|
||||
field.push('\n');
|
||||
}
|
||||
'\r' => {
|
||||
if chars.peek() == Some(&'\n') {
|
||||
chars.next();
|
||||
line += 1;
|
||||
field.push('\n');
|
||||
} else {
|
||||
return Err((line, CsvError::LoneCarriageReturn));
|
||||
}
|
||||
}
|
||||
other => field.push(other),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let newline = match c {
|
||||
'\n' => true,
|
||||
'\r' if chars.peek() == Some(&'\n') => {
|
||||
chars.next();
|
||||
true
|
||||
}
|
||||
'\r' => return Err((line, CsvError::LoneCarriageReturn)),
|
||||
_ => false,
|
||||
};
|
||||
if newline {
|
||||
fields.push(std::mem::take(&mut field));
|
||||
finish_row(&mut rows, &mut fields, row_start_line)?;
|
||||
line += 1;
|
||||
row_start_line = line;
|
||||
row_bytes = 0;
|
||||
was_quoted = false;
|
||||
field_started = false;
|
||||
ended_with_newline = true;
|
||||
continue;
|
||||
}
|
||||
if c == dialect.delimiter {
|
||||
fields.push(std::mem::take(&mut field));
|
||||
was_quoted = false;
|
||||
field_started = false;
|
||||
continue;
|
||||
}
|
||||
if was_quoted {
|
||||
return Err((line, CsvError::TextAfterQuote));
|
||||
}
|
||||
if c == '"' {
|
||||
if field_started {
|
||||
return Err((line, CsvError::BareQuote));
|
||||
}
|
||||
in_quotes = true;
|
||||
field_started = true;
|
||||
continue;
|
||||
}
|
||||
field_started = true;
|
||||
field.push(c);
|
||||
}
|
||||
|
||||
if in_quotes {
|
||||
return Err((row_start_line, CsvError::UnterminatedQuote));
|
||||
}
|
||||
let pending = field_started || was_quoted || !fields.is_empty();
|
||||
if pending {
|
||||
if dialect.final_newline {
|
||||
return Err((row_start_line, CsvError::MissingFinalNewline));
|
||||
}
|
||||
fields.push(field);
|
||||
finish_row(&mut rows, &mut fields, row_start_line)?;
|
||||
} else if dialect.final_newline && !ended_with_newline && !text.is_empty() {
|
||||
return Err((row_start_line, CsvError::MissingFinalNewline));
|
||||
}
|
||||
Ok(rows)
|
||||
}
|
||||
Reference in New Issue
Block a user