[release/8.0-staging] UInt64.CreateSaturating<Int128> truncates instead of saturates #97047
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.
Backport of #96369 to release/8.0-staging
/cc @tannergooding @pedrobsaila
Customer Impact
As reported by a customer, attempting to use generic math to convert an
Int128
to aUInt64
using saturation may see incorrect results. This conversion uses truncation behavior instead of saturation. For example,ulong.CreateSaturating((Int128)ulong.MaxValue + (Int128)10L))
returns9
instead ofulong.MaxValue
(18446744073709551615
).The customer found and illustrated scenarios/types where the correct behavior exists, comparing this to types where the incorrect behavior is present. This bug results in unexpected arithmetic results, which can cause data correctness issues in applications. More details can be found in #94523, where this was reported.
Regression
No. The bug exists back to .NET 7.
Testing
Additional tests covering the edge case were added.
Risk
Low. The general pattern is already established and this was using the wrong one (conversion to a smaller type use one pattern, conversion to a larger type use a different pattern), likely due to a copy/paste error when covering the full set of integral types that needed the code.