fix(compress): a negative --level gave maximum compression - #1046
Merged
Conversation
Negative compression levels were cast to u32 first, wrapping negative values to large unsigned integers. Clamping after the cast resulted in maximum compression instead of minimum. Fix: clamp on the i16 value before casting to u32. Add regression test to prevent silent wrap-around.
marcospb19
approved these changes
Aug 16, 2026
Member
|
Thanks!! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What's broken
A negative
--levelsilently gives maximum compression, which is the opposite of what was asked for.The fix
levelis anOption<i16>, and it was cast before being clamped:-1i16 as u32is4294967295, soclamp(0, 9)returns9. Clamping first and casting after gives the intended result:Brotli in the same match already does exactly this,
level.unwrap_or(default_level).clamp(0, 11) as u32, which is what the other arms were meant to look like.Six arms changed: Gzip, Bzip, Lzma, Xz, Lzip and Snappy.
Zstd is deliberately untouched. It casts to
i32, which preserves the sign for ani16, then clamps againstmin_c_level()andmax_c_level(). Negative zstd levels are a real feature and still work:Bzip3, Lz4 and the container formats ignore
levelentirely.After:
Verification
negative_compression_level_is_not_maximumintests/integration.rsasserts--level=-1and--level=9do not produce the same output. With the change reverted it fails with both sizes equal.The reason the existing coverage missed this: the
single_fileproptest right above it already drives-l, but its strategy is0i16..12, so it never generates a negative.cargo testpasses, no snapshot changed and none was regenerated, andcargo fmt -- --checkandcargo clippy --all-targetsare clean.