Skip to main content

external_buffered_stream/
error.rs

1use std::sync::PoisonError;
2
3#[derive(Debug)]
4pub enum Error {
5    Custom(Box<dyn std::error::Error + Send + Sync>),
6
7    #[cfg(feature = "bincode")]
8    EncodeError(bincode::error::EncodeError),
9    #[cfg(feature = "bincode")]
10    DecodeError(bincode::error::DecodeError),
11    #[cfg(feature = "sled")]
12    SledError(sled::Error),
13    #[cfg(feature = "sled")]
14    InvalidSledKeyFormat,
15
16    // Failed to accquire a mutex lock
17    MutexError,
18}
19
20impl core::fmt::Display for Error {
21    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
22        match self {
23            Error::Custom(inner) => write!(f, "Custom error: {}", inner),
24
25            #[cfg(feature = "bincode")]
26            Error::EncodeError(e) => write!(f, "Encode error: {}", e),
27            #[cfg(feature = "bincode")]
28            Error::DecodeError(e) => write!(f, "Decode error: {}", e),
29
30            #[cfg(feature = "sled")]
31            Error::SledError(e) => write!(f, "Sled error: {}", e),
32            #[cfg(feature = "sled")]
33            Error::InvalidSledKeyFormat => write!(f, "Invalid key format"),
34
35            Error::MutexError => write!(f, "Failed to acquire mutex lock"),
36        }
37    }
38}
39
40impl std::error::Error for Error {}
41
42pub fn make_custom_error(err: impl std::error::Error + Send + Sync + 'static) -> Error {
43    Error::Custom(Box::new(err))
44}
45
46#[cfg(test)]
47mod tests {
48    use super::make_custom_error;
49
50    #[test]
51    fn test_custom_error_display() {
52        let error = std::io::Error::new(std::io::ErrorKind::Other, "Test error");
53        let err = make_custom_error(error);
54        assert_eq!(format!("{}", err), "Custom error: Test error");
55    }
56}
57
58#[cfg(feature = "bincode")]
59impl From<bincode::error::EncodeError> for Error {
60    fn from(err: bincode::error::EncodeError) -> Self {
61        Error::EncodeError(err)
62    }
63}
64
65#[cfg(feature = "bincode")]
66impl From<bincode::error::DecodeError> for Error {
67    fn from(err: bincode::error::DecodeError) -> Self {
68        Error::DecodeError(err)
69    }
70}
71
72#[cfg(feature = "sled")]
73impl From<sled::Error> for Error {
74    fn from(err: sled::Error) -> Self {
75        Error::SledError(err)
76    }
77}
78
79impl<T> From<PoisonError<T>> for Error {
80    fn from(_: PoisonError<T>) -> Self {
81        Error::MutexError
82    }
83}