Skip to main content

contree/reader/
mod.rs

1pub mod data_reader;
2
3use std::error::Error;
4use std::fmt;
5use std::io::Error as IoError;
6use std::path::Path;
7
8/// Column delimiter of a text dataset.
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub enum DataFormat {
11    /// Comma separated.
12    Csv,
13    /// Tab separated.
14    Tsv,
15    /// Separated by any run of whitespace.
16    Space,
17    /// Separated by the given character.
18    Custom(char),
19}
20
21impl DataFormat {
22    fn delimiter(&self) -> char {
23        match self {
24            DataFormat::Csv => ',',
25            DataFormat::Tsv => '\t',
26            DataFormat::Space => ' ',
27            DataFormat::Custom(c) => *c,
28        }
29    }
30
31    /// The format implied by a file extension; whitespace when unknown.
32    pub fn from_extension(path: &Path) -> Self {
33        match path.extension().and_then(|e| e.to_str()) {
34            Some("csv") => DataFormat::Csv,
35            Some("tsv") => DataFormat::Tsv,
36            Some("txt") | Some("data") => DataFormat::Space,
37            _ => DataFormat::Space,
38        }
39    }
40}
41
42/// Why a dataset file could not be read.
43#[derive(Debug)]
44pub enum DataReaderError {
45    /// The file could not be read.
46    Io(IoError),
47    /// A value is not a number, or a label is not a non-negative integer.
48    Parse(String),
49    /// The file's shape is wrong: ragged rows, no rows, or invalid labels.
50    Format(String),
51}
52
53impl fmt::Display for DataReaderError {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        match self {
56            DataReaderError::Io(err) => write!(f, "I/O error: {}", err),
57            DataReaderError::Parse(msg) => write!(f, "Parse error: {}", msg),
58            DataReaderError::Format(msg) => write!(f, "Format error: {}", msg),
59        }
60    }
61}
62
63impl Error for DataReaderError {}
64
65impl From<IoError> for DataReaderError {
66    fn from(err: IoError) -> Self {
67        DataReaderError::Io(err)
68    }
69}