dryoc/
error.rs

1use std::fmt::{Display, Formatter};
2
3/// Errors generated by Dryoc.
4///
5/// Most errors just contain a message as to what went wrong.
6/// I/O errors are forwarded through.
7#[derive(Debug)]
8pub enum Error {
9    /// An internal Dryoc error.
10    Message(String),
11
12    /// Some I/O problem occurred.
13    Io(std::io::Error),
14
15    /// Unable to convert data from slice.
16    FromSlice(core::array::TryFromSliceError),
17}
18
19impl From<String> for Error {
20    fn from(message: String) -> Self {
21        Error::Message(message)
22    }
23}
24
25impl From<&str> for Error {
26    fn from(message: &str) -> Self {
27        Error::Message(message.into())
28    }
29}
30
31impl From<std::io::Error> for Error {
32    fn from(error: std::io::Error) -> Self {
33        Error::Io(error)
34    }
35}
36
37impl From<core::array::TryFromSliceError> for Error {
38    fn from(error: core::array::TryFromSliceError) -> Self {
39        Error::FromSlice(error)
40    }
41}
42
43impl Display for Error {
44    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
45        match self {
46            Error::Message(message) => f.write_str(message),
47            Error::Io(err) => write!(f, "I/O error: {}", err),
48            Error::FromSlice(err) => write!(f, "From slice error: {}", err),
49        }
50    }
51}
52
53impl std::error::Error for Error {
54    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
55        match self {
56            Error::Message(_) => None,
57            Error::Io(err) => Some(err),
58            Error::FromSlice(err) => Some(err),
59        }
60    }
61}
62
63macro_rules! dryoc_error {
64    ($msg:expr) => {{ crate::error::Error::from(format!("{}, from {}:{}", $msg, file!(), line!())) }};
65}
66
67macro_rules! validate {
68    ($min:expr, $max:expr, $value:expr, $name:literal) => {
69        if $value < $min {
70            return Err(dryoc_error!(format!(
71                "{} value of {} less than minimum {}",
72                $name, $value, $min
73            )));
74        } else if $value > $max {
75            return Err(dryoc_error!(format!(
76                "{} value of {} greater than minimum {}",
77                $name, $value, $max
78            )));
79        }
80    };
81}