Skip to content
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

Fix isnan so it doesn't cause FP errors #3951

Merged
merged 2 commits into from
May 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion include/fmt/format.h
Original file line number Diff line number Diff line change
Expand Up @@ -2695,7 +2695,7 @@ FMT_CONSTEXPR20 auto write_float(OutputIt out, const DecimalFP& f,
}

template <typename T> constexpr auto isnan(T value) -> bool {
return !(value >= value); // std::isnan doesn't support __float128.
return value != value; // std::isnan doesn't support __float128.
}

template <typename T, typename Enable = void>
Expand Down
20 changes: 20 additions & 0 deletions test/format-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

#include <stdint.h> // uint32_t

#include <cfenv> // fegetexceptflag and FE_ALL_EXCEPT
#include <climits> // INT_MAX
#include <cmath> // std::signbit
#include <condition_variable> // std::condition_variable
Expand Down Expand Up @@ -109,6 +110,14 @@ TEST(float_test, isfinite) {
#endif
}

void check_no_fp_exception() {
fexcept_t fe;
fegetexceptflag(&fe, FE_ALL_EXCEPT);

// No exception flags should have been set
EXPECT_TRUE(fe == 0);
}

template <typename Float> void check_isnan() {
using fmt::detail::isnan;
EXPECT_FALSE(isnan(Float(0.0)));
Expand All @@ -121,6 +130,17 @@ template <typename Float> void check_isnan() {
EXPECT_FALSE(isnan(Float(-limits::infinity())));
EXPECT_TRUE(isnan(Float(limits::quiet_NaN())));
EXPECT_TRUE(isnan(Float(-limits::quiet_NaN())));

// Sanity check: make sure no error has occurred before we start
check_no_fp_exception();

// Check that no exception is raised for the non-NaN case
isnan(Float(42.0));
check_no_fp_exception();

// Check that no exception is raised for the NaN case
isnan(Float(limits::quiet_NaN()));
check_no_fp_exception();
}

TEST(float_test, isnan) {
Expand Down
Loading