Skip to content

Commit

Permalink
error: Implement Display and Error
Browse files Browse the repository at this point in the history
  • Loading branch information
chrysn committed Sep 18, 2024
1 parent 5678a90 commit 88e3cae
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
2 changes: 2 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ fn main() {
"sock_aux_local",
"sock_tcp",
"sock_udp",
"tiny_strerror",
"tiny_strerror_minimal",
"udp",
"vfs",
"ws281x",
Expand Down
33 changes: 26 additions & 7 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
//! the list).
use core::convert::TryInto;
use core::ffi::CStr;
use core::num::NonZero;

pub trait NegativeErrorExt {
Expand Down Expand Up @@ -83,15 +84,33 @@ impl NumericError {
}
nb::Error::Other(self)
}

fn string(&self) -> Option<&'static CStr> {
#[cfg(all(riot_module_tiny_strerror, not(riot_module_tiny_strerror_minimal)))]
// unsafe: According to C API
// number cast: Disagreements on the numeric error size
// string cast: Disagreements on the signedness of char
return Some(unsafe {
CStr::from_ptr(riot_sys::tiny_strerror(-self.number.get() as _) as _)
});

#[cfg(not(all(riot_module_tiny_strerror, not(riot_module_tiny_strerror_minimal))))]
return None;
}
}

impl core::fmt::Display for NumericError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
if let Some(s) = self.string() {
write!(f, "Error {} ({})", self.number(), s.to_str().unwrap())?;
} else {
write!(f, "Error {}", self.number())?;
}
Ok(())
}
}

// Would be nice, but there's no strerror
//
// impl core::fmt::Display for NumericError {
// fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
// write!(f, "Error {} ({})", self.number(), ...)
// }
// }
impl core::error::Error for NumericError {}

impl<T> NegativeErrorExt for T
where
Expand Down

0 comments on commit 88e3cae

Please sign in to comment.