use alpha2_model::{
MAX_LOTTIE_DOCUMENT_BYTES, MAX_PROVIDER_DOCUMENT_BYTES, MAX_SVG_DOCUMENT_BYTES, ProviderSource,
};
use crate::api::ExtensionError;
pub const MAX_CANVAS_SIDE: u32 = 16_384;
pub const MAX_CANVAS_PIXELS: u64 = 7_680 * 4_320;
pub const MAX_ANIMATION_FRAMES: usize = 10_000;
pub const MAX_ANIMATION_PIXELS: u64 = 1 << 31;
pub const DEFAULT_FRAME_BUDGET: usize = 256 * 1024 * 1024;
pub const MAX_SOURCE_IMAGE_PIXELS: u64 = 4 * MAX_CANVAS_PIXELS;
#[cfg(any(feature = "svg", feature = "lottie"))]
pub(crate) const MAX_DRAWING: f64 = 256.0;
#[cfg(feature = "svg")]
pub(crate) const FLOOR_CANVAS: f64 = 1920.0 * 1080.0;
pub fn check_canvas(width: u32, height: u32) -> Result<(), ExtensionError> {
if width == 0 || height == 0 {
return Err(ExtensionError::Malformed("the canvas is empty".into()));
}
if width > MAX_CANVAS_SIDE
|| height > MAX_CANVAS_SIDE
|| u64::from(width) * u64::from(height) > MAX_CANVAS_PIXELS
{
return Err(ExtensionError::Budget(format!(
"a {width}x{height} canvas is larger than {MAX_CANVAS_PIXELS} pixels"
)));
}
Ok(())
}
#[must_use]
pub fn document_limit(source: &ProviderSource, head: &[u8]) -> Option<(usize, &'static str)> {
match source {
ProviderSource::Svg => Some((MAX_SVG_DOCUMENT_BYTES, "SVG document")),
ProviderSource::Lottie { .. } if head.starts_with(b"PK\x03\x04") => {
Some((MAX_PROVIDER_DOCUMENT_BYTES, "dotLottie package"))
}
ProviderSource::Lottie { .. } => Some((MAX_LOTTIE_DOCUMENT_BYTES, "Lottie file")),
_ => None,
}
}
pub fn check_document_size(
source: &ProviderSource,
head: &[u8],
length: u64,
) -> Result<(), ExtensionError> {
match document_limit(source, head) {
Some((limit, what)) if length > limit as u64 => Err(ExtensionError::Budget(format!(
"the {what} is {length} bytes, more than the {limit} a provider reads"
))),
_ => Ok(()),
}
}
pub fn check_image_pixels(pixels: u64) -> Result<(), ExtensionError> {
if pixels > MAX_SOURCE_IMAGE_PIXELS {
return Err(ExtensionError::Budget(format!(
"its images decode to {pixels} pixels, more than the {MAX_SOURCE_IMAGE_PIXELS} one source may"
)));
}
Ok(())
}