Skip to content

Commit

Permalink
Change TransformFn to allow memoization in the future
Browse files Browse the repository at this point in the history
This commit changes the `TransformFn` type alias from `fn(...)` into
`Box<dyn Fn(...)>`.  This allows the `TransformFn` to have store some
precomputer, memoized state that we plan to add in follow-up commits.

In theory this commit may have negative performance impact, but in the
grand scheme of things it disappears into the measurement noise.  In
particular, when there is no state, then `Box` shouldn't allocate.
  • Loading branch information
anforowicz authored and fintelia committed Feb 2, 2024
1 parent d9df1d7 commit b0cc095
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 17 deletions.
2 changes: 1 addition & 1 deletion src/decoder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,7 @@ impl<R: Read> Reader<R> {
if self.transform_fn.is_none() {
self.transform_fn = Some(create_transform_fn(self.info(), self.transform)?);
}
self.transform_fn.unwrap()
self.transform_fn.as_deref().unwrap()
};
transform_fn(row, output_buffer, self.info());

Expand Down
32 changes: 16 additions & 16 deletions src/decoder/transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use super::stream::FormatErrorInner;
///
/// TODO: If some precomputed state is needed (e.g. to make `expand_paletted...`
/// faster) then consider changing this into `Box<dyn Fn(...)>`.
pub type TransformFn = fn(&[u8], &mut [u8], &Info);
pub type TransformFn = Box<dyn Fn(&[u8], &mut [u8], &Info)>;

/// Returns a transformation function that should be applied to image rows based
/// on 1) decoded image metadata (`info`) and 2) the transformations requested
Expand Down Expand Up @@ -43,36 +43,36 @@ pub fn create_transform_fn(
.into(),
));
} else {
if trns {
Ok(palette::expand_paletted_into_rgba8)
Ok(Box::new(if trns {
palette::expand_paletted_into_rgba8
} else {
Ok(palette::expand_paletted_into_rgb8)
}
palette::expand_paletted_into_rgb8
}))
}
}
ColorType::Grayscale | ColorType::GrayscaleAlpha if bit_depth < 8 && expand => {
if trns {
Ok(expand_gray_u8_with_trns)
Ok(Box::new(if trns {
expand_gray_u8_with_trns
} else {
Ok(expand_gray_u8)
}
expand_gray_u8
}))
}
ColorType::Grayscale | ColorType::Rgb if expand && trns => {
if bit_depth == 8 {
Ok(expand_trns_line)
Ok(Box::new(if bit_depth == 8 {
expand_trns_line
} else if strip16 {
Ok(expand_trns_and_strip_line16)
expand_trns_and_strip_line16
} else {
assert_eq!(bit_depth, 16);
Ok(expand_trns_line16)
}
expand_trns_line16
}))
}
ColorType::Grayscale | ColorType::GrayscaleAlpha | ColorType::Rgb | ColorType::Rgba
if strip16 =>
{
Ok(transform_row_strip16)
Ok(Box::new(transform_row_strip16))
}
_ => Ok(copy_row),
_ => Ok(Box::new(copy_row)),
}
}

Expand Down

0 comments on commit b0cc095

Please sign in to comment.