use crate::error::{Error, Result};
use whereat::*;
#[inline]
pub(crate) fn stride_fits_i32(stride: usize, ctx: &'static str) -> Result<i32> {
if stride > i32::MAX as usize {
return Err(at!(Error::InvalidInput(alloc::format!(
"{}: stride {} exceeds i32::MAX (libwebp parameter is signed)",
ctx,
stride
))));
}
Ok(stride as i32)
}
#[allow(dead_code)] #[inline]
pub(crate) fn webp_returned_dim_positive(dim: i32, ctx: &'static str) -> Result<u32> {
if dim <= 0 {
return Err(at!(Error::InvalidInput(alloc::format!(
"{}: libwebp returned non-positive dimension {}",
ctx,
dim
))));
}
Ok(dim as u32)
}
#[allow(dead_code)] #[inline]
pub(crate) fn pixel_bytes(width: u32, height: u32, bpp: usize) -> usize {
(width as usize)
.saturating_mul(height as usize)
.saturating_mul(bpp)
}
#[allow(dead_code)] pub(crate) fn buffer_for_stride(
buf_len: usize,
stride: usize,
height: u32,
row_bytes: usize,
ctx: &'static str,
) -> Result<()> {
if stride < row_bytes {
return Err(at!(Error::InvalidInput(alloc::format!(
"{}: stride {} smaller than row_bytes {}",
ctx,
stride,
row_bytes
))));
}
let last_row_offset = (height as usize).saturating_sub(1).saturating_mul(stride);
let needed = last_row_offset.saturating_add(row_bytes);
if buf_len < needed {
return Err(at!(Error::InvalidInput(alloc::format!(
"{}: buffer too small ({} < {} for {} rows of {} bytes at stride {})",
ctx,
buf_len,
needed,
height,
row_bytes,
stride
))));
}
Ok(())
}