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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
use std::error;
use std::fmt;
use std::result;
use crate::vars::*;

/// Custom `Result` type.
pub type Result<T> = result::Result<T, Error>;

/// Custom `Error` type.
#[derive(Debug)]
pub enum Error {
    /// UnQLite error code map
    Custom(Custom),
    /// Any kind of other errors
    Other(Box<dyn error::Error>),
}

unsafe impl Send for Error {}
unsafe impl Sync for Error {}

impl From<Custom> for Error {
    fn from(err: Custom) -> Error {
        Error::Custom(err)
    }
}

impl From<::std::ffi::NulError> for Error {
    fn from(err: ::std::ffi::NulError) -> Error {
        Error::Other(Box::new(err))
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::Custom(ref c) => write!(f, "Custom error: {}", c),
            Error::Other(ref e) => write!(f, "Other error: {}", e),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Custom {
    kind: ErrorKind,
    raw: i32,
}

/// Error kinds from unqlite official documents.
#[allow(non_camel_case_types)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ErrorKind {
    /// Successful result
    OK = 0,
    /// Out of memory
    NOMEM,
    /// Another thread have released this instance
    ABORT,
    /// IO error
    IOERR,
    /// Corrupt pointer
    CORRUPT,
    /// Forbidden Operation
    LOCKED,
    /// The database file is locked
    BUSY,
    /// Operation done, not an error
    DONE,
    /// Permission error
    PERM,
    /// Method not implemented
    NOTIMPLEMENTED,
    /// No such record
    NOTFOUND,
    /// No such method
    NOOP,
    /// Invalid parameter
    INVALID,
    /// End Of Input
    EOF,
    /// Unknown configuration option
    UNKNOWN,
    /// Database limit reached
    LIMIT,
    /// Record exists
    EXISTS,
    /// Empty record
    EMPTY,
    /// Compilation error
    COMPILE_ERR,
    /// Virtual machine error
    VM_ERR,
    /// Full database unlikely
    FULL,
    /// Unable to open the database file
    CANTOPEN,
    /// Read only Key/Value storage engine
    READ_ONLY,
    /// Locking protocol error
    LOCKERR,
    #[doc(hidden)]
    __Nonexhaustive,
}

impl From<i32> for ErrorKind {
    fn from(code: i32) -> ErrorKind {
        match code {
            UNQLITE_OK => ErrorKind::OK,
            UNQLITE_NOMEM => ErrorKind::NOMEM,
            UNQLITE_ABORT => ErrorKind::ABORT,
            UNQLITE_IOERR => ErrorKind::IOERR,
            UNQLITE_CORRUPT => ErrorKind::CORRUPT,
            UNQLITE_LOCKED => ErrorKind::LOCKED,
            UNQLITE_BUSY => ErrorKind::BUSY,
            UNQLITE_DONE => ErrorKind::DONE,
            UNQLITE_PERM => ErrorKind::PERM,
            UNQLITE_NOTIMPLEMENTED => ErrorKind::NOTIMPLEMENTED,
            UNQLITE_NOTFOUND => ErrorKind::NOTFOUND,
            UNQLITE_NOOP => ErrorKind::NOOP,
            UNQLITE_INVALID => ErrorKind::INVALID,
            UNQLITE_EOF => ErrorKind::EOF,
            UNQLITE_UNKNOWN => ErrorKind::UNKNOWN,
            UNQLITE_LIMIT => ErrorKind::LIMIT,
            UNQLITE_EXISTS => ErrorKind::EXISTS,
            UNQLITE_EMPTY => ErrorKind::EMPTY,
            UNQLITE_COMPILE_ERR => ErrorKind::COMPILE_ERR,
            UNQLITE_VM_ERR => ErrorKind::VM_ERR,
            UNQLITE_FULL => ErrorKind::FULL,
            UNQLITE_CANTOPEN => ErrorKind::CANTOPEN,
            UNQLITE_READ_ONLY => ErrorKind::READ_ONLY,
            UNQLITE_LOCKERR => ErrorKind::LOCKERR,
            _ => ErrorKind::__Nonexhaustive,
        }
    }
}

/// A wrap trait for unqlite FFI error code to Rust-y `Result`.
///
/// To populate better visual style, we add a `Wrap` trait to original
/// unqlite return value. The `Wrap` trait has only one method `drop` -
/// which is used to wrap the unqlite return value to Rust `Result`.
/// So the FFI-related methods should just use `.wrap()` like this:
///
/// ```ignore
/// unsafe {
///     unqlite_open(...).wrap()  // Now it is Result<(), Error>
/// }
/// ```
///
/// This should be nice for functional programming style.
pub(crate) trait Wrap {
    fn wrap(self) -> Result<()>;
}

impl Wrap for i32 {
    fn wrap(self) -> Result<()> {
        Custom::from_raw(self)
    }
}

impl Custom {
    pub fn from_raw(result: i32) -> Result<()> {
        let kind = ErrorKind::from(result);
        match kind {
            ErrorKind::OK => Ok(()),
            _ => Err(Custom {
                kind: kind,
                raw: result,
            }
            .into()),
        }
    }

    pub fn error(&self) -> &str {
        match self.kind {
            ErrorKind::NOMEM => "Out of memory",
            ErrorKind::ABORT => "Another thread have released this instance",
            ErrorKind::IOERR => "IO error",
            ErrorKind::CORRUPT => "Corrupt pointer",
            ErrorKind::LOCKED => "Forbidden Operation",
            ErrorKind::BUSY => "The database file is locked",
            ErrorKind::DONE => "Operation done",
            ErrorKind::PERM => "Permission error",
            ErrorKind::NOTIMPLEMENTED => {
                "Method not implemented by the underlying Key/Value storage engine"
            }
            ErrorKind::NOTFOUND => "No such record",
            ErrorKind::NOOP => "No such method",
            ErrorKind::INVALID => "Invalid parameter",
            ErrorKind::EOF => "End Of Input",
            ErrorKind::UNKNOWN => "Unknown configuration option",
            ErrorKind::LIMIT => "Database limit reached",
            ErrorKind::EXISTS => "Record exists",
            ErrorKind::EMPTY => "Empty record",
            ErrorKind::COMPILE_ERR => "Compilation error",
            ErrorKind::VM_ERR => " Virtual machine error",
            ErrorKind::FULL => "Full database (unlikely)",
            ErrorKind::CANTOPEN => "Unable to open the database file",
            ErrorKind::READ_ONLY => "Read only Key/Value storage engine",
            ErrorKind::LOCKERR => "Locking protocol error",
            ErrorKind::OK => unreachable!(),
            ErrorKind::__Nonexhaustive => unreachable!(),
        }
    }
}

impl error::Error for Custom {
    fn description(&self) -> &str {
        self.error()
    }
}

impl fmt::Display for Custom {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Custom error: {}", self.error())
    }
}