Skip to content

Commit

Permalink
implement std::error for FromHexError.
Browse files Browse the repository at this point in the history
  • Loading branch information
mswift42 committed Dec 25, 2019
1 parent fedcb6f commit b7c86bf
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions palette/src/rgb/rgb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -972,6 +972,30 @@ impl From<&'static str> for FromHexError {
FromHexError::HexFormatError(err)
}
}
impl core::fmt::Display for FromHexError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &*self {
FromHexError::ParseIntError(e) => {
write!(f, "ParseIntError: {}", e)
}
FromHexError::HexFormatError(s) => {
write!(f, "HexFormatError: {}, please use format '#fff', 'fff', '#ffffff' or\
'ffffff'.", s)
}
}
}
}

#[cfg(feature="std")]
impl std::error::Error for FromHexError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &*self {
FromHexError::HexFormatError(_s) => None,
FromHexError::ParseIntError(e) => Some(e),
}
}
}


impl<S: RgbStandard> FromStr for Rgb<S, u8> {
type Err = FromHexError;
Expand Down Expand Up @@ -1158,6 +1182,10 @@ mod test {
assert_eq!(c.unwrap(), Rgb::<Srgb,u8>::new(18, 52, 86));
let c = Rgb::<Srgb,u8>::from_str("#iii");
assert!(c.is_err());
assert_eq!(
format!("{}", c.err().unwrap()),
"ParseIntError: invalid digit found in string"
);
let c = Rgb::<Srgb,u8>::from_str("#08f");
assert_eq!(c.unwrap(), Rgb::<Srgb,u8>::new(0, 136, 255));
let c = Rgb::<Srgb,u8>::from_str("08f");
Expand All @@ -1166,6 +1194,11 @@ mod test {
assert_eq!(c.unwrap(), Rgb::<Srgb,u8>::new(255,255,255));
let c = Rgb::<Srgb,u8>::from_str("#12");
assert!(c.is_err());
assert_eq!(
format!("{}", c.err().unwrap()),
"HexFormatError: invalid hex code format, \
please use format \'#fff\', \'fff\', \'#ffffff\' or\'ffffff\'."
);
let c = Rgb::<Srgb,u8>::from_str("da0bce");
assert_eq!(c.unwrap(), Rgb::<Srgb,u8>::new(218,11,206));
let c = Rgb::<Srgb,u8>::from_str("f034e6");
Expand Down

0 comments on commit b7c86bf

Please sign in to comment.