sqlite_loadable/
errors.rs

1//! Custom Error/Result for sqlite-loadable-rs APIs.
2use std::{
3    ffi::NulError,
4    fmt,
5    os::raw::{c_int, c_uint},
6    result,
7};
8
9/// A type alias for `Result<T, xxx::Error>`.
10pub type Result<T> = result::Result<T, Error>;
11
12/// Any error that occurs while creating or using a SQLite extension.
13#[derive(Debug, PartialEq, Eq)]
14pub struct Error(Box<ErrorKind>);
15
16/// Generic Error
17impl Error {
18    pub fn new(kind: ErrorKind) -> Error {
19        Error(Box::new(kind))
20    }
21    pub fn new_message(message: &str) -> Error {
22        Error(Box::new(ErrorKind::Message(message.to_owned())))
23    }
24
25    /// Return the specific type of this error.
26    pub fn kind(&self) -> &ErrorKind {
27        &self.0
28    }
29
30    /// Unwrap this error into its underlying type.
31    pub fn into_kind(self) -> ErrorKind {
32        *self.0
33    }
34
35    pub fn code(self) -> c_int {
36        1
37    }
38    pub fn code_extended(self) -> c_uint {
39        1
40    }
41    pub fn result_error_message(self) -> String {
42        match *self.0 {
43            ErrorKind::DefineScalarFunction(_) => "Error defining scalar function".to_owned(),
44            ErrorKind::CStringError(e) => format!("String Nul error: {}", e),
45            ErrorKind::CStringUtf8Error(_) => "utf8 err".to_owned(),
46            ErrorKind::Message(msg) => msg,
47            ErrorKind::TableFunction(_) => "table func error".to_owned(),
48        }
49    }
50}
51
52/// The specific type of an error.
53#[derive(Debug, PartialEq, Eq)]
54pub enum ErrorKind {
55    DefineScalarFunction(c_int),
56    CStringError(NulError),
57    CStringUtf8Error(std::str::Utf8Error),
58    TableFunction(c_int),
59    Message(String),
60}
61
62impl From<NulError> for Error {
63    fn from(err: NulError) -> Error {
64        Error::new(ErrorKind::CStringError(err))
65    }
66}
67impl From<std::str::Utf8Error> for Error {
68    fn from(err: std::str::Utf8Error) -> Error {
69        Error::new(ErrorKind::CStringUtf8Error(err))
70    }
71}
72
73impl From<&str> for Error {
74    fn from(err: &str) -> Error {
75        Error::new_message(err)
76    }
77}
78
79impl From<String> for Error {
80    fn from(err: String) -> Error {
81        Error::new_message(err.as_str())
82    }
83}
84
85impl ErrorKind {}
86
87impl fmt::Display for Error {
88    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
89        match *self.0 {
90            ErrorKind::DefineScalarFunction(ref err) => err.fmt(f),
91            _ => unreachable!(),
92        }
93    }
94}