Skip to content

Commit 07ad8ab

Browse files
committed
Implement Display and Error for ModuleError
1 parent fa86c3e commit 07ad8ab

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

libchisel/src/lib.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ pub mod trimexports;
1111
pub mod verifyexports;
1212
pub mod verifyimports;
1313

14+
use std::{error, fmt};
15+
1416
#[derive(Eq, PartialEq, Debug)]
1517
pub enum ModuleError {
1618
NotSupported,
@@ -35,10 +37,38 @@ pub trait ModuleValidator {
3537
fn validate(&self, module: &Module) -> Result<bool, ModuleError>;
3638
}
3739

40+
impl fmt::Display for ModuleError {
41+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
42+
write!(
43+
f,
44+
"{}",
45+
match self {
46+
ModuleError::NotSupported => "Method unsupported",
47+
ModuleError::Custom(msg) => msg,
48+
}
49+
)
50+
}
51+
}
52+
53+
impl error::Error for ModuleError {
54+
fn description(&self) -> &str {
55+
match self {
56+
ModuleError::NotSupported => "Method unsupported",
57+
ModuleError::Custom(msg) => msg,
58+
}
59+
}
60+
61+
fn cause(&self) -> Option<&error::Error> {
62+
None
63+
}
64+
}
65+
3866
#[cfg(test)]
3967
mod tests {
4068
use super::*;
4169

70+
use std::error::Error;
71+
4272
struct SampleModule {}
4373

4474
impl ModuleCreator for SampleModule {
@@ -89,4 +119,26 @@ mod tests {
89119
let result = validator.validate(&Module::default());
90120
assert!(result.is_ok());
91121
}
122+
123+
#[test]
124+
fn fmt_good() {
125+
// Add new tests for each enum variant here as they are implemented.
126+
let fmt_result_unsupported = format!("{}", ModuleError::NotSupported);
127+
assert_eq!("Method unsupported", fmt_result_unsupported);
128+
129+
let fmt_result_custom = format!("{}", ModuleError::Custom("foo".to_string()));
130+
assert_eq!("foo", fmt_result_custom);
131+
}
132+
133+
#[test]
134+
fn error_good() {
135+
// Add new tests for each enum variant here as they are implemented.
136+
let err_unsupported = ModuleError::NotSupported;
137+
let err_description_unsupported = err_unsupported.description();
138+
assert_eq!("Method unsupported", err_description_unsupported);
139+
140+
let err_custom = ModuleError::Custom("bar".to_string());
141+
let err_description_custom = err_custom.description();
142+
assert_eq!("bar", err_description_custom);
143+
}
92144
}

0 commit comments

Comments
 (0)