pub(crate) const fn moves_pixels(tag: u16) -> bool {
matches!(tag, 2..=8)
}
pub(crate) fn reorient(width: u32, height: u32, channels: usize, pixels: Vec<u8>, tag: u16) -> (u32, u32, Vec<u8>) {
if !moves_pixels(tag) {
return (width, height, pixels);
}
let (w, h) = (width as usize, height as usize);
let (out_width, out_height) = if tag >= 5 { (h, w) } else { (w, h) };
let mut out = Vec::with_capacity(pixels.len());
for y in 0..out_height {
for x in 0..out_width {
let (sx, sy) = match tag {
2 => (w - 1 - x, y),
3 => (w - 1 - x, h - 1 - y),
4 => (x, h - 1 - y),
5 => (y, x),
6 => (y, h - 1 - x),
7 => (w - 1 - y, h - 1 - x),
_ => (w - 1 - y, x),
};
let at = (sy * w + sx) * channels;
out.extend_from_slice(&pixels[at..at + channels]);
}
}
(out_width as u32, out_height as u32, out)
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Vec<u8> {
vec![1, 2, 3, 4, 5, 6]
}
#[test]
fn each_tag_moves_pixels_as_exif_defines_it() {
let cases: [(u16, u32, u32, [u8; 6]); 8] = [
(1, 3, 2, [1, 2, 3, 4, 5, 6]),
(2, 3, 2, [3, 2, 1, 6, 5, 4]),
(3, 3, 2, [6, 5, 4, 3, 2, 1]),
(4, 3, 2, [4, 5, 6, 1, 2, 3]),
(5, 2, 3, [1, 4, 2, 5, 3, 6]),
(6, 2, 3, [4, 1, 5, 2, 6, 3]),
(7, 2, 3, [6, 3, 5, 2, 4, 1]),
(8, 2, 3, [3, 6, 2, 5, 1, 4]),
];
for (tag, width, height, pixels) in cases {
assert_eq!(
reorient(3, 2, 1, sample(), tag),
(width, height, pixels.to_vec()),
"tag {tag}"
);
}
assert_eq!(reorient(3, 2, 1, sample(), 9), (3, 2, sample()));
}
#[test]
fn whole_pixels_move_together() {
let rgba: Vec<u8> = (0..8).collect();
assert_eq!(reorient(2, 1, 4, rgba, 6), (1, 2, vec![0, 1, 2, 3, 4, 5, 6, 7]));
}
}