rosier 0.5.2

A fast picture and video viewer for large folders
//! Decoded pictures as gpui draws them: BGRA pixels, and the small helpers
//! every decoder shares. Free of the C libraries, so the fuzz targets
//! (fuzz/) build it as it is.

/// A decoded image in BGRA order (what gpui uploads as a texture).
#[derive(Clone)]
pub struct Bgra {
    pub width: u32,
    pub height: u32,
    pub pixels: Vec<u8>,
}

impl Bgra {
    /// Straight RGBA pixels (what the `image` crate decodes) as BGRA.
    pub fn from_rgba(width: u32, height: u32, mut pixels: Vec<u8>) -> Self {
        swap_red_blue(&mut pixels);
        Bgra { width, height, pixels }
    }
}

/// Turns RGBA pixels into BGRA, or BGRA into RGBA: the two differ only in
/// where red and blue sit.
pub fn swap_red_blue(pixels: &mut [u8]) {
    for px in pixels.as_chunks_mut::<4>().0 {
        px.swap(0, 2);
    }
}

/// (w, h) scaled down so the longer side is at most `max_long`, keeping
/// the aspect ratio; never scaled up, and never below one pixel.
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]);
    }
}