pancake_db_core/
errors.rs1use std::array::TryFromSliceError;
2use std::error::Error;
3use std::fmt;
4use std::fmt::{Display, Formatter};
5use std::string::FromUtf8Error;
6
7use q_compress::errors::{QCompressError, ErrorKind as QCompressErrorKind};
8
9pub trait OtherUpcastable: Error {}
10impl OtherUpcastable for FromUtf8Error {}
11impl OtherUpcastable for TryFromSliceError {}
12impl OtherUpcastable for std::io::Error {}
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum CoreErrorKind {
16 Invalid,
17 Other,
18 Corrupt,
19}
20
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct CoreError {
23 message: String,
24 pub kind: CoreErrorKind,
25}
26
27impl Error for CoreError {}
28
29impl CoreError {
30 fn create(explanation: &str, kind: CoreErrorKind) -> CoreError {
31 CoreError {
32 message: explanation.to_string(),
33 kind,
34 }
35 }
36
37 pub fn invalid(explanation: &str) -> CoreError {
38 CoreError::create(explanation, CoreErrorKind::Invalid)
39 }
40
41 pub fn corrupt(explanation: &str) -> CoreError {
42 CoreError::create(explanation, CoreErrorKind::Corrupt)
43 }
44}
45
46impl Display for CoreError {
47 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
48 match &self.kind {
49 CoreErrorKind::Invalid => write!(
50 f,
51 "invalid input; {}",
52 self.message
53 ),
54 CoreErrorKind::Other => write!(
55 f,
56 "{}",
57 self.message
58 ),
59 CoreErrorKind::Corrupt => write!(
60 f,
61 "corrupt data or incorrect decoder/decompressor; {}",
62 self.message
63 )
64 }
65 }
66}
67
68impl<T> From<T> for CoreError where T: OtherUpcastable {
69 fn from(e: T) -> CoreError {
70 CoreError {
71 message: e.to_string(),
72 kind: CoreErrorKind::Other,
73 }
74 }
75}
76
77impl From<QCompressError> for CoreError {
78 fn from(e: QCompressError) -> CoreError {
79 let kind = match e.kind {
80 QCompressErrorKind::Compatibility => CoreErrorKind::Other,
81 QCompressErrorKind::Corruption => CoreErrorKind::Corrupt,
82 QCompressErrorKind::InsufficientData => CoreErrorKind::Corrupt,
83 QCompressErrorKind::InvalidArgument => CoreErrorKind::Invalid,
84 };
85 CoreError {
86 message: e.to_string(),
87 kind,
88 }
89 }
90}
91
92pub type CoreResult<T> = Result<T, CoreError>;