use std::fmt;
use crate::luma::check_size;
use crate::{Luma, Result};
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Rgba<'a> {
width: u32,
height: u32,
pixels: &'a [u8],
}
impl<'a> Rgba<'a> {
pub fn new(width: u32, height: u32, pixels: &'a [u8]) -> Result<Self> {
check_size(width, height, 4, pixels.len())?;
Ok(Self { width, height, pixels })
}
#[must_use]
pub const fn width(&self) -> u32 {
self.width
}
#[must_use]
pub const fn height(&self) -> u32 {
self.height
}
#[must_use]
pub const fn pixels(&self) -> &'a [u8] {
self.pixels
}
}
impl fmt::Debug for Rgba<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Rgba")
.field("width", &self.width)
.field("height", &self.height)
.finish_non_exhaustive()
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct RgbaBuf {
width: u32,
height: u32,
pixels: Vec<u8>,
}
impl RgbaBuf {
pub fn new(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self> {
check_size(width, height, 4, pixels.len())?;
Ok(Self { width, height, pixels })
}
pub fn from_rgb8(width: u32, height: u32, rgb: &[u8]) -> Result<Self> {
check_size(width, height, 3, rgb.len())?;
let (pixels, _) = rgb.as_chunks::<3>();
let pixels = pixels
.iter()
.flat_map(|&[red, green, blue]| [red, green, blue, u8::MAX])
.collect();
Ok(Self { width, height, pixels })
}
#[must_use]
pub fn from_luma(image: Luma<'_>) -> Self {
Self {
width: image.width(),
height: image.height(),
pixels: image.pixels().iter().flat_map(|&v| [v, v, v, u8::MAX]).collect(),
}
}
#[must_use]
pub fn view(&self) -> Rgba<'_> {
Rgba {
width: self.width,
height: self.height,
pixels: &self.pixels,
}
}
#[must_use]
pub const fn width(&self) -> u32 {
self.width
}
#[must_use]
pub const fn height(&self) -> u32 {
self.height
}
#[must_use]
pub fn pixels(&self) -> &[u8] {
&self.pixels
}
#[must_use]
pub fn into_pixels(self) -> Vec<u8> {
self.pixels
}
}
impl fmt::Debug for RgbaBuf {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RgbaBuf")
.field("width", &self.width)
.field("height", &self.height)
.finish_non_exhaustive()
}
}