Skip to content

Commit

Permalink
safely handle floating point target dimensions
Browse files Browse the repository at this point in the history
  • Loading branch information
walterbm committed Mar 26, 2022
1 parent 931f53b commit 71e6aa0
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 4 deletions.
9 changes: 6 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ impl Configuration {
#[derive(Deserialize)]
struct ResizeOptions {
source: String,
height: Option<usize>,
width: Option<usize>,
height: Option<f32>,
width: Option<f32>,
quality: Option<u8>,
}

Expand All @@ -105,7 +105,10 @@ async fn resize<'app>(
Ok(response) => {
let mut image = Image::from_bytes(&response)?;

image.resize(options.width, options.height);
image.resize(
options.width.map(|f| f.round() as usize),
options.height.map(|f| f.round() as usize),
);

let buffer =
image.to_buffer_mut(options.quality.unwrap_or(configuration.default_quality))?;
Expand Down
47 changes: 46 additions & 1 deletion tests/resize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ async fn test_resize_can_resize_an_image_with_one_outsized_dimension_and_preserv
}

#[actix_rt::test]
async fn test_resize_will_noop_if_target_dimensions_are_the_same_as_target_image() {
async fn test_resize_can_noop_if_target_dimensions_are_the_same_as_target_image() {
// Arrange
let address = spawn_app();
let client = reqwest::Client::new();
Expand Down Expand Up @@ -250,3 +250,48 @@ async fn test_resize_will_noop_if_target_dimensions_are_the_same_as_target_image
assert_eq!(width, 2250, "width is equal to 2250px");
assert_eq!(height, 2250, "height is equal to 2250px");
}

#[actix_rt::test]
async fn test_resize_can_handle_floating_point_target_dimensions() {
// Arrange
let address = spawn_app();
let client = reqwest::Client::new();
let test_image_one = "https://raw.githubusercontent.com/walterbm/rusty-resizer/main/tests/fixtures/test-image-one.jpg";

// Act
let response = client
.get(format!(
"{}/resize?source={}&width=225.0&height=225.0",
address, test_image_one
))
.send()
.await
.expect("Failed to execute request.");

// Assert
assert!(response.status().is_success());
assert_eq!(
response.headers().get("Content-Type").unwrap(),
"image/jpeg",
"content type is equal to image/jpeg"
);
assert_eq!(
response.headers().get("Cache-Control").unwrap(),
"max-age=3600",
"cache control max age is equal to 3600"
);

let bytes = response
.bytes()
.await
.expect("Failed to read response bytes");

let image = ImageReader::new(Cursor::new(bytes))
.with_guessed_format()
.unwrap()
.decode()
.expect("Failed to decode image");
let (width, height) = image.dimensions();
assert_eq!(width, 225, "width is equal to 225px");
assert_eq!(height, 225, "height is equal to 225px");
}

0 comments on commit 71e6aa0

Please sign in to comment.