fix: use saturating casts in lean_float_to_uint8
to avoid UB
#1458
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.
The C Standard, 6.3.1.4, paragraph 1 [ISO/IEC 9899:2011], says,
This means that the simple implementation
uint8_t f(double d) { return (uint8_t)d; }
is undefined behavior for large values ofd
. The correct version is to check that the value would truncate to a value in the range of the target type, that is,0 <= d < 2^8
. We have to write out2^8
as a double constant though since this doesn't appear in any standard headers.This changes the observable behavior of the cast from wrapping modulo 2^8 to saturating, but I think this behavior is more defensible (and it's also what rust did when they hit the same issue).
See also the Zulip thread.