souvenir_core/
error.rs

1use std::fmt::{Display, Formatter};
2
3/// A convenience type for [`Result<T, Error>`](core::result::Result)
4pub type Result<T> = std::result::Result<T, Error>;
5
6/// An enum providing all possible errors generated by this crate.
7#[derive(Debug, Hash, PartialEq, Eq)]
8pub enum Error {
9    /// Thrown when a string with invalid data is attempted to be parsed into
10    /// an identifier.
11    InvalidData,
12
13    /// The provided prefix contains invalid characters or is the wrong length.
14    InvalidPrefix,
15
16    /// The provided input is in an invalid format.
17    InvalidFormat,
18
19    /// Thrown when a string containing an invalid character is attempted to
20    /// be pasrsed into an identifier.
21    InvalidChar { found: char },
22
23    /// Thrown when a string of invalid length is attempted to be parsed into
24    /// an identifier.
25    InvalidLength { expected: usize, found: usize },
26}
27
28impl Error {
29    /// Get the error message
30    pub fn message(&self) -> String {
31        match self {
32            Self::InvalidData => "input contains invalid data".to_owned(),
33            Self::InvalidPrefix => "prefix is not valid".to_owned(),
34            Self::InvalidFormat => "format is not correct".to_owned(),
35            Self::InvalidChar { found } => format!("invalid character: {}", found),
36            Self::InvalidLength { expected, found } => format!(
37                "input is the wrong length: expected {} but found {}",
38                expected, found
39            ),
40        }
41    }
42}
43
44impl Display for Error {
45    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
46        write!(f, "{}", self.message())
47    }
48}
49
50impl std::error::Error for Error {}