Skip to main content

dtrees_rs/reader/
mod.rs

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