Include RGBA to crossterm conversion.
@@ -302,3 +302,87 @@ impl From<RGB> for RGBA {
Self::from_f32(item.r, item.g, item.b, 1.0)
}
}
+
+#[cfg(feature = "crossterm")]
+mod crossterm_features {
+ use crossterm::style::Color;
+ use std::convert::TryFrom;
+ use super::RGBA;
+
+ impl TryFrom<RGBA> for Color {
+ type Error = &'static str;
+
+ fn try_from(rgb: RGBA) -> Result<Self, Self::Error> {
+ let (r, g, b) = (rgb.r, rgb.g, rgb.b);
+ for c in [r, g, b].iter() {
+ if *c < 0.0 {
+ return Err("Value < 0.0 found!");
+ }
+ if *c > 1.0 {
+ return Err("Value > 1.0 found!");
+ }
+ }
+ let (r, g, b) = (
+ (r * 255.0) as u8,
+ (g * 255.0) as u8,
+ (b * 255.0) as u8,
+ );
+ let rgb = Color::Rgb {
+ r,
+ g,
+ b,
+ };
+ Ok(rgb)
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use crate::prelude::RGBA;
+ use crossterm::style::Color;
+ use std::convert::TryInto;
+
+ #[test]
+ fn basic_conversion() {
+ let rgb = RGBA {
+ r: 0.0,
+ g: 0.5,
+ b: 1.0,
+ a: 1.0
+ };
+ let rgb: Color = rgb.try_into().unwrap();
+ match rgb {
+ Color::Rgb {r, g, b} => {
+ assert_eq!(r, 0);
+ assert_eq!(g, 127);
+ assert_eq!(b, 255);
+ }
+ _ => unreachable!(),
+ }
+ }
+
+ #[test]
+ fn negative_rgb() {
+ let rgb = RGBA {
+ r: 0.0,
+ g: 0.5,
+ b: -1.0,
+ a: 1.0
+ };
+ let rgb: Result<Color, _> = rgb.try_into();
+ assert!(rgb.is_err());
+ }
+
+ #[test]
+ fn too_large_rgb() {
+ let rgb = RGBA {
+ r: 0.0,
+ g: 0.5,
+ b: 1.1,
+ a: 1.0
+ };
+ let rgb: Result<Color, _> = rgb.try_into();
+ assert!(rgb.is_err());
+ }
+ }
+}
\ No newline at end of file
