1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
use std::num;
use thiserror::Error;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Color {
pub(crate) space_coordinates: (f32, f32),
pub(crate) brightness: Option<u8>,
}
impl Color {
pub fn from_space_coordinates(x: f32, y: f32) -> Self {
Self {
space_coordinates: (x, y),
brightness: None,
}
}
pub fn from_rgb(red: u8, green: u8, blue: u8) -> Self {
let gamma_correct = |v: f32| {
if v > 0.04045 {
((v + 0.055) / (1.0 + 0.055)).powf(2.4)
} else {
v / 12.92
}
};
let red = gamma_correct(red as f32 / 255.0);
let green = gamma_correct(green as f32 / 255.0);
let blue = gamma_correct(blue as f32 / 255.0);
let x = red * 0.649_926 + green * 0.103_455 + blue * 0.197_109;
let y = red * 0.234_327 + green * 0.743_075 + blue * 0.022_598;
let z = red * 0.000_000 + green * 0.053_077 + blue * 1.035_763;
Self {
space_coordinates: (
x / (x + y + z + std::f32::MIN_POSITIVE),
y / (x + y + z + std::f32::MIN_POSITIVE),
),
brightness: Some((y * 255.0) as u8),
}
}
pub fn from_hex<S: AsRef<str>>(s: S) -> Result<Self, ParseHexError> {
let s = s.as_ref();
match s.len() {
4 => {
let red = u8::from_str_radix(&s[1..2], 16)?;
let green = u8::from_str_radix(&s[2..3], 16)?;
let blue = u8::from_str_radix(&s[3..4], 16)?;
Ok(Self::from_rgb(
red * 16 + red,
green * 16 + green,
blue * 16 + blue,
))
}
7 => Ok(Self::from_rgb(
u8::from_str_radix(&s[1..3], 16)?,
u8::from_str_radix(&s[3..5], 16)?,
u8::from_str_radix(&s[5..7], 16)?,
)),
_ => Err(ParseHexError::InvalidLenght),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Error)]
pub enum ParseHexError {
#[error("Invalid string length")]
InvalidLenght,
#[error("Failed to parse a int value")]
ParseInt(#[from] num::ParseIntError),
}