Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change validation to a debug assert #481

Merged
merged 1 commit into from
Dec 22, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 25 additions & 21 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -657,28 +657,9 @@ fn optimize_png(
);
}

let (old_png, new_png) = rayon::join(
|| load_png_image_from_memory(original_data),
|| load_png_image_from_memory(&output),
);

if let Ok(new_png) = new_png {
if let Ok(old_png) = old_png {
if images_equal(&old_png, &new_png) {
return Ok(output);
}
} else {
// The original image might be invalid if, for example, there is a CRC error,
// and we set fix_errors to true. In that case, all we can do is check that the
// new image is decodable.
return Ok(output);
}
}
debug_assert!(validate_output(&output, original_data));

error!(
"The resulting image is corrupted and will not be outputted.\nThis is a bug! Please report it at https://github.com/shssoichiro/oxipng/issues"
);
Err(PngError::new("The resulting image is corrupted"))
Ok(output)
}

fn perform_reductions(
Expand Down Expand Up @@ -1061,6 +1042,29 @@ fn copy_times(input_path_meta: &Metadata, out_path: &Path) -> PngResult<()> {
})
}

/// Validate that the output png data still matches the original image
fn validate_output(output: &[u8], original_data: &[u8]) -> bool {
let (old_png, new_png) = rayon::join(
|| load_png_image_from_memory(original_data),
|| load_png_image_from_memory(output),
);

match (new_png, old_png) {
(Err(new_err), _) => {
error!("Failed to read output image for validation: {}", new_err);
false
}
(_, Err(old_err)) => {
// The original image might be invalid if, for example, there is a CRC error,
// and we set fix_errors to true. In that case, all we can do is check that the
// new image is decodable.
warn!("Failed to read input image for validation: {}", old_err);
true
}
(Ok(new_png), Ok(old_png)) => images_equal(&old_png, &new_png),
}
}

/// Loads a PNG image from memory to a [DynamicImage]
fn load_png_image_from_memory(png_data: &[u8]) -> Result<DynamicImage, image::ImageError> {
let mut reader = image::io::Reader::new(Cursor::new(png_data));
Expand Down