From e90248898cf0a81e8ed14a59c8d119a4b72c9b8b Mon Sep 17 00:00:00 2001 From: Luracasmus <77991691+Luracasmus@users.noreply.github.com> Date: Tue, 9 Dec 2025 11:23:12 +0100 Subject: [PATCH] Shrink the `PngError` type This brings `PngError` from 40 to 32 bytes on a 64-bit system, and should only have a cost when a a `ReadFailed` or `WriteFailed` is created --- src/error.rs | 4 ++-- src/lib.rs | 9 ++++++--- src/png/mod.rs | 3 ++- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/error.rs b/src/error.rs index 92937e3f..448d87c2 100644 --- a/src/error.rs +++ b/src/error.rs @@ -15,9 +15,9 @@ pub enum PngError { InvalidData, InvalidDepthForType(BitDepth, ColorType), NotPNG, - ReadFailed(String, std::io::Error), + ReadFailed(Box, std::io::Error), TruncatedData, - WriteFailed(String, std::io::Error), + WriteFailed(Box, std::io::Error), Other(Box), } diff --git a/src/lib.rs b/src/lib.rs index c09432d3..f1109c39 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -257,8 +257,9 @@ pub fn optimize(input: &InFile, output: &OutFile, opts: &Options) -> PngResult<( let output_path = path .as_ref() .map_or_else(|| input.path().unwrap(), PathBuf::as_path); - let out_file = File::create(output_path) - .map_err(|err| PngError::WriteFailed(output_path.display().to_string(), err))?; + let out_file = File::create(output_path).map_err(|err| { + PngError::WriteFailed(output_path.display().to_string().into_boxed_str(), err) + })?; if let Some(metadata_input) = &opt_metadata_preserved { copy_permissions(metadata_input, &out_file)?; } @@ -268,7 +269,9 @@ pub fn optimize(input: &InFile, output: &OutFile, opts: &Options) -> PngResult<( .write_all(&optimized_output) // flush BufWriter so IO errors don't get swallowed silently on close() by drop! .and_then(|()| buffer.flush()) - .map_err(|e| PngError::WriteFailed(output_path.display().to_string(), e))?; + .map_err(|e| { + PngError::WriteFailed(output_path.display().to_string().into_boxed_str(), e) + })?; // force drop and thereby closing of file handle before modifying any timestamp std::mem::drop(buffer); if let Some(metadata_input) = &opt_metadata_preserved { diff --git a/src/png/mod.rs b/src/png/mod.rs index c1395bb9..df5285f6 100644 --- a/src/png/mod.rs +++ b/src/png/mod.rs @@ -52,7 +52,8 @@ impl PngData { } pub fn read_file(filepath: &Path) -> Result, PngError> { - fs::read(filepath).map_err(|e| PngError::ReadFailed(filepath.display().to_string(), e)) + fs::read(filepath) + .map_err(|e| PngError::ReadFailed(filepath.display().to_string().into_boxed_str(), e)) } /// Create a new `PngData` struct by reading a slice