Skip to main content

lab_rs/
error.rs

1//! error types for parsing `.lab` files
2
3use std::fmt;
4
5/// an error produced while parsing a `.lab` file
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct ParseError {
8    /// 1-indexed line number the error occurred on
9    pub line: usize,
10    /// what went wrong on that line
11    pub kind: ParseErrorKind,
12}
13
14/// the specific kind of parse failure
15#[derive(Debug, Clone, PartialEq, Eq)]
16#[non_exhaustive]
17pub enum ParseErrorKind {
18    /// a field that looked like a time could not be parsed as an integer
19    InvalidTime(String),
20    /// the start time is greater than the end time
21    StartAfterEnd {
22        /// parsed start time, in 100ns units
23        start: u64,
24        /// parsed end time, in 100ns units
25        end: u64,
26    },
27}
28
29impl fmt::Display for ParseError {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        write!(f, "line {}: ", self.line)?;
32        match &self.kind {
33            ParseErrorKind::InvalidTime(s) => write!(f, "invalid time value `{s}`"),
34            ParseErrorKind::StartAfterEnd { start, end } => {
35                write!(f, "start time {start} is after end time {end}")
36            }
37        }
38    }
39}
40
41impl std::error::Error for ParseError {}
42
43/// an error produced while reading a .lab from a reader or path
44#[derive(Debug)]
45#[non_exhaustive]
46pub enum ReadError {
47    /// an io error occurred while reading
48    Io(std::io::Error),
49    /// the contents were read but could not be parsed
50    Parse(ParseError),
51}
52
53impl fmt::Display for ReadError {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        match self {
56            ReadError::Io(e) => write!(f, "i/o error: {e}"),
57            ReadError::Parse(e) => write!(f, "parse error: {e}"),
58        }
59    }
60}
61
62impl std::error::Error for ReadError {
63    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
64        match self {
65            ReadError::Io(e) => Some(e),
66            ReadError::Parse(e) => Some(e),
67        }
68    }
69}
70
71impl From<std::io::Error> for ReadError {
72    fn from(e: std::io::Error) -> Self {
73        ReadError::Io(e)
74    }
75}
76
77impl From<ParseError> for ReadError {
78    fn from(e: ParseError) -> Self {
79        ReadError::Parse(e)
80    }
81}