#[derive(Clone)]
pub struct Bgra {
pub width: u32,
pub height: u32,
pub pixels: Vec<u8>,
}
impl Bgra {
pub fn from_rgba(width: u32, height: u32, mut pixels: Vec<u8>) -> Self {
swap_red_blue(&mut pixels);
Bgra { width, height, pixels }
}
}
pub fn swap_red_blue(pixels: &mut [u8]) {
for px in pixels.as_chunks_mut::<4>().0 {
px.swap(0, 2);
}
}
pub fn fit_size(w: u32, h: u32, max_long: u32) -> (u32, u32) {
let long = w.max(h);
if long <= max_long {
return (w, h);
}
let s = max_long as f64 / long as f64;
(((w as f64 * s).round() as u32).max(1), ((h as f64 * s).round() as u32).max(1))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sizes_fit_within_the_long_side() {
assert_eq!(fit_size(1920, 1080, 960), (960, 540));
assert_eq!(fit_size(100, 50, 960), (100, 50));
assert_eq!(fit_size(10_000, 1, 100), (100, 1));
}
#[test]
fn red_and_blue_trade_places() {
let b = Bgra::from_rgba(1, 2, vec![1, 2, 3, 4, 5, 6, 7, 8]);
assert_eq!(b.pixels, vec![3, 2, 1, 4, 7, 6, 5, 8]);
let mut px = b.pixels;
swap_red_blue(&mut px);
assert_eq!(px, vec![1, 2, 3, 4, 5, 6, 7, 8]);
}
}