Skip to main content

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