leveldb/database/
error.rs

1//! The module defining custom leveldb error type.
2
3use cruzbit_leveldb_sys::leveldb_free;
4use libc::{c_char, c_void};
5use std;
6
7/// A leveldb error, just containing the error string
8/// provided by leveldb.
9#[derive(Debug)]
10pub struct Error {
11    message: String,
12}
13
14impl Error {
15    /// create a new Error, using the String provided
16    pub fn new(message: String) -> Error {
17        Error { message }
18    }
19
20    /// create an error from a c-string buffer.
21    ///
22    /// This method is `unsafe` because the pointer must be valid and point to heap.
23    /// The pointer will be passed to `free`!
24    ///
25    /// # Safety
26    pub unsafe fn new_from_char(message: *const c_char) -> Error {
27        use std::ffi::CStr;
28        use std::str::from_utf8;
29
30        let err_string = from_utf8(CStr::from_ptr(message).to_bytes())
31            .unwrap()
32            .to_string();
33        leveldb_free(message as *mut c_void);
34        Error::new(err_string)
35    }
36}
37
38impl std::fmt::Display for Error {
39    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
40        write!(f, "LevelDB error: {}", self.message)
41    }
42}
43
44impl std::error::Error for Error {
45    fn description(&self) -> &str {
46        &self.message
47    }
48    fn cause(&self) -> Option<&dyn std::error::Error> {
49        None
50    }
51}