image/images/
flat.rs

1//! Image representations for ffi.
2//!
3//! # Usage
4//!
5//! Imagine you want to offer a very simple ffi interface: The caller provides an image buffer and
6//! your program creates a thumbnail from it and dumps that image as `png`. This module is designed
7//! to help you transition from raw memory data to Rust representation.
8//!
9//! ```no_run
10//! use std::ptr;
11//! use std::slice;
12//! use image::Rgb;
13//! use image::flat::{FlatSamples, SampleLayout};
14//! use image::imageops::thumbnail;
15//!
16//! #[no_mangle]
17//! pub extern "C" fn store_rgb8_compressed(
18//!     data: *const u8, len: usize,
19//!     layout: *const SampleLayout
20//! )
21//!     -> bool
22//! {
23//!     let samples = unsafe { slice::from_raw_parts(data, len) };
24//!     let layout = unsafe { ptr::read(layout) };
25//!
26//!     let buffer = FlatSamples {
27//!         samples,
28//!         layout,
29//!         color_hint: None,
30//!     };
31//!
32//!     let view = match buffer.as_view::<Rgb<u8>>() {
33//!         Err(_) => return false, // Invalid layout.
34//!         Ok(view) => view,
35//!     };
36//!
37//!     thumbnail(&view, 64, 64)
38//!         .save("output.png")
39//!         .map(|_| true)
40//!         .unwrap_or_else(|_| false)
41//! }
42//! ```
43//!
44use std::marker::PhantomData;
45use std::ops::{Deref, Index, IndexMut};
46use std::{cmp, error, fmt};
47
48use num_traits::Zero;
49
50use crate::color::ColorType;
51use crate::error::{
52    DecodingError, ImageError, ImageFormatHint, ParameterError, ParameterErrorKind,
53    UnsupportedError, UnsupportedErrorKind,
54};
55use crate::traits::Pixel;
56use crate::{GenericImage, GenericImageView, ImageBuffer};
57
58/// A flat buffer over a (multi channel) image.
59///
60/// In contrast to `ImageBuffer`, this representation of a sample collection is much more lenient
61/// in the layout thereof. It also allows grouping by color planes instead of by pixel as long as
62/// the strides of each extent are constant. This struct itself has no invariants on the strides
63/// but not every possible configuration can be interpreted as a [`GenericImageView`] or
64/// [`GenericImage`]. The methods [`as_view`] and [`as_view_mut`] construct the actual implementors
65/// of these traits and perform necessary checks. To manually perform this and other layout checks
66/// use [`is_normal`] or [`has_aliased_samples`].
67///
68/// Instances can be constructed not only by hand. The buffer instances returned by library
69/// functions such as [`ImageBuffer::as_flat_samples`] guarantee that the conversion to a generic
70/// image or generic view succeeds. A very different constructor is [`with_monocolor`]. It uses a
71/// single pixel as the backing storage for an arbitrarily sized read-only raster by mapping each
72/// pixel to the same samples by setting some strides to `0`.
73///
74/// [`GenericImage`]: ../trait.GenericImage.html
75/// [`GenericImageView`]: ../trait.GenericImageView.html
76/// [`ImageBuffer::as_flat_samples`]: ../struct.ImageBuffer.html#method.as_flat_samples
77/// [`is_normal`]: #method.is_normal
78/// [`has_aliased_samples`]: #method.has_aliased_samples
79/// [`as_view`]: #method.as_view
80/// [`as_view_mut`]: #method.as_view_mut
81/// [`with_monocolor`]: #method.with_monocolor
82#[derive(Clone, Debug)]
83pub struct FlatSamples<Buffer> {
84    /// Underlying linear container holding sample values.
85    pub samples: Buffer,
86
87    /// A `repr(C)` description of the layout of buffer samples.
88    pub layout: SampleLayout,
89
90    /// Supplementary color information.
91    ///
92    /// You may keep this as `None` in most cases. This is NOT checked in `View` or other
93    /// converters. It is intended mainly as a way for types that convert to this buffer type to
94    /// attach their otherwise static color information. A dynamic image representation could
95    /// however use this to resolve representational ambiguities such as the order of RGB channels.
96    pub color_hint: Option<ColorType>,
97}
98
99/// A ffi compatible description of a sample buffer.
100#[repr(C)]
101#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
102pub struct SampleLayout {
103    /// The number of channels in the color representation of the image.
104    pub channels: u8,
105
106    /// Add this to an index to get to the sample in the next channel.
107    pub channel_stride: usize,
108
109    /// The width of the represented image.
110    pub width: u32,
111
112    /// Add this to an index to get to the next sample in x-direction.
113    pub width_stride: usize,
114
115    /// The height of the represented image.
116    pub height: u32,
117
118    /// Add this to an index to get to the next sample in y-direction.
119    pub height_stride: usize,
120}
121
122/// Helper struct for an unnamed (stride, length) pair.
123#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
124struct Dim(usize, usize);
125
126impl SampleLayout {
127    /// Describe a row-major image packed in all directions.
128    ///
129    /// The resulting will surely be `NormalForm::RowMajorPacked`. It can therefore be converted to
130    /// safely to an `ImageBuffer` with a large enough underlying buffer.
131    ///
132    /// ```
133    /// # use image::flat::{NormalForm, SampleLayout};
134    /// let layout = SampleLayout::row_major_packed(3, 640, 480);
135    /// assert!(layout.is_normal(NormalForm::RowMajorPacked));
136    /// ```
137    ///
138    /// # Panics
139    ///
140    /// On platforms where `usize` has the same size as `u32` this panics when the resulting stride
141    /// in the `height` direction would be larger than `usize::MAX`. On other platforms
142    /// where it can surely accommodate `u8::MAX * u32::MAX`, this can never happen.
143    #[must_use]
144    pub fn row_major_packed(channels: u8, width: u32, height: u32) -> Self {
145        let height_stride = (channels as usize).checked_mul(width as usize).expect(
146            "Row major packed image can not be described because it does not fit into memory",
147        );
148        SampleLayout {
149            channels,
150            channel_stride: 1,
151            width,
152            width_stride: channels as usize,
153            height,
154            height_stride,
155        }
156    }
157
158    /// Describe a column-major image packed in all directions.
159    ///
160    /// The resulting will surely be `NormalForm::ColumnMajorPacked`. This is not particularly
161    /// useful for conversion but can be used to describe such a buffer without pitfalls.
162    ///
163    /// ```
164    /// # use image::flat::{NormalForm, SampleLayout};
165    /// let layout = SampleLayout::column_major_packed(3, 640, 480);
166    /// assert!(layout.is_normal(NormalForm::ColumnMajorPacked));
167    /// ```
168    ///
169    /// # Panics
170    ///
171    /// On platforms where `usize` has the same size as `u32` this panics when the resulting stride
172    /// in the `width` direction would be larger than `usize::MAX`. On other platforms
173    /// where it can surely accommodate `u8::MAX * u32::MAX`, this can never happen.
174    #[must_use]
175    pub fn column_major_packed(channels: u8, width: u32, height: u32) -> Self {
176        let width_stride = (channels as usize).checked_mul(height as usize).expect(
177            "Column major packed image can not be described because it does not fit into memory",
178        );
179        SampleLayout {
180            channels,
181            channel_stride: 1,
182            height,
183            height_stride: channels as usize,
184            width,
185            width_stride,
186        }
187    }
188
189    /// Get the strides for indexing matrix-like `[(c, w, h)]`.
190    ///
191    /// For a row-major layout with grouped samples, this tuple is strictly
192    /// increasing.
193    #[must_use]
194    pub fn strides_cwh(&self) -> (usize, usize, usize) {
195        (self.channel_stride, self.width_stride, self.height_stride)
196    }
197
198    /// Get the dimensions `(channels, width, height)`.
199    ///
200    /// The interface is optimized for use with `strides_cwh` instead. The channel extent will be
201    /// before width and height.
202    #[must_use]
203    pub fn extents(&self) -> (usize, usize, usize) {
204        (
205            self.channels as usize,
206            self.width as usize,
207            self.height as usize,
208        )
209    }
210
211    /// Tuple of bounds in the order of coordinate inputs.
212    ///
213    /// This function should be used whenever working with image coordinates opposed to buffer
214    /// coordinates. The only difference compared to `extents` is the output type.
215    #[must_use]
216    pub fn bounds(&self) -> (u8, u32, u32) {
217        (self.channels, self.width, self.height)
218    }
219
220    /// Get the minimum length of a buffer such that all in-bounds samples have valid indices.
221    ///
222    /// This method will allow zero strides, allowing compact representations of monochrome images.
223    /// To check that no aliasing occurs, try `check_alias_invariants`. For compact images (no
224    /// aliasing and no unindexed samples) this is `width*height*channels`. But for both of the
225    /// other cases, the reasoning is slightly more involved.
226    ///
227    /// # Explanation
228    ///
229    /// Note that there is a difference between `min_length` and the index of the sample
230    /// 'one-past-the-end'. This is due to strides that may be larger than the dimension below.
231    ///
232    /// ## Example with holes
233    ///
234    /// Let's look at an example of a grayscale image with
235    /// * `width_stride = 1`
236    /// * `width = 2`
237    /// * `height_stride = 3`
238    /// * `height = 2`
239    ///
240    /// ```text
241    /// | x x   | x x m | $
242    ///  min_length m ^
243    ///                   ^ one-past-the-end $
244    /// ```
245    ///
246    /// The difference is also extreme for empty images with large strides. The one-past-the-end
247    /// sample index is still as large as the largest of these strides while `min_length = 0`.
248    ///
249    /// ## Example with aliasing
250    ///
251    /// The concept gets even more important when you allow samples to alias each other. Here we
252    /// have the buffer of a small grayscale image where this is the case, this time we will first
253    /// show the buffer and then the individual rows below.
254    ///
255    /// * `width_stride = 1`
256    /// * `width = 3`
257    /// * `height_stride = 2`
258    /// * `height = 2`
259    ///
260    /// ```text
261    ///  1 2 3 4 5 m
262    /// |1 2 3| row one
263    ///     |3 4 5| row two
264    ///            ^ m min_length
265    ///          ^ ??? one-past-the-end
266    /// ```
267    ///
268    /// This time 'one-past-the-end' is not even simply the largest stride times the extent of its
269    /// dimension. That still points inside the image because `height*height_stride = 4` but also
270    /// `index_of(1, 2) = 4`.
271    #[must_use]
272    pub fn min_length(&self) -> Option<usize> {
273        if self.width == 0 || self.height == 0 || self.channels == 0 {
274            return Some(0);
275        }
276
277        self.index(self.channels - 1, self.width - 1, self.height - 1)
278            .and_then(|idx| idx.checked_add(1))
279    }
280
281    /// Check if a buffer of length `len` is large enough.
282    #[must_use]
283    pub fn fits(&self, len: usize) -> bool {
284        self.min_length().is_some_and(|min| len >= min)
285    }
286
287    /// The extents of this array, in order of increasing strides.
288    fn increasing_stride_dims(&self) -> [Dim; 3] {
289        // Order extents by strides, then check that each is less equal than the next stride.
290        let mut grouped: [Dim; 3] = [
291            Dim(self.channel_stride, self.channels as usize),
292            Dim(self.width_stride, self.width as usize),
293            Dim(self.height_stride, self.height as usize),
294        ];
295
296        grouped.sort();
297
298        let (min_dim, mid_dim, max_dim) = (grouped[0], grouped[1], grouped[2]);
299        assert!(min_dim.stride() <= mid_dim.stride() && mid_dim.stride() <= max_dim.stride());
300
301        grouped
302    }
303
304    /// If there are any samples aliasing each other.
305    ///
306    /// If this is not the case, it would always be safe to allow mutable access to two different
307    /// samples at the same time. Otherwise, this operation would need additional checks. When one
308    /// dimension overflows `usize` with its stride we also consider this aliasing.
309    #[must_use]
310    pub fn has_aliased_samples(&self) -> bool {
311        let grouped = self.increasing_stride_dims();
312        let (min_dim, mid_dim, max_dim) = (grouped[0], grouped[1], grouped[2]);
313
314        let min_size = match min_dim.checked_len() {
315            None => return true,
316            Some(size) => size,
317        };
318
319        let mid_size = match mid_dim.checked_len() {
320            None => return true,
321            Some(size) => size,
322        };
323
324        if max_dim.checked_len().is_none() {
325            return true;
326        }
327
328        // Each higher dimension must walk over all of one lower dimension.
329        min_size > mid_dim.stride() || mid_size > max_dim.stride()
330    }
331
332    /// Check if a buffer fulfills the requirements of a normal form.
333    ///
334    /// Certain conversions have preconditions on the structure of the sample buffer that are not
335    /// captured (by design) by the type system. These are then checked before the conversion. Such
336    /// checks can all be done in constant time and will not inspect the buffer content. You can
337    /// perform these checks yourself when the conversion is not required at this moment but maybe
338    /// still performed later.
339    #[must_use]
340    pub fn is_normal(&self, form: NormalForm) -> bool {
341        if self.has_aliased_samples() {
342            return false;
343        }
344
345        if form >= NormalForm::PixelPacked && self.channel_stride != 1 {
346            return false;
347        }
348
349        if form >= NormalForm::ImagePacked {
350            // has aliased already checked for overflows.
351            let grouped = self.increasing_stride_dims();
352            let (min_dim, mid_dim, max_dim) = (grouped[0], grouped[1], grouped[2]);
353
354            if 1 != min_dim.stride() {
355                return false;
356            }
357
358            if min_dim.len() != mid_dim.stride() {
359                return false;
360            }
361
362            if mid_dim.len() != max_dim.stride() {
363                return false;
364            }
365        }
366
367        if form >= NormalForm::RowMajorPacked {
368            if self.width_stride != self.channels as usize {
369                return false;
370            }
371
372            if self.width as usize * self.width_stride != self.height_stride {
373                return false;
374            }
375        }
376
377        if form >= NormalForm::ColumnMajorPacked {
378            if self.height_stride != self.channels as usize {
379                return false;
380            }
381
382            if self.height as usize * self.height_stride != self.width_stride {
383                return false;
384            }
385        }
386
387        true
388    }
389
390    /// Check that the pixel and the channel index are in bounds.
391    ///
392    /// An in-bound coordinate does not yet guarantee that the corresponding calculation of a
393    /// buffer index does not overflow. However, if such a buffer large enough to hold all samples
394    /// actually exists in memory, this property of course follows.
395    #[must_use]
396    pub fn in_bounds(&self, channel: u8, x: u32, y: u32) -> bool {
397        channel < self.channels && x < self.width && y < self.height
398    }
399
400    /// Resolve the index of a particular sample.
401    ///
402    /// `None` if the index is outside the bounds or does not fit into a `usize`.
403    #[must_use]
404    pub fn index(&self, channel: u8, x: u32, y: u32) -> Option<usize> {
405        if !self.in_bounds(channel, x, y) {
406            return None;
407        }
408
409        self.index_ignoring_bounds(channel as usize, x as usize, y as usize)
410    }
411
412    /// Get the theoretical position of sample (channel, x, y).
413    ///
414    /// The 'check' is for overflow during index calculation, not that it is contained in the
415    /// image. Two samples may return the same index, even when one of them is out of bounds. This
416    /// happens when all strides are `0`, i.e. the image is an arbitrarily large monochrome image.
417    #[must_use]
418    pub fn index_ignoring_bounds(&self, channel: usize, x: usize, y: usize) -> Option<usize> {
419        let idx_c = channel.checked_mul(self.channel_stride);
420        let idx_x = x.checked_mul(self.width_stride);
421        let idx_y = y.checked_mul(self.height_stride);
422
423        let (Some(idx_c), Some(idx_x), Some(idx_y)) = (idx_c, idx_x, idx_y) else {
424            return None;
425        };
426
427        Some(0usize)
428            .and_then(|b| b.checked_add(idx_c))
429            .and_then(|b| b.checked_add(idx_x))
430            .and_then(|b| b.checked_add(idx_y))
431    }
432
433    /// Get an index provided it is inbouds.
434    ///
435    /// Assumes that the image is backed by some sufficiently large buffer. Then computation can
436    /// not overflow as we could represent the maximum coordinate. Since overflow is defined either
437    /// way, this method can not be unsafe.
438    ///
439    /// Behavior is *unspecified* if the index is out of bounds or this sample layout would require
440    /// a buffer larger than `isize::MAX` bytes.
441    #[must_use]
442    pub fn in_bounds_index(&self, c: u8, x: u32, y: u32) -> usize {
443        let (c_stride, x_stride, y_stride) = self.strides_cwh();
444        (y as usize * y_stride) + (x as usize * x_stride) + (c as usize * c_stride)
445    }
446
447    /// Shrink the image to the minimum of current and given extents.
448    ///
449    /// This does not modify the strides, so that the resulting sample buffer may have holes
450    /// created by the shrinking operation. Shrinking could also lead to an non-aliasing image when
451    /// samples had aliased each other before.
452    pub fn shrink_to(&mut self, channels: u8, width: u32, height: u32) {
453        self.channels = self.channels.min(channels);
454        self.width = self.width.min(width);
455        self.height = self.height.min(height);
456    }
457}
458
459impl Dim {
460    fn stride(self) -> usize {
461        self.0
462    }
463
464    /// Length of this dimension in memory.
465    fn checked_len(self) -> Option<usize> {
466        self.0.checked_mul(self.1)
467    }
468
469    fn len(self) -> usize {
470        self.0 * self.1
471    }
472}
473
474impl<Buffer> FlatSamples<Buffer> {
475    /// Get the strides for indexing matrix-like `[(c, w, h)]`.
476    ///
477    /// For a row-major layout with grouped samples, this tuple is strictly
478    /// increasing.
479    pub fn strides_cwh(&self) -> (usize, usize, usize) {
480        self.layout.strides_cwh()
481    }
482
483    /// Get the dimensions `(channels, width, height)`.
484    ///
485    /// The interface is optimized for use with `strides_cwh` instead. The channel extent will be
486    /// before width and height.
487    pub fn extents(&self) -> (usize, usize, usize) {
488        self.layout.extents()
489    }
490
491    /// Tuple of bounds in the order of coordinate inputs.
492    ///
493    /// This function should be used whenever working with image coordinates opposed to buffer
494    /// coordinates. The only difference compared to `extents` is the output type.
495    pub fn bounds(&self) -> (u8, u32, u32) {
496        self.layout.bounds()
497    }
498
499    /// Get a reference based version.
500    pub fn as_ref<T>(&self) -> FlatSamples<&[T]>
501    where
502        Buffer: AsRef<[T]>,
503    {
504        FlatSamples {
505            samples: self.samples.as_ref(),
506            layout: self.layout,
507            color_hint: self.color_hint,
508        }
509    }
510
511    /// Get a mutable reference based version.
512    pub fn as_mut<T>(&mut self) -> FlatSamples<&mut [T]>
513    where
514        Buffer: AsMut<[T]>,
515    {
516        FlatSamples {
517            samples: self.samples.as_mut(),
518            layout: self.layout,
519            color_hint: self.color_hint,
520        }
521    }
522
523    /// Copy the data into an owned vector.
524    pub fn to_vec<T>(&self) -> FlatSamples<Vec<T>>
525    where
526        T: Clone,
527        Buffer: AsRef<[T]>,
528    {
529        FlatSamples {
530            samples: self.samples.as_ref().to_vec(),
531            layout: self.layout,
532            color_hint: self.color_hint,
533        }
534    }
535
536    /// Get a reference to a single sample.
537    ///
538    /// This more restrictive than the method based on `std::ops::Index` but guarantees to properly
539    /// check all bounds and not panic as long as `Buffer::as_ref` does not do so.
540    ///
541    /// ```
542    /// # use image::{RgbImage};
543    /// let flat = RgbImage::new(480, 640).into_flat_samples();
544    ///
545    /// // Get the blue channel at (10, 10).
546    /// assert!(flat.get_sample(1, 10, 10).is_some());
547    ///
548    /// // There is no alpha channel.
549    /// assert!(flat.get_sample(3, 10, 10).is_none());
550    /// ```
551    ///
552    /// For cases where a special buffer does not provide `AsRef<[T]>`, consider encapsulating
553    /// bounds checks with `min_length` in a type similar to `View`. Then you may use
554    /// `in_bounds_index` as a small speedup over the index calculation of this method which relies
555    /// on `index_ignoring_bounds` since it can not have a-priori knowledge that the sample
556    /// coordinate is in fact backed by any memory buffer.
557    pub fn get_sample<T>(&self, channel: u8, x: u32, y: u32) -> Option<&T>
558    where
559        Buffer: AsRef<[T]>,
560    {
561        self.index(channel, x, y)
562            .and_then(|idx| self.samples.as_ref().get(idx))
563    }
564
565    /// Get a mutable reference to a single sample.
566    ///
567    /// This more restrictive than the method based on `std::ops::IndexMut` but guarantees to
568    /// properly check all bounds and not panic as long as `Buffer::as_ref` does not do so.
569    /// Contrary to conversion to `ViewMut`, this does not require that samples are packed since it
570    /// does not need to convert samples to a color representation.
571    ///
572    /// **WARNING**: Note that of course samples may alias, so that the mutable reference returned
573    /// here can in fact modify more than the coordinate in the argument.
574    ///
575    /// ```
576    /// # use image::{RgbImage};
577    /// let mut flat = RgbImage::new(480, 640).into_flat_samples();
578    ///
579    /// // Assign some new color to the blue channel at (10, 10).
580    /// *flat.get_mut_sample(1, 10, 10).unwrap() = 255;
581    ///
582    /// // There is no alpha channel.
583    /// assert!(flat.get_mut_sample(3, 10, 10).is_none());
584    /// ```
585    ///
586    /// For cases where a special buffer does not provide `AsRef<[T]>`, consider encapsulating
587    /// bounds checks with `min_length` in a type similar to `View`. Then you may use
588    /// `in_bounds_index` as a small speedup over the index calculation of this method which relies
589    /// on `index_ignoring_bounds` since it can not have a-priori knowledge that the sample
590    /// coordinate is in fact backed by any memory buffer.
591    pub fn get_mut_sample<T>(&mut self, channel: u8, x: u32, y: u32) -> Option<&mut T>
592    where
593        Buffer: AsMut<[T]>,
594    {
595        match self.index(channel, x, y) {
596            None => None,
597            Some(idx) => self.samples.as_mut().get_mut(idx),
598        }
599    }
600
601    /// View this buffer as an image over some type of pixel.
602    ///
603    /// This first ensures that all in-bounds coordinates refer to valid indices in the sample
604    /// buffer. It also checks that the specified pixel format expects the same number of channels
605    /// that are present in this buffer. Neither are larger nor a smaller number will be accepted.
606    /// There is no automatic conversion.
607    pub fn as_view<P>(&self) -> Result<View<&[P::Subpixel], P>, Error>
608    where
609        P: Pixel,
610        Buffer: AsRef<[P::Subpixel]>,
611    {
612        FlatSamples {
613            samples: self.samples.as_ref(),
614            layout: self.layout,
615            color_hint: self.color_hint,
616        }
617        .into_view()
618    }
619
620    /// Convert this descriptor into a readable image.
621    ///
622    /// An owned version of [`Self::as_view`] that uses the original buffer type.
623    pub(crate) fn into_view<P>(self) -> Result<View<Buffer, P>, Error>
624    where
625        P: Pixel,
626        Buffer: AsRef<[P::Subpixel]>,
627    {
628        if self.layout.channels != P::CHANNEL_COUNT {
629            return Err(Error::ChannelCountMismatch(
630                self.layout.channels,
631                P::CHANNEL_COUNT,
632            ));
633        }
634
635        if !self.layout.fits(self.samples.as_ref().len()) {
636            return Err(Error::TooLarge);
637        }
638
639        Ok(View {
640            inner: self,
641            phantom: PhantomData,
642        })
643    }
644
645    /// View this buffer but keep mutability at a sample level.
646    ///
647    /// This is similar to `as_view` but subtly different from `as_view_mut`. The resulting type
648    /// can be used as a `GenericImage` with the same prior invariants needed as for `as_view`.
649    /// It can not be used as a mutable `GenericImage` but does not need channels to be packed in
650    /// their pixel representation.
651    ///
652    /// This first ensures that all in-bounds coordinates refer to valid indices in the sample
653    /// buffer. It also checks that the specified pixel format expects the same number of channels
654    /// that are present in this buffer. Neither are larger nor a smaller number will be accepted.
655    /// There is no automatic conversion.
656    ///
657    /// **WARNING**: Note that of course samples may alias, so that the mutable reference returned
658    /// for one sample can in fact modify other samples as well. Sometimes exactly this is
659    /// intended.
660    pub fn as_view_with_mut_samples<P>(&mut self) -> Result<View<&mut [P::Subpixel], P>, Error>
661    where
662        P: Pixel,
663        Buffer: AsMut<[P::Subpixel]>,
664    {
665        if self.layout.channels != P::CHANNEL_COUNT {
666            return Err(Error::ChannelCountMismatch(
667                self.layout.channels,
668                P::CHANNEL_COUNT,
669            ));
670        }
671
672        let as_mut = self.samples.as_mut();
673        if !self.layout.fits(as_mut.len()) {
674            return Err(Error::TooLarge);
675        }
676
677        Ok(View {
678            inner: FlatSamples {
679                samples: as_mut,
680                layout: self.layout,
681                color_hint: self.color_hint,
682            },
683            phantom: PhantomData,
684        })
685    }
686
687    /// Interpret this buffer as a mutable image.
688    ///
689    /// To succeed, the pixels in this buffer may not alias each other and the samples of each
690    /// pixel must be packed (i.e. `channel_stride` is `1`). The number of channels must be
691    /// consistent with the channel count expected by the pixel format.
692    ///
693    /// This is similar to an `ImageBuffer` except it is a temporary view that is not normalized as
694    /// strongly. To get an owning version, consider copying the data into an `ImageBuffer`. This
695    /// provides many more operations, is possibly faster (if not you may want to open an issue) is
696    /// generally polished. You can also try to convert this buffer inline, see
697    /// `ImageBuffer::from_raw`.
698    pub fn as_view_mut<P>(&mut self) -> Result<ViewMut<&mut [P::Subpixel], P>, Error>
699    where
700        P: Pixel,
701        Buffer: AsMut<[P::Subpixel]>,
702    {
703        if !self.layout.is_normal(NormalForm::PixelPacked) {
704            return Err(Error::NormalFormRequired(NormalForm::PixelPacked));
705        }
706
707        if self.layout.channels != P::CHANNEL_COUNT {
708            return Err(Error::ChannelCountMismatch(
709                self.layout.channels,
710                P::CHANNEL_COUNT,
711            ));
712        }
713
714        let as_mut = self.samples.as_mut();
715        if !self.layout.fits(as_mut.len()) {
716            return Err(Error::TooLarge);
717        }
718
719        Ok(ViewMut {
720            inner: FlatSamples {
721                samples: as_mut,
722                layout: self.layout,
723                color_hint: self.color_hint,
724            },
725            phantom: PhantomData,
726        })
727    }
728
729    /// View the samples as a slice.
730    ///
731    /// The slice is not limited to the region of the image and not all sample indices are valid
732    /// indices into this buffer. See `image_mut_slice` as an alternative.
733    pub fn as_slice<T>(&self) -> &[T]
734    where
735        Buffer: AsRef<[T]>,
736    {
737        self.samples.as_ref()
738    }
739
740    /// View the samples as a slice.
741    ///
742    /// The slice is not limited to the region of the image and not all sample indices are valid
743    /// indices into this buffer. See `image_mut_slice` as an alternative.
744    pub fn as_mut_slice<T>(&mut self) -> &mut [T]
745    where
746        Buffer: AsMut<[T]>,
747    {
748        self.samples.as_mut()
749    }
750
751    /// Return the portion of the buffer that holds sample values.
752    ///
753    /// This may fail when the coordinates in this image are either out-of-bounds of the underlying
754    /// buffer or can not be represented. Note that the slice may have holes that do not correspond
755    /// to any sample in the image represented by it.
756    pub fn image_slice<T>(&self) -> Option<&[T]>
757    where
758        Buffer: AsRef<[T]>,
759    {
760        let min_length = self.min_length()?;
761
762        let slice = self.samples.as_ref();
763        if slice.len() < min_length {
764            return None;
765        }
766
767        Some(&slice[..min_length])
768    }
769
770    /// Mutable portion of the buffer that holds sample values.
771    pub fn image_mut_slice<T>(&mut self) -> Option<&mut [T]>
772    where
773        Buffer: AsMut<[T]>,
774    {
775        let min_length = self.min_length()?;
776
777        let slice = self.samples.as_mut();
778        if slice.len() < min_length {
779            return None;
780        }
781
782        Some(&mut slice[..min_length])
783    }
784
785    /// Move the data into an image buffer.
786    ///
787    /// This does **not** convert the sample layout. The buffer needs to be in packed row-major form
788    /// before calling this function. In case of an error, returns the buffer again so that it does
789    /// not release any allocation.
790    pub fn try_into_buffer<P>(self) -> Result<ImageBuffer<P, Buffer>, (Error, Self)>
791    where
792        P: Pixel + 'static,
793        P::Subpixel: 'static,
794        Buffer: Deref<Target = [P::Subpixel]>,
795    {
796        if !self.is_normal(NormalForm::RowMajorPacked) {
797            return Err((Error::NormalFormRequired(NormalForm::RowMajorPacked), self));
798        }
799
800        if self.layout.channels != P::CHANNEL_COUNT {
801            return Err((
802                Error::ChannelCountMismatch(self.layout.channels, P::CHANNEL_COUNT),
803                self,
804            ));
805        }
806
807        if !self.fits(self.samples.deref().len()) {
808            return Err((Error::TooLarge, self));
809        }
810
811        Ok(
812            ImageBuffer::from_raw(self.layout.width, self.layout.height, self.samples)
813                .unwrap_or_else(|| {
814                    panic!("Preconditions should have been ensured before conversion")
815                }),
816        )
817    }
818
819    /// Get the minimum length of a buffer such that all in-bounds samples have valid indices.
820    ///
821    /// This method will allow zero strides, allowing compact representations of monochrome images.
822    /// To check that no aliasing occurs, try `check_alias_invariants`. For compact images (no
823    /// aliasing and no unindexed samples) this is `width*height*channels`. But for both of the
824    /// other cases, the reasoning is slightly more involved.
825    ///
826    /// # Explanation
827    ///
828    /// Note that there is a difference between `min_length` and the index of the sample
829    /// 'one-past-the-end'. This is due to strides that may be larger than the dimension below.
830    ///
831    /// ## Example with holes
832    ///
833    /// Let's look at an example of a grayscale image with
834    /// * `width_stride = 1`
835    /// * `width = 2`
836    /// * `height_stride = 3`
837    /// * `height = 2`
838    ///
839    /// ```text
840    /// | x x   | x x m | $
841    ///  min_length m ^
842    ///                   ^ one-past-the-end $
843    /// ```
844    ///
845    /// The difference is also extreme for empty images with large strides. The one-past-the-end
846    /// sample index is still as large as the largest of these strides while `min_length = 0`.
847    ///
848    /// ## Example with aliasing
849    ///
850    /// The concept gets even more important when you allow samples to alias each other. Here we
851    /// have the buffer of a small grayscale image where this is the case, this time we will first
852    /// show the buffer and then the individual rows below.
853    ///
854    /// * `width_stride = 1`
855    /// * `width = 3`
856    /// * `height_stride = 2`
857    /// * `height = 2`
858    ///
859    /// ```text
860    ///  1 2 3 4 5 m
861    /// |1 2 3| row one
862    ///     |3 4 5| row two
863    ///            ^ m min_length
864    ///          ^ ??? one-past-the-end
865    /// ```
866    ///
867    /// This time 'one-past-the-end' is not even simply the largest stride times the extent of its
868    /// dimension. That still points inside the image because `height*height_stride = 4` but also
869    /// `index_of(1, 2) = 4`.
870    pub fn min_length(&self) -> Option<usize> {
871        self.layout.min_length()
872    }
873
874    /// Check if a buffer of length `len` is large enough.
875    pub fn fits(&self, len: usize) -> bool {
876        self.layout.fits(len)
877    }
878
879    /// If there are any samples aliasing each other.
880    ///
881    /// If this is not the case, it would always be safe to allow mutable access to two different
882    /// samples at the same time. Otherwise, this operation would need additional checks. When one
883    /// dimension overflows `usize` with its stride we also consider this aliasing.
884    pub fn has_aliased_samples(&self) -> bool {
885        self.layout.has_aliased_samples()
886    }
887
888    /// Check if a buffer fulfills the requirements of a normal form.
889    ///
890    /// Certain conversions have preconditions on the structure of the sample buffer that are not
891    /// captured (by design) by the type system. These are then checked before the conversion. Such
892    /// checks can all be done in constant time and will not inspect the buffer content. You can
893    /// perform these checks yourself when the conversion is not required at this moment but maybe
894    /// still performed later.
895    pub fn is_normal(&self, form: NormalForm) -> bool {
896        self.layout.is_normal(form)
897    }
898
899    /// Check that the pixel and the channel index are in bounds.
900    ///
901    /// An in-bound coordinate does not yet guarantee that the corresponding calculation of a
902    /// buffer index does not overflow. However, if such a buffer large enough to hold all samples
903    /// actually exists in memory, this property of course follows.
904    pub fn in_bounds(&self, channel: u8, x: u32, y: u32) -> bool {
905        self.layout.in_bounds(channel, x, y)
906    }
907
908    /// Resolve the index of a particular sample.
909    ///
910    /// `None` if the index is outside the bounds or does not fit into a `usize`.
911    pub fn index(&self, channel: u8, x: u32, y: u32) -> Option<usize> {
912        self.layout.index(channel, x, y)
913    }
914
915    /// Get the theoretical position of sample (x, y, channel).
916    ///
917    /// The 'check' is for overflow during index calculation, not that it is contained in the
918    /// image. Two samples may return the same index, even when one of them is out of bounds. This
919    /// happens when all strides are `0`, i.e. the image is an arbitrarily large monochrome image.
920    pub fn index_ignoring_bounds(&self, channel: usize, x: usize, y: usize) -> Option<usize> {
921        self.layout.index_ignoring_bounds(channel, x, y)
922    }
923
924    /// Get an index provided it is inbouds.
925    ///
926    /// Assumes that the image is backed by some sufficiently large buffer. Then computation can
927    /// not overflow as we could represent the maximum coordinate. Since overflow is defined either
928    /// way, this method can not be unsafe.
929    pub fn in_bounds_index(&self, channel: u8, x: u32, y: u32) -> usize {
930        self.layout.in_bounds_index(channel, x, y)
931    }
932
933    /// Shrink the image to the minimum of current and given extents.
934    ///
935    /// This does not modify the strides, so that the resulting sample buffer may have holes
936    /// created by the shrinking operation. Shrinking could also lead to an non-aliasing image when
937    /// samples had aliased each other before.
938    pub fn shrink_to(&mut self, channels: u8, width: u32, height: u32) {
939        self.layout.shrink_to(channels, width, height);
940    }
941}
942
943impl<'buf, Subpixel> FlatSamples<&'buf [Subpixel]> {
944    /// Create a monocolor image from a single pixel.
945    ///
946    /// This can be used as a very cheap source of a `GenericImageView` with an arbitrary number of
947    /// pixels of a single color, without any dynamic allocation.
948    ///
949    /// ## Examples
950    ///
951    /// ```
952    /// # fn paint_something<T>(_: T) {}
953    /// use image::{flat::FlatSamples, GenericImage, RgbImage, Rgb};
954    ///
955    /// let background = Rgb([20, 20, 20]);
956    /// let bg = FlatSamples::with_monocolor(&background, 200, 200);
957    ///
958    /// let mut image = RgbImage::new(200, 200);
959    /// paint_something(&mut image);
960    ///
961    /// // Reset the canvas
962    /// image.copy_from(&bg.as_view().unwrap(), 0, 0);
963    /// ```
964    pub fn with_monocolor<P>(pixel: &'buf P, width: u32, height: u32) -> Self
965    where
966        P: Pixel<Subpixel = Subpixel>,
967        Subpixel: crate::Primitive,
968    {
969        FlatSamples {
970            samples: pixel.channels(),
971            layout: SampleLayout {
972                channels: P::CHANNEL_COUNT,
973                channel_stride: 1,
974                width,
975                width_stride: 0,
976                height,
977                height_stride: 0,
978            },
979
980            // TODO this value is never set. It should be set in all places where the Pixel type implements PixelWithColorType
981            color_hint: None,
982        }
983    }
984}
985
986/// A flat buffer that can be used as an image view.
987///
988/// This is a nearly trivial wrapper around a buffer but at least sanitizes by checking the buffer
989/// length first and constraining the pixel type.
990///
991/// Note that this does not eliminate panics as the `AsRef<[T]>` implementation of `Buffer` may be
992/// unreliable, i.e. return different buffers at different times. This of course is a non-issue for
993/// all common collections where the bounds check once must be enough.
994///
995/// # Inner invariants
996///
997/// * For all indices inside bounds, the corresponding index is valid in the buffer
998/// * `P::channel_count()` agrees with `self.inner.layout.channels`
999#[derive(Clone, Debug)]
1000pub struct View<Buffer, P: Pixel>
1001where
1002    Buffer: AsRef<[P::Subpixel]>,
1003{
1004    inner: FlatSamples<Buffer>,
1005    phantom: PhantomData<P>,
1006}
1007
1008/// Type alias for a view based on a pixel's channels.
1009pub type ViewOfPixel<'lt, P> = View<&'lt [<P as Pixel>::Subpixel], P>;
1010
1011/// A mutable owning version of a flat buffer.
1012///
1013/// While this wraps a buffer similar to `ImageBuffer`, this is mostly intended as a utility. The
1014/// library endorsed normalized representation is still `ImageBuffer`. Also, the implementation of
1015/// `AsMut<[P::Subpixel]>` must always yield the same buffer. Therefore there is no public way to
1016/// construct this with an owning buffer.
1017///
1018/// # Inner invariants
1019///
1020/// * For all indices inside bounds, the corresponding index is valid in the buffer
1021/// * There is no aliasing of samples
1022/// * The samples are packed, i.e. `self.inner.layout.sample_stride == 1`
1023/// * `P::channel_count()` agrees with `self.inner.layout.channels`
1024#[derive(Clone, Debug)]
1025pub struct ViewMut<Buffer, P: Pixel>
1026where
1027    Buffer: AsMut<[P::Subpixel]>,
1028{
1029    inner: FlatSamples<Buffer>,
1030    phantom: PhantomData<P>,
1031}
1032
1033/// Type alias for a mutable view based on a pixel's channels.
1034pub type ViewMutOfPixel<'lt, P> = ViewMut<&'lt mut [<P as Pixel>::Subpixel], P>;
1035
1036/// Denotes invalid flat sample buffers when trying to convert to stricter types.
1037///
1038/// The biggest use case being `ImageBuffer` which expects closely packed
1039/// samples in a row major matrix representation. But this error type may be
1040/// reused for other import functions. A more versatile user may also try to
1041/// correct the underlying representation depending on the error variant.
1042#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1043pub enum Error {
1044    /// The represented image was too large.
1045    ///
1046    /// The optional value denotes a possibly accepted maximal bound.
1047    TooLarge,
1048
1049    /// The represented image can not use this representation.
1050    ///
1051    /// Has an additional value of the normalized form that would be accepted.
1052    NormalFormRequired(NormalForm),
1053
1054    /// The color format did not match the channel count.
1055    ///
1056    /// In some cases you might be able to fix this by lowering the reported pixel count of the
1057    /// buffer without touching the strides.
1058    ///
1059    /// In very special circumstances you *may* do the opposite. This is **VERY** dangerous but not
1060    /// directly memory unsafe although that will likely alias pixels. One scenario is when you
1061    /// want to construct an `Rgba` image but have only 3 bytes per pixel and for some reason don't
1062    /// care about the value of the alpha channel even though you need `Rgba`.
1063    ChannelCountMismatch(u8, u8),
1064
1065    /// Deprecated - `ChannelCountMismatch` is used instead
1066    WrongColor(ColorType),
1067}
1068
1069/// Different normal forms of buffers.
1070///
1071/// A normal form is an unaliased buffer with some additional constraints.  The `ÌmageBuffer` uses
1072/// row major form with packed samples.
1073#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1074pub enum NormalForm {
1075    /// No pixel aliases another.
1076    ///
1077    /// Unaliased also guarantees that all index calculations in the image bounds using
1078    /// `dim_index*dim_stride` (such as `x*width_stride + y*height_stride`) do not overflow.
1079    Unaliased,
1080
1081    /// At least pixels are packed.
1082    ///
1083    /// Images of these types can wrap `[T]`-slices into the standard color types. This is a
1084    /// precondition for `GenericImage` which requires by-reference access to pixels.
1085    PixelPacked,
1086
1087    /// All samples are packed.
1088    ///
1089    /// This is orthogonal to `PixelPacked`. It requires that there are no holes in the image but
1090    /// it is not necessary that the pixel samples themselves are adjacent. An example of this
1091    /// behaviour is a planar image layout.
1092    ImagePacked,
1093
1094    /// The samples are in row-major form and all samples are packed.
1095    ///
1096    /// In addition to `PixelPacked` and `ImagePacked` this also asserts that the pixel matrix is
1097    /// in row-major form.
1098    RowMajorPacked,
1099
1100    /// The samples are in column-major form and all samples are packed.
1101    ///
1102    /// In addition to `PixelPacked` and `ImagePacked` this also asserts that the pixel matrix is
1103    /// in column-major form.
1104    ColumnMajorPacked,
1105}
1106
1107impl<Buffer, P: Pixel> View<Buffer, P>
1108where
1109    Buffer: AsRef<[P::Subpixel]>,
1110{
1111    /// Take out the sample buffer.
1112    ///
1113    /// Gives up the normalization invariants on the buffer format.
1114    pub fn into_inner(self) -> FlatSamples<Buffer> {
1115        self.inner
1116    }
1117
1118    /// Get a reference on the inner sample descriptor.
1119    ///
1120    /// There is no mutable counterpart as modifying the buffer format, including strides and
1121    /// lengths, could invalidate the accessibility invariants of the `View`. It is not specified
1122    /// if the inner buffer is the same as the buffer of the image from which this view was
1123    /// created. It might have been truncated as an optimization.
1124    pub fn flat(&self) -> &FlatSamples<Buffer> {
1125        &self.inner
1126    }
1127
1128    /// Get a reference on the inner buffer.
1129    ///
1130    /// There is no mutable counter part since it is not intended to allow you to reassign the
1131    /// buffer or otherwise change its size or properties.
1132    pub fn samples(&self) -> &Buffer {
1133        &self.inner.samples
1134    }
1135
1136    /// Get a reference to a selected subpixel if it is in-bounds.
1137    ///
1138    /// This method will return `None` when the sample is out-of-bounds. All errors that could
1139    /// occur due to overflow have been eliminated while construction the `View`.
1140    pub fn get_sample(&self, channel: u8, x: u32, y: u32) -> Option<&P::Subpixel> {
1141        if !self.inner.in_bounds(channel, x, y) {
1142            return None;
1143        }
1144
1145        let index = self.inner.in_bounds_index(channel, x, y);
1146        // Should always be `Some(_)` but checking is more costly.
1147        self.samples().as_ref().get(index)
1148    }
1149
1150    /// Get a mutable reference to a selected subpixel if it is in-bounds.
1151    ///
1152    /// This is relevant only when constructed with `FlatSamples::as_view_with_mut_samples`.  This
1153    /// method will return `None` when the sample is out-of-bounds. All errors that could occur due
1154    /// to overflow have been eliminated while construction the `View`.
1155    ///
1156    /// **WARNING**: Note that of course samples may alias, so that the mutable reference returned
1157    /// here can in fact modify more than the coordinate in the argument.
1158    pub fn get_mut_sample(&mut self, channel: u8, x: u32, y: u32) -> Option<&mut P::Subpixel>
1159    where
1160        Buffer: AsMut<[P::Subpixel]>,
1161    {
1162        if !self.inner.in_bounds(channel, x, y) {
1163            return None;
1164        }
1165
1166        let index = self.inner.in_bounds_index(channel, x, y);
1167        // Should always be `Some(_)` but checking is more costly.
1168        self.inner.samples.as_mut().get_mut(index)
1169    }
1170
1171    /// Get the minimum length of a buffer such that all in-bounds samples have valid indices.
1172    ///
1173    /// See `FlatSamples::min_length`. This method will always succeed.
1174    pub fn min_length(&self) -> usize {
1175        self.inner.min_length().unwrap()
1176    }
1177
1178    /// Return the portion of the buffer that holds sample values.
1179    ///
1180    /// While this can not fail–the validity of all coordinates has been validated during the
1181    /// conversion from `FlatSamples`–the resulting slice may still contain holes.
1182    pub fn image_slice(&self) -> &[P::Subpixel] {
1183        &self.samples().as_ref()[..self.min_length()]
1184    }
1185
1186    pub(crate) fn strides_wh(&self) -> (usize, usize) {
1187        // Note `c` stride must be `1` for a valid `View` so we can ignore it here.
1188        let (_, w, h) = self.inner.layout.strides_cwh();
1189        (w, h)
1190    }
1191
1192    /// Return the mutable portion of the buffer that holds sample values.
1193    ///
1194    /// This is relevant only when constructed with `FlatSamples::as_view_with_mut_samples`. While
1195    /// this can not fail–the validity of all coordinates has been validated during the conversion
1196    /// from `FlatSamples`–the resulting slice may still contain holes.
1197    pub fn image_mut_slice(&mut self) -> &mut [P::Subpixel]
1198    where
1199        Buffer: AsMut<[P::Subpixel]>,
1200    {
1201        let min_length = self.min_length();
1202        &mut self.inner.samples.as_mut()[..min_length]
1203    }
1204
1205    /// Shrink the inner image.
1206    ///
1207    /// The new dimensions will be the minimum of the previous dimensions. Since the set of
1208    /// in-bounds pixels afterwards is a subset of the current ones, this is allowed on a `View`.
1209    /// Note that you can not change the number of channels as an intrinsic property of `P`.
1210    pub fn shrink_to(&mut self, width: u32, height: u32) {
1211        let channels = self.inner.layout.channels;
1212        self.inner.shrink_to(channels, width, height);
1213    }
1214
1215    /// Try to convert this into an image with mutable pixels.
1216    ///
1217    /// The resulting image implements `GenericImage` in addition to `GenericImageView`. While this
1218    /// has mutable samples, it does not enforce that pixel can not alias and that samples are
1219    /// packed enough for a mutable pixel reference. This is slightly cheaper than the chain
1220    /// `self.into_inner().as_view_mut()` and keeps the `View` alive on failure.
1221    ///
1222    /// ```
1223    /// # use image::RgbImage;
1224    /// # use image::Rgb;
1225    /// let mut buffer = RgbImage::new(480, 640).into_flat_samples();
1226    /// let view = buffer.as_view_with_mut_samples::<Rgb<u8>>().unwrap();
1227    ///
1228    /// // Inspect some pixels, …
1229    ///
1230    /// // Doesn't fail because it was originally an `RgbImage`.
1231    /// let view_mut = view.try_upgrade().unwrap();
1232    /// ```
1233    pub fn try_upgrade(self) -> Result<ViewMut<Buffer, P>, (Error, Self)>
1234    where
1235        Buffer: AsMut<[P::Subpixel]>,
1236    {
1237        if !self.inner.is_normal(NormalForm::PixelPacked) {
1238            return Err((Error::NormalFormRequired(NormalForm::PixelPacked), self));
1239        }
1240
1241        // No length check or channel count check required, all the same.
1242        Ok(ViewMut {
1243            inner: self.inner,
1244            phantom: PhantomData,
1245        })
1246    }
1247}
1248
1249impl<Buffer, P: Pixel> ViewMut<Buffer, P>
1250where
1251    Buffer: AsMut<[P::Subpixel]>,
1252{
1253    /// Take out the sample buffer.
1254    ///
1255    /// Gives up the normalization invariants on the buffer format.
1256    pub fn into_inner(self) -> FlatSamples<Buffer> {
1257        self.inner
1258    }
1259
1260    /// Get a reference on the sample buffer descriptor.
1261    ///
1262    /// There is no mutable counterpart as modifying the buffer format, including strides and
1263    /// lengths, could invalidate the accessibility invariants of the `View`. It is not specified
1264    /// if the inner buffer is the same as the buffer of the image from which this view was
1265    /// created. It might have been truncated as an optimization.
1266    pub fn flat(&self) -> &FlatSamples<Buffer> {
1267        &self.inner
1268    }
1269
1270    /// Get a reference on the inner buffer.
1271    ///
1272    /// There is no mutable counter part since it is not intended to allow you to reassign the
1273    /// buffer or otherwise change its size or properties. However, its contents can be accessed
1274    /// mutable through a slice with `image_mut_slice`.
1275    pub fn samples(&self) -> &Buffer {
1276        &self.inner.samples
1277    }
1278
1279    /// Get the minimum length of a buffer such that all in-bounds samples have valid indices.
1280    ///
1281    /// See `FlatSamples::min_length`. This method will always succeed.
1282    pub fn min_length(&self) -> usize {
1283        self.inner.min_length().unwrap()
1284    }
1285
1286    /// Get a reference to a selected subpixel.
1287    ///
1288    /// This method will return `None` when the sample is out-of-bounds. All errors that could
1289    /// occur due to overflow have been eliminated while construction the `View`.
1290    pub fn get_sample(&self, channel: u8, x: u32, y: u32) -> Option<&P::Subpixel>
1291    where
1292        Buffer: AsRef<[P::Subpixel]>,
1293    {
1294        if !self.inner.in_bounds(channel, x, y) {
1295            return None;
1296        }
1297
1298        let index = self.inner.in_bounds_index(channel, x, y);
1299        // Should always be `Some(_)` but checking is more costly.
1300        self.samples().as_ref().get(index)
1301    }
1302
1303    /// Get a mutable reference to a selected sample.
1304    ///
1305    /// This method will return `None` when the sample is out-of-bounds. All errors that could
1306    /// occur due to overflow have been eliminated while construction the `View`.
1307    pub fn get_mut_sample(&mut self, channel: u8, x: u32, y: u32) -> Option<&mut P::Subpixel> {
1308        if !self.inner.in_bounds(channel, x, y) {
1309            return None;
1310        }
1311
1312        let index = self.inner.in_bounds_index(channel, x, y);
1313        // Should always be `Some(_)` but checking is more costly.
1314        self.inner.samples.as_mut().get_mut(index)
1315    }
1316
1317    /// Return the portion of the buffer that holds sample values.
1318    ///
1319    /// While this can not fail–the validity of all coordinates has been validated during the
1320    /// conversion from `FlatSamples`–the resulting slice may still contain holes.
1321    pub fn image_slice(&self) -> &[P::Subpixel]
1322    where
1323        Buffer: AsRef<[P::Subpixel]>,
1324    {
1325        &self.inner.samples.as_ref()[..self.min_length()]
1326    }
1327
1328    /// Return the mutable buffer that holds sample values.
1329    pub fn image_mut_slice(&mut self) -> &mut [P::Subpixel] {
1330        let length = self.min_length();
1331        &mut self.inner.samples.as_mut()[..length]
1332    }
1333
1334    /// Shrink the inner image.
1335    ///
1336    /// The new dimensions will be the minimum of the previous dimensions. Since the set of
1337    /// in-bounds pixels afterwards is a subset of the current ones, this is allowed on a `View`.
1338    /// Note that you can not change the number of channels as an intrinsic property of `P`.
1339    pub fn shrink_to(&mut self, width: u32, height: u32) {
1340        let channels = self.inner.layout.channels;
1341        self.inner.shrink_to(channels, width, height);
1342    }
1343}
1344
1345// The out-of-bounds panic for single sample access similar to `slice::index`.
1346#[inline(never)]
1347#[cold]
1348fn panic_cwh_out_of_bounds(
1349    (c, x, y): (u8, u32, u32),
1350    bounds: (u8, u32, u32),
1351    strides: (usize, usize, usize),
1352) -> ! {
1353    panic!(
1354        "Sample coordinates {:?} out of sample matrix bounds {:?} with strides {:?}",
1355        (c, x, y),
1356        bounds,
1357        strides
1358    )
1359}
1360
1361// The out-of-bounds panic for pixel access similar to `slice::index`.
1362#[inline(never)]
1363#[cold]
1364fn panic_pixel_out_of_bounds((x, y): (u32, u32), bounds: (u32, u32)) -> ! {
1365    panic!("Image index {:?} out of bounds {:?}", (x, y), bounds)
1366}
1367
1368impl<Buffer> Index<(u8, u32, u32)> for FlatSamples<Buffer>
1369where
1370    Buffer: Index<usize>,
1371{
1372    type Output = Buffer::Output;
1373
1374    /// Return a reference to a single sample at specified coordinates.
1375    ///
1376    /// # Panics
1377    ///
1378    /// When the coordinates are out of bounds or the index calculation fails.
1379    fn index(&self, (c, x, y): (u8, u32, u32)) -> &Self::Output {
1380        let bounds = self.bounds();
1381        let strides = self.strides_cwh();
1382        let index = self
1383            .index(c, x, y)
1384            .unwrap_or_else(|| panic_cwh_out_of_bounds((c, x, y), bounds, strides));
1385        &self.samples[index]
1386    }
1387}
1388
1389impl<Buffer> IndexMut<(u8, u32, u32)> for FlatSamples<Buffer>
1390where
1391    Buffer: IndexMut<usize>,
1392{
1393    /// Return a mutable reference to a single sample at specified coordinates.
1394    ///
1395    /// # Panics
1396    ///
1397    /// When the coordinates are out of bounds or the index calculation fails.
1398    fn index_mut(&mut self, (c, x, y): (u8, u32, u32)) -> &mut Self::Output {
1399        let bounds = self.bounds();
1400        let strides = self.strides_cwh();
1401        let index = self
1402            .index(c, x, y)
1403            .unwrap_or_else(|| panic_cwh_out_of_bounds((c, x, y), bounds, strides));
1404        &mut self.samples[index]
1405    }
1406}
1407
1408impl<Buffer, P: Pixel> GenericImageView for View<Buffer, P>
1409where
1410    Buffer: AsRef<[P::Subpixel]>,
1411{
1412    type Pixel = P;
1413
1414    fn dimensions(&self) -> (u32, u32) {
1415        (self.inner.layout.width, self.inner.layout.height)
1416    }
1417
1418    fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel {
1419        if !self.inner.in_bounds(0, x, y) {
1420            panic_pixel_out_of_bounds((x, y), self.dimensions())
1421        }
1422
1423        let image = self.inner.samples.as_ref();
1424        let base_index = self.inner.in_bounds_index(0, x, y);
1425        let channels = P::CHANNEL_COUNT as usize;
1426
1427        let mut buffer = [Zero::zero(); 256];
1428        buffer
1429            .iter_mut()
1430            .enumerate()
1431            .take(channels)
1432            .for_each(|(c, to)| {
1433                let index = base_index + c * self.inner.layout.channel_stride;
1434                *to = image[index];
1435            });
1436
1437        *P::from_slice(&buffer[..channels])
1438    }
1439
1440    fn to_pixel_view(&self) -> Option<ViewOfPixel<'_, Self::Pixel>> {
1441        Some(View {
1442            inner: FlatSamples {
1443                samples: self.inner.samples.as_ref(),
1444                layout: self.inner.layout,
1445                color_hint: None,
1446            },
1447            phantom: PhantomData,
1448        })
1449    }
1450}
1451
1452impl<Buffer, P: Pixel> GenericImageView for ViewMut<Buffer, P>
1453where
1454    Buffer: AsMut<[P::Subpixel]> + AsRef<[P::Subpixel]>,
1455{
1456    type Pixel = P;
1457
1458    fn dimensions(&self) -> (u32, u32) {
1459        (self.inner.layout.width, self.inner.layout.height)
1460    }
1461
1462    fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel {
1463        if !self.inner.in_bounds(0, x, y) {
1464            panic_pixel_out_of_bounds((x, y), self.dimensions())
1465        }
1466
1467        let image = self.inner.samples.as_ref();
1468        let base_index = self.inner.in_bounds_index(0, x, y);
1469        let channels = P::CHANNEL_COUNT as usize;
1470
1471        let mut buffer = [Zero::zero(); 256];
1472        buffer
1473            .iter_mut()
1474            .enumerate()
1475            .take(channels)
1476            .for_each(|(c, to)| {
1477                let index = base_index + c * self.inner.layout.channel_stride;
1478                *to = image[index];
1479            });
1480
1481        *P::from_slice(&buffer[..channels])
1482    }
1483
1484    fn to_pixel_view(&self) -> Option<ViewOfPixel<'_, Self::Pixel>> {
1485        Some(View {
1486            inner: FlatSamples {
1487                samples: self.inner.samples.as_ref(),
1488                layout: self.inner.layout,
1489                color_hint: None,
1490            },
1491            phantom: PhantomData,
1492        })
1493    }
1494}
1495
1496impl<Buffer, P: Pixel> GenericImage for ViewMut<Buffer, P>
1497where
1498    Buffer: AsMut<[P::Subpixel]> + AsRef<[P::Subpixel]>,
1499{
1500    fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut Self::Pixel {
1501        if !self.inner.in_bounds(0, x, y) {
1502            panic_pixel_out_of_bounds((x, y), self.dimensions())
1503        }
1504
1505        let base_index = self.inner.in_bounds_index(0, x, y);
1506        let channel_count = <P as Pixel>::CHANNEL_COUNT as usize;
1507        let pixel_range = base_index..base_index + channel_count;
1508        P::from_slice_mut(&mut self.inner.samples.as_mut()[pixel_range])
1509    }
1510
1511    #[allow(deprecated)]
1512    fn put_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
1513        *self.get_pixel_mut(x, y) = pixel;
1514    }
1515
1516    #[allow(deprecated)]
1517    fn blend_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
1518        self.get_pixel_mut(x, y).blend(&pixel);
1519    }
1520}
1521
1522impl From<Error> for ImageError {
1523    fn from(error: Error) -> ImageError {
1524        #[derive(Debug)]
1525        struct NormalFormRequiredError(NormalForm);
1526        impl fmt::Display for NormalFormRequiredError {
1527            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1528                write!(f, "Required sample buffer in normal form {:?}", self.0)
1529            }
1530        }
1531        impl error::Error for NormalFormRequiredError {}
1532
1533        match error {
1534            Error::TooLarge => ImageError::Parameter(ParameterError::from_kind(
1535                ParameterErrorKind::DimensionMismatch,
1536            )),
1537            Error::NormalFormRequired(form) => ImageError::Decoding(DecodingError::new(
1538                ImageFormatHint::Unknown,
1539                NormalFormRequiredError(form),
1540            )),
1541            Error::ChannelCountMismatch(_lc, _pc) => ImageError::Parameter(
1542                ParameterError::from_kind(ParameterErrorKind::DimensionMismatch),
1543            ),
1544            Error::WrongColor(color) => {
1545                ImageError::Unsupported(UnsupportedError::from_format_and_kind(
1546                    ImageFormatHint::Unknown,
1547                    UnsupportedErrorKind::Color(color.into()),
1548                ))
1549            }
1550        }
1551    }
1552}
1553
1554impl fmt::Display for Error {
1555    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1556        match self {
1557            Error::TooLarge => write!(f, "The layout is too large"),
1558            Error::NormalFormRequired(form) => write!(
1559                f,
1560                "The layout needs to {}",
1561                match form {
1562                    NormalForm::ColumnMajorPacked => "be packed and in column major form",
1563                    NormalForm::ImagePacked => "be fully packed",
1564                    NormalForm::PixelPacked => "have packed pixels",
1565                    NormalForm::RowMajorPacked => "be packed and in row major form",
1566                    NormalForm::Unaliased => "not have any aliasing channels",
1567                }
1568            ),
1569            Error::ChannelCountMismatch(layout_channels, pixel_channels) => {
1570                write!(f, "The channel count of the chosen pixel (={pixel_channels}) does agree with the layout (={layout_channels})")
1571            }
1572            Error::WrongColor(color) => {
1573                write!(f, "The chosen color type does not match the hint {color:?}")
1574            }
1575        }
1576    }
1577}
1578
1579impl error::Error for Error {}
1580
1581impl PartialOrd for NormalForm {
1582    /// Compares the logical preconditions.
1583    ///
1584    /// `a < b` if the normal form `a` has less preconditions than `b`.
1585    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
1586        match (*self, *other) {
1587            (NormalForm::Unaliased, NormalForm::Unaliased) => Some(cmp::Ordering::Equal),
1588            (NormalForm::PixelPacked, NormalForm::PixelPacked) => Some(cmp::Ordering::Equal),
1589            (NormalForm::ImagePacked, NormalForm::ImagePacked) => Some(cmp::Ordering::Equal),
1590            (NormalForm::RowMajorPacked, NormalForm::RowMajorPacked) => Some(cmp::Ordering::Equal),
1591            (NormalForm::ColumnMajorPacked, NormalForm::ColumnMajorPacked) => {
1592                Some(cmp::Ordering::Equal)
1593            }
1594
1595            (NormalForm::Unaliased, _) => Some(cmp::Ordering::Less),
1596            (_, NormalForm::Unaliased) => Some(cmp::Ordering::Greater),
1597
1598            (NormalForm::PixelPacked, NormalForm::ColumnMajorPacked) => Some(cmp::Ordering::Less),
1599            (NormalForm::PixelPacked, NormalForm::RowMajorPacked) => Some(cmp::Ordering::Less),
1600            (NormalForm::RowMajorPacked, NormalForm::PixelPacked) => Some(cmp::Ordering::Greater),
1601            (NormalForm::ColumnMajorPacked, NormalForm::PixelPacked) => {
1602                Some(cmp::Ordering::Greater)
1603            }
1604
1605            (NormalForm::ImagePacked, NormalForm::ColumnMajorPacked) => Some(cmp::Ordering::Less),
1606            (NormalForm::ImagePacked, NormalForm::RowMajorPacked) => Some(cmp::Ordering::Less),
1607            (NormalForm::RowMajorPacked, NormalForm::ImagePacked) => Some(cmp::Ordering::Greater),
1608            (NormalForm::ColumnMajorPacked, NormalForm::ImagePacked) => {
1609                Some(cmp::Ordering::Greater)
1610            }
1611
1612            (NormalForm::ImagePacked, NormalForm::PixelPacked) => None,
1613            (NormalForm::PixelPacked, NormalForm::ImagePacked) => None,
1614            (NormalForm::RowMajorPacked, NormalForm::ColumnMajorPacked) => None,
1615            (NormalForm::ColumnMajorPacked, NormalForm::RowMajorPacked) => None,
1616        }
1617    }
1618}
1619
1620#[cfg(test)]
1621mod tests {
1622    use super::*;
1623    use crate::color::{LumaA, Rgb};
1624    use crate::images::buffer::GrayAlphaImage;
1625
1626    #[test]
1627    fn aliasing_view() {
1628        let buffer = FlatSamples {
1629            samples: &[42],
1630            layout: SampleLayout {
1631                channels: 3,
1632                channel_stride: 0,
1633                width: 100,
1634                width_stride: 0,
1635                height: 100,
1636                height_stride: 0,
1637            },
1638            color_hint: None,
1639        };
1640
1641        let view = buffer.as_view::<Rgb<u8>>().expect("This is a valid view");
1642        let pixel_count = view
1643            .pixels()
1644            .inspect(|pixel| assert!(pixel.2 == Rgb([42, 42, 42])))
1645            .count();
1646        assert_eq!(pixel_count, 100 * 100);
1647    }
1648
1649    #[test]
1650    fn mutable_view() {
1651        let mut buffer = FlatSamples {
1652            samples: [0; 18],
1653            layout: SampleLayout {
1654                channels: 2,
1655                channel_stride: 1,
1656                width: 3,
1657                width_stride: 2,
1658                height: 3,
1659                height_stride: 6,
1660            },
1661            color_hint: None,
1662        };
1663
1664        {
1665            let mut view = buffer
1666                .as_view_mut::<LumaA<u16>>()
1667                .expect("This should be a valid mutable buffer");
1668            assert_eq!(view.dimensions(), (3, 3));
1669            #[allow(deprecated)]
1670            for i in 0..9 {
1671                *view.get_pixel_mut(i % 3, i / 3) = LumaA([2 * i as u16, 2 * i as u16 + 1]);
1672            }
1673        }
1674
1675        buffer
1676            .samples
1677            .iter()
1678            .enumerate()
1679            .for_each(|(idx, sample)| assert_eq!(idx, *sample as usize));
1680    }
1681
1682    #[test]
1683    fn normal_forms() {
1684        assert!(FlatSamples {
1685            samples: [0u8; 0],
1686            layout: SampleLayout {
1687                channels: 2,
1688                channel_stride: 1,
1689                width: 3,
1690                width_stride: 9,
1691                height: 3,
1692                height_stride: 28,
1693            },
1694            color_hint: None,
1695        }
1696        .is_normal(NormalForm::PixelPacked));
1697
1698        assert!(FlatSamples {
1699            samples: [0u8; 0],
1700            layout: SampleLayout {
1701                channels: 2,
1702                channel_stride: 8,
1703                width: 4,
1704                width_stride: 1,
1705                height: 2,
1706                height_stride: 4,
1707            },
1708            color_hint: None,
1709        }
1710        .is_normal(NormalForm::ImagePacked));
1711
1712        assert!(FlatSamples {
1713            samples: [0u8; 0],
1714            layout: SampleLayout {
1715                channels: 2,
1716                channel_stride: 1,
1717                width: 4,
1718                width_stride: 2,
1719                height: 2,
1720                height_stride: 8,
1721            },
1722            color_hint: None,
1723        }
1724        .is_normal(NormalForm::RowMajorPacked));
1725
1726        assert!(FlatSamples {
1727            samples: [0u8; 0],
1728            layout: SampleLayout {
1729                channels: 2,
1730                channel_stride: 1,
1731                width: 4,
1732                width_stride: 4,
1733                height: 2,
1734                height_stride: 2,
1735            },
1736            color_hint: None,
1737        }
1738        .is_normal(NormalForm::ColumnMajorPacked));
1739    }
1740
1741    #[test]
1742    fn image_buffer_conversion() {
1743        let expected_layout = SampleLayout {
1744            channels: 2,
1745            channel_stride: 1,
1746            width: 4,
1747            width_stride: 2,
1748            height: 2,
1749            height_stride: 8,
1750        };
1751
1752        let initial = GrayAlphaImage::new(expected_layout.width, expected_layout.height);
1753        let buffer = initial.into_flat_samples();
1754
1755        assert_eq!(buffer.layout, expected_layout);
1756
1757        let _: GrayAlphaImage = buffer
1758            .try_into_buffer()
1759            .unwrap_or_else(|(error, _)| panic!("Expected buffer to be convertible but {error:?}"));
1760    }
1761}