Skip to content

Commit

Permalink
Implement std::error::Error for TryFromIntError (#61)
Browse files Browse the repository at this point in the history
  • Loading branch information
barometz authored Sep 5, 2023
1 parent 31b5d11 commit 54c7e61
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ categories = ["embedded", "no-std", "data-structures"]

[features]
default = []
# This is a no-op feature only provided for compatibility in case it is
# explicitly selected by a user. This crate works without explicit indication
# both on std and no_std systems.
# The std feature only toggles whether the Error trait is implemented for error
# types. Apart from that, this crate works without explicit indication both on
# std and no_std systems.
std = []
18 changes: 18 additions & 0 deletions src/conversion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ impl From<lib::core::convert::Infallible> for TryFromIntError {
}
}

impl Display for TryFromIntError {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "out of range integral type conversion attempted")
}
}

#[cfg(feature = "std")]
impl std::error::Error for TryFromIntError {}

// Only implement if $from can be converted into $name lossless
macro_rules! implement_from {
{[$($name:ident),*], [$($from:ident),*] } => {$(implement_from!($name, $from);)*};
Expand Down Expand Up @@ -1829,4 +1838,13 @@ mod tests {
assert!(i6::try_from(i7(64)).is_err());
assert!(i6::try_from(i7(-64)).is_err());
}

#[test]
#[cfg(feature = "std")]
fn error_trait() {
assert_eq!(
(&TryFromIntError(()) as &dyn std::error::Error).to_string(),
"out of range integral type conversion attempted"
);
}
}
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
//! and thus does not use it:
//! an `Option<u7>` still takes up two bytes.

#![no_std]
#![cfg_attr(not(feature = "std"), no_std)]

mod lib {
pub use core;
Expand Down

0 comments on commit 54c7e61

Please sign in to comment.