2022-10-09 02:43:25 +11:00
|
|
|
use std::str::FromStr;
|
|
|
|
|
2021-04-20 09:40:07 +10:00
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
|
|
pub struct Colour {
|
|
|
|
pub r: u8,
|
|
|
|
pub g: u8,
|
|
|
|
pub b: u8,
|
2022-05-23 04:23:29 +10:00
|
|
|
pub a: u8,
|
2021-04-20 09:40:07 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Colour {
|
2022-05-23 04:23:29 +10:00
|
|
|
pub fn from_rgb(r: u8, g: u8, b: u8, a: u8) -> Self {
|
|
|
|
Colour { r, g, b, a }
|
2021-04-20 09:40:07 +10:00
|
|
|
}
|
2021-04-21 05:41:04 +10:00
|
|
|
|
2021-04-21 07:56:47 +10:00
|
|
|
pub fn to_rgb15(self) -> u16 {
|
2021-04-21 05:41:04 +10:00
|
|
|
let (r, g, b) = (self.r as u16, self.g as u16, self.b as u16);
|
|
|
|
((r >> 3) & 31) | (((g >> 3) & 31) << 5) | (((b >> 3) & 31) << 10)
|
|
|
|
}
|
2022-05-23 04:23:29 +10:00
|
|
|
|
|
|
|
pub fn is_transparent(self) -> bool {
|
|
|
|
self.a != 255
|
|
|
|
}
|
2021-04-20 09:40:07 +10:00
|
|
|
}
|
2022-10-09 02:43:25 +11:00
|
|
|
|
|
|
|
impl FromStr for Colour {
|
|
|
|
type Err = String;
|
|
|
|
|
|
|
|
fn from_str(colour: &str) -> Result<Self, Self::Err> {
|
|
|
|
if colour.len() != 6 {
|
2023-03-24 08:47:44 +11:00
|
|
|
return Err(format!("Expected colour to be 6 characters, got {colour}"));
|
2022-10-09 02:43:25 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
let r = u8::from_str_radix(&colour[0..2], 16).unwrap();
|
|
|
|
let g = u8::from_str_radix(&colour[2..4], 16).unwrap();
|
|
|
|
let b = u8::from_str_radix(&colour[4..6], 16).unwrap();
|
|
|
|
|
|
|
|
Ok(Colour::from_rgb(r, g, b, 255))
|
|
|
|
}
|
|
|
|
}
|