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