1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
use std::{error::Error as StdError, fmt, sync::PoisonError};

pub(crate) type Result<T> = std::result::Result<T, Error>;

/// Possible database errors
#[derive(Debug)]
pub enum Error {
    /// Tried to create a bucket that already exists
    BucketExists,
    /// Tried to get a bucket that does not exist
    BucketMissing,
    /// Tried to delete a key / value pair that does not exist
    KeyValueMissing,
    /// Tried to get a bucket but found a key / value pair instead, or tried to put a key / value pair but found an existing bucket
    IncompatibleValue,
    /// Tried to write to a read only transaction
    ReadOnlyTx,
    /// Wrapper around a [`std::io::Error`] that occurred while opening the file or writing to it
    Io(std::io::Error),
    /// Wrapper around a [`PoisonError`]
    Sync(&'static str),
    /// Error returned when the DB is found to be in an invalid state
    InvalidDB(String),
    /// Errors that can occur during allocation
    Alloc(std::alloc::LayoutError),
}

impl StdError for Error {}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::BucketExists => write!(f, "Bucket already exists"),
            Error::BucketMissing => write!(f, "Bucket does not exist"),
            Error::KeyValueMissing => write!(f, "Key / Value pair does not exist"),
            Error::IncompatibleValue => write!(f, "Value not compatible"),
            Error::ReadOnlyTx => write!(f, "Cannot write in a read-only transaction"),
            Error::Io(e) => write!(f, "IO Error: {}", e),
            Error::Sync(s) => write!(f, "Sync Error: {}", s),
            Error::InvalidDB(s) => write!(f, "Invalid DB: {}", s),
            Error::Alloc(e) => write!(f, "Allocation error: {}", e),
        }
    }
}

impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Error {
        Error::Io(err)
    }
}

impl From<std::alloc::LayoutError> for Error {
    fn from(err: std::alloc::LayoutError) -> Error {
        Error::Alloc(err)
    }
}

impl<T> From<PoisonError<T>> for Error {
    fn from(_: PoisonError<T>) -> Error {
        Error::Sync("lock poisoned")
    }
}

impl PartialEq for Error {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Error::BucketExists, Error::BucketExists) => true,
            (Error::BucketMissing, Error::BucketMissing) => true,
            (Error::KeyValueMissing, Error::KeyValueMissing) => true,
            (Error::IncompatibleValue, Error::IncompatibleValue) => true,
            (Error::ReadOnlyTx, Error::ReadOnlyTx) => true,
            (Error::Sync(s1), Error::Sync(s2)) => s1 == s2,
            (Error::InvalidDB(s1), Error::InvalidDB(s2)) => s1 == s2,
            _ => false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_display() {
        assert_eq!(format!("{}", Error::BucketExists), "Bucket already exists");
        assert_eq!(format!("{}", Error::BucketMissing), "Bucket does not exist");
        assert_eq!(
            format!("{}", Error::KeyValueMissing),
            "Key / Value pair does not exist"
        );
        assert_eq!(
            format!("{}", Error::IncompatibleValue),
            "Value not compatible"
        );
        assert_eq!(
            format!("{}", Error::ReadOnlyTx),
            "Cannot write in a read-only transaction"
        );

        assert_eq!(
            format!(
                "{}",
                Error::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "oopsie"))
            ),
            "IO Error: oopsie"
        );
        assert_eq!(format!("{}", Error::Sync("abc")), "Sync Error: abc");
        assert_eq!(
            format!("{}", Error::InvalidDB(String::from("uh oh"))),
            "Invalid DB: uh oh"
        );
    }
}