-
Notifications
You must be signed in to change notification settings - Fork 581
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
C++: Avoid undefined behaviour when casting float to int #6564
Conversation
When the truncated float can't be represented as int, it's undefined behaviour to cast. Work around this by clamping. Unfortunately this has the side-effect of eliminating an implicit sign conversion that causes signed vs. unsigned comparison warning, when comparing images. The compiler is told that the width/height is Type::Int32, when we return it as uint32_t. This is eliminated with a private helper function.
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
@@ -129,6 +129,13 @@ inline void debug(const SharedString &str) | |||
cbindgen_private::slint_debug(&str); | |||
} | |||
|
|||
constexpr inline int cast_float_to_int(float f) | |||
{ | |||
// Casting > int_max, etc. is UB, so clamp. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why not use std::clamp? Because of NaN?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just me being forgetful - thanks :). Maybe that also helps with the CI.
(best part, I even wrote clamp in the comment!)
api/cpp/include/slint.h
Outdated
{ | ||
// Casting > int_max, etc. is UB, so clamp. | ||
return static_cast<int>(std::min(std::max(f, float(std::numeric_limits<int>::min())), | ||
float(std::numeric_limits<int>::max()))); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It is possible that MAX_INT cannot be represented as a float and is still larger
Grmbl. This also fails. My excitement for this change is.. reducing. I'm going to start over fixing the test to use floats. |
When the truncated float can't be represented as int, it's undefined behaviour to cast. Work around this by clamping.
Unfortunately this has the side-effect of eliminating an implicit sign conversion that causes signed vs. unsigned comparison warning, when comparing images. The compiler is told that the width/height is Type::Int32, when we return it as uint32_t. This is eliminated with a private helper function.