type optimization

This commit is contained in:
Breval Ferrari 2024-06-27 18:43:01 +02:00
parent 5597879592
commit d23ba1a238
Signed by: p6nj
GPG key ID: 9938940698D8E2EF

View file

@ -5,12 +5,15 @@ use bmp::{open, Pixel};
use dasp_sample::{FromSample, Sample, ToSample, U24}; use dasp_sample::{FromSample, Sample, ToSample, U24};
fn main() -> Result<()> { fn main() -> Result<()> {
dbg!((45 << 16) + (18 << 8) + 143);
let mut bmp = open("bmp/sample.bmp")?; let mut bmp = open("bmp/sample.bmp")?;
for y in 0..bmp.get_height() { for y in 0..bmp.get_height() {
for x in 0..bmp.get_width() { for x in 0..bmp.get_width() {
if x > 100 && x < 300 { if x > 100 && x < 300 {
bmp.set_pixel(x, y, Pixel::new(0, 0, 0)); bmp.set_pixel(
x,
y,
sample_to_rgb(rgb_to_sample::<f64>(bmp.get_pixel(x, y))),
);
} }
} }
} }
@ -19,15 +22,14 @@ fn main() -> Result<()> {
} }
fn rgb_to_sample<T: Sample + FromSample<U24>>(pix: Pixel) -> T { fn rgb_to_sample<T: Sample + FromSample<U24>>(pix: Pixel) -> T {
U24::new(((pix.r as i32) << 16) + ((pix.g as i32) << 8) + (pix.b as i32)) (((U24::from(pix.r)) << 16.into()) | (U24::from(pix.g) << 8.into()) | U24::from(pix.b))
.unwrap()
.to_sample() .to_sample()
} }
fn sample_to_rgb<T: Sample + ToSample<U24>>(sample: T) -> Pixel { fn sample_to_rgb<T: Sample + ToSample<U24>>(sample: T) -> Pixel {
let rgb: U24 = sample.to_sample(); let rgb: U24 = sample.to_sample();
let rg = rgb >> 8.try_into().unwrap(); let rg = rgb >> 8.into();
let r = rg >> 8.try_into().unwrap(); let r = rg >> 8.into();
Pixel::new( Pixel::new(
r.inner() as u8, r.inner() as u8,
(rg - r).inner() as u8, (rg - r).inner() as u8,
@ -38,12 +40,30 @@ fn sample_to_rgb<T: Sample + ToSample<U24>>(sample: T) -> Pixel {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use bmp::Pixel; use bmp::Pixel;
use dasp_sample::{I24, I48, U24, U48};
use super::{rgb_to_sample, sample_to_rgb}; use super::{rgb_to_sample, sample_to_rgb};
#[test] #[test]
fn rgb2s2rgb() { fn rgb2s2rgb_type_consistency() {
let pix = Pixel::new(45, 18, 143); let pix = Pixel::new(45, 18, 143);
assert_eq!(pix, sample_to_rgb(rgb_to_sample::<f64>(pix))); assert_eq!(
sample_to_rgb(rgb_to_sample::<f32>(pix)),
sample_to_rgb(rgb_to_sample::<f64>(pix))
);
assert_eq!(
sample_to_rgb(rgb_to_sample::<I24>(pix)),
sample_to_rgb(rgb_to_sample::<I48>(pix))
);
assert_eq!(
sample_to_rgb(rgb_to_sample::<U24>(pix)),
sample_to_rgb(rgb_to_sample::<U48>(pix))
);
}
#[test]
fn rgb2s2rgb() {
let pix = dbg!(Pixel::new(45, 18, 143));
assert_eq!(pix, dbg!(sample_to_rgb(dbg!(rgb_to_sample::<f64>(pix)))));
} }
} }