Files

113 lines
4.4 KiB
Rust

//! Statement parsing for Fiscus Domi. Hostile input: strict, typed errors, never a partial row.
//!
//! **Only banks with real samples in `fixtures/` are supported.** No bank format is ever written from memory
//! or documentation alone. Until a bank's redacted samples arrive, [`parse`] returns
//! [`ParseError::UnsupportedFormat`] for it, and the app says so. What this crate already holds is the
//! strict ground every bank parser stands on: [`csv`], [`field`] and [`decode`].
pub mod csv;
pub mod field;
use fiscus_ledger::import::StatementLine;
use serde::{Deserialize, Serialize};
/// A statement file larger than this is refused before it is read.
pub const MAX_FILE: usize = 16 * 1024 * 1024;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Statement {
pub bank: String,
pub account: String,
pub lines: Vec<StatementLine>,
}
/// A supported bank: which formats it parses, built from which samples.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub struct Bank {
pub id: &'static str,
pub name: &'static str,
pub formats: &'static [&'static str],
}
/// Every bank with a parser. Empty until real samples arrive (see the crate docs).
pub const BANKS: &[Bank] = &[];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Encoding {
/// Strict UTF-8; a leading BOM is dropped.
Utf8,
/// Windows-1250 (Central European), which many Czech banks still export.
Windows1250,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error, Serialize)]
pub enum ParseError {
#[error("the file is empty")]
Empty,
#[error("the file is {size} bytes; the limit is {MAX_FILE}")]
TooLarge { size: usize },
#[error("the file is not valid text in the expected encoding (byte {offset})")]
Encoding { offset: usize },
#[error("this is not a statement format Fiscus knows; no bank is supported until its real samples are added")]
UnsupportedFormat,
#[error("line {line}: {kind}")]
Csv { line: usize, kind: csv::CsvError },
#[error("line {line}, {column}: {error}")]
Field { line: usize, column: String, error: field::FieldError },
#[error("the header is not the one this bank writes")]
Header,
}
/// Decodes a whole file. Strict: invalid UTF-8 is an error, never replaced; NUL bytes are refused.
pub fn decode(bytes: &[u8], encoding: Encoding) -> Result<String, ParseError> {
if bytes.is_empty() {
return Err(ParseError::Empty);
}
if bytes.len() > MAX_FILE {
return Err(ParseError::TooLarge { size: bytes.len() });
}
if let Some(offset) = bytes.iter().position(|b| *b == 0) {
return Err(ParseError::Encoding { offset });
}
let (text, bom) = match encoding {
Encoding::Utf8 => {
let body = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
let bom = bytes.len() - body.len();
let text = std::str::from_utf8(body).map_err(|e| ParseError::Encoding { offset: e.valid_up_to() + bom })?;
(text.to_owned(), bom)
}
Encoding::Windows1250 => {
// The WHATWG table maps Windows-1250's five unassigned bytes to C1 controls, refused below.
let (text, _, had_errors) = encoding_rs::WINDOWS_1250.decode(bytes);
if had_errors {
return Err(ParseError::Encoding { offset: 0 });
}
(text.into_owned(), 0)
}
};
// A statement is text: no control characters but tab and line breaks. Report the byte where it starts.
if let Some((i, _)) = text.char_indices().find(|(_, c)| c.is_control() && !matches!(c, '\t' | '\r' | '\n')) {
let offset = match encoding {
Encoding::Utf8 => i + bom,
Encoding::Windows1250 => text[..i].chars().count(), // one byte per character
};
return Err(ParseError::Encoding { offset });
}
Ok(text)
}
/// Parses a statement file with the bank parser that recognises it.
///
/// No bank parser exists yet, so after the size checks every file is `UnsupportedFormat`.
pub fn parse(bytes: &[u8]) -> Result<Statement, ParseError> {
if bytes.is_empty() {
return Err(ParseError::Empty);
}
if bytes.len() > MAX_FILE {
return Err(ParseError::TooLarge { size: bytes.len() });
}
// Each bank in BANKS gets a `detect(bytes) -> bool` and a `parse(bytes)` here, in its own module,
// with its fixtures under fixtures/<bank>/.
Err(ParseError::UnsupportedFormat)
}