Skip to main content

novel_segment/
error.rs

1//! Error type.
2
3use std::fmt;
4use std::io;
5use std::path::PathBuf;
6
7/// Library error.
8#[derive(Debug)]
9pub enum Error {
10    Io(io::Error),
11    DictNotFound { name: String },
12    InvalidDictLine { path: PathBuf, line: String },
13    InvalidInput(String),
14}
15
16impl fmt::Display for Error {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        match self {
19            Error::Io(e) => write!(f, "io error: {e}"),
20            Error::DictNotFound { name } => write!(f, "cannot find dict file `{name}`"),
21            Error::InvalidDictLine { path, line } => {
22                write!(f, "invalid dict line in {}: {line}", path.display())
23            }
24            Error::InvalidInput(s) => write!(f, "invalid input: {s}"),
25        }
26    }
27}
28
29impl std::error::Error for Error {
30    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
31        match self {
32            Error::Io(e) => Some(e),
33            _ => None,
34        }
35    }
36}
37
38impl From<io::Error> for Error {
39    fn from(value: io::Error) -> Self {
40        Error::Io(value)
41    }
42}
43
44pub type Result<T> = std::result::Result<T, Error>;