Skip to main content

leveldb/database/
error.rs

1//! The module defines LevelDB Error type.
2
3use crate::binding::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    pub 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    /// This method is `unsafe` because the pointer must be valid and point to heap.
24    /// The pointer will be passed to `free`!
25    ///
26    /// # Safety
27    ///
28    /// The caller must ensure that:
29    /// - `message` is a valid pointer to a null-terminated C string
30    /// - The C string is valid UTF-8
31    /// - The memory pointed to by `message` was allocated by LevelDB and can be safely freed
32    pub unsafe fn new_from_char(message: *const c_char) -> Error {
33        use std::ffi::CStr;
34        use std::str::from_utf8;
35
36        unsafe {
37            let err_string = from_utf8(CStr::from_ptr(message).to_bytes())
38                .unwrap()
39                .to_string();
40            leveldb_free(message as *mut c_void);
41            Error::new(err_string)
42        }
43    }
44}
45
46impl std::fmt::Display for Error {
47    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
48        write!(f, "LevelDB error: {}", self.message)
49    }
50}
51
52impl std::error::Error for Error {
53    fn description(&self) -> &str {
54        &self.message
55    }
56    fn cause(&self) -> Option<&dyn std::error::Error> {
57        None
58    }
59}