pub fn fit_within_max_dimension(width: u32, height: u32, max: u32) -> (u32, u32) {
if width == 0 || height == 0 || max == 0 {
return (width, height);
}
if width <= max && height <= max {
return (width, height);
}
let scale = (max as f64 / width as f64).min(max as f64 / height as f64);
let w = ((width as f64 * scale).floor() as u32).clamp(1, max);
let h = ((height as f64 * scale).floor() as u32).clamp(1, max);
(w, h)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sizes_within_the_limit_pass_through_untouched() {
assert_eq!(fit_within_max_dimension(1280, 720, 2048), (1280, 720));
assert_eq!(fit_within_max_dimension(2048, 2048, 2048), (2048, 2048));
}
#[test]
fn oversized_widths_shrink_to_the_limit() {
assert_eq!(fit_within_max_dimension(2560, 1440, 2048), (2048, 1152));
}
#[test]
fn aspect_ratio_survives_the_clamp() {
for (w, h) in [(2560u32, 1440u32), (3840, 2160), (5000, 1000), (999, 4001)] {
let (cw, ch) = fit_within_max_dimension(w, h, 2048);
let before = w as f64 / h as f64;
let after = cw as f64 / ch as f64;
assert!(
(before - after).abs() / before < 0.01,
"{w}x{h} -> {cw}x{ch}: {before} vs {after}",
);
}
}
#[test]
fn both_axes_end_up_within_the_limit() {
for (w, h) in [(4096u32, 4096u32), (8000, 100), (100, 8000), (2049, 2049)] {
let (cw, ch) = fit_within_max_dimension(w, h, 2048);
assert!(cw <= 2048 && ch <= 2048, "{w}x{h} -> {cw}x{ch}");
assert!(cw >= 1 && ch >= 1, "{w}x{h} -> {cw}x{ch} collapsed an axis");
}
}
#[test]
fn an_extreme_aspect_ratio_never_collapses_an_axis_to_zero() {
let (w, h) = fit_within_max_dimension(100_000, 1, 2048);
assert!(w <= 2048 && h >= 1, "got {w}x{h}");
}
#[test]
fn zero_sizes_are_passed_through_for_the_caller_to_reject() {
assert_eq!(fit_within_max_dimension(0, 720, 2048), (0, 720));
assert_eq!(fit_within_max_dimension(1280, 0, 2048), (1280, 0));
}
}