Skip to main content

niko/
color.rs

1use std::ops::{Add, Sub, Mul, Div};
2
3#[derive(Debug, Copy, Clone, Eq, PartialEq)]
4pub struct Color {
5    r: u8,
6    g: u8,
7    b: u8,
8    a: u8,
9}
10
11impl Color {
12
13    /// construct a new color from red, green, blue and alpha
14    pub fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
15        Self {
16            r,
17            g,
18            b,
19            a,
20        }
21    }
22
23    /// construct a new color from red, green and blue
24    pub fn rgb(r: u8, g: u8, b: u8) -> Self {
25        Self {
26            r,
27            g,
28            b,
29            a: std::u8::MAX,
30        }
31    }
32
33    /// returns normalized (between 0.0 and 1.0) values for all color channels
34    pub fn into_normalized(self) -> (f32, f32, f32, f32) {
35        (
36            self.r as f32 / 255.0,
37            self.g as f32 / 255.0,
38            self.b as f32 / 255.0,
39            self.a as f32 / 255.0,
40        )
41    }
42}
43
44impl Add for Color {
45    type Output = Self;
46
47    fn add(self, other: Self) -> Self {
48        Self {
49            r: self.r + other.r,
50            g: self.g + other.g,
51            b: self.b + other.b,
52            a: self.a + other.a,
53        }
54    }
55}
56
57impl Sub for Color {
58    type Output = Self;
59
60    fn sub(self, other: Self) -> Self {
61        Self {
62            r: self.r - other.r,
63            g: self.g - other.g,
64            b: self.b - other.b,
65            a: self.a - other.a,
66        }
67    }
68}
69
70impl Mul for Color {
71    type Output = Self;
72
73    fn mul(self, other: Self) -> Self {
74        Self {
75            r: self.r * other.r,
76            g: self.g * other.g,
77            b: self.b * other.b,
78            a: self.a * other.a,
79        }
80    }
81}
82
83impl Div for Color {
84    type Output = Self;
85
86    fn div(self, other: Self) -> Self {
87        Self {
88            r: self.r / other.r,
89            g: self.g / other.g,
90            b: self.b / other.b,
91            a: self.a / other.a,
92        }
93    }
94}
95
96impl Into<(u8, u8, u8, u8)> for Color {
97    fn into(self) -> (u8, u8, u8, u8) {
98        (self.r, self.g, self.b, self.a)
99    }
100}
101
102impl From<(u8, u8, u8, u8)> for Color {
103    fn from(values: (u8, u8, u8, u8)) -> Self {
104        Self::new(values.0, values.1, values.2, values.3)
105    }
106}