leveldb_minimal/database/
error.rs

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