1#![deny(unsafe_code)]
9#![warn(missing_docs)]
10
11use std::ops::{Index, IndexMut};
12
13#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
15pub enum ImageError {
16 #[error("image channel count must be greater than zero")]
18 ZeroChannels,
19 #[error("image dimensions overflow addressable memory")]
21 DimensionOverflow,
22 #[error("image storage is too short: need at least {required} elements, found {found}")]
24 StorageTooShort {
25 required: usize,
27 found: usize,
29 },
30 #[error("row stride {stride} is smaller than packed row width {minimum}")]
32 InvalidStride {
33 stride: usize,
35 minimum: usize,
37 },
38 #[error("plane stride {stride} is smaller than one plane span {minimum}")]
40 InvalidPlaneStride {
41 stride: usize,
43 minimum: usize,
45 },
46 #[error("color space {color_space:?} requires {expected} channels, image has {found}")]
48 MetadataChannelMismatch {
49 color_space: ColorSpace,
51 expected: usize,
53 found: usize,
55 },
56 #[error("region ({x}, {y}, {region_width}, {region_height}) exceeds image bounds {image_width}x{image_height}")]
58 InvalidRegion {
59 x: usize,
61 y: usize,
63 region_width: usize,
65 region_height: usize,
67 image_width: usize,
69 image_height: usize,
71 },
72 #[error("pixel ({x}, {y}) is outside image bounds {width}x{height}")]
74 OutOfBounds {
75 x: usize,
77 y: usize,
79 width: usize,
81 height: usize,
83 },
84}
85
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
88pub enum ImageLayout {
89 #[default]
91 Interleaved,
92 Planar,
94}
95
96#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
98pub enum ColorSpace {
99 #[default]
101 Unknown,
102 Gray,
104 Rgb,
106 Bgr,
108 Rgba,
110 Bgra,
112 LinearRgb,
114 Hsv,
116 Depth,
118 Label,
120}
121
122impl ColorSpace {
123 #[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
137pub enum ColorRange {
138 #[default]
140 Unspecified,
141 Full,
143 Limited,
145}
146
147#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
149pub enum AlphaMode {
150 #[default]
152 None,
153 Straight,
155 Premultiplied,
157}
158
159#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
161pub struct ImageMetadata {
162 pub color_space: ColorSpace,
164 pub color_range: ColorRange,
166 pub alpha_mode: AlphaMode,
168}
169
170impl ImageMetadata {
171 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
191pub struct ImageRegion {
192 pub x: usize,
194 pub y: usize,
196 pub width: usize,
198 pub height: usize,
200}
201
202impl ImageRegion {
203 #[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#[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 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 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 #[must_use]
280 pub const fn width(&self) -> usize {
281 self.width
282 }
283
284 #[must_use]
286 pub const fn height(&self) -> usize {
287 self.height
288 }
289
290 #[must_use]
292 pub const fn row_stride(&self) -> usize {
293 self.width * CHANNELS
294 }
295
296 #[must_use]
298 pub const fn layout(&self) -> ImageLayout {
299 ImageLayout::Interleaved
300 }
301
302 #[must_use]
304 pub const fn metadata(&self) -> ImageMetadata {
305 self.metadata
306 }
307
308 pub fn set_metadata(&mut self, metadata: ImageMetadata) -> Result<(), ImageError> {
310 metadata.validate::<CHANNELS>()?;
311 self.metadata = metadata;
312 Ok(())
313 }
314
315 #[must_use]
317 pub fn as_slice(&self) -> &[T] {
318 &self.data
319 }
320
321 #[must_use]
323 pub fn as_mut_slice(&mut self) -> &mut [T] {
324 &mut self.data
325 }
326
327 #[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 #[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 #[must_use]
353 pub fn get(&self, x: usize, y: usize) -> Option<&[T; CHANNELS]> {
354 self.view().get(x, y)
355 }
356
357 #[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 #[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 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#[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 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 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 #[must_use]
456 pub const fn width(self) -> usize {
457 self.width
458 }
459
460 #[must_use]
462 pub const fn height(self) -> usize {
463 self.height
464 }
465
466 #[must_use]
468 pub const fn row_stride(self) -> usize {
469 self.row_stride
470 }
471
472 #[must_use]
474 pub const fn layout(self) -> ImageLayout {
475 ImageLayout::Interleaved
476 }
477
478 #[must_use]
480 pub const fn metadata(self) -> ImageMetadata {
481 self.metadata
482 }
483
484 #[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 #[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 #[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 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#[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 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 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 #[must_use]
588 pub const fn width(&self) -> usize {
589 self.width
590 }
591
592 #[must_use]
594 pub const fn height(&self) -> usize {
595 self.height
596 }
597
598 #[must_use]
600 pub const fn row_stride(&self) -> usize {
601 self.row_stride
602 }
603
604 #[must_use]
606 pub const fn metadata(&self) -> ImageMetadata {
607 self.metadata
608 }
609
610 pub fn set_metadata(&mut self, metadata: ImageMetadata) -> Result<(), ImageError> {
612 metadata.validate::<CHANNELS>()?;
613 self.metadata = metadata;
614 Ok(())
615 }
616
617 #[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 #[must_use]
631 pub fn get(&self, x: usize, y: usize) -> Option<&[T; CHANNELS]> {
632 self.as_view().get(x, y)
633 }
634
635 #[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 #[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 #[must_use]
660 pub fn as_mut_slice(&mut self) -> &mut [T] {
661 self.data
662 }
663
664 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#[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 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 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 #[must_use]
727 pub const fn width(&self) -> usize {
728 self.width
729 }
730
731 #[must_use]
733 pub const fn height(&self) -> usize {
734 self.height
735 }
736
737 #[must_use]
739 pub const fn layout(&self) -> ImageLayout {
740 ImageLayout::Planar
741 }
742
743 #[must_use]
745 pub const fn row_stride(&self) -> usize {
746 self.width
747 }
748
749 #[must_use]
751 pub const fn plane_stride(&self) -> usize {
752 self.width * self.height
753 }
754
755 #[must_use]
757 pub const fn metadata(&self) -> ImageMetadata {
758 self.metadata
759 }
760
761 pub fn set_metadata(&mut self, metadata: ImageMetadata) -> Result<(), ImageError> {
763 metadata.validate::<CHANNELS>()?;
764 self.metadata = metadata;
765 Ok(())
766 }
767
768 #[must_use]
770 pub fn as_slice(&self) -> &[T] {
771 &self.data
772 }
773
774 #[must_use]
776 pub fn as_mut_slice(&mut self) -> &mut [T] {
777 &mut self.data
778 }
779
780 #[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 #[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 #[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 #[must_use]
811 pub fn into_vec(self) -> Vec<T> {
812 self.data
813 }
814}
815
816#[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 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 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 #[must_use]
882 pub const fn width(self) -> usize {
883 self.width
884 }
885
886 #[must_use]
888 pub const fn height(self) -> usize {
889 self.height
890 }
891
892 #[must_use]
894 pub const fn row_stride(self) -> usize {
895 self.row_stride
896 }
897
898 #[must_use]
900 pub const fn plane_stride(self) -> usize {
901 self.plane_stride
902 }
903
904 #[must_use]
906 pub const fn layout(self) -> ImageLayout {
907 ImageLayout::Planar
908 }
909
910 #[must_use]
912 pub const fn metadata(self) -> ImageMetadata {
913 self.metadata
914 }
915
916 #[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 #[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 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
967pub type GrayImage<T> = Image<T, 1>;
969pub 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 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;