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
#![doc(html_root_url = "https://andoriyu.github.io/blunder.rs/")]
#[macro_use] extern crate enum_primitive;
extern crate num;
extern crate errno;
use std::error::Error as StdError;
use std::fmt;
use std::result::Result;
use std::ops::Deref;
use std::convert::From;
mod bsd;
pub use bsd::*;
#[macro_export]
macro_rules! fail {
($expr:expr) => (
return Result::Err(::std::convert::From::from($expr));
)
}
#[macro_export]
macro_rules! maybe_fail {
($expr:expr) => ({
if let Some(err) = $expr {
fail!(err)
}
})
}
#[derive(Debug, PartialEq)]
pub struct Blunder<T: StdError> {
kind: T,
detail: Option<String>
}
impl <T: StdError> Deref for Blunder<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
&self.kind
}
}
impl <T: StdError> Blunder<T> {
pub fn detail(&self) -> Option<String> {
self.detail.clone()
}
}
impl <T: StdError> StdError for Blunder<T> {
fn description(&self) -> &str {
self.kind.description()
}
fn cause(&self) -> Option<&StdError> {
self.kind.cause()
}
}
impl <T: StdError> fmt::Display for Blunder<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,"{}", self.description())
}
}
impl <E: StdError> From<E> for Blunder<E> {
fn from(err: E) -> Blunder<E> {
Blunder { kind: err, detail: None }
}
}
#[test]
fn it_works() {
#[derive(Debug, PartialEq)]
enum Wat {
One,
};
impl fmt::Display for Wat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,"{}", "wat")
}
}
impl StdError for Wat {
fn description(&self) -> &str {
"wat"
}
fn cause(&self) -> Option<&StdError> {
None
}
}
let error: Blunder<Wat> = Blunder { kind: Wat::One, detail: None };
assert_eq!(error.cause().is_some(), false);
assert_eq!(error.description(), "wat");
assert_eq!(*error, Wat::One);
fn goto_fail() -> Result<(), Blunder<Wat>> {
fail!(Wat::One)
};
let fail = Blunder { kind: Wat::One, detail: None };
if let Err(err) = goto_fail() {
assert_eq!(err, fail);
} else {
panic!();
}
}