leveldb/database/
error.rs

1//! The module defining custom leveldb error type.
2
3use libc::{c_void, c_char};
4use leveldb_sys::leveldb_free;
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: 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    pub unsafe fn new_from_char(message: *const c_char) -> Error {
25        use std::str::from_utf8;
26        use std::ffi::CStr;
27
28        let err_string = from_utf8(CStr::from_ptr(message).to_bytes()).unwrap().to_string();
29        leveldb_free(message as *mut c_void);
30        Error::new(err_string)
31    }
32}
33
34impl std::fmt::Display for Error {
35    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
36        write!(f, "LevelDB error: {}", self.message)
37    }
38}
39
40impl std::error::Error for Error {
41    fn description(&self) -> &str {
42        &self.message
43    }
44    fn cause(&self) -> Option<&dyn std::error::Error> {
45        None
46    }
47}