Skip to content

Correctly invert signed integers#3067

Open
RunDevelopment wants to merge 2 commits into
image-rs:mainfrom
RunDevelopment:invert-signed
Open

Correctly invert signed integers#3067
RunDevelopment wants to merge 2 commits into
image-rs:mainfrom
RunDevelopment:invert-signed

Conversation

@RunDevelopment

Copy link
Copy Markdown
Member

This fixes the bug(?) that Pixel::invert was not implemented correctly for signed integer types. E.g. Rgb([-20_i8, 0_i8, 125_i8]).invert() produced Rgb([?, 127_i8, 2_i8]). I put a "?" there, because the calculation overflows. It's a panic in debug and -109_i8 in release.

With this PR, the inverted color is now Rgb([19_i8, -1_i8, -126_i8]).

I'm not sure if the new semantics I assigned to this are useful. They "make sense" in that they never panic and swap T::MIN_VALUE and T::MAX_VALUE, but I'm not sure if this operation makes sense for signed integers in the first place.

Breaking change, since the behavior for signed ints changed.


Frankly, I don't see the value in supporting signed integers for pixels. As I pointed out in #2851

@mstoeckl

mstoeckl commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

I think that operations like invert probably should not be part of the Pixel trait; they predate the introduction of floating point color types and color space information, and don't do particularly meaningful things to the color when either are involved, let alone with signed integers. Because invert is not very useful for anything but traditional unsigned integer images of indeterminate color space, I would not be surprised if it gets removed in a distant future 2.0 release (or moved to imageproc, as per #2238). But hopefully not soon, it hasn't been deprecated yet and I think image's 1.0 release already has many breaking changes and TODOs.

Assuming such a soft deprecation, I do not see much benefit in changing the behavior of the trait. If anyone was using signed integer types and invert() together then they likely already are aware of the issue and had a way to avoid passing negative signed integer values to invert(), but this change would silently break their code. And if the combination hasn't been seen yet, then it probably won't be before Pixel gets changed.

I'm not sure if the new semantics I assigned to this are useful.

Possible alternatives:

  • Documenting that invert() may panic or overflow on signed integer types.
  • Use saturating_sub (or wrapping_sub) instead, which preserves the behavior in the range where the function does not panic in debug mode.

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.

2 participants