From f31776fed4a6e7466599eb70e00ac60fe953f874 Mon Sep 17 00:00:00 2001 From: "Christopher N. Hesse" Date: Sun, 5 Feb 2023 20:59:04 +0100 Subject: [PATCH] iter: Add write() method write() allows callers to directly write pixels to an output stream (aka Iterator). The parameter P2 allows for direct conversion from one pixel format to another. Signed-off-by: Christopher N. Hesse --- ffimage/src/iter.rs | 41 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/ffimage/src/iter.rs b/ffimage/src/iter.rs index 915a605..5f78abe 100644 --- a/ffimage/src/iter.rs +++ b/ffimage/src/iter.rs @@ -1,11 +1,11 @@ -use core::marker::PhantomData; +use core::{marker::PhantomData, ops::Deref}; /// Adapter which converts a bytestream into a typed pixel stream. /// /// The trait is automatically implemented for all pixel types which implement the `From<[T; C]>` /// trait where T: Copy and C means the number of channels (e.g. 3 for RGB). -pub trait PixelsExt: Iterator { - fn pixels(self) -> Pixels +pub trait PixelsExt: Iterator { + fn pixels

(self) -> Pixels where Self: Sized, { @@ -13,7 +13,7 @@ pub trait PixelsExt: Iterator { } } -impl PixelsExt for I where I: Iterator {} +impl PixelsExt for I where I: Iterator {} pub struct Pixels { _marker: PhantomData<(T, P)>, @@ -29,6 +29,26 @@ impl Pixels { } } +impl<'a, T, I, P, const C: usize> Pixels +where + T: Copy + 'a, + I: Iterator, + P: From<[T; C]>, +{ + pub fn write(self, mut out: impl Iterator) + where + P2: From

+ Deref, + ::Target: AsRef<[T]>, + { + self.map(|p| P2::from(p)).for_each(|p2| { + p2.as_ref().iter().for_each(|t| { + let _out = out.next().unwrap(); + *_out = *t; + }); + }); + } +} + impl Iterator for Pixels where T: Copy, @@ -49,7 +69,7 @@ where #[cfg(test)] mod tests { use super::*; - use crate::color::Rgb; + use crate::color::{Bgr, Rgb}; #[test] fn pixels() { @@ -61,4 +81,15 @@ mod tests { assert_eq!(pixels.next(), Some(Rgb::([7, 8, 9]))); assert_eq!(pixels.next(), None); } + + #[test] + fn write() { + let buf = [1, 2, 3, 4, 5, 6, 7, 8, 9]; + let mut out = [0; 9]; + buf.iter() + .copied() + .pixels::>() + .write::>(out.iter_mut()); + assert_eq!(out, [3, 2, 1, 6, 5, 4, 9, 8, 7]); + } }