1use std::fmt;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7pub enum ColorType {
8 Gray,
10 GrayAlpha,
12 Rgb,
14 Rgba,
16 Indexed,
18}
19
20impl ColorType {
21 pub const fn channels(self) -> usize {
23 match self {
24 Self::Gray | Self::Indexed => 1,
25 Self::GrayAlpha => 2,
26 Self::Rgb => 3,
27 Self::Rgba => 4,
28 }
29 }
30
31 pub const fn has_alpha(self) -> bool {
33 matches!(self, Self::GrayAlpha | Self::Rgba)
34 }
35
36 pub(crate) const fn code(self) -> u8 {
38 match self {
39 Self::Gray => 0,
40 Self::Rgb => 2,
41 Self::Indexed => 3,
42 Self::GrayAlpha => 4,
43 Self::Rgba => 6,
44 }
45 }
46
47 pub(crate) const fn from_code(code: u8) -> Option<Self> {
49 match code {
50 0 => Some(Self::Gray),
51 2 => Some(Self::Rgb),
52 3 => Some(Self::Indexed),
53 4 => Some(Self::GrayAlpha),
54 6 => Some(Self::Rgba),
55 _ => None,
56 }
57 }
58}
59
60impl fmt::Display for ColorType {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 f.write_str(match self {
63 Self::Gray => "grey",
64 Self::GrayAlpha => "grey + alpha",
65 Self::Rgb => "RGB",
66 Self::Rgba => "RGBA",
67 Self::Indexed => "indexed",
68 })
69 }
70}
71
72#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
74pub enum BitDepth {
75 One,
77 Two,
79 Four,
81 Eight,
83 Sixteen,
85}
86
87impl BitDepth {
88 pub const fn bits(self) -> u8 {
90 match self {
91 Self::One => 1,
92 Self::Two => 2,
93 Self::Four => 4,
94 Self::Eight => 8,
95 Self::Sixteen => 16,
96 }
97 }
98
99 pub const fn from_bits(bits: u8) -> Option<Self> {
101 match bits {
102 1 => Some(Self::One),
103 2 => Some(Self::Two),
104 4 => Some(Self::Four),
105 8 => Some(Self::Eight),
106 16 => Some(Self::Sixteen),
107 _ => None,
108 }
109 }
110
111 pub const fn max_value(self) -> u16 {
113 match self {
114 Self::Sixteen => u16::MAX,
115 _ => (1 << self.bits()) - 1,
116 }
117 }
118}
119
120impl fmt::Display for BitDepth {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 write!(f, "{}-bit", self.bits())
123 }
124}
125
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
128pub(crate) struct PixelFormat {
129 pub(crate) color: ColorType,
130 pub(crate) depth: BitDepth,
131}
132
133impl PixelFormat {
134 pub(crate) fn new(color: ColorType, depth: BitDepth) -> Option<Self> {
136 let allowed = match color {
137 ColorType::Gray => true,
138 ColorType::Indexed => depth != BitDepth::Sixteen,
139 ColorType::GrayAlpha | ColorType::Rgb | ColorType::Rgba => depth >= BitDepth::Eight,
140 };
141 allowed.then_some(Self { color, depth })
142 }
143
144 pub(crate) fn bits_per_pixel(self) -> usize {
145 self.color.channels() * usize::from(self.depth.bits())
146 }
147
148 pub(crate) fn filter_stride(self) -> usize {
151 self.bits_per_pixel().div_ceil(8)
152 }
153
154 pub(crate) fn row_bytes(self, width: u32) -> Option<usize> {
157 usize::try_from(width)
158 .ok()?
159 .checked_mul(self.bits_per_pixel())
160 .map(|bits| bits.div_ceil(8))
161 }
162
163 pub(crate) fn image_bytes(self, width: u32, height: u32) -> Option<usize> {
165 self.row_bytes(width)?
166 .checked_mul(usize::try_from(height).ok()?)
167 }
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 const COLORS: [ColorType; 5] = [
175 ColorType::Gray,
176 ColorType::GrayAlpha,
177 ColorType::Rgb,
178 ColorType::Rgba,
179 ColorType::Indexed,
180 ];
181 const DEPTHS: [BitDepth; 5] = [
182 BitDepth::One,
183 BitDepth::Two,
184 BitDepth::Four,
185 BitDepth::Eight,
186 BitDepth::Sixteen,
187 ];
188
189 #[test]
190 fn exactly_the_fifteen_standard_formats_are_allowed() {
191 let allowed: Vec<(u8, u8)> = COLORS
192 .iter()
193 .flat_map(|&c| DEPTHS.iter().map(move |&d| (c, d)))
194 .filter_map(|(c, d)| PixelFormat::new(c, d))
195 .map(|f| (f.color.code(), f.depth.bits()))
196 .collect();
197 assert_eq!(allowed.len(), 15);
198 for (code, bits) in [
199 (0, 1),
200 (0, 16),
201 (2, 8),
202 (2, 16),
203 (3, 1),
204 (3, 8),
205 (4, 16),
206 (6, 8),
207 ] {
208 assert!(allowed.contains(&(code, bits)), "{code}/{bits}");
209 }
210 assert!(!allowed.contains(&(3, 16)));
211 assert!(!allowed.contains(&(2, 4)));
212 }
213
214 #[test]
215 fn codes_and_bits_round_trip() {
216 for color in COLORS {
217 assert_eq!(ColorType::from_code(color.code()), Some(color));
218 }
219 assert_eq!(ColorType::from_code(1), None);
220 for depth in DEPTHS {
221 assert_eq!(BitDepth::from_bits(depth.bits()), Some(depth));
222 }
223 assert_eq!(BitDepth::from_bits(3), None);
224 assert_eq!(BitDepth::Four.max_value(), 15);
225 assert_eq!(BitDepth::Sixteen.max_value(), 65_535);
226 }
227
228 #[test]
229 fn row_geometry() {
230 let gray1 = PixelFormat::new(ColorType::Gray, BitDepth::One).unwrap();
231 assert_eq!(gray1.row_bytes(9), Some(2));
232 assert_eq!(gray1.filter_stride(), 1);
233 let rgba16 = PixelFormat::new(ColorType::Rgba, BitDepth::Sixteen).unwrap();
234 assert_eq!(rgba16.row_bytes(3), Some(24));
235 assert_eq!(rgba16.filter_stride(), 8);
236 let rgb8 = PixelFormat::new(ColorType::Rgb, BitDepth::Eight).unwrap();
237 assert_eq!(rgb8.image_bytes(4, 5), Some(60));
238 assert_eq!(rgb8.filter_stride(), 3);
239 }
240}