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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use std::fmt::{self, Display, Debug, Formatter};
use std::error::Error;
use super::{MsgPack};
pub struct ConversionError {
pub original: MsgPack,
pub attempted: &'static str,
}
impl Display for ConversionError {
fn fmt (&self, f: &mut Formatter) -> fmt::Result {
let original_type = match self.original {
MsgPack::Nil => "nil",
MsgPack::Int(_) => "int",
MsgPack::Uint(_) => "uint",
MsgPack::Float(_) => "float",
MsgPack::Boolean(_) => "boolean",
MsgPack::String(_) => "string",
MsgPack::Binary(_) => "binary",
MsgPack::Array(_) => "array",
MsgPack::Map(_) => "map",
MsgPack::Extension(_) => "extension",
};
write!(f, "MsgPack conversion error: cannot use {} as {}", original_type, self.attempted)
}
}
impl Debug for ConversionError {
fn fmt (&self, f: &mut Formatter) -> fmt::Result {
let original_type = match self.original {
MsgPack::Nil => "nil",
MsgPack::Int(_) => "int",
MsgPack::Uint(_) => "uint",
MsgPack::Float(_) => "float",
MsgPack::Boolean(_) => "boolean",
MsgPack::String(_) => "string",
MsgPack::Binary(_) => "binary",
MsgPack::Array(_) => "array",
MsgPack::Map(_) => "map",
MsgPack::Extension(_) => "extension",
};
write!(f, "MsgPack conversion error: cannot use {} as {} (original value: {:?})", original_type, self.attempted, self.original)
}
}
impl Error for ConversionError {}
impl ConversionError {
pub fn recover (self) -> MsgPack {
self.original
}
}
pub struct ParseError {
pub byte: usize
}
impl Display for ParseError {
fn fmt (&self, f: &mut Formatter) -> fmt::Result {
write!(f, "MsgPack parse error at byte {}", self.byte)
}
}
impl Debug for ParseError {
fn fmt (&self, f: &mut Formatter) -> fmt::Result {
write!(f, "MsgPack parse error at byte {}", self.byte)
}
}
impl Error for ParseError {}
impl ParseError {
pub fn offset (&self, value: usize) -> ParseError {
ParseError { byte: self.byte + value }
}
pub fn offset_result <T> (result: Result<T, ParseError>, value: usize) -> Result<T, ParseError> {
result.map_err(|err| err.offset(value))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn conversion_error () {
let error = ConversionError { original: MsgPack::Float(4.2), attempted: "int" };
let error_message = format!("{}", error);
assert_eq!(error_message, "MsgPack conversion error: cannot use float as int");
let recovered = error.recover();
assert!(recovered.is_float());
assert_eq!(recovered.as_float().unwrap(), 4.2);
}
#[test]
fn parse_error () {
let error = ParseError { byte: 42 };
let error_message = format!("{}", error);
assert_eq!(error_message, "MsgPack parse error at byte 42");
}
}