1pub const MAX_PIXELS: u64 = 178_956_970;
9
10#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct Palette {
13 colors: Vec<[u8; 3]>,
14 transparent: Option<u8>,
15}
16
17impl Palette {
18 pub fn new(mut colors: Vec<[u8; 3]>, transparent: Option<u8>) -> Self {
21 colors.truncate(256);
22 Self {
23 colors,
24 transparent,
25 }
26 }
27
28 pub fn colors(&self) -> &[[u8; 3]] {
30 &self.colors
31 }
32
33 pub fn transparent(&self) -> Option<u8> {
35 self.transparent
36 }
37
38 pub fn rgba(&self, index: u8) -> [u8; 4] {
42 let [r, g, b] = self
43 .colors
44 .get(usize::from(index))
45 .copied()
46 .unwrap_or_default();
47 let alpha = if self.transparent == Some(index) {
48 0
49 } else {
50 255
51 };
52 [r, g, b, alpha]
53 }
54}
55
56#[derive(Clone, Debug, PartialEq, Eq)]
58pub enum Pixels {
59 Bilevel(Vec<u8>),
61 Gray(Vec<u8>),
63 Gray16(Vec<u16>),
65 GrayAlpha(Vec<[u8; 2]>),
67 Rgb(Vec<[u8; 3]>),
69 Rgba(Vec<[u8; 4]>),
71 Cmyk(Vec<[u8; 4]>),
73 Indexed {
75 palette: Palette,
77 indices: Vec<u8>,
79 },
80 IndexedAlpha {
82 palette: Palette,
84 pixels: Vec<[u8; 2]>,
86 },
87}
88
89impl Pixels {
90 pub fn len(&self) -> usize {
92 match self {
93 Self::Bilevel(v) | Self::Gray(v) => v.len(),
94 Self::Gray16(v) => v.len(),
95 Self::GrayAlpha(v) => v.len(),
96 Self::Rgb(v) => v.len(),
97 Self::Rgba(v) | Self::Cmyk(v) => v.len(),
98 Self::Indexed { indices, .. } => indices.len(),
99 Self::IndexedAlpha { pixels, .. } => pixels.len(),
100 }
101 }
102
103 pub fn is_empty(&self) -> bool {
105 self.len() == 0
106 }
107
108 pub fn to_rgba8(&self) -> Vec<[u8; 4]> {
110 let gray = |v: u8| [v, v, v, 255];
111 match self {
112 Self::Bilevel(v) => v
113 .iter()
114 .map(|&v| gray(if v == 0 { 0 } else { 255 }))
115 .collect(),
116 Self::Gray(v) => v.iter().map(|&v| gray(v)).collect(),
117 Self::Gray16(v) => v
118 .iter()
119 .map(|&v| gray(u8::try_from(v).unwrap_or(u8::MAX)))
120 .collect(),
121 Self::GrayAlpha(v) => v.iter().map(|&[l, a]| [l, l, l, a]).collect(),
122 Self::Rgb(v) => v.iter().map(|&[r, g, b]| [r, g, b, 255]).collect(),
123 Self::Rgba(v) => v.clone(),
124 Self::Cmyk(v) => v.iter().map(|&cmyk| cmyk_to_rgba(cmyk)).collect(),
125 Self::Indexed { palette, indices } => {
126 indices.iter().map(|&i| palette.rgba(i)).collect()
127 }
128 Self::IndexedAlpha { palette, pixels } => pixels
129 .iter()
130 .map(|&[i, a]| {
131 let [r, g, b, _] = palette.rgba(i);
132 [r, g, b, a]
133 })
134 .collect(),
135 }
136 }
137}
138
139fn cmyk_to_rgba([c, m, y, k]: [u8; 4]) -> [u8; 4] {
142 let remaining = 255 - u32::from(k);
143 let channel = |ink: u8| {
144 let product = u32::from(ink) * remaining + 128;
145 let scaled = ((product >> 8) + product) >> 8;
146 u8::try_from(remaining - scaled).expect("at most the remaining 255 - k")
147 };
148 [channel(c), channel(m), channel(y), 255]
149}
150
151#[derive(Clone, Debug, PartialEq, Eq)]
153pub struct Raster {
154 width: u32,
155 height: u32,
156 pixels: Pixels,
157}
158
159impl Raster {
160 pub(crate) fn new(width: u32, height: u32, pixels: Pixels) -> Self {
163 debug_assert_eq!(
164 pixels.len() as u64,
165 u64::from(width) * u64::from(height),
166 "the pixels fill the image"
167 );
168 Self {
169 width,
170 height,
171 pixels,
172 }
173 }
174
175 pub fn width(&self) -> u32 {
177 self.width
178 }
179
180 pub fn height(&self) -> u32 {
182 self.height
183 }
184
185 pub fn pixels(&self) -> &Pixels {
187 &self.pixels
188 }
189
190 pub fn into_pixels(self) -> Pixels {
192 self.pixels
193 }
194
195 pub fn to_rgba8(&self) -> Vec<[u8; 4]> {
197 self.pixels.to_rgba8()
198 }
199}
200
201pub(crate) fn fits(width: u32, height: u32, input_len: usize, per_byte: u64) -> bool {
206 let pixels = u64::from(width) * u64::from(height);
207 let input = u64::try_from(input_len).unwrap_or(u64::MAX);
208 pixels <= MAX_PIXELS && pixels <= input.saturating_mul(per_byte)
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 #[test]
216 fn palettes_fill_missing_entries_with_opaque_black() {
217 let palette = Palette::new(vec![[1, 2, 3], [4, 5, 6]], Some(1));
218 assert_eq!(palette.rgba(0), [1, 2, 3, 255]);
219 assert_eq!(palette.rgba(1), [4, 5, 6, 0]);
220 assert_eq!(palette.rgba(9), [0, 0, 0, 255]);
221 let transparent_past_end = Palette::new(vec![[1, 2, 3]], Some(200));
222 assert_eq!(transparent_past_end.rgba(200), [0, 0, 0, 0]);
223 assert_eq!(Palette::new(vec![[0; 3]; 300], None).colors().len(), 256);
224 }
225
226 #[test]
227 fn conversions_follow_pillow() {
228 assert_eq!(
229 Pixels::Bilevel(vec![0, 255]).to_rgba8(),
230 [[0, 0, 0, 255], [255; 4]]
231 );
232 assert_eq!(
233 Pixels::Gray16(vec![7, 300]).to_rgba8(),
234 [[7, 7, 7, 255], [255; 4]]
235 );
236 assert_eq!(Pixels::GrayAlpha(vec![[9, 3]]).to_rgba8(), [[9, 9, 9, 3]]);
237 let palette = Palette::new(vec![[10, 20, 30]], None);
238 assert_eq!(
239 Pixels::IndexedAlpha {
240 palette,
241 pixels: vec![[0, 77]]
242 }
243 .to_rgba8(),
244 [[10, 20, 30, 77]]
245 );
246 }
247
248 #[test]
249 fn cmyk_converts_like_pillow() {
250 assert_eq!(cmyk_to_rgba([0, 0, 0, 0]), [255, 255, 255, 255]);
251 assert_eq!(cmyk_to_rgba([255, 0, 0, 0]), [0, 255, 255, 255]);
252 assert_eq!(cmyk_to_rgba([0, 0, 0, 255]), [0, 0, 0, 255]);
253 assert_eq!(cmyk_to_rgba([100, 0, 0, 100])[0], 94);
255 }
256
257 #[test]
258 fn size_limits() {
259 assert!(fits(10, 10, 1, 100));
260 assert!(!fits(10, 11, 1, 100));
261 assert!(!fits(65_535, 65_535, usize::MAX, u64::MAX));
262 }
263}