Skip to main content

spatialrust_image/
lib.rs

1//! Typed, CPU-resident image buffers and zero-copy strided views.
2//!
3//! Channel count is part of the type. Packed interleaved ownership is the
4//! default; planar ownership and explicitly-strided views are also available.
5//! Device-backed images belong in dedicated GPU crates so transfers remain
6//! explicit.
7
8#![deny(unsafe_code)]
9#![warn(missing_docs)]
10
11use std::ops::{Index, IndexMut};
12
13/// Errors raised while constructing or indexing images.
14#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
15pub enum ImageError {
16    /// A zero channel image type was requested.
17    #[error("image channel count must be greater than zero")]
18    ZeroChannels,
19    /// Image dimensions overflowed `usize` arithmetic.
20    #[error("image dimensions overflow addressable memory")]
21    DimensionOverflow,
22    /// The provided storage does not match the image layout.
23    #[error("image storage is too short: need at least {required} elements, found {found}")]
24    StorageTooShort {
25        /// Minimum required element count.
26        required: usize,
27        /// Provided element count.
28        found: usize,
29    },
30    /// A row stride cannot hold one row of pixels.
31    #[error("row stride {stride} is smaller than packed row width {minimum}")]
32    InvalidStride {
33        /// Provided stride in scalar elements.
34        stride: usize,
35        /// Packed row size in scalar elements.
36        minimum: usize,
37    },
38    /// A planar channel stride overlaps the preceding channel plane.
39    #[error("plane stride {stride} is smaller than one plane span {minimum}")]
40    InvalidPlaneStride {
41        /// Provided plane stride in scalar elements.
42        stride: usize,
43        /// Minimum non-overlapping plane span.
44        minimum: usize,
45    },
46    /// Color metadata is incompatible with the compile-time channel count.
47    #[error("color space {color_space:?} requires {expected} channels, image has {found}")]
48    MetadataChannelMismatch {
49        /// Declared color space.
50        color_space: ColorSpace,
51        /// Required channel count.
52        expected: usize,
53        /// Image channel count.
54        found: usize,
55    },
56    /// A requested image region lies outside its parent image.
57    #[error("region ({x}, {y}, {region_width}, {region_height}) exceeds image bounds {image_width}x{image_height}")]
58    InvalidRegion {
59        /// Region x origin.
60        x: usize,
61        /// Region y origin.
62        y: usize,
63        /// Region width.
64        region_width: usize,
65        /// Region height.
66        region_height: usize,
67        /// Parent image width.
68        image_width: usize,
69        /// Parent image height.
70        image_height: usize,
71    },
72    /// Pixel coordinates were outside the image.
73    #[error("pixel ({x}, {y}) is outside image bounds {width}x{height}")]
74    OutOfBounds {
75        /// Pixel x coordinate.
76        x: usize,
77        /// Pixel y coordinate.
78        y: usize,
79        /// Image width.
80        width: usize,
81        /// Image height.
82        height: usize,
83    },
84}
85
86/// Physical channel arrangement in CPU storage.
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
88pub enum ImageLayout {
89    /// Pixel channels are adjacent (`RGBRGB...`).
90    #[default]
91    Interleaved,
92    /// Each channel occupies a separate plane (`RR...GG...BB...`).
93    Planar,
94}
95
96/// Semantic interpretation of image channels.
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
98pub enum ColorSpace {
99    /// Channel semantics are not specified.
100    #[default]
101    Unknown,
102    /// One-channel luminance.
103    Gray,
104    /// Nonlinear red, green, blue.
105    Rgb,
106    /// Nonlinear blue, green, red.
107    Bgr,
108    /// Nonlinear red, green, blue, alpha.
109    Rgba,
110    /// Nonlinear blue, green, red, alpha.
111    Bgra,
112    /// Linear-light red, green, blue.
113    LinearRgb,
114    /// Hue, saturation, value.
115    Hsv,
116    /// Metric or sensor depth values.
117    Depth,
118    /// Integer semantic or instance labels.
119    Label,
120}
121
122impl ColorSpace {
123    /// Returns the required channel count when the color space fixes one.
124    #[must_use]
125    pub const fn required_channels(self) -> Option<usize> {
126        match self {
127            Self::Unknown => None,
128            Self::Gray | Self::Depth | Self::Label => Some(1),
129            Self::Rgb | Self::Bgr | Self::LinearRgb | Self::Hsv => Some(3),
130            Self::Rgba | Self::Bgra => Some(4),
131        }
132    }
133}
134
135/// Numeric range convention associated with image channels.
136#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
137pub enum ColorRange {
138    /// Range is not specified or is naturally unbounded (for example depth).
139    #[default]
140    Unspecified,
141    /// Full dtype or normalized range.
142    Full,
143    /// Video-range encoding such as limited-range YUV.
144    Limited,
145}
146
147/// Alpha-channel interpretation.
148#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
149pub enum AlphaMode {
150    /// No alpha channel is declared.
151    #[default]
152    None,
153    /// Straight (unassociated) alpha.
154    Straight,
155    /// RGB values are premultiplied by alpha.
156    Premultiplied,
157}
158
159/// Lightweight semantic metadata carried by images and borrowed views.
160#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
161pub struct ImageMetadata {
162    /// Channel color/depth/label interpretation.
163    pub color_space: ColorSpace,
164    /// Numeric range convention.
165    pub color_range: ColorRange,
166    /// Alpha convention.
167    pub alpha_mode: AlphaMode,
168}
169
170impl ImageMetadata {
171    /// Validates metadata against a compile-time channel count.
172    pub fn validate<const CHANNELS: usize>(self) -> Result<(), ImageError> {
173        if CHANNELS == 0 {
174            return Err(ImageError::ZeroChannels);
175        }
176        if let Some(expected) = self.color_space.required_channels() {
177            if expected != CHANNELS {
178                return Err(ImageError::MetadataChannelMismatch {
179                    color_space: self.color_space,
180                    expected,
181                    found: CHANNELS,
182                });
183            }
184        }
185        Ok(())
186    }
187}
188
189/// A checked rectangular image region.
190#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
191pub struct ImageRegion {
192    /// Horizontal origin.
193    pub x: usize,
194    /// Vertical origin.
195    pub y: usize,
196    /// Region width.
197    pub width: usize,
198    /// Region height.
199    pub height: usize,
200}
201
202impl ImageRegion {
203    /// Creates a rectangular region.
204    #[must_use]
205    pub const fn new(x: usize, y: usize, width: usize, height: usize) -> Self {
206        Self { x, y, width, height }
207    }
208
209    fn validate(self, image_width: usize, image_height: usize) -> Result<(), ImageError> {
210        let end_x = self.x.checked_add(self.width).ok_or(ImageError::DimensionOverflow)?;
211        let end_y = self.y.checked_add(self.height).ok_or(ImageError::DimensionOverflow)?;
212        if end_x > image_width || end_y > image_height {
213            return Err(ImageError::InvalidRegion {
214                x: self.x,
215                y: self.y,
216                region_width: self.width,
217                region_height: self.height,
218                image_width,
219                image_height,
220            });
221        }
222        Ok(())
223    }
224}
225
226fn packed_len<const CHANNELS: usize>(width: usize, height: usize) -> Result<usize, ImageError> {
227    if CHANNELS == 0 {
228        return Err(ImageError::ZeroChannels);
229    }
230    width
231        .checked_mul(height)
232        .and_then(|value| value.checked_mul(CHANNELS))
233        .ok_or(ImageError::DimensionOverflow)
234}
235
236fn strided_span(height: usize, row_stride: usize, packed_row: usize) -> Result<usize, ImageError> {
237    if height == 0 {
238        return Ok(0);
239    }
240    row_stride
241        .checked_mul(height - 1)
242        .and_then(|offset| offset.checked_add(packed_row))
243        .ok_or(ImageError::DimensionOverflow)
244}
245
246/// An owning, densely packed, interleaved image.
247#[derive(Clone, Debug, PartialEq, Eq)]
248pub struct Image<T, const CHANNELS: usize> {
249    width: usize,
250    height: usize,
251    data: Vec<T>,
252    metadata: ImageMetadata,
253}
254
255impl<T, const CHANNELS: usize> Image<T, CHANNELS> {
256    /// Creates an image from densely packed, interleaved scalar elements.
257    pub fn try_new(width: usize, height: usize, data: Vec<T>) -> Result<Self, ImageError> {
258        let required = packed_len::<CHANNELS>(width, height)?;
259        if data.len() != required {
260            return Err(ImageError::StorageTooShort { required, found: data.len() });
261        }
262        Ok(Self { width, height, data, metadata: ImageMetadata::default() })
263    }
264
265    /// Creates a packed image and validates its semantic metadata.
266    pub fn try_new_with_metadata(
267        width: usize,
268        height: usize,
269        data: Vec<T>,
270        metadata: ImageMetadata,
271    ) -> Result<Self, ImageError> {
272        metadata.validate::<CHANNELS>()?;
273        let mut image = Self::try_new(width, height, data)?;
274        image.metadata = metadata;
275        Ok(image)
276    }
277
278    /// Returns image width in pixels.
279    #[must_use]
280    pub const fn width(&self) -> usize {
281        self.width
282    }
283
284    /// Returns image height in pixels.
285    #[must_use]
286    pub const fn height(&self) -> usize {
287        self.height
288    }
289
290    /// Returns the packed row stride in scalar elements.
291    #[must_use]
292    pub const fn row_stride(&self) -> usize {
293        self.width * CHANNELS
294    }
295
296    /// Returns physical channel layout.
297    #[must_use]
298    pub const fn layout(&self) -> ImageLayout {
299        ImageLayout::Interleaved
300    }
301
302    /// Returns semantic image metadata.
303    #[must_use]
304    pub const fn metadata(&self) -> ImageMetadata {
305        self.metadata
306    }
307
308    /// Replaces semantic metadata after validating the channel count.
309    pub fn set_metadata(&mut self, metadata: ImageMetadata) -> Result<(), ImageError> {
310        metadata.validate::<CHANNELS>()?;
311        self.metadata = metadata;
312        Ok(())
313    }
314
315    /// Returns the packed scalar storage.
316    #[must_use]
317    pub fn as_slice(&self) -> &[T] {
318        &self.data
319    }
320
321    /// Returns mutable packed scalar storage.
322    #[must_use]
323    pub fn as_mut_slice(&mut self) -> &mut [T] {
324        &mut self.data
325    }
326
327    /// Borrows this image as a zero-copy view.
328    #[must_use]
329    pub fn view(&self) -> ImageView<'_, T, CHANNELS> {
330        ImageView {
331            width: self.width,
332            height: self.height,
333            row_stride: self.row_stride(),
334            data: &self.data,
335            metadata: self.metadata,
336        }
337    }
338
339    /// Borrows this image as a mutable zero-copy view.
340    #[must_use]
341    pub fn view_mut(&mut self) -> ImageViewMut<'_, T, CHANNELS> {
342        ImageViewMut {
343            width: self.width,
344            height: self.height,
345            row_stride: self.width * CHANNELS,
346            data: &mut self.data,
347            metadata: self.metadata,
348        }
349    }
350
351    /// Returns one pixel, or `None` outside image bounds.
352    #[must_use]
353    pub fn get(&self, x: usize, y: usize) -> Option<&[T; CHANNELS]> {
354        self.view().get(x, y)
355    }
356
357    /// Returns one mutable pixel, or `None` outside image bounds.
358    #[must_use]
359    pub fn get_mut(&mut self, x: usize, y: usize) -> Option<&mut [T; CHANNELS]> {
360        if x >= self.width || y >= self.height {
361            return None;
362        }
363        let offset = (y * self.width + x) * CHANNELS;
364        self.data.get_mut(offset..offset + CHANNELS)?.try_into().ok()
365    }
366
367    /// Consumes the image and returns its packed scalar storage.
368    #[must_use]
369    pub fn into_vec(self) -> Vec<T> {
370        self.data
371    }
372}
373
374impl<T: Clone, const CHANNELS: usize> Image<T, CHANNELS> {
375    /// Creates a densely packed image filled with one pixel value.
376    pub fn from_pixel(
377        width: usize,
378        height: usize,
379        pixel: [T; CHANNELS],
380    ) -> Result<Self, ImageError> {
381        let required = packed_len::<CHANNELS>(width, height)?;
382        let mut data = Vec::with_capacity(required);
383        for _ in 0..width.saturating_mul(height) {
384            data.extend_from_slice(&pixel);
385        }
386        Self::try_new(width, height, data)
387    }
388}
389
390impl<T, const CHANNELS: usize> Index<(usize, usize)> for Image<T, CHANNELS> {
391    type Output = [T; CHANNELS];
392
393    fn index(&self, (x, y): (usize, usize)) -> &Self::Output {
394        self.get(x, y).expect("image index out of bounds")
395    }
396}
397
398impl<T, const CHANNELS: usize> IndexMut<(usize, usize)> for Image<T, CHANNELS> {
399    fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut Self::Output {
400        self.get_mut(x, y).expect("image index out of bounds")
401    }
402}
403
404/// A read-only, zero-copy image view with an explicit row stride.
405#[derive(Clone, Copy, Debug)]
406pub struct ImageView<'a, T, const CHANNELS: usize> {
407    width: usize,
408    height: usize,
409    row_stride: usize,
410    data: &'a [T],
411    metadata: ImageMetadata,
412}
413
414impl<'a, T, const CHANNELS: usize> ImageView<'a, T, CHANNELS> {
415    /// Creates a view over interleaved storage.
416    ///
417    /// `row_stride` is measured in scalar elements, not bytes.
418    pub fn new(
419        width: usize,
420        height: usize,
421        row_stride: usize,
422        data: &'a [T],
423    ) -> Result<Self, ImageError> {
424        Self::new_with_metadata(width, height, row_stride, data, ImageMetadata::default())
425    }
426
427    /// Creates a view with validated semantic metadata.
428    pub fn new_with_metadata(
429        width: usize,
430        height: usize,
431        row_stride: usize,
432        data: &'a [T],
433        metadata: ImageMetadata,
434    ) -> Result<Self, ImageError> {
435        metadata.validate::<CHANNELS>()?;
436        let packed_row = width.checked_mul(CHANNELS).ok_or(ImageError::DimensionOverflow)?;
437        if row_stride < packed_row {
438            return Err(ImageError::InvalidStride { stride: row_stride, minimum: packed_row });
439        }
440        let required = if height == 0 {
441            0
442        } else {
443            row_stride
444                .checked_mul(height - 1)
445                .and_then(|offset| offset.checked_add(packed_row))
446                .ok_or(ImageError::DimensionOverflow)?
447        };
448        if data.len() < required {
449            return Err(ImageError::StorageTooShort { required, found: data.len() });
450        }
451        Ok(Self { width, height, row_stride, data, metadata })
452    }
453
454    /// Returns image width in pixels.
455    #[must_use]
456    pub const fn width(self) -> usize {
457        self.width
458    }
459
460    /// Returns image height in pixels.
461    #[must_use]
462    pub const fn height(self) -> usize {
463        self.height
464    }
465
466    /// Returns row stride in scalar elements.
467    #[must_use]
468    pub const fn row_stride(self) -> usize {
469        self.row_stride
470    }
471
472    /// Returns physical channel layout.
473    #[must_use]
474    pub const fn layout(self) -> ImageLayout {
475        ImageLayout::Interleaved
476    }
477
478    /// Returns semantic image metadata.
479    #[must_use]
480    pub const fn metadata(self) -> ImageMetadata {
481        self.metadata
482    }
483
484    /// Borrows exactly the logical pixels when they occupy one packed slice.
485    ///
486    /// Empty views return an empty slice. A single row is packed regardless of
487    /// its stride; multiple rows require a stride of `width * CHANNELS`.
488    /// Padding and pixels outside a subview are never included.
489    #[must_use]
490    pub fn as_packed_slice(&self) -> Option<&'a [T]> {
491        if self.width == 0 || self.height == 0 {
492            return Some(&self.data[..0]);
493        }
494        let row = self.width.checked_mul(CHANNELS)?;
495        if self.height > 1 && self.row_stride != row {
496            return None;
497        }
498        self.data.get(..row.checked_mul(self.height)?)
499    }
500
501    /// Returns one pixel, or `None` outside image bounds.
502    #[must_use]
503    pub fn get(self, x: usize, y: usize) -> Option<&'a [T; CHANNELS]> {
504        if x >= self.width || y >= self.height {
505            return None;
506        }
507        let offset = y * self.row_stride + x * CHANNELS;
508        self.data.get(offset..offset + CHANNELS)?.try_into().ok()
509    }
510
511    /// Returns a packed row without its trailing padding.
512    #[must_use]
513    pub fn row(self, y: usize) -> Option<&'a [T]> {
514        if y >= self.height {
515            return None;
516        }
517        let start = y * self.row_stride;
518        self.data.get(start..start + self.width * CHANNELS)
519    }
520
521    /// Creates a checked zero-copy subview.
522    pub fn subview(self, region: ImageRegion) -> Result<Self, ImageError> {
523        region.validate(self.width, self.height)?;
524        if region.width == 0 || region.height == 0 {
525            return Ok(Self {
526                width: region.width,
527                height: region.height,
528                row_stride: self.row_stride,
529                data: &self.data[..0],
530                metadata: self.metadata,
531            });
532        }
533        let start = region.y * self.row_stride + region.x * CHANNELS;
534        let span = (region.height - 1) * self.row_stride + region.width * CHANNELS;
535        Ok(Self {
536            width: region.width,
537            height: region.height,
538            row_stride: self.row_stride,
539            data: &self.data[start..start + span],
540            metadata: self.metadata,
541        })
542    }
543}
544
545/// A mutable, zero-copy interleaved image view with an explicit row stride.
546#[derive(Debug)]
547pub struct ImageViewMut<'a, T, const CHANNELS: usize> {
548    width: usize,
549    height: usize,
550    row_stride: usize,
551    data: &'a mut [T],
552    metadata: ImageMetadata,
553}
554
555impl<'a, T, const CHANNELS: usize> ImageViewMut<'a, T, CHANNELS> {
556    /// Creates a mutable view over interleaved storage.
557    pub fn new(
558        width: usize,
559        height: usize,
560        row_stride: usize,
561        data: &'a mut [T],
562    ) -> Result<Self, ImageError> {
563        Self::new_with_metadata(width, height, row_stride, data, ImageMetadata::default())
564    }
565
566    /// Creates a mutable view with validated semantic metadata.
567    pub fn new_with_metadata(
568        width: usize,
569        height: usize,
570        row_stride: usize,
571        data: &'a mut [T],
572        metadata: ImageMetadata,
573    ) -> Result<Self, ImageError> {
574        metadata.validate::<CHANNELS>()?;
575        let packed_row = width.checked_mul(CHANNELS).ok_or(ImageError::DimensionOverflow)?;
576        if row_stride < packed_row {
577            return Err(ImageError::InvalidStride { stride: row_stride, minimum: packed_row });
578        }
579        let required = strided_span(height, row_stride, packed_row)?;
580        if data.len() < required {
581            return Err(ImageError::StorageTooShort { required, found: data.len() });
582        }
583        Ok(Self { width, height, row_stride, data, metadata })
584    }
585
586    /// Returns image width in pixels.
587    #[must_use]
588    pub const fn width(&self) -> usize {
589        self.width
590    }
591
592    /// Returns image height in pixels.
593    #[must_use]
594    pub const fn height(&self) -> usize {
595        self.height
596    }
597
598    /// Returns row stride in scalar elements.
599    #[must_use]
600    pub const fn row_stride(&self) -> usize {
601        self.row_stride
602    }
603
604    /// Returns semantic image metadata.
605    #[must_use]
606    pub const fn metadata(&self) -> ImageMetadata {
607        self.metadata
608    }
609
610    /// Replaces semantic metadata after validating the channel count.
611    pub fn set_metadata(&mut self, metadata: ImageMetadata) -> Result<(), ImageError> {
612        metadata.validate::<CHANNELS>()?;
613        self.metadata = metadata;
614        Ok(())
615    }
616
617    /// Reborrows this mutable view as read-only.
618    #[must_use]
619    pub fn as_view(&self) -> ImageView<'_, T, CHANNELS> {
620        ImageView {
621            width: self.width,
622            height: self.height,
623            row_stride: self.row_stride,
624            data: self.data,
625            metadata: self.metadata,
626        }
627    }
628
629    /// Returns one read-only pixel, or `None` outside image bounds.
630    #[must_use]
631    pub fn get(&self, x: usize, y: usize) -> Option<&[T; CHANNELS]> {
632        self.as_view().get(x, y)
633    }
634
635    /// Returns one mutable pixel, or `None` outside image bounds.
636    #[must_use]
637    pub fn get_mut(&mut self, x: usize, y: usize) -> Option<&mut [T; CHANNELS]> {
638        if x >= self.width || y >= self.height {
639            return None;
640        }
641        let offset = y * self.row_stride + x * CHANNELS;
642        self.data.get_mut(offset..offset + CHANNELS)?.try_into().ok()
643    }
644
645    /// Returns a mutable packed row without trailing padding.
646    #[must_use]
647    pub fn row_mut(&mut self, y: usize) -> Option<&mut [T]> {
648        if y >= self.height {
649            return None;
650        }
651        let start = y * self.row_stride;
652        self.data.get_mut(start..start + self.width * CHANNELS)
653    }
654
655    /// Returns the complete mutable backing span, including inter-row padding.
656    ///
657    /// The final row has no required trailing padding, so the returned length is
658    /// the minimum checked span accepted by [`ImageViewMut::new`].
659    #[must_use]
660    pub fn as_mut_slice(&mut self) -> &mut [T] {
661        self.data
662    }
663
664    /// Creates a checked mutable zero-copy subview.
665    pub fn subview(
666        &mut self,
667        region: ImageRegion,
668    ) -> Result<ImageViewMut<'_, T, CHANNELS>, ImageError> {
669        region.validate(self.width, self.height)?;
670        if region.width == 0 || region.height == 0 {
671            return Ok(ImageViewMut {
672                width: region.width,
673                height: region.height,
674                row_stride: self.row_stride,
675                data: &mut self.data[..0],
676                metadata: self.metadata,
677            });
678        }
679        let start = region.y * self.row_stride + region.x * CHANNELS;
680        let span = (region.height - 1) * self.row_stride + region.width * CHANNELS;
681        Ok(ImageViewMut {
682            width: region.width,
683            height: region.height,
684            row_stride: self.row_stride,
685            data: &mut self.data[start..start + span],
686            metadata: self.metadata,
687        })
688    }
689}
690
691/// An owning, densely packed planar image.
692///
693/// Storage order is all values for channel 0, followed by channel 1, and so on.
694#[derive(Clone, Debug, PartialEq, Eq)]
695pub struct PlanarImage<T, const CHANNELS: usize> {
696    width: usize,
697    height: usize,
698    data: Vec<T>,
699    metadata: ImageMetadata,
700}
701
702impl<T, const CHANNELS: usize> PlanarImage<T, CHANNELS> {
703    /// Creates an image from densely packed planar scalar elements.
704    pub fn try_new(width: usize, height: usize, data: Vec<T>) -> Result<Self, ImageError> {
705        let required = packed_len::<CHANNELS>(width, height)?;
706        if data.len() != required {
707            return Err(ImageError::StorageTooShort { required, found: data.len() });
708        }
709        Ok(Self { width, height, data, metadata: ImageMetadata::default() })
710    }
711
712    /// Creates a planar image with validated semantic metadata.
713    pub fn try_new_with_metadata(
714        width: usize,
715        height: usize,
716        data: Vec<T>,
717        metadata: ImageMetadata,
718    ) -> Result<Self, ImageError> {
719        metadata.validate::<CHANNELS>()?;
720        let mut image = Self::try_new(width, height, data)?;
721        image.metadata = metadata;
722        Ok(image)
723    }
724
725    /// Returns image width in pixels.
726    #[must_use]
727    pub const fn width(&self) -> usize {
728        self.width
729    }
730
731    /// Returns image height in pixels.
732    #[must_use]
733    pub const fn height(&self) -> usize {
734        self.height
735    }
736
737    /// Returns physical channel layout.
738    #[must_use]
739    pub const fn layout(&self) -> ImageLayout {
740        ImageLayout::Planar
741    }
742
743    /// Returns packed row stride within each plane.
744    #[must_use]
745    pub const fn row_stride(&self) -> usize {
746        self.width
747    }
748
749    /// Returns the scalar distance between channel-plane origins.
750    #[must_use]
751    pub const fn plane_stride(&self) -> usize {
752        self.width * self.height
753    }
754
755    /// Returns semantic image metadata.
756    #[must_use]
757    pub const fn metadata(&self) -> ImageMetadata {
758        self.metadata
759    }
760
761    /// Replaces semantic metadata after validating the channel count.
762    pub fn set_metadata(&mut self, metadata: ImageMetadata) -> Result<(), ImageError> {
763        metadata.validate::<CHANNELS>()?;
764        self.metadata = metadata;
765        Ok(())
766    }
767
768    /// Returns planar scalar storage.
769    #[must_use]
770    pub fn as_slice(&self) -> &[T] {
771        &self.data
772    }
773
774    /// Returns mutable planar scalar storage.
775    #[must_use]
776    pub fn as_mut_slice(&mut self) -> &mut [T] {
777        &mut self.data
778    }
779
780    /// Borrows this image as a planar view.
781    #[must_use]
782    pub fn view(&self) -> PlanarImageView<'_, T, CHANNELS> {
783        PlanarImageView {
784            width: self.width,
785            height: self.height,
786            row_stride: self.width,
787            plane_stride: self.width * self.height,
788            data: &self.data,
789            metadata: self.metadata,
790        }
791    }
792
793    /// Returns one channel value, or `None` outside image bounds.
794    #[must_use]
795    pub fn get(&self, channel: usize, x: usize, y: usize) -> Option<&T> {
796        self.view().get(channel, x, y)
797    }
798
799    /// Returns one mutable channel value, or `None` outside image bounds.
800    #[must_use]
801    pub fn get_mut(&mut self, channel: usize, x: usize, y: usize) -> Option<&mut T> {
802        if channel >= CHANNELS || x >= self.width || y >= self.height {
803            return None;
804        }
805        let offset = channel * self.width * self.height + y * self.width + x;
806        self.data.get_mut(offset)
807    }
808
809    /// Consumes the image and returns planar scalar storage.
810    #[must_use]
811    pub fn into_vec(self) -> Vec<T> {
812        self.data
813    }
814}
815
816/// A read-only, zero-copy planar image view with explicit strides.
817#[derive(Clone, Copy, Debug)]
818pub struct PlanarImageView<'a, T, const CHANNELS: usize> {
819    width: usize,
820    height: usize,
821    row_stride: usize,
822    plane_stride: usize,
823    data: &'a [T],
824    metadata: ImageMetadata,
825}
826
827impl<'a, T, const CHANNELS: usize> PlanarImageView<'a, T, CHANNELS> {
828    /// Creates a planar view. Strides are measured in scalar elements.
829    pub fn new(
830        width: usize,
831        height: usize,
832        row_stride: usize,
833        plane_stride: usize,
834        data: &'a [T],
835    ) -> Result<Self, ImageError> {
836        Self::new_with_metadata(
837            width,
838            height,
839            row_stride,
840            plane_stride,
841            data,
842            ImageMetadata::default(),
843        )
844    }
845
846    /// Creates a planar view with validated semantic metadata.
847    pub fn new_with_metadata(
848        width: usize,
849        height: usize,
850        row_stride: usize,
851        plane_stride: usize,
852        data: &'a [T],
853        metadata: ImageMetadata,
854    ) -> Result<Self, ImageError> {
855        metadata.validate::<CHANNELS>()?;
856        if row_stride < width {
857            return Err(ImageError::InvalidStride { stride: row_stride, minimum: width });
858        }
859        let plane_span = strided_span(height, row_stride, width)?;
860        if plane_stride < plane_span {
861            return Err(ImageError::InvalidPlaneStride {
862                stride: plane_stride,
863                minimum: plane_span,
864            });
865        }
866        let required = if width == 0 || height == 0 {
867            0
868        } else {
869            plane_stride
870                .checked_mul(CHANNELS - 1)
871                .and_then(|offset| offset.checked_add(plane_span))
872                .ok_or(ImageError::DimensionOverflow)?
873        };
874        if data.len() < required {
875            return Err(ImageError::StorageTooShort { required, found: data.len() });
876        }
877        Ok(Self { width, height, row_stride, plane_stride, data, metadata })
878    }
879
880    /// Returns image width in pixels.
881    #[must_use]
882    pub const fn width(self) -> usize {
883        self.width
884    }
885
886    /// Returns image height in pixels.
887    #[must_use]
888    pub const fn height(self) -> usize {
889        self.height
890    }
891
892    /// Returns row stride within a plane.
893    #[must_use]
894    pub const fn row_stride(self) -> usize {
895        self.row_stride
896    }
897
898    /// Returns scalar distance between channel-plane origins.
899    #[must_use]
900    pub const fn plane_stride(self) -> usize {
901        self.plane_stride
902    }
903
904    /// Returns physical channel layout.
905    #[must_use]
906    pub const fn layout(self) -> ImageLayout {
907        ImageLayout::Planar
908    }
909
910    /// Returns semantic image metadata.
911    #[must_use]
912    pub const fn metadata(self) -> ImageMetadata {
913        self.metadata
914    }
915
916    /// Returns one channel value, or `None` outside image bounds.
917    #[must_use]
918    pub fn get(self, channel: usize, x: usize, y: usize) -> Option<&'a T> {
919        if channel >= CHANNELS || x >= self.width || y >= self.height {
920            return None;
921        }
922        self.data.get(channel * self.plane_stride + y * self.row_stride + x)
923    }
924
925    /// Copies one pixel from its channel planes.
926    #[must_use]
927    pub fn pixel(self, x: usize, y: usize) -> Option<[T; CHANNELS]>
928    where
929        T: Copy,
930    {
931        if x >= self.width || y >= self.height {
932            return None;
933        }
934        Some(std::array::from_fn(|channel| {
935            *self.get(channel, x, y).expect("validated planar coordinate")
936        }))
937    }
938
939    /// Creates a checked zero-copy planar subview.
940    pub fn subview(self, region: ImageRegion) -> Result<Self, ImageError> {
941        region.validate(self.width, self.height)?;
942        if region.width == 0 || region.height == 0 {
943            return Ok(Self {
944                width: region.width,
945                height: region.height,
946                row_stride: self.row_stride,
947                plane_stride: self.plane_stride,
948                data: &self.data[..0],
949                metadata: self.metadata,
950            });
951        }
952        let start = region.y * self.row_stride + region.x;
953        let span = (CHANNELS - 1) * self.plane_stride
954            + (region.height - 1) * self.row_stride
955            + region.width;
956        Ok(Self {
957            width: region.width,
958            height: region.height,
959            row_stride: self.row_stride,
960            plane_stride: self.plane_stride,
961            data: &self.data[start..start + span],
962            metadata: self.metadata,
963        })
964    }
965}
966
967/// A one-channel image.
968pub type GrayImage<T> = Image<T, 1>;
969/// A three-channel RGB image.
970pub type RgbImage<T> = Image<T, 3>;
971
972#[cfg(test)]
973mod tests {
974    use super::{
975        AlphaMode, ColorRange, ColorSpace, Image, ImageError, ImageMetadata, ImageRegion,
976        ImageView, ImageViewMut, PlanarImage, PlanarImageView,
977    };
978
979    #[test]
980    fn packed_image_indexes_pixels() {
981        let mut image = Image::<u8, 3>::try_new(2, 1, vec![1, 2, 3, 4, 5, 6]).unwrap();
982        assert_eq!(image[(1, 0)], [4, 5, 6]);
983        image[(0, 0)] = [7, 8, 9];
984        assert_eq!(image.as_slice(), &[7, 8, 9, 4, 5, 6]);
985    }
986
987    #[test]
988    fn strided_view_skips_padding() {
989        let data = [1_u16, 2, 99, 3, 4];
990        let view = ImageView::<u16, 1>::new(2, 2, 3, &data).unwrap();
991        assert_eq!(view.get(0, 1), Some(&[3]));
992        assert_eq!(view.row(0), Some(&[1, 2][..]));
993    }
994
995    #[test]
996    fn rejects_short_storage() {
997        assert_eq!(
998            Image::<u8, 1>::try_new(2, 2, vec![0; 3]).unwrap_err(),
999            ImageError::StorageTooShort { required: 4, found: 3 }
1000        );
1001    }
1002
1003    #[test]
1004    fn mutable_roi_updates_only_selected_pixels() {
1005        let mut data = [0_u8, 1, 2, 99, 3, 4, 5];
1006        let mut view = ImageViewMut::<u8, 1>::new(3, 2, 4, &mut data).unwrap();
1007        {
1008            let mut roi = view.subview(ImageRegion::new(1, 0, 2, 2)).unwrap();
1009            *roi.get_mut(0, 0).unwrap() = [10];
1010            *roi.get_mut(1, 1).unwrap() = [20];
1011        }
1012        assert_eq!(data, [0, 10, 2, 99, 3, 4, 20]);
1013    }
1014
1015    #[test]
1016    fn immutable_roi_preserves_parent_stride() {
1017        let data = [0_u8, 1, 2, 99, 3, 4, 5];
1018        let view = ImageView::<u8, 1>::new(3, 2, 4, &data).unwrap();
1019        let roi = view.subview(ImageRegion::new(1, 0, 2, 2)).unwrap();
1020        assert_eq!(roi.row_stride(), 4);
1021        assert_eq!(roi.get(0, 0), Some(&[1]));
1022        assert_eq!(roi.get(1, 1), Some(&[5]));
1023        assert!(view.subview(ImageRegion::new(2, 1, 2, 1)).is_err());
1024    }
1025
1026    #[test]
1027    fn planar_image_reads_channels_and_subviews() {
1028        // R plane, G plane, B plane.
1029        let mut image = PlanarImage::<u8, 3>::try_new(
1030            2,
1031            2,
1032            vec![1, 2, 3, 4, 10, 20, 30, 40, 100, 110, 120, 130],
1033        )
1034        .unwrap();
1035        assert_eq!(image.view().pixel(1, 1), Some([4, 40, 130]));
1036        *image.get_mut(1, 0, 1).unwrap() = 31;
1037        let roi = image.view().subview(ImageRegion::new(0, 1, 2, 1)).unwrap();
1038        assert_eq!(roi.pixel(0, 0), Some([3, 31, 120]));
1039        assert_eq!(roi.pixel(1, 0), Some([4, 40, 130]));
1040    }
1041
1042    #[test]
1043    fn planar_view_honors_row_and_plane_padding() {
1044        let data = [1_u8, 2, 99, 3, 4, 88, 77, 10, 20, 99, 30, 40];
1045        let view = PlanarImageView::<u8, 2>::new(2, 2, 3, 7, &data).unwrap();
1046        assert_eq!(view.pixel(0, 1), Some([3, 30]));
1047        assert_eq!(view.pixel(1, 1), Some([4, 40]));
1048    }
1049
1050    #[test]
1051    fn validates_color_metadata_channel_count() {
1052        let metadata = ImageMetadata {
1053            color_space: ColorSpace::Rgb,
1054            color_range: ColorRange::Full,
1055            alpha_mode: AlphaMode::None,
1056        };
1057        let image = Image::<u8, 3>::try_new_with_metadata(1, 1, vec![1, 2, 3], metadata).unwrap();
1058        assert_eq!(image.metadata(), metadata);
1059        assert!(matches!(
1060            Image::<u8, 1>::try_new_with_metadata(1, 1, vec![1], metadata),
1061            Err(ImageError::MetadataChannelMismatch { .. })
1062        ));
1063    }
1064}
1065
1066#[cfg(test)]
1067#[path = "packed_slice_tests.rs"]
1068mod packed_slice_tests;