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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
use std::os::raw::c_char;
use std::panic::{self, RefUnwindSafe};
use std::path::Path;
use chemfiles_sys::*;
use crate::strings;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Error {
pub status: Status,
pub message: String,
}
#[repr(C)]
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Status {
Success = chfl_status::CHFL_SUCCESS as isize,
MemoryError = chfl_status::CHFL_MEMORY_ERROR as isize,
FileError = chfl_status::CHFL_FILE_ERROR as isize,
FormatError = chfl_status::CHFL_FORMAT_ERROR as isize,
SelectionError = chfl_status::CHFL_SELECTION_ERROR as isize,
ConfigurationError = chfl_status::CHFL_CONFIGURATION_ERROR as isize,
OutOfBounds = chfl_status::CHFL_OUT_OF_BOUNDS as isize,
PropertyError = chfl_status::CHFL_PROPERTY_ERROR as isize,
ChemfilesError = chfl_status::CHFL_GENERIC_ERROR as isize,
StdCppError = chfl_status::CHFL_CXX_ERROR as isize,
UTF8PathError,
}
impl From<chfl_status> for Error {
fn from(status: chfl_status) -> Error {
let status = match status {
chfl_status::CHFL_SUCCESS => Status::Success,
chfl_status::CHFL_CXX_ERROR => Status::StdCppError,
chfl_status::CHFL_GENERIC_ERROR => Status::ChemfilesError,
chfl_status::CHFL_MEMORY_ERROR => Status::MemoryError,
chfl_status::CHFL_FILE_ERROR => Status::FileError,
chfl_status::CHFL_FORMAT_ERROR => Status::FormatError,
chfl_status::CHFL_SELECTION_ERROR => Status::SelectionError,
chfl_status::CHFL_CONFIGURATION_ERROR => Status::ConfigurationError,
chfl_status::CHFL_OUT_OF_BOUNDS => Status::OutOfBounds,
chfl_status::CHFL_PROPERTY_ERROR => Status::PropertyError,
};
let message = Error::last_error();
Error { status, message }
}
}
impl From<std::str::Utf8Error> for Error {
fn from(_: std::str::Utf8Error) -> Self {
Error {
status: Status::UTF8PathError,
message: "failed to convert data to UTF8 string".into(),
}
}
}
impl Error {
pub(crate) fn utf8_path_error(path: &Path) -> Error {
Error {
status: Status::UTF8PathError,
message: format!("Could not convert '{}' to UTF8", path.display()),
}
}
pub fn last_error() -> String {
unsafe { strings::from_c(chfl_last_error()) }
}
pub fn cleanup() {
unsafe {
check(chfl_clear_errors()).expect("error in chfl_clear_errors. Things went very bad");
}
}
}
pub(crate) fn check(status: chfl_status) -> Result<(), Error> {
if status == chfl_status::CHFL_SUCCESS {
Ok(())
} else {
Err(Error::from(status))
}
}
pub(crate) fn check_success(status: chfl_status) {
assert!(
status == chfl_status::CHFL_SUCCESS,
"unexpected failure: {}",
Error::last_error()
);
}
pub(crate) fn check_not_null<T>(ptr: *const T) {
assert!(!ptr.is_null(), "unexpected null pointer: {}", Error::last_error());
}
pub trait WarningCallback: RefUnwindSafe + Fn(&str) {}
impl<T> WarningCallback for T where T: RefUnwindSafe + Fn(&str) {}
static mut LOGGING_CALLBACK: Option<*mut dyn WarningCallback<Output = ()>> = None;
extern "C" fn warning_callback(message: *const c_char) {
unsafe {
let callback = &*LOGGING_CALLBACK.expect("No callback provided, this is an internal bug");
let _result = panic::catch_unwind(|| {
callback(&strings::from_c(message));
});
}
}
pub fn set_warning_callback<F>(callback: F)
where
F: WarningCallback + 'static,
{
let callback = Box::into_raw(Box::new(callback));
unsafe {
if let Some(previous) = LOGGING_CALLBACK {
let previous = Box::from_raw(previous);
std::mem::drop(previous);
LOGGING_CALLBACK = Some(callback);
} else {
LOGGING_CALLBACK = Some(callback);
check_success(chfl_set_warning_callback(warning_callback));
}
}
}
impl std::fmt::Display for Error {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(fmt, "{}", self.message)
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
match self.status {
Status::Success => "Success",
Status::StdCppError => "Exception from the C++ standard library",
Status::ChemfilesError => "Exception from the chemfiles library",
Status::MemoryError => "Error in memory allocations",
Status::FileError => "Error while reading or writing a file",
Status::FormatError => "Error in file formatting, i.e. the file is invalid",
Status::SelectionError => "Error in selection string syntax",
Status::UTF8PathError => "A string is not valid UTF8",
Status::ConfigurationError => "Error in configuration files",
Status::OutOfBounds => "Out of bounds indexing",
Status::PropertyError => "Error in property",
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::Trajectory;
#[test]
fn errors() {
Error::cleanup();
assert_eq!(Error::last_error(), "");
assert!(Trajectory::open("nope", 'r').is_err());
assert_eq!(
Error::last_error(),
"file at \'nope\' does not have an extension, provide a format name to read it"
);
Error::cleanup();
assert_eq!(Error::last_error(), "");
}
#[test]
fn codes() {
assert_eq!(Error::from(chfl_status::CHFL_SUCCESS).status, Status::Success);
assert_eq!(Error::from(chfl_status::CHFL_CXX_ERROR).status, Status::StdCppError);
assert_eq!(
Error::from(chfl_status::CHFL_GENERIC_ERROR).status,
Status::ChemfilesError
);
assert_eq!(Error::from(chfl_status::CHFL_MEMORY_ERROR).status, Status::MemoryError);
assert_eq!(Error::from(chfl_status::CHFL_FILE_ERROR).status, Status::FileError);
assert_eq!(Error::from(chfl_status::CHFL_FORMAT_ERROR).status, Status::FormatError);
assert_eq!(
Error::from(chfl_status::CHFL_SELECTION_ERROR).status,
Status::SelectionError
);
assert_eq!(Error::from(chfl_status::CHFL_OUT_OF_BOUNDS).status, Status::OutOfBounds);
assert_eq!(
Error::from(chfl_status::CHFL_PROPERTY_ERROR).status,
Status::PropertyError
);
}
}