Skip to content

Commit b7c86bf

Browse files
committed
implement std::error for FromHexError.
1 parent fedcb6f commit b7c86bf

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

palette/src/rgb/rgb.rs

+33
Original file line numberDiff line numberDiff line change
@@ -972,6 +972,30 @@ impl From<&'static str> for FromHexError {
972972
FromHexError::HexFormatError(err)
973973
}
974974
}
975+
impl core::fmt::Display for FromHexError {
976+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
977+
match &*self {
978+
FromHexError::ParseIntError(e) => {
979+
write!(f, "ParseIntError: {}", e)
980+
}
981+
FromHexError::HexFormatError(s) => {
982+
write!(f, "HexFormatError: {}, please use format '#fff', 'fff', '#ffffff' or\
983+
'ffffff'.", s)
984+
}
985+
}
986+
}
987+
}
988+
989+
#[cfg(feature="std")]
990+
impl std::error::Error for FromHexError {
991+
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
992+
match &*self {
993+
FromHexError::HexFormatError(_s) => None,
994+
FromHexError::ParseIntError(e) => Some(e),
995+
}
996+
}
997+
}
998+
975999

9761000
impl<S: RgbStandard> FromStr for Rgb<S, u8> {
9771001
type Err = FromHexError;
@@ -1158,6 +1182,10 @@ mod test {
11581182
assert_eq!(c.unwrap(), Rgb::<Srgb,u8>::new(18, 52, 86));
11591183
let c = Rgb::<Srgb,u8>::from_str("#iii");
11601184
assert!(c.is_err());
1185+
assert_eq!(
1186+
format!("{}", c.err().unwrap()),
1187+
"ParseIntError: invalid digit found in string"
1188+
);
11611189
let c = Rgb::<Srgb,u8>::from_str("#08f");
11621190
assert_eq!(c.unwrap(), Rgb::<Srgb,u8>::new(0, 136, 255));
11631191
let c = Rgb::<Srgb,u8>::from_str("08f");
@@ -1166,6 +1194,11 @@ mod test {
11661194
assert_eq!(c.unwrap(), Rgb::<Srgb,u8>::new(255,255,255));
11671195
let c = Rgb::<Srgb,u8>::from_str("#12");
11681196
assert!(c.is_err());
1197+
assert_eq!(
1198+
format!("{}", c.err().unwrap()),
1199+
"HexFormatError: invalid hex code format, \
1200+
please use format \'#fff\', \'fff\', \'#ffffff\' or\'ffffff\'."
1201+
);
11691202
let c = Rgb::<Srgb,u8>::from_str("da0bce");
11701203
assert_eq!(c.unwrap(), Rgb::<Srgb,u8>::new(218,11,206));
11711204
let c = Rgb::<Srgb,u8>::from_str("f034e6");

0 commit comments

Comments
 (0)