Skip to content

Commit

Permalink
Better testing of float to_string lengths.
Browse files Browse the repository at this point in the history
More portable ways of trying to hit the worst-case string length for
floating-point conversions to strings.  Thanks @GordonLElliott.
  • Loading branch information
jtv committed Jun 23, 2020
1 parent 79f241d commit 29f8c73
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions test/unit/test_float.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -126,46 +126,44 @@ void test_long_float()

test_float_length(std::numeric_limits<float>::denorm_min());
test_float_length(-std::numeric_limits<float>::denorm_min());
test_float_length(std::numeric_limits<float>::min());
test_float_length(-std::numeric_limits<float>::min());
test_float_length(std::numeric_limits<float>::max());
test_float_length(-std::numeric_limits<float>::max());
test_float_length(-std::nextafter(1.0f, 2.0f));

test_float_length(std::numeric_limits<double>::denorm_min());
test_float_length(-std::numeric_limits<double>::denorm_min());
test_float_length(std::numeric_limits<double>::min());
test_float_length(-std::numeric_limits<double>::min());
test_float_length(std::numeric_limits<double>::max());
test_float_length(-std::numeric_limits<double>::max());
test_float_length(-std::nextafter(1.0, 2.0));

test_float_length(std::numeric_limits<long double>::denorm_min());
test_float_length(-std::numeric_limits<long double>::denorm_min());
test_float_length(std::numeric_limits<long double>::min());
test_float_length(-std::numeric_limits<long double>::min());
test_float_length(std::numeric_limits<long double>::max());
test_float_length(-std::numeric_limits<long double>::max());
test_float_length(-std::nextafter(1.0L, 2.0L));

auto constexpr awkward{-2.2250738585072014e-308};
test_float_length(-1.3339772437713657e-322);
test_float_length(awkward);
test_float_length(-1.7976931348623157e+308);

test_float_length(-1.3339772437713657e-322L);
test_float_length(static_cast<long double>(awkward));
test_float_length(-1.7976931348623157e+308L);

// Ahem. I'm not proud of this. We really can't assume much about the
// floating-point types, but I'd really like to try a few things to see that
// buffer sizes are in the right ballpark. So, if "double" is at least 64
// bits, check for some examples of long conversions.
if constexpr (sizeof(double) >= 8)
{
auto constexpr awkward{-2.2250738585072014e-308};
auto const text{pqxx::to_string(awkward)};
PQXX_CHECK_LESS_EQUAL(
text.size(), 25u, text + " converted to too long a string.");
}
if constexpr (sizeof(double) <= 8)
{
auto const text{pqxx::to_string(awkward)};
auto const text{pqxx::to_string(0.99)};
PQXX_CHECK_LESS_EQUAL(
pqxx::string_traits<double>::size_buffer(awkward), 25u,
pqxx::string_traits<double>::size_buffer(0.99), 25u,
text + " converted to too long a string.");
}
}
Expand Down

0 comments on commit 29f8c73

Please sign in to comment.