ptnet_core/
error.rs

1/*!
2Provides the crate's Error and Result types as well as helper
3functions.
4
5 */
6
7use std::fmt::{Debug, Display};
8
9// ------------------------------------------------------------------------------------------------
10// Public Types
11// ------------------------------------------------------------------------------------------------
12
13///
14/// The Error type for this crate.
15///
16#[derive(Debug)]
17pub enum Error {
18    /// An error was signaled by the standard library I/O functions.
19    IoError {
20        source: std::io::Error,
21    },
22    FromUtf8Error {
23        source: std::string::FromUtf8Error,
24    },
25}
26
27///
28/// A Result type that specifically uses this crate's Error.
29///
30pub type Result<T> = std::result::Result<Error, T>;
31
32// ------------------------------------------------------------------------------------------------
33// Public Functions
34// ------------------------------------------------------------------------------------------------
35
36/// Construct an Error from the provided source.
37#[inline]
38pub fn io_error(source: std::io::Error) -> Error {
39    Error::IoError { source }
40}
41
42/// Construct an Error from the provided source.
43#[inline]
44pub fn from_utf8_error(source: std::string::FromUtf8Error) -> Error {
45    Error::FromUtf8Error { source }
46}
47
48// ------------------------------------------------------------------------------------------------
49// Implementations
50// ------------------------------------------------------------------------------------------------
51
52impl Display for Error {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        write!(
55            f,
56            "{}",
57            match self {
58                Error::IoError { source } => format!("An I/O error occurred; source: {}", source),
59                Error::FromUtf8Error { source } => format!(
60                    "An error occurred making a string from UTF-8 bytes; source: {}",
61                    source
62                ),
63            }
64        )
65    }
66}
67
68impl std::error::Error for Error {
69    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
70        #[allow(unreachable_patterns)]
71        match self {
72            Error::IoError { source } => Some(source),
73            Error::FromUtf8Error { source } => Some(source),
74            _ => None,
75        }
76    }
77}
78
79impl From<std::io::Error> for Error {
80    fn from(source: std::io::Error) -> Self {
81        io_error(source)
82    }
83}
84
85impl From<std::string::FromUtf8Error> for Error {
86    fn from(source: std::string::FromUtf8Error) -> Self {
87        from_utf8_error(source)
88    }
89}