use std::str::FromStr;
use crate::error::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Gravity {
#[default]
Center,
TopLeft,
Top,
TopRight,
Left,
Right,
BottomLeft,
Bottom,
BottomRight,
}
impl Gravity {
pub const ALL: [Gravity; 9] = [
Gravity::Center,
Gravity::TopLeft,
Gravity::Top,
Gravity::TopRight,
Gravity::Left,
Gravity::Right,
Gravity::BottomLeft,
Gravity::Bottom,
Gravity::BottomRight,
];
pub const fn name(self) -> &'static str {
match self {
Gravity::Center => "center",
Gravity::TopLeft => "top-left",
Gravity::Top => "top",
Gravity::TopRight => "top-right",
Gravity::Left => "left",
Gravity::Right => "right",
Gravity::BottomLeft => "bottom-left",
Gravity::Bottom => "bottom",
Gravity::BottomRight => "bottom-right",
}
}
pub fn from_name(name: &str) -> Option<Gravity> {
Gravity::ALL.into_iter().find(|g| g.name() == name)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FocalPoint {
x: f64,
y: f64,
}
impl FocalPoint {
pub fn new(x: f64, y: f64) -> Result<Self> {
if !x.is_finite() || !y.is_finite() || !(0.0..=1.0).contains(&x) || !(0.0..=1.0).contains(&y) {
return Err(Error::InvalidArgument("Focal point coordinates must be finite and between 0 and 1".into()));
}
Ok(FocalPoint { x, y })
}
pub fn from_parts(x: Option<f64>, y: Option<f64>) -> Result<Option<Self>> {
match (x, y) {
(None, None) => Ok(None),
(Some(x), Some(y)) => FocalPoint::new(x, y).map(Some),
_ => Err(Error::InvalidArgument("Both focal point coordinates are required".into())),
}
}
pub const fn x(self) -> f64 {
self.x
}
pub const fn y(self) -> f64 {
self.y
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OutputFormat {
Jpeg,
Gif,
Png,
Webp,
Avif,
Heic,
}
impl FromStr for OutputFormat {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
Ok(match s {
"jpg" | "jpeg" => OutputFormat::Jpeg,
"gif" => OutputFormat::Gif,
"png" => OutputFormat::Png,
"webp" => OutputFormat::Webp,
"avif" => OutputFormat::Avif,
"heic" => OutputFormat::Heic,
_ => return Err(Error::UnsupportedFormat(format!("Unsupported output format: {s}"))),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limits {
pub width: u64,
pub height: u64,
pub memory: u64,
}
impl Default for Limits {
fn default() -> Self {
Limits { width: 16_000, height: 16_000, memory: 512 * 1024 * 1024 }
}
}
thread_local! {
static ACTIVE: std::cell::Cell<Limits> = std::cell::Cell::new(Limits::default());
}
impl Limits {
pub(crate) fn scope<T>(self, work: impl FnOnce() -> T) -> T {
struct Restore(Limits);
impl Drop for Restore {
fn drop(&mut self) {
ACTIVE.set(self.0);
}
}
let _restore = Restore(ACTIVE.replace(self));
work()
}
fn active() -> Limits {
ACTIVE.get()
}
}
pub(crate) fn canvas_bytes(width: u64, height: u64) -> u64 {
width.saturating_mul(height).saturating_mul(4)
}
pub(crate) fn pixel_budget() -> u64 {
Limits::active().memory
}
pub(crate) fn check_pixels(bytes: u64) -> Result<()> {
if bytes > pixel_budget() {
return Err(Error::LimitExceeded);
}
Ok(())
}
pub(crate) fn check_dimensions(width: u64, height: u64) -> Result<()> {
let limits = Limits::active();
if width > limits.width || height > limits.height {
return Err(Error::LimitExceeded);
}
check_pixels(canvas_bytes(width, height))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_panic_inside_a_scope_restores_the_limits() {
let narrow = Limits { width: 1, height: 1, memory: 4 };
let panicked = std::panic::catch_unwind(|| narrow.scope(|| panic!("a codec panicked")));
assert!(panicked.is_err());
assert_eq!(Limits::active(), Limits::default());
assert!(check_dimensions(100, 100).is_ok());
}
}