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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
use std::num::ParseIntError;
use thiserror::Error as ThisError;

/// Struct for setting the color of a light.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Color {
    /// Color space coordinates.
    pub(crate) space_coordinates: (f32, f32),
    /// Brightness of the color.
    pub(crate) brightness: Option<u8>,
}

impl Color {
    /// Creates a new color from space coordinates.
    ///
    /// This only changes the color of a light and not the brightness.
    ///
    /// # Examples
    ///
    /// Generate a color and use it in a modifier:
    /// ```
    /// use huelib::{Color, resource::light};
    ///
    /// let color = Color::from_space_coordinates(0.1, 0.2);
    /// let modifier = light::StateModifier::new().with_color(color);
    /// ```
    pub fn from_space_coordinates(x: f32, y: f32) -> Self {
        Self {
            space_coordinates: (x, y),
            brightness: None,
        }
    }

    /// Creates a new color from rgb values.
    ///
    /// This changes the color and brightness of a light.
    ///
    /// # Examples
    ///
    /// Generate a color and use it in a modifier:
    /// ```
    /// use huelib::{Color, resource::light};
    ///
    /// let color = Color::from_rgb(255, 0, 0);
    /// let modifier = light::StateModifier::new().with_color(color);
    /// ```
    pub fn from_rgb(red: u8, green: u8, blue: u8) -> Self {
        // NOTE: More information: https://gist.github.com/popcorn245/30afa0f98eea1c2fd34d
        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),
        }
    }

    /// Creates a new color from a hex value.
    ///
    /// The string must begin with a `#` followed by either 3 or 6 hexadecimal digits.
    ///
    /// This changes the color and brightness of a light.
    ///
    /// # Examples
    ///
    /// Generate a color and use it in a modifier:
    /// ```
    /// use huelib::{Color, resource::light};
    ///
    /// # fn main() -> Result<(), huelib::color::ParseHexError> {
    /// let red = Color::from_hex("#FF0000")?;
    /// let modifier = light::StateModifier::new().with_color(red);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Generate a color using the short version:
    /// ```
    /// # fn main() -> Result<(), huelib::color::ParseHexError> {
    /// let color = huelib::Color::from_hex("#02B")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_hex(s: impl AsRef<str>) -> 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),
        }
    }
}

/// Errors that can occur while parsing a hex string to a color.
#[derive(Clone, Debug, Eq, PartialEq, ThisError)]
pub enum ParseHexError {
    /// Error that occurs when the length of the hex string is invalid.
    #[error("Invalid string length")]
    InvalidLenght,
    /// Error that can occur while parsing a int value.
    #[error("Failed to parse a int value")]
    ParseInt(#[from] ParseIntError),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn space_coordinates() {
        let color = Color::from_space_coordinates(0.1, 0.2);
        assert_eq!(color.space_coordinates, (0.1, 0.2));
        assert_eq!(color.brightness, None);
    }

    #[test]
    fn rgb_white() {
        let color = Color::from_rgb(255, 255, 255);
        assert_eq!(color.brightness, Some(255));
    }

    #[test]
    fn rgb_black() {
        let color = Color::from_rgb(0, 0, 0);
        assert_eq!(color.brightness, Some(0));
    }

    #[test]
    fn hex_white() {
        let color = Color::from_hex("#FFFFFF").unwrap();
        assert_eq!(color.brightness, Some(255));
        let color = Color::from_hex("#ffffff").unwrap();
        assert_eq!(color.brightness, Some(255));
        let color = Color::from_hex("#FFF").unwrap();
        assert_eq!(color.brightness, Some(255));
        let color = Color::from_hex("#fff").unwrap();
        assert_eq!(color.brightness, Some(255));
    }

    #[test]
    fn hex_black() {
        let color = Color::from_hex("#000000").unwrap();
        assert_eq!(color.brightness, Some(0));
        let color = Color::from_hex("#000").unwrap();
        assert_eq!(color.brightness, Some(0));
    }

    #[test]
    fn hex_short() {
        let color = Color::from_hex("#FFF").unwrap();
        assert_eq!(color, Color::from_hex("#FFFFFF").unwrap());
        let color = Color::from_hex("#f00").unwrap();
        assert_eq!(color, Color::from_hex("#FF0000").unwrap());
        let color = Color::from_hex("#123").unwrap();
        assert_eq!(color, Color::from_hex("#112233").unwrap());
    }

    #[test]
    fn rgb_and_hex() {
        let color1 = Color::from_hex("#fff").unwrap();
        let color2 = Color::from_rgb(255, 255, 255);
        assert_eq!(color1, color2);
        let color1 = Color::from_hex("#000").unwrap();
        let color2 = Color::from_rgb(0, 0, 0);
        assert_eq!(color1, color2);
        let color1 = Color::from_hex("#0F0").unwrap();
        let color2 = Color::from_rgb(0, 255, 0);
        assert_eq!(color1, color2);
        let color1 = Color::from_hex("#100").unwrap();
        let color2 = Color::from_rgb(17, 0, 0);
        assert_eq!(color1, color2);
        let color1 = Color::from_hex("#02F").unwrap();
        let color2 = Color::from_rgb(0, 34, 255);
        assert_eq!(color1, color2);
    }
}