1#[derive(Debug, thiserror::Error)]
9pub enum HalError {
10 #[error("io: {0}")]
12 Io(#[from] std::io::Error),
13 #[error("device not found: {0}")]
15 DeviceNotFound(String),
16 #[error("unsupported framebuffer format: {0}")]
18 UnsupportedFormat(String),
19 #[error("value out of range: {0}")]
21 OutOfRange(String),
22 #[error("parse error: {0}")]
24 Parse(String),
25}
26
27pub type HalResult<T> = Result<T, HalError>;
29
30impl From<HalError> for std::io::Error {
35 fn from(e: HalError) -> Self {
36 match e {
37 HalError::Io(io) => io,
38 other => std::io::Error::other(other.to_string()),
39 }
40 }
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46
47 #[test]
48 fn io_error_converts_via_from() {
49 let io = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "nope");
50 let err: HalError = io.into();
51 assert!(matches!(err, HalError::Io(_)));
52 }
53
54 #[test]
55 fn display_strings_name_the_cause() {
56 assert_eq!(
57 HalError::DeviceNotFound("ifm-keypad".into()).to_string(),
58 "device not found: ifm-keypad"
59 );
60 assert_eq!(
61 HalError::UnsupportedFormat("16 bpp".into()).to_string(),
62 "unsupported framebuffer format: 16 bpp"
63 );
64 assert_eq!(
65 HalError::OutOfRange("500 > 400".into()).to_string(),
66 "value out of range: 500 > 400"
67 );
68 }
69
70 #[test]
71 fn io_variant_round_trips_back_to_io_error() {
72 let original = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
73 let io: std::io::Error = HalError::from(original).into();
74 assert_eq!(io.kind(), std::io::ErrorKind::NotFound);
75 }
76
77 #[test]
78 fn non_io_variant_degrades_to_other_kind() {
79 let io: std::io::Error = HalError::DeviceNotFound("x".into()).into();
80 assert_eq!(io.kind(), std::io::ErrorKind::Other);
81 assert!(io.to_string().contains("device not found: x"));
82 }
83
84 #[test]
85 fn question_mark_propagates_io_as_hal_error() {
86 fn inner() -> HalResult<String> {
87 let s = std::fs::read_to_string("/definitely/not/a/real/path/xyz")?;
88 Ok(s)
89 }
90 assert!(matches!(inner(), Err(HalError::Io(_))));
91 }
92}