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
use std::ffi::CStr;
use std::error;
use std::fmt;
use std::str;
use translate::*;
use ffi as glib_ffi;
glib_wrapper! {
pub struct Error(Boxed<glib_ffi::GError>);
match fn {
copy => |ptr| glib_ffi::g_error_copy(ptr),
free => |ptr| glib_ffi::g_error_free(ptr),
}
}
impl Error {
pub fn new<T: ErrorDomain>(error: T, message: &str) -> Error {
unsafe {
from_glib_full(
glib_ffi::g_error_new_literal(T::domain(), error.code(), message.to_glib_none().0))
}
}
pub fn is<T: ErrorDomain>(&self) -> bool {
self.0.domain == T::domain()
}
pub fn kind<T: ErrorDomain>(&self) -> Option<T> {
if self.0.domain == T::domain() {
T::from(self.0.code)
}
else {
None
}
}
fn message(&self) -> &str {
unsafe {
let bytes = CStr::from_ptr(self.0.message).to_bytes();
str::from_utf8(bytes).unwrap_or_else(|err| {
str::from_utf8(&bytes[..err.valid_up_to()]).unwrap()
})
}
}
pub fn wrap(ptr: *mut glib_ffi::GError) -> Error {
unsafe { from_glib_full(ptr) }
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.message())
}
}
impl error::Error for Error {
fn description(&self) -> &str {
self.message()
}
}
pub trait ErrorDomain: Copy {
fn domain() -> glib_ffi::GQuark;
fn code(self) -> i32;
fn from(code: i32) -> Option<Self> where Self: Sized;
}
#[derive(Debug)]
pub struct BoolError(pub &'static str);
impl BoolError {
pub fn from_glib(b: glib_ffi::gboolean, s: &'static str) -> Result<(), Self> {
match b {
glib_ffi::GFALSE => Err(BoolError(s)),
_ => Ok(()),
}
}
}
impl fmt::Display for BoolError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl error::Error for BoolError {
fn description(&self) -> &str {
self.0
}
}