use crate::{Error, Result};
pub(crate) const MAX_PIXELS: u64 = 134_217_728;
pub fn checked_buffer_size(
width: u32,
height: u32,
bytes_per_pixel: u32,
row_stride_bytes: Option<u32>,
) -> Result<usize> {
let pixels = (width as u64)
.checked_mul(height as u64)
.ok_or_else(|| Error::InvalidRegion("Image dimensions overflow".to_string()))?;
if pixels > MAX_PIXELS {
return Err(Error::InvalidRegion(format!(
"Image exceeds maximum pixel limit ({})",
MAX_PIXELS
)));
}
let bytes = match row_stride_bytes {
Some(stride) => (stride as u64)
.checked_mul(height as u64)
.ok_or_else(|| Error::BufferCreation("Buffer size overflow".to_string()))?,
None => pixels
.checked_mul(bytes_per_pixel as u64)
.ok_or_else(|| Error::BufferCreation("Buffer size overflow".to_string()))?,
};
usize::try_from(bytes).map_err(|_| Error::BufferCreation("Buffer size overflow".to_string()))
}