1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use std::error::Error as StdError;
use std::fmt::{self, Display};
use crate::database::Database;
use crate::types::HasSqlType;
pub enum DecodeError {
UnexpectedNull,
Message(Box<dyn Display + Send + Sync>),
Other(Box<dyn StdError + Send + Sync>),
}
pub trait Decode<DB>: Sized
where
DB: Database + ?Sized,
{
fn decode(raw: &[u8]) -> Result<Self, DecodeError>;
fn decode_null() -> Result<Self, DecodeError> {
Err(DecodeError::UnexpectedNull)
}
fn decode_nullable(raw: Option<&[u8]>) -> Result<Self, DecodeError> {
if let Some(raw) = raw {
Self::decode(raw)
} else {
Self::decode_null()
}
}
}
impl<T, DB> Decode<DB> for Option<T>
where
DB: Database + HasSqlType<T>,
T: Decode<DB>,
{
fn decode(buf: &[u8]) -> Result<Self, DecodeError> {
T::decode(buf).map(Some)
}
fn decode_null() -> Result<Self, DecodeError> {
Ok(None)
}
}
impl fmt::Debug for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("DecodeError(")?;
match self {
DecodeError::UnexpectedNull => write!(f, "unexpected null for non-null column")?,
DecodeError::Message(err) => write!(f, "{}", err)?,
DecodeError::Other(err) => write!(f, "{:?}", err)?,
}
f.write_str(")")
}
}
impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
DecodeError::UnexpectedNull => f.write_str("unexpected null for non-null column"),
DecodeError::Message(err) => write!(f, "{}", err),
DecodeError::Other(err) => write!(f, "{}", err),
}
}
}
impl<E> From<E> for DecodeError
where
E: StdError + Send + Sync + 'static,
{
fn from(err: E) -> DecodeError {
DecodeError::Other(Box::new(err))
}
}