color_art/color/
mod.rs

1pub mod color_channel;
2pub mod color_macros;
3pub mod from_num;
4pub mod from_space;
5pub mod from_str;
6pub mod stringify;
7pub mod vec_of;
8
9use std::fmt::Display;
10
11#[cfg(feature = "serde")]
12use serde::{Deserialize, Serialize};
13
14/// Color is a struct that represents a color.
15#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
16#[derive(PartialEq, Debug, Clone, Copy)]
17pub struct Color {
18    pub(crate) rgb: [f64; 3],
19    pub(crate) alpha: f64,
20}
21
22impl Color {
23    /// Creates a new [`Color`].
24    pub fn new<T>(r: T, g: T, b: T, alpha: f64) -> Self
25    where
26        T: Into<f64>,
27    {
28        let r = r.into();
29        let g = g.into();
30        let b = b.into();
31        Color {
32            rgb: [r, g, b],
33            alpha,
34        }
35    }
36}
37
38impl Default for Color {
39    /// default returns a black color.
40    fn default() -> Self {
41        Color::new(0, 0, 0, 1.0)
42    }
43}
44
45impl Display for Color {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        write!(f, "{}", self.hex())
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn test_color_default() {
57        let color = Color::default();
58        assert_eq!(color, Color::new(0, 0, 0, 1.0));
59    }
60
61    #[test]
62    fn test_color_display() {
63        let color = Color::new(255, 255, 0, 1.0);
64        println!("color is \"{}\"", color);
65    }
66}