//! Colours without a toolkit. /// An opaque colour as `0xrrggbb`. Where "no colour" means something (a /// text's own colour), the field is an `Option`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct Rgb(pub u32); impl Rgb { /// The colour with these channels. pub const fn new(r: u8, g: u8, b: u8) -> Self { Self((r as u32) << 16 | (g as u32) << 8 | b as u32) } /// The red channel. pub const fn r(self) -> u8 { (self.0 >> 16) as u8 } /// The green channel. pub const fn g(self) -> u8 { (self.0 >> 8) as u8 } /// The blue channel. pub const fn b(self) -> u8 { self.0 as u8 } } impl From for Rgb { /// `0xrrggbb`; the top byte is ignored. fn from(rgb: u32) -> Self { Self(rgb & 0x00ff_ffff) } } impl From<[u8; 3]> for Rgb { fn from([r, g, b]: [u8; 3]) -> Self { Self::new(r, g, b) } } #[cfg(test)] mod tests { use super::*; #[test] fn channels() { let c = Rgb::from(0x2d6bff); assert_eq!((c.r(), c.g(), c.b()), (0x2d, 0x6b, 0xff)); assert_eq!(Rgb::new(0x2d, 0x6b, 0xff), c); assert_eq!(Rgb::from([1, 2, 3]), Rgb(0x010203)); assert_eq!(Rgb::from(0xff12_3456), Rgb(0x123456)); } }