pub const MAX_EDGE: i32 = 4096;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Plan {
pub x: i32,
pub y: i32,
pub width: i32,
pub height: i32,
pub source_width: u32,
pub source_height: u32,
}
impl Plan {
pub const fn stretches(&self) -> bool {
self.source_width as i32 != self.width || self.source_height as i32 != self.height
}
}
pub fn plan(left: i32, top: i32, right: i32, bottom: i32) -> Option<Plan> {
let x = left.min(right);
let y = top.min(bottom);
let width = i64::from(left.max(right)) - i64::from(x);
let height = i64::from(top.max(bottom)) - i64::from(y);
if width == 0 || height == 0 {
return None;
}
let longest = width.max(height);
let bound = i64::from(MAX_EDGE);
let divisor = ((longest + bound - 1) / bound).max(1);
Some(Plan {
x,
y,
width: width.min(i64::from(i32::MAX)) as i32,
height: height.min(i64::from(i32::MAX)) as i32,
source_width: (width / divisor).max(1) as u32,
source_height: (height / divisor).max(1) as u32,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_ordinary_rectangle_is_rendered_at_its_own_size() {
let plan = plan(10, 20, 210, 140).expect("something to draw");
assert_eq!(
(plan.x, plan.y, plan.width, plan.height),
(10, 20, 200, 120)
);
assert_eq!((plan.source_width, plan.source_height), (200, 120));
assert!(
!plan.stretches(),
"a 1:1 blit must not go through a resample"
);
}
#[test]
fn an_inverted_rectangle_is_normalised_rather_than_trusted() {
let plan = plan(210, 140, 10, 20).expect("something to draw");
assert_eq!(
(plan.x, plan.y, plan.width, plan.height),
(10, 20, 200, 120)
);
assert_eq!((plan.source_width, plan.source_height), (200, 120));
}
#[test]
fn an_empty_rectangle_is_nothing_to_draw() {
assert_eq!(plan(10, 20, 10, 140), None);
assert_eq!(plan(10, 20, 210, 20), None);
assert_eq!(plan(0, 0, 0, 0), None);
}
#[test]
fn an_enormous_rectangle_is_drawn_from_a_bounded_surface() {
let plan = plan(0, 0, 100_000, 50_000).expect("something to draw");
assert_eq!((plan.width, plan.height), (100_000, 50_000));
assert!(plan.source_width <= MAX_EDGE as u32);
assert!(plan.source_height <= MAX_EDGE as u32);
assert!(plan.stretches());
let ratio = f64::from(plan.source_width) / f64::from(plan.source_height);
assert!((ratio - 2.0).abs() < 0.01, "the aspect ratio was not kept");
}
#[test]
fn the_widest_possible_rectangle_neither_overflows_nor_allocates() {
let plan = plan(i32::MIN, i32::MIN, i32::MAX, i32::MAX).expect("something to draw");
assert_eq!((plan.x, plan.y), (i32::MIN, i32::MIN));
assert_eq!((plan.width, plan.height), (i32::MAX, i32::MAX));
assert!(plan.source_width <= MAX_EDGE as u32);
assert!(plan.source_height <= MAX_EDGE as u32);
}
#[test]
fn a_sliver_still_produces_a_surface_with_pixels_in_it() {
let plan = plan(0, 0, 1, 200_000).expect("something to draw");
assert_eq!(
plan.source_width, 1,
"an edge may not be scaled away to zero"
);
assert!(plan.source_height >= 1);
}
}