Skip to content

Conversation

mstoeckl
Copy link
Contributor

@mstoeckl mstoeckl commented Oct 18, 2025

This is a small step toward eliminating the variable size allocations from the PNM decoder.

Specifically, for the P1-P6-type PNM formats, the width, height, and maxval fields were previously being parsed by reading their digits into a String and then calling u32::from_str_radix. However, the fields could be as almost long as the input file and would still be loaded into RAM even if invalid. (For example, the image P3 1000 1 255 1 1 1 where 000 is replaced by a very large number of 0s.) This usually isn't a big issue since image files are often small compared to available RAM, but there are a few exceptions (externally compressed .ppm.gz images, which some image viewers like ImageMagick's display automatically uncompress; images stored as sparse files or on compressed or networked filesystems).

Since I am already modifying the integer parsing, this change also rejects integers in the header that start with a leading + (like in P6 5 +7 255\n); Netpbm and most other implementations that I've tried also reject them.

Also, now that the DecoderError::Overflow error can come from multiple places, I've added an ErrorDataSource to it.

(I have a similar patch planned to avoid the unbounded allocations in the PAM header decoding, but am holding off on it to make this one easier to review and to not have too many PRs active.)

Note: The current CI failure is unrelated (clippy, about src/codecs/avif/decoder.rs).

PNM images are sometimes stored or piped under compression,
in which case reading the integers from the PNM header into a
string before parsing them can consume memory far in excess
of the compressed file size.

This change ensures the PNM parser rejects integer specifications
which are not purely ASCII decimal, like '+10'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant