gamut_core/image.rs
1//! Branded, length-validated interleaved image buffers: [`ImageRef`] (borrowed) and [`ImageBuf`]
2//! (owned).
3//!
4//! Both wrap a flat sample slice/vec of `P::Sample` (`u8` or `u16`) plus [`Dimensions`], branded
5//! with a [`Pixel`] marker `P`. The invariant `len == width * height * P::CHANNELS` (with non-zero
6//! dimensions) is checked **once**, at construction, so codecs receive a buffer that is already
7//! known-good and can pull the raw slice back out via [`ImageRef::as_samples`] with zero overhead —
8//! their hot loops are byte-identical to operating on a bare `&[u8]`. The brand is what makes a
9//! format mismatch (e.g. feeding [`crate::Cmyk8`] data to an [`crate::Rgba8`] encoder) a compile
10//! error instead of a silent reinterpretation.
11
12use core::marker::PhantomData;
13
14use crate::convert::RawImage;
15use crate::{Dimensions, Error, Pixel, Result};
16
17/// The required sample count for `dims` at `P`'s channel count, rejecting empty or overflowing
18/// dimensions. The single validation shared by every buffer constructor.
19fn expected_len<P: Pixel>(dims: Dimensions) -> Result<usize> {
20 if dims.is_empty() {
21 return Err(Error::InvalidInput("zero-sized image").with_origin(env!("CARGO_PKG_NAME")));
22 }
23 dims.sample_count(P::CHANNELS).ok_or_else(|| {
24 Error::InvalidInput("image dimensions overflow usize").with_origin(env!("CARGO_PKG_NAME"))
25 })
26}
27
28/// Checks the length invariant `data_len == width * height * P::CHANNELS` (with non-empty,
29/// non-overflowing `dims`). The single source of truth both buffer constructors call, so the
30/// rejection messages never drift between the borrowed and owned paths.
31fn validate_len<P: Pixel>(data_len: usize, dims: Dimensions) -> Result<()> {
32 if data_len != expected_len::<P>(dims)? {
33 return Err(
34 Error::InvalidInput("image buffer length does not match dimensions")
35 .with_origin(env!("CARGO_PKG_NAME")),
36 );
37 }
38 Ok(())
39}
40
41/// A borrowed, length-validated view of an interleaved image of pixel type `P`.
42///
43/// Cheap to copy (a slice + [`Dimensions`] + a zero-sized marker). Construct one at an API boundary
44/// with [`ImageRef::new`]; pass it to an [`crate::EncodeImage`] implementation.
45#[derive(Debug, Clone, Copy)]
46#[must_use]
47pub struct ImageRef<'a, P: Pixel> {
48 data: &'a [P::Sample],
49 dims: Dimensions,
50 _p: PhantomData<P>,
51}
52
53impl<'a, P: Pixel> ImageRef<'a, P> {
54 /// Brands `data` as an image of `dims`, validating that its length is exactly
55 /// `width * height * P::CHANNELS`.
56 ///
57 /// # Errors
58 ///
59 /// Returns [`Error::InvalidInput`] if `dims` is zero-sized, if `width * height * channels`
60 /// overflows `usize`, or if `data.len()` does not equal that product.
61 pub fn new(data: &'a [P::Sample], dims: Dimensions) -> Result<Self> {
62 validate_len::<P>(data.len(), dims)?;
63 Ok(Self {
64 data,
65 dims,
66 _p: PhantomData,
67 })
68 }
69
70 /// The image dimensions.
71 #[must_use]
72 pub fn dimensions(self) -> Dimensions {
73 self.dims
74 }
75
76 /// Image width in pixels.
77 #[must_use]
78 pub fn width(self) -> u32 {
79 self.dims.width
80 }
81
82 /// Image height in pixels.
83 #[must_use]
84 pub fn height(self) -> u32 {
85 self.dims.height
86 }
87
88 /// The raw interleaved samples (`width * height * P::CHANNELS` of them, row-major). The
89 /// zero-cost escape hatch a codec uses to feed its existing slice-based hot path.
90 #[must_use]
91 pub fn as_samples(self) -> &'a [P::Sample] {
92 self.data
93 }
94
95 /// Row `y` as a `width * P::CHANNELS`-sample slice.
96 ///
97 /// # Panics
98 ///
99 /// Panics if `y >= height`.
100 #[must_use]
101 pub fn row(self, y: u32) -> &'a [P::Sample] {
102 let row_len = self.dims.width as usize * P::CHANNELS;
103 let start = y as usize * row_len;
104 &self.data[start..start + row_len]
105 }
106
107 /// Iterates the rows top to bottom, each a `width * P::CHANNELS`-sample slice.
108 pub fn rows(self) -> impl ExactSizeIterator<Item = &'a [P::Sample]> {
109 let row_len = self.dims.width as usize * P::CHANNELS;
110 self.data.chunks_exact(row_len)
111 }
112
113 /// The `P::CHANNELS` samples of the pixel at `(x, y)`.
114 ///
115 /// # Panics
116 ///
117 /// Panics if `x >= width` or `y >= height`.
118 #[must_use]
119 pub fn pixel(self, x: u32, y: u32) -> &'a [P::Sample] {
120 let i = (y as usize * self.dims.width as usize + x as usize) * P::CHANNELS;
121 &self.data[i..i + P::CHANNELS]
122 }
123
124 /// Re-describes this view with `P`'s layout carried as a runtime [`crate::PixelFormat`] tag
125 /// instead of a brand, for [`crate::convert`]'s raw entry points.
126 ///
127 /// Infallible: the brand guarantees everything [`RawImage::new`] would otherwise check.
128 pub fn as_raw(self) -> RawImage<'a, P::Sample> {
129 RawImage::from_branded(self.data, P::FORMAT, self.dims)
130 }
131}
132
133/// Two views are equal when they have the same dimensions and the same samples. Hand-written rather
134/// than derived so the brand `P` carries no `PartialEq` bound (only the samples and dimensions are
135/// compared). Comparing dimensions first short-circuits the sample comparison on a size mismatch.
136impl<P: Pixel> PartialEq for ImageRef<'_, P> {
137 fn eq(&self, other: &Self) -> bool {
138 self.dims == other.dims && self.data == other.data
139 }
140}
141
142impl<P: Pixel> Eq for ImageRef<'_, P> {}
143
144/// An owned, length-validated interleaved image of pixel type `P`.
145///
146/// The owning counterpart of [`ImageRef`]; the natural return of a decoder, carrying its
147/// dimensions, samples, and layout brand as one unit so a caller can never misinterpret the result.
148#[derive(Debug, Clone)]
149#[must_use]
150pub struct ImageBuf<P: Pixel> {
151 data: Vec<P::Sample>,
152 dims: Dimensions,
153 _p: PhantomData<P>,
154}
155
156impl<P: Pixel> ImageBuf<P> {
157 /// Takes ownership of `data` as an image of `dims`, validating its length the same way as
158 /// [`ImageRef::new`].
159 ///
160 /// # Errors
161 ///
162 /// Returns [`Error::InvalidInput`] if `dims` is zero-sized, if the sample count overflows
163 /// `usize`, or if `data.len()` does not equal `width * height * P::CHANNELS`.
164 pub fn new(data: Vec<P::Sample>, dims: Dimensions) -> Result<Self> {
165 // Same length invariant as `ImageRef::new`, without building a throwaway borrowed view.
166 validate_len::<P>(data.len(), dims)?;
167 Ok(Self {
168 data,
169 dims,
170 _p: PhantomData,
171 })
172 }
173
174 /// An all-zero image of `dims` (every sample `P::Sample::default()`).
175 ///
176 /// # Errors
177 ///
178 /// Returns [`Error::InvalidInput`] if `dims` is zero-sized or the sample count overflows `usize`.
179 pub fn zeroed(dims: Dimensions) -> Result<Self> {
180 let want = expected_len::<P>(dims)?;
181 Ok(Self {
182 data: vec![P::Sample::default(); want],
183 dims,
184 _p: PhantomData,
185 })
186 }
187
188 /// Borrows this image as an [`ImageRef`]. Infallible — the invariant already holds.
189 pub fn as_ref(&self) -> ImageRef<'_, P> {
190 ImageRef {
191 data: &self.data,
192 dims: self.dims,
193 _p: PhantomData,
194 }
195 }
196
197 /// The image dimensions.
198 #[must_use]
199 pub fn dimensions(&self) -> Dimensions {
200 self.dims
201 }
202
203 /// Image width in pixels.
204 #[must_use]
205 pub fn width(&self) -> u32 {
206 self.dims.width
207 }
208
209 /// Image height in pixels.
210 #[must_use]
211 pub fn height(&self) -> u32 {
212 self.dims.height
213 }
214
215 /// The raw interleaved samples, row-major.
216 #[must_use]
217 pub fn as_samples(&self) -> &[P::Sample] {
218 &self.data
219 }
220
221 /// The raw interleaved samples as a mutable slice, row-major.
222 ///
223 /// Lets a caller edit pixels in place — post-process a decoded image, or refill an existing
224 /// buffer (see [`DecodeImage::decode_image_into`](crate::DecodeImage::decode_image_into)) —
225 /// without the [`ImageBuf::into_samples`] + [`ImageBuf::new`] round-trip. The slice length is
226 /// fixed at `width * height * P::CHANNELS`, so the length invariant is preserved: values may
227 /// change, the count cannot.
228 #[must_use]
229 pub fn as_mut_samples(&mut self) -> &mut [P::Sample] {
230 &mut self.data
231 }
232
233 /// Consumes the image, returning its backing sample vector.
234 #[must_use]
235 pub fn into_samples(self) -> Vec<P::Sample> {
236 self.data
237 }
238}
239
240/// Two images are equal when they have the same dimensions and the same samples. Hand-written
241/// rather than derived so the brand `P` carries no `PartialEq` bound (only the samples and
242/// dimensions are compared). Comparing dimensions first short-circuits the sample comparison on a
243/// size mismatch.
244impl<P: Pixel> PartialEq for ImageBuf<P> {
245 fn eq(&self, other: &Self) -> bool {
246 self.dims == other.dims && self.data == other.data
247 }
248}
249
250impl<P: Pixel> Eq for ImageBuf<P> {}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255 use crate::{Gray8, Rgb8, Rgb16};
256
257 fn dims(w: u32, h: u32) -> Dimensions {
258 Dimensions {
259 width: w,
260 height: h,
261 }
262 }
263
264 #[test]
265 fn new_validates_length() {
266 let rgb = vec![0u8; 2 * 2 * 3];
267 let img = ImageRef::<Rgb8>::new(&rgb, dims(2, 2)).unwrap();
268 assert_eq!(img.dimensions(), dims(2, 2));
269 assert_eq!((img.width(), img.height()), (2, 2));
270 assert_eq!(img.as_samples().len(), 12);
271 // Too short and too long both rejected.
272 assert!(ImageRef::<Rgb8>::new(&rgb[..11], dims(2, 2)).is_err());
273 let long = vec![0u8; 13];
274 assert!(ImageRef::<Rgb8>::new(&long, dims(2, 2)).is_err());
275 }
276
277 #[test]
278 fn new_rejects_zero_sized() {
279 let empty: [u8; 0] = [];
280 assert!(ImageRef::<Rgb8>::new(&empty, dims(0, 4)).is_err());
281 assert!(ImageRef::<Rgb8>::new(&empty, dims(4, 0)).is_err());
282 }
283
284 #[test]
285 fn rejects_overflowing_dimensions() {
286 // width*height fits usize on 64-bit but *3 channels overflows; on 32-bit width*height
287 // already overflows. Either way expected_len returns the overflow error.
288 let big = dims(u32::MAX, u32::MAX);
289 assert!(ImageRef::<Rgb8>::new(&[], big).is_err());
290 assert!(ImageBuf::<Rgb8>::zeroed(big).is_err());
291 }
292
293 #[test]
294 fn row_and_pixel_access() {
295 // 3x2 RGB, pixel (x,y) tagged so we can spot misindexing.
296 let mut rgb = vec![0u8; 3 * 2 * 3];
297 for y in 0..2u32 {
298 for x in 0..3u32 {
299 let i = (y as usize * 3 + x as usize) * 3;
300 rgb[i] = x as u8;
301 rgb[i + 1] = y as u8;
302 rgb[i + 2] = 0xAA;
303 }
304 }
305 let img = ImageRef::<Rgb8>::new(&rgb, dims(3, 2)).unwrap();
306 // Assert row *contents*, not just length: `row(y)` length is `row_len` regardless of the
307 // start offset, so a mutated offset (e.g. `y * row_len` → `y / row_len`, which aliases
308 // row 0) is caught only by checking the actual samples.
309 assert_eq!(img.row(0), &[0, 0, 0xAA, 1, 0, 0xAA, 2, 0, 0xAA]);
310 assert_eq!(img.row(1), &[0, 1, 0xAA, 1, 1, 0xAA, 2, 1, 0xAA]);
311 assert_eq!(img.pixel(2, 1), &[2, 1, 0xAA]);
312 assert_eq!(img.pixel(0, 0), &[0, 0, 0xAA]);
313 // `rows()` must yield the same per-row samples in order (not merely two slices of length 9).
314 let rows: Vec<_> = img.rows().collect();
315 assert_eq!(rows.len(), 2);
316 assert_eq!(rows[0], img.row(0));
317 assert_eq!(rows[1], img.row(1));
318 }
319
320 #[test]
321 fn high_bit_depth_samples() {
322 // 2x1 RGB16 = 2 pixels * 3 channels = 6 u16 samples.
323 let rgb16 = vec![1000u16; 6];
324 let img = ImageRef::<Rgb16>::new(&rgb16, dims(2, 1)).unwrap();
325 assert_eq!(img.as_samples().len(), 6);
326 assert_eq!(img.pixel(1, 0), &[1000, 1000, 1000]);
327 // A u16 buffer of the wrong length is still rejected.
328 assert!(ImageRef::<Rgb16>::new(&[0u16; 5], dims(2, 1)).is_err());
329 }
330
331 #[test]
332 fn owned_buffer_roundtrips() {
333 let buf = ImageBuf::<Rgb8>::new(vec![7u8; 12], dims(2, 2)).unwrap();
334 assert_eq!(buf.dimensions(), dims(2, 2));
335 assert_eq!(buf.as_samples().len(), 12);
336 assert_eq!(buf.as_ref().pixel(0, 0), &[7, 7, 7]);
337 assert_eq!(buf.into_samples(), vec![7u8; 12]);
338 // Wrong length rejected on the owned path too.
339 assert!(ImageBuf::<Rgb8>::new(vec![0u8; 11], dims(2, 2)).is_err());
340 }
341
342 #[test]
343 fn equality_compares_both_dimensions_and_samples() {
344 let a = ImageBuf::<Rgb8>::new(vec![1, 2, 3, 4, 5, 6], dims(2, 1)).unwrap();
345 let b = ImageBuf::<Rgb8>::new(vec![1, 2, 3, 4, 5, 6], dims(2, 1)).unwrap();
346 assert_eq!(a, b);
347 assert_eq!(b, a); // symmetric
348
349 // Same dimensions, different samples -> not equal (catches "compares only dims").
350 let diff_data = ImageBuf::<Rgb8>::new(vec![1, 2, 3, 4, 5, 7], dims(2, 1)).unwrap();
351 assert_ne!(a, diff_data);
352
353 // Same samples and same total count, different dimensions -> not equal (catches "compares
354 // only data", and the `&&` collapsing to a single clause). 2x3 and 3x2 are both 6 Gray8
355 // samples.
356 let portrait = ImageBuf::<Gray8>::new(vec![0, 1, 2, 3, 4, 5], dims(2, 3)).unwrap();
357 let landscape = ImageBuf::<Gray8>::new(vec![0, 1, 2, 3, 4, 5], dims(3, 2)).unwrap();
358 assert_eq!(portrait.as_samples(), landscape.as_samples());
359 assert_ne!(portrait, landscape);
360
361 // The borrowed view mirrors the owned equality through `as_ref()`.
362 assert_eq!(a.as_ref(), b.as_ref());
363 assert_ne!(a.as_ref(), diff_data.as_ref());
364 assert_ne!(portrait.as_ref(), landscape.as_ref());
365 }
366
367 #[test]
368 fn width_height_report_each_dimension() {
369 // Non-square so a width<->height swap is observable; assert exact values, not just non-zero.
370 let buf = ImageBuf::<Rgb8>::zeroed(dims(4, 3)).unwrap();
371 assert_eq!(buf.width(), 4);
372 assert_eq!(buf.height(), 3);
373 assert_eq!(buf.width(), buf.dimensions().width);
374 assert_eq!(buf.height(), buf.dimensions().height);
375 }
376
377 #[test]
378 fn as_mut_samples_edits_in_place() {
379 let mut buf = ImageBuf::<Rgb8>::zeroed(dims(2, 2)).unwrap();
380 // Distinct per-index sentinels (not a uniform fill) so a slice that aliases the wrong
381 // region or length is caught, not just a no-op write.
382 let samples = buf.as_mut_samples();
383 assert_eq!(samples.len(), 2 * 2 * 3);
384 for (i, s) in samples.iter_mut().enumerate() {
385 *s = i as u8;
386 }
387 // The edits are observable through the shared accessor...
388 assert_eq!(buf.as_samples(), &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
389 // ...and persist into the owned vector (i.e. we mutated the backing storage, not a copy).
390 assert_eq!(
391 buf.into_samples(),
392 vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
393 );
394 }
395
396 #[test]
397 fn zeroed_is_all_default_and_correct_length() {
398 let buf = ImageBuf::<Rgb8>::zeroed(dims(4, 3)).unwrap();
399 assert_eq!(buf.as_samples().len(), 4 * 3 * 3);
400 assert!(buf.as_samples().iter().all(|&s| s == 0));
401 assert!(ImageBuf::<Rgb8>::zeroed(dims(0, 3)).is_err());
402 }
403}