rusty_vision/
color.rs

1use std::ops::Index;
2
3use crate::image::Image;
4
5#[derive(Debug, PartialEq, Eq, Clone, Copy)]
6#[allow(clippy::upper_case_acronyms)]
7pub enum ColorSpace {
8    RGB,
9    RGBA,
10    BGR,
11    BRGA,
12}
13
14#[derive(Debug, Copy, Clone, PartialEq, Eq)]
15pub struct Color {
16    pub red: u8,
17    pub green: u8,
18    pub blue: u8,
19    pub alpha: u8,
20}
21
22trait Convert {
23    fn convert(to_colorspace: ColorSpace) -> Self;
24}
25
26impl ColorSpace {
27    pub fn channels(&self) -> usize {
28        match self {
29            ColorSpace::RGB => 3,
30            ColorSpace::RGBA => 4,
31            ColorSpace::BGR => 3,
32            ColorSpace::BRGA => 4,
33        }
34    }
35
36    pub fn can_convert_to(&self, color_space: &ColorSpace) -> bool {
37        color_space != self
38    }
39
40    // TODO
41    #[allow(unused_variables)]
42    pub fn convert_to(&self, image: &Image, color_space: &ColorSpace) -> Result<(), ()> {
43        if !self.can_convert_to(color_space) {
44            Err(())
45        } else {
46            Ok(())
47        }
48    }
49}
50
51impl Color {
52    pub fn new(red: u8, green: u8, blue: u8, alpha: f32) -> Self {
53        let alpha = (alpha * 255.0) as u8;
54        Color {
55            red,
56            green,
57            blue,
58            alpha,
59        }
60    }
61
62    pub fn as_vec(&self) -> Vec<u8> {
63        vec![self.red, self.green, self.blue, self.alpha]
64    }
65
66    pub fn as_rgb_slice(&self) -> [u8; 3] {
67        [self.red, self.green, self.blue]
68    }
69}
70
71impl Index<usize> for Color {
72    type Output = u8;
73
74    fn index(&self, index: usize) -> &Self::Output {
75        match index {
76            0 => &self.red,
77            1 => &self.green,
78            2 => &self.blue,
79            _ => &self.red, // todo fix this
80        }
81    }
82}