From e33e35c4eabe253a828e6e7d01dcadd989a8c5f9 Mon Sep 17 00:00:00 2001 From: Daniel Lemire Date: Fri, 27 Nov 2026 10:16:18 -0500 Subject: [PATCH 1/3] Parse hexadecimal floating-point numbers with chars_format::hex Supersedes #125. With fast_float::chars_format::hex, from_chars parses hexadecimal floating-point numbers as std::from_chars does with std::chars_format::hex: the std::strtod form without the assumed 0x prefix, with an optional binary exponent (required with scientific but not fixed, not allowed with fixed but not scientific). The result is correctly rounded, ties to even, using only integer arithmetic, so it does not depend on the rounding mode. Subnormals, overflow and underflow follow the conventions of the decimal parser. The conversion is a cold, out-of-line function reached from the same branch as the JavaScript parser, so the decimal path is unchanged. For char inputs, eight hexadecimal digits are validated and converted at once (SWAR); other code units go one digit at a time through the existing lookup table. It works in constant expressions (C++20). Adds tests/hex_float_test.cpp (hand-written cases, round trips of random float/double through printf %a, random strings against strtod/strtof, every byte value at every position of a digit run) and benchmarks/bench_hex.cpp (fast_float vs std::from_chars vs strtod). --- README.md | 31 +- benchmarks/CMakeLists.txt | 8 + benchmarks/bench_hex.cpp | 208 ++++++++++++++ include/fast_float/fast_float.h | 4 +- include/fast_float/parse_number.h | 288 ++++++++++++++++++- tests/BUILD.bazel | 8 + tests/CMakeLists.txt | 1 + tests/basictest.cpp | 12 + tests/fixedwidthtest.cpp | 66 +++++ tests/hex_float_test.cpp | 453 ++++++++++++++++++++++++++++++ 10 files changed, 1076 insertions(+), 3 deletions(-) create mode 100644 benchmarks/bench_hex.cpp create mode 100644 tests/hex_float_test.cpp diff --git a/README.md b/README.md index 50884721..b78da99a 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,8 @@ check whether `fmt & fast_float::chars_format::fixed` and `fmt & fast_float::chars_format::scientific` are set to determine whether we allow the fixed point and scientific notation respectively. The default is `fast_float::chars_format::general` which allows both `fixed` and `scientific`. +With `fast_float::chars_format::hex`, we parse hexadecimal floating-point +numbers instead (see [Hexadecimal floating-point numbers](#hexadecimal-floating-point-numbers)). The library seeks to follow the C++17 (see [28.2.3.(6.1)](https://eel.is/c++draft/charconv.from.chars#6.1)) specification. @@ -144,7 +146,6 @@ Furthermore, we have the following restrictions: * We support `float` and `double`, but not `long double`. We also support fixed-width floating-point types such as `std::float64_t`, `std::float32_t`, `std::float16_t`, and `std::bfloat16_t`. -* We only support the decimal format: we do not support hexadecimal strings. * For values that are very large positives or negatives (e.g., `1e9999`), we represent them using a positive or negative infinity and the returned `ec` is set to `std::errc::result_out_of_range`. @@ -441,6 +442,34 @@ int main() { } ``` +## Hexadecimal floating-point numbers + +With `fast_float::chars_format::hex`, `from_chars` parses hexadecimal +floating-point numbers, as `std::from_chars` does with `std::chars_format::hex`: +the expected form is that of `std::strtod` (e.g., `1.921fb54442d18p+1`), except +that the `0x` or `0X` prefix is assumed and must not appear. The significand is +made of hexadecimal digits with an optional decimal point, and it is optionally +followed by a binary exponent: `p` or `P`, then an optionally signed decimal +integer. The value is correctly rounded (to nearest, ties to even) whatever the +rounding mode, and out-of-range values are reported as for decimal inputs. The +`allow_leading_plus`, `skip_white_space` and `no_infnan` flags apply, and so does +a custom decimal point. If you also set `fast_float::chars_format::scientific` +but not `fast_float::chars_format::fixed`, the exponent is required; if you set +`fixed` but not `scientific`, the exponent is not allowed. + +```C++ +#include "fast_float/fast_float.h" +#include + +int main() { + std::string input = "1.921fb54442d18p+1"; // printf("%a", 3.141592653589793) without "0x" + double result; + auto answer = fast_float::from_chars(input.data(), input.data() + input.size(), result, fast_float::chars_format::hex); + if (answer.ec != std::errc() || result != 3.141592653589793) { std::cerr << "should have parsed pi\n"; return EXIT_FAILURE; } + return EXIT_SUCCESS; +} +``` + ## Multiplication of an integer by a power of 10 An integer `W` can be multiplied by a power of ten `10^Q` and converted to `double` with correctly rounded value diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index cf479b4c..79b403d6 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -13,9 +13,11 @@ target_link_libraries(realbenchmark PRIVATE counters::counters) add_executable(bench_ip bench_ip.cpp) add_executable(bench_uint16 bench_uint16.cpp) add_executable(bench_int bench_int.cpp) +add_executable(bench_hex bench_hex.cpp) target_link_libraries(bench_ip PRIVATE counters::counters) target_link_libraries(bench_uint16 PRIVATE counters::counters) target_link_libraries(bench_int PRIVATE counters::counters) +target_link_libraries(bench_hex PRIVATE counters::counters) set_property( TARGET realbenchmark @@ -29,10 +31,14 @@ set_property( set_property( TARGET bench_int PROPERTY CXX_STANDARD 17) +set_property( + TARGET bench_hex + PROPERTY CXX_STANDARD 17) target_link_libraries(realbenchmark PUBLIC fast_float) target_link_libraries(bench_ip PUBLIC fast_float) target_link_libraries(bench_uint16 PUBLIC fast_float) target_link_libraries(bench_int PUBLIC fast_float) +target_link_libraries(bench_hex PUBLIC fast_float) include(ExternalProject) @@ -53,4 +59,6 @@ add_custom_target(CopyData ALL DEPENDS simple_fastfloat_benchmark ) add_dependencies(realbenchmark CopyData) +add_dependencies(bench_hex CopyData) target_compile_definitions(realbenchmark PUBLIC BENCHMARK_DATA_DIR="${CMAKE_CURRENT_BINARY_DIR}/data") +target_compile_definitions(bench_hex PUBLIC BENCHMARK_DATA_DIR="${CMAKE_CURRENT_BINARY_DIR}/data") diff --git a/benchmarks/bench_hex.cpp b/benchmarks/bench_hex.cpp new file mode 100644 index 00000000..12b13b23 --- /dev/null +++ b/benchmarks/bench_hex.cpp @@ -0,0 +1,208 @@ +// Benchmark for hexadecimal floating-point parsing (chars_format::hex). +// +// We turn decimal numbers (from a file, or random doubles) into hexadecimal +// strings with printf("%a"), and we parse them back with fast_float, +// std::from_chars (when the standard library supports it) and std::strtod. +// +// Usage: bench_hex [file] (without a file: canada.txt, mesh.txt, random) +#if defined(__linux__) || (__APPLE__ && __aarch64__) +#define USING_COUNTERS +#endif +#include "counters/event_counter.h" +#include "fast_float/fast_float.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__cpp_lib_to_chars) && __cpp_lib_to_chars >= 201611L +#define HAVE_STD_FROM_CHARS_FLOAT 1 +#endif + +counters::event_collector collector{}; + +template +void bench(std::string const &name, std::vector const &lines, + F const &function, size_t repeat = 200) { + size_t volume = 0; + for (auto const &l : lines) { + volume += l.size(); + } + std::vector events; + for (size_t i = 0; i < repeat; i++) { + collector.start(); + double ts = function(lines); + events.push_back(collector.end()); + if (ts == 0) { + std::printf("bug\n"); + } + } + double min_ns = DBL_MAX, cycles = DBL_MAX, instructions = DBL_MAX; + for (auto const &e : events) { + min_ns = std::min(min_ns, double(e.elapsed_ns())); + cycles = std::min(cycles, double(e.cycles())); + instructions = std::min(instructions, double(e.instructions())); + } + double const n = double(lines.size()); + std::printf("%-28s: %8.2f MB/s %8.2f Mfloat/s %7.2f ns/f", name.c_str(), + double(volume) * 1000 / min_ns / 1.048576, n * 1000 / min_ns, + min_ns / n); + if (collector.has_events()) { + std::printf(" %8.2f i/f %8.2f c/f %6.2f i/c", instructions / n, cycles / n, + instructions / cycles); + } + std::printf("\n"); +} + +template +double findmax_fastfloat(std::vector const &lines) { + T answer = 0; + T x = 0; + for (auto const &st : lines) { + auto r = fast_float::from_chars(st.data(), st.data() + st.size(), x, + fast_float::chars_format::hex); + if (r.ptr != st.data() + st.size()) { + throw std::runtime_error("bug in findmax_fastfloat"); + } + answer = answer > x ? answer : x; + } + return double(answer); +} + +#ifdef HAVE_STD_FROM_CHARS_FLOAT +template +double findmax_from_chars(std::vector const &lines) { + T answer = 0; + T x = 0; + for (auto const &st : lines) { + auto r = std::from_chars(st.data(), st.data() + st.size(), x, + std::chars_format::hex); + if (r.ptr != st.data() + st.size()) { + throw std::runtime_error("bug in findmax_from_chars"); + } + answer = answer > x ? answer : x; + } + return double(answer); +} +#endif + +// strtod and strtof need the "0x" prefix: they get their own strings. +double findmax_strtod(std::vector const &lines) { + double answer = 0; + for (auto const &st : lines) { + char *end; + double x = std::strtod(st.c_str(), &end); + if (end != st.data() + st.size()) { + throw std::runtime_error("bug in findmax_strtod"); + } + answer = answer > x ? answer : x; + } + return answer; +} + +double findmax_strtof(std::vector const &lines) { + float answer = 0; + for (auto const &st : lines) { + char *end; + float x = std::strtof(st.c_str(), &end); + if (end != st.data() + st.size()) { + throw std::runtime_error("bug in findmax_strtof"); + } + answer = answer > x ? answer : x; + } + return double(answer); +} + +// x must be finite: printf("%a") writes inf and nan without the "0x". +std::string to_hex(double x) { + char buffer[64]; + std::snprintf(buffer, sizeof(buffer), "%a", x); + std::string s = buffer; + size_t const at = s.find('x'); + return s.substr(0, at - 1) + s.substr(at + 1); // drop the "0x" +} + +void process(std::vector const &values) { + std::vector hex, prefixed; + size_t volume = 0; + for (double v : values) { + if (!std::isfinite(v)) { + continue; + } + std::string s = to_hex(v); + volume += s.size(); + hex.push_back(s); + std::string p = s; + p.insert(p[0] == '-' ? 1 : 0, "0x"); + prefixed.push_back(p); + } + std::printf("# %zu numbers, %.1f bytes/number, e.g., %s\n", hex.size(), + double(volume) / double(hex.size()), hex[hex.size() / 2].c_str()); + bench("fastfloat (64)", hex, findmax_fastfloat); +#ifdef HAVE_STD_FROM_CHARS_FLOAT + bench("std::from_chars (64)", hex, findmax_from_chars); +#endif + bench("strtod (64)", prefixed, findmax_strtod); + bench("fastfloat (32)", hex, findmax_fastfloat); +#ifdef HAVE_STD_FROM_CHARS_FLOAT + bench("std::from_chars (32)", hex, findmax_from_chars); +#endif + bench("strtof (32)", prefixed, findmax_strtof); +} + +void fileload(std::string const &filename) { + std::ifstream inputfile(filename); + if (!inputfile) { + std::cerr << "can't open " << filename << std::endl; + return; + } + std::printf("# reading %s\n", filename.c_str()); + std::vector values; + std::string line; + while (std::getline(inputfile, line)) { + double x; + auto r = fast_float::from_chars(line.data(), line.data() + line.size(), x); + if (r.ec == std::errc()) { + values.push_back(x); + } + } + process(values); +} + +void random_values(size_t n) { + std::printf("# random doubles in [0,1)\n"); + std::mt19937_64 rng(42); + std::uniform_real_distribution dis(0, 1); + std::vector values; + for (size_t i = 0; i < n; i++) { + values.push_back(dis(rng)); + } + process(values); +} + +int main(int argc, char **argv) { + if (collector.has_events()) { + std::printf("# Using hardware counters\n"); + } +#ifndef HAVE_STD_FROM_CHARS_FLOAT + std::printf("# std::from_chars for floats is not available\n"); +#endif + if (argc > 1) { + fileload(argv[1]); + return EXIT_SUCCESS; + } + fileload(std::string(BENCHMARK_DATA_DIR) + "/canada.txt"); + fileload(std::string(BENCHMARK_DATA_DIR) + "/mesh.txt"); + random_values(100000); + return EXIT_SUCCESS; +} diff --git a/include/fast_float/fast_float.h b/include/fast_float/fast_float.h index 1e79ac61..47998ded 100644 --- a/include/fast_float/fast_float.h +++ b/include/fast_float/fast_float.h @@ -28,7 +28,9 @@ namespace fast_float { * fast_float::chars_format::scientific` are set to determine whether we allow * the fixed point and scientific notation respectively. The default is * `fast_float::chars_format::general` which allows both `fixed` and - * `scientific`. + * `scientific`. With `fast_float::chars_format::hex`, we parse hexadecimal + * floating-point numbers (e.g., "1.8p1" for 3.0) as std::from_chars does: the + * "0x" prefix is assumed and must not appear. */ template ::value)> diff --git a/include/fast_float/parse_number.h b/include/fast_float/parse_number.h index 19dab3b8..5ae2871a 100644 --- a/include/fast_float/parse_number.h +++ b/include/fast_float/parse_number.h @@ -385,6 +385,288 @@ from_chars_float_javascript(UC const *first, UC const *last, T &value, return from_chars_advanced(pns, value); } +namespace detail { +// Value of a hexadecimal digit, or a value of at least 16 if c is not one. +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR14 uint32_t hex_digit(UC c) { + if (cpp20_and_in_constexpr()) { + // The lookup table cannot be read in a constant expression. Any code unit + // (signed or not, of any width) maps to a distinct unsigned value, and + // only the 22 hexadecimal digits map below 16. + uint32_t const u = uint32_t(c); + if (u - uint32_t('0') < 10) { + return u - uint32_t('0'); + } + if ((u | 0x20) - uint32_t('a') < 6) { + return (u | 0x20) - uint32_t('a') + 10; + } + return 16; + } + // Branchless: the digits and the letters of a hexadecimal significand come + // in no predictable order. + return ch_to_digit(c); +} + +// Parses 8 hexadecimal digits given as 8 bytes, the first digit in the least +// significant byte (see read8_to_u64). Returns false, leaving out untouched, +// if one of the bytes is not a hexadecimal digit. +fastfloat_really_inline FASTFLOAT_CONSTEXPR14 bool +parse_eight_hex_digits(uint64_t v, uint32_t &out) noexcept { + // For a byte x < 0x80, (x + 0x80 - lo) has its high bit set if x >= lo and + // (x + 0x7f - hi) has its high bit set if x > hi, and no carry leaves the + // byte. A byte x >= 0x80 never passes either test (both sums have their + // high bit set, or the first one wraps around below 0x80), even with a + // carry from the byte below it, so it is rejected; the carry it may send to + // the byte above does not matter. + uint64_t const high = 0x8080808080808080; + uint64_t const lower = v | 0x2020202020202020; // 'A'-'F' becomes 'a'-'f' + uint64_t const is_digit = + (v + 0x5050505050505050) & ~(v + 0x4646464646464646); // '0'-'9' + uint64_t const is_letter = + (lower + 0x1f1f1f1f1f1f1f1f) & ~(lower + 0x1919191919191919); // 'a'-'f' + if (((is_digit | is_letter) & high) != high) { + return false; + } + // '0'-'9' have their value in the low nibble, 'a'-'f' and 'A'-'F' have + // their value minus 9. + uint64_t const nibbles = + (v & 0x0f0f0f0f0f0f0f0f) + ((is_letter & high) >> 7) * 9; + // Put the first digit in the most significant byte, then pack the nibbles. + uint64_t x = byteswap(nibbles); + x = (x | (x >> 4)) & 0x00ff00ff00ff00ff; + x = (x | (x >> 8)) & 0x0000ffff0000ffff; + out = uint32_t(x | (x >> 16)); + return true; +} + +// Adds one hexadecimal digit to the mantissa if it has room (at most 16 +// significant digits). In the integer part, each digit dropped adds 4 to the +// exponent; in the fraction, each digit kept subtracts 4. A dropped nonzero +// digit sets sticky. +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR14 void +add_hex_digit(uint32_t digit, uint64_t &mantissa, int64_t &exponent, + bool &sticky) noexcept { + if ((mantissa >> 60) == 0) { + mantissa = (mantissa << 4) | digit; + if (fraction) { + exponent -= 4; + } + } else { + if (!fraction) { + exponent += 4; + } + sticky |= (digit != 0); + } +} + +// Parses a run of hexadecimal digits (see add_hex_digit). +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void +parse_hex_digits(UC const *&p, UC const *last, uint64_t &mantissa, + int64_t &exponent, bool &sticky) noexcept { + uint32_t digit; + if ((p == last) || ((digit = hex_digit(*p)) >= 16)) { + return; + } + add_hex_digit(digit, mantissa, exponent, sticky); + ++p; + // Blocks of 8 digits, only for char (other code units would need to be + // checked for high bits), while the mantissa has room for them. We start + // after one digit, and only if a second one follows: printf("%a") and + // std::to_chars write a single digit before the point, and failing a + // block costs about as much as parsing one. + if (!cpp20_and_in_constexpr() && std::is_same::value && + (p != last) && (hex_digit(*p) < 16)) { + uint32_t eight; + while ((last - p >= 8) && (mantissa >> 32) == 0 && + parse_eight_hex_digits(read8_to_u64(p), eight)) { + mantissa = (mantissa << 32) | eight; + if (fraction) { + exponent -= 32; + } + p += 8; + } + } + while ((p != last) && ((digit = hex_digit(*p)) < 16)) { + add_hex_digit(digit, mantissa, exponent, sticky); + ++p; + } +} + +// Rounds m * 2^e2 + (a sticky fraction below m's last bit, if sticky is set) +// to the nearest value of type T, ties to even, and stores it with the sign. +// m must be nonzero. Returns false if the result overflows to infinity or +// underflows to zero. Only integer arithmetic is used, so the result does not +// depend on the rounding mode of the thread. +template +FASTFLOAT_CONSTEXPR20 bool hex_to_float(bool negative, uint64_t m, int64_t e2, + bool sticky, T &value) noexcept { + constexpr int mbits = binary_format::mantissa_explicit_bits(); + constexpr int bias = -binary_format::minimum_exponent(); + constexpr int infinite_power = binary_format::infinite_power(); + int const lz = leading_zeroes(m); + m <<= lz; + // Now the value is 1.xxx * 2^(e2 + 63 - lz). With a bias, this exponent + // is the IEEE exponent field when the value is normal. + int64_t biased = e2 + 63 - lz + bias; + adjusted_mantissa am; + if (biased >= infinite_power) { + am.mantissa = 0; + am.power2 = infinite_power; + to_float(negative, am, value); + return false; + } + // We keep mbits + 1 bits when normal, fewer when subnormal. + int64_t shift = 63 - mbits; + if (biased <= 0) { + shift += 1 - biased; + biased = 1; // undone below, if the result stays subnormal + } + // round_bit and rest are 0 or 1. Rounding is branchless: when the input + // has more bits than T (e.g., a double parsed as a float), the round bit + // is unpredictable. + uint64_t kept; + uint64_t round_bit; + uint64_t rest; + if (shift < 64) { + kept = m >> shift; + round_bit = (m >> (shift - 1)) & 1; + rest = uint64_t(sticky) | + uint64_t((m & ((uint64_t(1) << (shift - 1)) - 1)) != 0); + } else if (shift == 64) { + kept = 0; + round_bit = 1; // m has its top bit set + rest = uint64_t(sticky) | uint64_t((m << 1) != 0); + } else { + kept = 0; + round_bit = 0; + rest = 1; + } + kept += round_bit & (rest | (kept & 1)); + if (kept == (uint64_t(2) << mbits)) { // carried into the next binade + kept >>= 1; + biased++; + if (biased >= infinite_power) { + am.mantissa = 0; + am.power2 = infinite_power; + to_float(negative, am, value); + return false; + } + } + // A subnormal result has no implicit bit (the value can round up to the + // smallest normal number, which then gets its implicit bit). + if (kept < (uint64_t(1) << mbits)) { + biased = 0; + } + am.mantissa = kept & ((uint64_t(1) << mbits) - 1); + am.power2 = int32_t(biased); + to_float(negative, am, value); + return kept != 0; +} +} // namespace detail + +// Cold: the whole chars_format::hex conversion. Follows C++17 +// [charconv.from.chars]: the expected form is that of std::strtod for a +// hexadecimal floating-point number, without the "0x" or "0X" prefix (it is +// assumed). The binary exponent ('p' or 'P' followed by an optionally signed +// decimal integer) is optional, unless chars_format::scientific is set but not +// chars_format::fixed, in which case it is required. If chars_format::fixed is +// set but not chars_format::scientific, it is not allowed. The result is +// correctly rounded (nearest, ties to even) whatever the rounding mode. +template +fastfloat_never_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t +from_chars_float_hex(UC const *first, UC const *last, T &value, + parse_options_t options) noexcept { + chars_format const fmt = detail::adjust_for_feature_macros(options.format); + if (uint64_t(fmt & chars_format::skip_white_space)) { + while ((first != last) && fast_float::is_space(*first)) { + first++; + } + } + from_chars_result_t answer; + answer.ec = std::errc::invalid_argument; + answer.ptr = first; + if (first == last) { + return answer; + } + UC const *p = first; + bool const negative = (*p == UC('-')); + if (negative || + (uint64_t(fmt & chars_format::allow_leading_plus) && *p == UC('+'))) { + ++p; + } + // The value is mantissa * 2^exponent, plus something less than one unit of + // the mantissa when sticky is set. We keep up to 16 significant hexadecimal + // digits (64 bits): this is more than enough for a correct rounding as long + // as we remember whether any of the dropped digits was nonzero. + uint64_t mantissa = 0; + int64_t exponent = 0; + bool sticky = false; + UC const *const start_digits = p; + detail::parse_hex_digits(p, last, mantissa, exponent, sticky); + bool has_digits = (p != start_digits); + if ((p != last) && (*p == options.decimal_point)) { + ++p; + UC const *const start_fraction = p; + detail::parse_hex_digits(p, last, mantissa, exponent, sticky); + has_digits |= (p != start_fraction); + } + if (!has_digits) { + if (uint64_t(fmt & chars_format::no_infnan)) { + return answer; + } + return detail::parse_infnan(first, last, value, fmt); + } + bool const scientific = uint64_t(fmt & chars_format::scientific) != 0; + bool const fixed = uint64_t(fmt & chars_format::fixed) != 0; + if ((scientific || !fixed) && (p != last) && + ((*p == UC('p')) || (*p == UC('P')))) { + UC const *const location_of_p = p; + ++p; + bool neg_exp = false; + if ((p != last) && (*p == UC('-'))) { + neg_exp = true; + ++p; + } else if ((p != last) && (*p == UC('+'))) { + ++p; + } + if ((p == last) || !is_integer(*p)) { + if (scientific && !fixed) { + return answer; + } + p = location_of_p; // not an exponent: we stop before the 'p' + } else { + // The digits shift the exponent by at most 4 per digit, so by less + // than 2^59 for any string that fits in memory. Past 2^59, we saturate + // at 2^62: no significand can bring that back into range, and adding + // it to the exponent cannot overflow. + int64_t exp_number = 0; + while ((p != last) && is_integer(*p)) { + if (exp_number < (int64_t(1) << 59)) { + exp_number = 10 * exp_number + int64_t(*p - UC('0')); + } else { + exp_number = int64_t(1) << 62; + } + ++p; + } + exponent += neg_exp ? -exp_number : exp_number; + } + } else if (scientific && !fixed) { + return answer; // the exponent is required + } + answer.ptr = p; + if (mantissa == 0) { + value = negative ? T(-0.) : T(0.); + answer.ec = std::errc(); + return answer; + } + answer.ec = detail::hex_to_float(negative, mantissa, exponent, sticky, value) + ? std::errc() + : std::errc::result_out_of_range; + return answer; +} + template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars_float_advanced(UC const *first, UC const *last, T &value, @@ -407,7 +689,11 @@ from_chars_float_advanced(UC const *first, UC const *last, T &value, #pragma clang diagnostic ignored "-Wc++20-extensions" #endif #endif - if fastfloat_unlikely (uint64_t(fmt & detail::basic_javascript_fmt)) { + if fastfloat_unlikely (uint64_t(fmt & (detail::basic_javascript_fmt | + chars_format::hex))) { + if (uint64_t(fmt & chars_format::hex)) { + return from_chars_float_hex(first, last, value, options); + } return from_chars_float_javascript(first, last, value, options); } #ifdef __clang__ diff --git a/tests/BUILD.bazel b/tests/BUILD.bazel index 7c56f641..7f1bdd50 100644 --- a/tests/BUILD.bazel +++ b/tests/BUILD.bazel @@ -123,3 +123,11 @@ cc_test( "@doctest//doctest", ], ) + +cc_test( + name = "hex_float_test", + srcs = ["hex_float_test.cpp"], + deps = [ + "//:fast_float", + ], +) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 1ab20fbd..cb5ad6d4 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -90,6 +90,7 @@ target_compile_features(int_swar_test PRIVATE cxx_std_17) fast_float_add_cpp_test(json_fmt) fast_float_add_cpp_test(javascript_fmt) fast_float_add_cpp_test(fortran) +fast_float_add_cpp_test(hex_float_test) if(CMAKE_CXX_STANDARD GREATER_EQUAL 23) option(FASTFLOAT_FIXEDWIDTH_TESTS "Require fixed width test for C++23 (build will fail if the compiler won't support it)" ON) else() diff --git a/tests/basictest.cpp b/tests/basictest.cpp index 7bdf5cfe..311f4b3b 100644 --- a/tests/basictest.cpp +++ b/tests/basictest.cpp @@ -1561,6 +1561,18 @@ TEST_CASE("double.decimal_point") { 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022250738585072008890245868760858598876504231122409594654935248025624400092282356951787758888037591552642309780950434312085877387158357291821993020294379224223559819827501242041788969571311791082261043971979604000454897391938079198936081525613113376149842043271751033627391549782731594143828136275113838604094249464942286316695429105080201815926642134996606517803095075913058719846423906068637102005108723282784678843631944515866135041223479014792369585208321597621066375401613736583044193603714778355306682834535634005074073040135602968046375918583163124224521599262546494300836851861719422417646455137135420132217031370496583210154654068035397417906022589503023501937519773030945763173210852507299305089761582519159720757232455434770912461317493580281734466552734375); } +TEST_CASE("double.hex") { + constexpr fast_float::parse_options options{fast_float::chars_format::hex}; + verify_options("1.921fb54442d18p+1", 0x1.921fb54442d18p+1); + verify_options("-a.8p-3", -0xa.8p-3); + verify_options("1p-1074", 0x1p-1074); + verify_options("1.fffffffffffff7ffffffp1023", 0x1.fffffffffffffp1023); + verify_options("1p-1075", 0.0, std::errc::result_out_of_range); + verify_options("1.fffffffffffff8p1023", + std::numeric_limits::infinity(), + std::errc::result_out_of_range); +} + TEST_CASE("float.inf") { verify("INF", std::numeric_limits::infinity()); verify("-INF", -std::numeric_limits::infinity()); diff --git a/tests/fixedwidthtest.cpp b/tests/fixedwidthtest.cpp index 0eebd24b..df1c98fb 100644 --- a/tests/fixedwidthtest.cpp +++ b/tests/fixedwidthtest.cpp @@ -6,6 +6,9 @@ #include #include "fast_float/fast_float.h" #include +#include +#include +#include #if __cplusplus >= 202300L #include @@ -44,6 +47,57 @@ template bool check_invalid_input_preserves_value() { return true; } +// Hexadecimal inputs (chars_format::hex) for a 16-bit type: every finite +// value, and every midpoint between consecutive positive values (ties to +// even), printed exactly with %a. +template bool check_hex_16bit(uint16_t infinity_bits) { + for (uint32_t b = 0; b < 65536; b++) { + uint16_t const bits = uint16_t(b); + T x; + std::memcpy(&x, &bits, sizeof(x)); + double const d = double(x); + if (!std::isfinite(d)) { + continue; + } + for (int midpoint = 0; midpoint < 2; midpoint++) { + double target = d; + uint16_t expected = bits; + if (midpoint) { + uint16_t const next_bits = uint16_t(bits + 1); + T next; + std::memcpy(&next, &next_bits, sizeof(next)); + if (std::signbit(d) || !std::isfinite(double(next))) { + continue; // negative values are symmetric + } + target = (d + double(next)) / 2; // exact in double + expected = (bits & 1) ? next_bits : bits; + } + char buffer[64]; + std::snprintf(buffer, sizeof(buffer), "%a", target); + std::string s = buffer; + size_t const x_at = s.find('x'); + s = s.substr(0, x_at - 1) + s.substr(x_at + 1); // drop the "0x" + T result; + auto answer = fast_float::from_chars( + s.data(), s.data() + s.size(), result, fast_float::chars_format::hex); + uint16_t result_bits; + std::memcpy(&result_bits, &result, sizeof(result)); + // Overflow to infinity, or a midpoint that rounds to zero, is out of + // range. + bool const out_of_range = ((expected & 0x7fff) == infinity_bits) || + (target != 0 && (expected & 0x7fff) == 0); + std::errc const ec = + out_of_range ? std::errc::result_out_of_range : std::errc(); + if (result_bits != expected || answer.ptr != s.data() + s.size() || + answer.ec != ec) { + std::cerr << "hex parsing failed for \"" << s << "\"" << std::endl; + return false; + } + } + } + return true; +} + int main() { // Write some testcases for the parsing of floating point numbers in the // float32_t type. We use the from_chars function defined in this library. @@ -103,6 +157,18 @@ int main() { } #else std::cout << "No std::float64_t type available." << std::endl; +#endif +#ifdef __STDCPP_FLOAT16_T__ + std::cout << "runing float16 hex test" << std::endl; + if (!check_hex_16bit(0x7c00)) { + return EXIT_FAILURE; + } +#endif +#ifdef __STDCPP_BFLOAT16_T__ + std::cout << "runing bfloat16 hex test" << std::endl; + if (!check_hex_16bit(0x7f80)) { + return EXIT_FAILURE; + } #endif std::cout << "All tests passed successfully." << std::endl; return EXIT_SUCCESS; diff --git a/tests/hex_float_test.cpp b/tests/hex_float_test.cpp new file mode 100644 index 00000000..06cb2d2f --- /dev/null +++ b/tests/hex_float_test.cpp @@ -0,0 +1,453 @@ +/* + * Exercise chars_format::hex (hexadecimal floating-point numbers). + * + * We check hand-written cases, then compare against std::strtod/std::strtof + * (which take the same form, with a "0x" prefix) on random inputs. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "fast_float/fast_float.h" + +namespace { + +template struct bits_of; + +template <> struct bits_of { + using type = uint64_t; +}; + +template <> struct bits_of { + using type = uint32_t; +}; + +template typename bits_of::type to_bits(T x) { + typename bits_of::type b; + std::memcpy(&b, &x, sizeof(x)); + return b; +} + +template T reference_parse(std::string const &s); + +template <> double reference_parse(std::string const &s) { + return std::strtod(s.c_str(), nullptr); +} + +template <> float reference_parse(std::string const &s) { + return std::strtof(s.c_str(), nullptr); +} + +template bool same(T a, T b) { + if (std::isnan(a) && std::isnan(b)) { + return std::signbit(a) == std::signbit(b); + } + return to_bits(a) == to_bits(b); +} + +int failures = 0; + +struct hex_case { + char const *input; + double expected; + size_t consumed; + std::errc ec; + fast_float::chars_format fmt; +}; + +constexpr double inf = std::numeric_limits::infinity(); +constexpr fast_float::chars_format hex = fast_float::chars_format::hex; + +void check_cases() { + using fast_float::chars_format; + std::vector const cases = { + {"1", 1.0, 1, std::errc(), hex}, + {"1p0", 1.0, 3, std::errc(), hex}, + {"1P0", 1.0, 3, std::errc(), hex}, + {"a", 10.0, 1, std::errc(), hex}, + {"A.8", 10.5, 3, std::errc(), hex}, + {"-1.8p1", -3.0, 6, std::errc(), hex}, + {"1.921fb54442d18p+1", 3.141592653589793, 18, std::errc(), hex}, + {"1p-1", 0.5, 4, std::errc(), hex}, + {".8", 0.5, 2, std::errc(), hex}, + {"1.", 1.0, 2, std::errc(), hex}, + {"0", 0.0, 1, std::errc(), hex}, + {"-0", -0.0, 2, std::errc(), hex}, + {"0.000p-99999", 0.0, 12, std::errc(), hex}, + {"0p99999", 0.0, 7, std::errc(), hex}, + // The "0x" prefix is assumed, so it cannot appear: we parse the 0. + {"0x1p0", 0.0, 1, std::errc(), hex}, + // An incomplete exponent is not part of the number. + {"1p", 1.0, 1, std::errc(), hex}, + {"1p+", 1.0, 1, std::errc(), hex}, + {"1p-x", 1.0, 1, std::errc(), hex}, + {"1.8g", 1.5, 3, std::errc(), hex}, + // Limits of double. + {"1.fffffffffffffp1023", 1.7976931348623157e308, 20, std::errc(), hex}, + {"1p-1022", 2.2250738585072014e-308, 7, std::errc(), hex}, + {"1p-1074", 4.9406564584124654e-324, 7, std::errc(), hex}, + {"0.0000000000001p-1022", 4.9406564584124654e-324, 21, std::errc(), hex}, + {"fffffffffffff8p-1078", 2.2250738585072014e-308, 20, std::errc(), hex}, + // Rounding: exactly halfway between max double and 2^1024 rounds to even + // which is infinity. + {"1.fffffffffffff8p1023", inf, 21, std::errc::result_out_of_range, hex}, + {"1.fffffffffffff7ffffffp1023", 1.7976931348623157e308, 27, std::errc(), + hex}, + {"1p1024", inf, 6, std::errc::result_out_of_range, hex}, + {"-1p1024", -inf, 7, std::errc::result_out_of_range, hex}, + {"1p99999999999999999999", inf, 22, std::errc::result_out_of_range, hex}, + // Half of the smallest subnormal rounds to zero (ties to even), anything + // above rounds to the smallest subnormal. + {"1p-1075", 0.0, 7, std::errc::result_out_of_range, hex}, + {"-1p-1075", -0.0, 8, std::errc::result_out_of_range, hex}, + {"1.0000000000000000000001p-1075", 4.9406564584124654e-324, 30, + std::errc(), hex}, + {"1.8p-1075", 4.9406564584124654e-324, 9, std::errc(), hex}, + {"1p-99999999999999999999", 0.0, 23, std::errc::result_out_of_range, hex}, + // Ties to even on normal numbers. + {"1.00000000000008p0", 1.0, 18, std::errc(), hex}, + {"1.00000000000018p0", 1.0000000000000004, 18, std::errc(), hex}, + {"1.000000000000080000000000000000000001p0", 1.0000000000000002, 40, + std::errc(), hex}, + // Many digits before the point. + {"10000000000000000000000000000000", 2.1267647932558654e+37, 32, + std::errc(), hex}, + {"00000000000000000000000000000001.8", 1.5, 34, std::errc(), hex}, + // Special values. + {"inf", inf, 3, std::errc(), hex}, + {"-infinity", -inf, 9, std::errc(), hex}, + // Errors. + {"", 0.0, 0, std::errc::invalid_argument, hex}, + {".", 0.0, 0, std::errc::invalid_argument, hex}, + {"-", 0.0, 0, std::errc::invalid_argument, hex}, + {"+1", 0.0, 0, std::errc::invalid_argument, hex}, + {"p1", 0.0, 0, std::errc::invalid_argument, hex}, + {"g", 0.0, 0, std::errc::invalid_argument, hex}, + {"inf", 0.0, 0, std::errc::invalid_argument, + hex | chars_format::no_infnan}, + // Options. + {"+1", 1.0, 2, std::errc(), hex | chars_format::allow_leading_plus}, + {" 1p4", 16.0, 5, std::errc(), hex | chars_format::skip_white_space}, + // scientific without fixed: the exponent is required. + {"1p4", 16.0, 3, std::errc(), hex | chars_format::scientific}, + {"1", 0.0, 0, std::errc::invalid_argument, + hex | chars_format::scientific}, + {"1p", 0.0, 0, std::errc::invalid_argument, + hex | chars_format::scientific}, + // fixed without scientific: the exponent is not allowed. + {"1p4", 1.0, 1, std::errc(), hex | chars_format::fixed}, + // both: the exponent is optional. + {"1p4", 16.0, 3, std::errc(), hex | chars_format::general}, + {"1", 1.0, 1, std::errc(), hex | chars_format::general}, + }; + for (auto const &c : cases) { + size_t const len = std::strlen(c.input); + double result = 12345.0; + auto answer = fast_float::from_chars(c.input, c.input + len, result, c.fmt); + bool ok = + (answer.ec == c.ec) && (size_t(answer.ptr - c.input) == c.consumed); + if (ok && c.ec != std::errc::invalid_argument) { + ok = same(result, c.expected); + } + if (ok && c.ec == std::errc::invalid_argument) { + ok = (result == 12345.0); // left unmodified + } + if (!ok) { + std::printf("FAIL: \"%s\" -> %a (consumed %zu, ec %d), expected %a " + "(consumed %zu, ec %d)\n", + c.input, result, size_t(answer.ptr - c.input), int(answer.ec), + c.expected, c.consumed, int(c.ec)); + failures++; + } + } +} + +void check_float_cases() { + struct float_case { + char const *input; + float expected; + std::errc ec; + }; + + constexpr float finf = std::numeric_limits::infinity(); + std::vector const cases = { + {"1.fffffep127", 3.40282347e+38f, std::errc()}, + {"1.ffffffp127", finf, std::errc::result_out_of_range}, + {"1p-149", 1.40129846e-45f, std::errc()}, + {"1p-150", 0.0f, std::errc::result_out_of_range}, + {"1.000001p-150", 1.40129846e-45f, std::errc()}, + {"1p-126", 1.17549435e-38f, std::errc()}, + {"0.fffffffp-126", 1.17549435e-38f, std::errc()}, + {"1.000001p0", 1.0f, std::errc()}, + {"1.000003p0", 1.00000024f, std::errc()}, + }; + for (auto const &c : cases) { + size_t const len = std::strlen(c.input); + float result; + auto answer = fast_float::from_chars(c.input, c.input + len, result, hex); + if (answer.ec != c.ec || answer.ptr != c.input + len || + !same(result, c.expected)) { + std::printf("FAIL (float): \"%s\" -> %a, expected %a\n", c.input, + double(result), double(c.expected)); + failures++; + } + } +} + +void check_wide() { + std::u16string const s16 = u"-1.8p1"; + double result; + auto answer = + fast_float::from_chars(s16.data(), s16.data() + s16.size(), result, hex); + if (answer.ec != std::errc() || answer.ptr != s16.data() + s16.size() || + result != -3.0) { + std::printf("FAIL: char16_t\n"); + failures++; + } + std::u32string const s32 = U"ff.8p-1"; + auto answer32 = + fast_float::from_chars(s32.data(), s32.data() + s32.size(), result, hex); + if (answer32.ec != std::errc() || answer32.ptr != s32.data() + s32.size() || + result != 127.75) { + std::printf("FAIL: char32_t\n"); + failures++; + } + // A code unit whose low byte is a hexadecimal digit is not a digit. + std::u16string const bad = u"1İ"; + answer = + fast_float::from_chars(bad.data(), bad.data() + bad.size(), result, hex); + if (answer.ec != std::errc() || answer.ptr != bad.data() + 1 || + result != 1.0) { + std::printf("FAIL: char16_t with high bits\n"); + failures++; + } + // A comma as the decimal point. + std::string const comma = "1,8p1"; + fast_float::parse_options options{hex, ','}; + auto answer_comma = fast_float::from_chars_advanced( + comma.data(), comma.data() + comma.size(), result, options); + if (answer_comma.ec != std::errc() || result != 3.0) { + std::printf("FAIL: comma\n"); + failures++; + } +} + +// Every finite double printed with %a parses back to itself. +template void check_roundtrip(std::mt19937_64 &rng, size_t n) { + using U = typename bits_of::type; + for (size_t i = 0; i < n; i++) { + U const b = U(rng()); + T x; + std::memcpy(&x, &b, sizeof(x)); + if (!std::isfinite(x)) { + continue; + } + char buffer[64]; + std::snprintf(buffer, sizeof(buffer), "%a", double(x)); + // Drop the sign and the "0x". + char const *start = buffer + (buffer[0] == '-' ? 3 : 2); + std::string s = (buffer[0] == '-' ? "-" : ""); + s += start; + T result; + auto answer = + fast_float::from_chars(s.data(), s.data() + s.size(), result, hex); + if (answer.ec != std::errc() || answer.ptr != s.data() + s.size() || + !same(result, x)) { + std::printf("FAIL roundtrip: %s\n", s.c_str()); + failures++; + return; + } + } +} + +std::string random_hex_string(std::mt19937_64 &rng) { + static char const digits[] = "0123456789abcdefABCDEF"; + std::string s; + if (rng() % 4 == 0) { + s += '-'; + } + size_t const ndigits = 1 + size_t(rng() % 40); + size_t const point = size_t(rng() % (ndigits + 2)); // > ndigits: no point + int const style = int(rng() % 4); + for (size_t i = 0; i < ndigits; i++) { + if (i == point) { + s += '.'; + } + char c; + switch (style) { + case 0: // uniform + c = digits[rng() % 22]; + break; + case 1: // near ties: one leading digit, then mostly zeros or 8s + c = (i == 0) ? '1' : ((rng() % 8 == 0) ? digits[rng() % 16] : '0'); + break; + case 2: // long runs of f + c = (rng() % 8 == 0) ? digits[rng() % 16] : 'f'; + break; + default: // leading zeros + c = (i < ndigits / 2) ? '0' : digits[rng() % 16]; + break; + } + s += c; + } + if (point == ndigits) { + s += '.'; + } + if (rng() % 8 != 0) { + s += (rng() % 2) ? 'p' : 'P'; + int const r = int(rng() % 3); + if (r == 0) { + s += '-'; + } else if (r == 1) { + s += '+'; + } + // Exponents that reach subnormals and overflow from any digit count. + s += std::to_string(rng() % 1300); + } + return s; +} + +template void check_random(std::mt19937_64 &rng, size_t n) { + for (size_t i = 0; i < n; i++) { + std::string const s = random_hex_string(rng); + std::string prefixed = s; + size_t const sign = (s[0] == '-') ? 1 : 0; + prefixed.insert(sign, "0x"); + T const expected = reference_parse(prefixed); + T result; + auto answer = + fast_float::from_chars(s.data(), s.data() + s.size(), result, hex); + bool ok = answer.ptr == s.data() + s.size() && same(result, expected); + if (ok) { + bool const out_of_range = + std::isinf(expected) || + (expected == 0 && + s.find_first_of("123456789abcdefABCDEF") < s.find_first_of("pP")); + ok = (answer.ec == + (out_of_range ? std::errc::result_out_of_range : std::errc())); + } + if (!ok) { + std::printf("FAIL random: %s -> %a (ec %d) expected %a\n", s.c_str(), + double(result), int(answer.ec), double(expected)); + failures++; + if (failures > 20) { + return; + } + } + } +} + +// Put every byte value at every position of a run of digits, so that the +// blocks of 8 digits see every kind of non-digit byte, and compare the value +// and the number of characters consumed with strtod. +void check_all_bytes() { + std::string const base = "1234567890abcdefABCDEF0123456789"; + for (int b = 0; b < 256; b++) { + for (size_t k = 0; k < 18; k++) { + if (k == 0 && (b == '-' || b == '+')) { + continue; // a sign, which strtod does not take after "0x" + } + for (size_t point : {size_t(0), size_t(3), size_t(100)}) { + std::string s = base; + if (point < s.size()) { + s.insert(point, "."); + } + s[k] = char(b); + double result = 0; + auto answer = + fast_float::from_chars(s.data(), s.data() + s.size(), result, hex); + std::string prefixed = "0x" + s; + char *end = nullptr; + double const expected = std::strtod(prefixed.c_str(), &end); + size_t const consumed = + (end == prefixed.c_str()) ? 0 : size_t(end - prefixed.c_str()) - 2; + // strtod reads "0x" as the number 0 when no digit follows. + bool const strtod_parsed_zero = (consumed == size_t(-1)); + bool ok; + if (strtod_parsed_zero || consumed == 0) { + ok = (answer.ec == std::errc::invalid_argument); + } else { + // An exponent can follow the first digits ("1p345..."). + std::errc const ec = (std::isinf(expected) || expected == 0) + ? std::errc::result_out_of_range + : std::errc(); + ok = (answer.ec == ec) && + (size_t(answer.ptr - s.data()) == consumed) && + same(result, expected); + } + if (!ok) { + std::printf("FAIL: byte %d at %zu (point %zu)\n", b, k, point); + failures++; + return; + } + } + } + } +} + +// The exponent must not stop counting while a long significand still moves +// it: 4 * 67108864 = 2^28, so 0.(67108863 zeros)1 is 2^-268435456. +void check_long_exponent() { + std::string const zeros(67108863, '0'); + struct long_case { + std::string input; + double expected; + std::errc ec; + }; + long_case const cases[] = { + {"0." + zeros + "1p268435456", 1.0, std::errc()}, + {"0." + zeros + "1p268435457", 2.0, std::errc()}, + {"0." + zeros + "1p2684354560", std::numeric_limits::infinity(), + std::errc::result_out_of_range}, + {"1" + zeros + "0p-268435456", 1.0, std::errc()}, + {"1" + zeros + "0p-2684354560", 0.0, std::errc::result_out_of_range}, + {"1" + zeros + "0p-99999999999999999999999999", 0.0, + std::errc::result_out_of_range}, + {"0." + zeros + "1p99999999999999999999999999", + std::numeric_limits::infinity(), std::errc::result_out_of_range}, + }; + for (auto const &c : cases) { + double result = 12345.0; + auto answer = + fast_float::from_chars(c.input.data(), c.input.data() + c.input.size(), + result, fast_float::chars_format::hex); + if (answer.ec != c.ec || answer.ptr != c.input.data() + c.input.size() || + !same(result, c.expected)) { + std::printf("FAIL: long input ending in %s -> %a (ec %d), expected %a " + "(ec %d)\n", + c.input.c_str() + c.input.size() - 16, result, + int(answer.ec), c.expected, int(c.ec)); + failures++; + } + } +} + +} // namespace + +int main() { + check_cases(); + check_long_exponent(); + check_float_cases(); + check_wide(); + check_all_bytes(); + std::mt19937_64 rng(1234); + check_roundtrip(rng, 1000000); + check_roundtrip(rng, 1000000); + check_random(rng, 1000000); + check_random(rng, 1000000); + if (failures != 0) { + std::printf("%d failures\n", failures); + return EXIT_FAILURE; + } + std::printf("all hex float tests pass\n"); + return EXIT_SUCCESS; +} From cf219082ca792601ab24f393630471248defdece Mon Sep 17 00:00:00 2001 From: Daniel Lemire Date: Fri, 27 Nov 2026 16:51:34 -0500 Subject: [PATCH 2/3] hex_float_test: use an exact reference instead of strtod Some C libraries misround hexadecimal subnormals: glibc 2.35 and 2.39 (Ubuntu 22.04 and 24.04) round 682c27c.7e61b22p-1052 down, and the Windows UCRT returns 2^-1020 for values that round to 2^-1022. The random tests now compare against an exact reference that expands the digits into bits and rounds them. strtod still gives the number of characters consumed in check_all_bytes. Also apply clang-format. --- tests/hex_float_test.cpp | 124 ++++++++++++++++++++++++++++++++++----- 1 file changed, 108 insertions(+), 16 deletions(-) diff --git a/tests/hex_float_test.cpp b/tests/hex_float_test.cpp index 06cb2d2f..d3e5ab3c 100644 --- a/tests/hex_float_test.cpp +++ b/tests/hex_float_test.cpp @@ -1,8 +1,10 @@ /* * Exercise chars_format::hex (hexadecimal floating-point numbers). * - * We check hand-written cases, then compare against std::strtod/std::strtof - * (which take the same form, with a "0x" prefix) on random inputs. + * We check hand-written cases, then compare against an exact reference on + * random inputs. We do not use std::strtod as the reference for values: some + * C libraries misround hexadecimal subnormals (glibc 2.35 and 2.39 on Ubuntu, + * the Windows UCRT). We still use it for the number of characters consumed. */ #include #include @@ -37,14 +39,97 @@ template typename bits_of::type to_bits(T x) { return b; } -template T reference_parse(std::string const &s); - -template <> double reference_parse(std::string const &s) { - return std::strtod(s.c_str(), nullptr); +int hex_value(char c) { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; + } + return -1; } -template <> float reference_parse(std::string const &s) { - return std::strtof(s.c_str(), nullptr); +// Exact reference: we expand every digit into bits and round to nearest, ties +// to even, by looking at the bits. The input has no "0x" prefix. +template T reference_parse(std::string const &s) { + constexpr int precision = std::numeric_limits::digits; // 53 or 24 + constexpr int min_exp = std::numeric_limits::min_exponent - 1; // -1022 + constexpr int max_exp = std::numeric_limits::max_exponent - 1; // 1023 + size_t i = 0; + bool negative = false; + if (i < s.size() && (s[i] == '-' || s[i] == '+')) { + negative = (s[i] == '-'); + i++; + } + std::vector bits; // most significant first + long long exponent = 0; // the value is bits * 2^exponent + bool seen_point = false; + for (; i < s.size(); i++) { + if (s[i] == '.' && !seen_point) { + seen_point = true; + continue; + } + int const d = hex_value(s[i]); + if (d < 0) { + break; + } + for (int k = 3; k >= 0; k--) { + bits.push_back((d >> k) & 1); + } + if (seen_point) { + exponent -= 4; + } + } + if (i + 1 < s.size() && (s[i] == 'p' || s[i] == 'P')) { + size_t j = i + 1; + bool neg_exp = false; + if (s[j] == '-' || s[j] == '+') { + neg_exp = (s[j] == '-'); + j++; + } + long long e = 0; + for (; j < s.size() && s[j] >= '0' && s[j] <= '9'; j++) { + if (e < 1000000000) { + e = 10 * e + (s[j] - '0'); + } + } + exponent += neg_exp ? -e : e; + } + T const sign = negative ? T(-1) : T(1); + size_t first = 0; + while (first < bits.size() && bits[first] == 0) { + first++; + } + long long const n = static_cast(bits.size() - first); + if (n == 0) { + return sign * T(0); + } + long long const top = exponent + n - 1; // the value is 1.xxx * 2^top + if (top > max_exp) { + return sign * std::numeric_limits::infinity(); + } + long long keep = precision; // bits kept, fewer when subnormal + if (top < min_exp) { + keep -= min_exp - top; + } + uint64_t kept = 0; + for (long long k = 0; k < keep; k++) { + kept = 2 * kept + uint64_t(k < n ? bits[first + size_t(k)] : 0); + } + int const round_bit = + (keep >= 0 && keep < n) ? bits[first + size_t(keep)] : 0; + bool sticky = false; + for (long long k = (keep + 1 > 0 ? keep + 1 : 0); k < n; k++) { + sticky |= (bits[first + size_t(k)] != 0); + } + if (round_bit && (sticky || (kept & 1))) { + kept++; + } + // Exact, or infinity when rounding carries past the largest value. + return sign * std::ldexp(T(kept), int(top - keep + 1)); } template bool same(T a, T b) { @@ -113,6 +198,11 @@ void check_cases() { std::errc(), hex}, {"1.8p-1075", 4.9406564584124654e-324, 9, std::errc(), hex}, {"1p-99999999999999999999", 0.0, 23, std::errc::result_out_of_range, hex}, + // glibc 2.35 and 2.39 round this subnormal down; the Windows UCRT + // returns 2^-1020 for the second one. + {"682c27c.7e61b22p-1052", 2.263588539952014e-309, 21, std::errc(), hex}, + {"fffffffffffff.fffffp-1074", 2.2250738585072014e-308, 25, std::errc(), + hex}, // Ties to even on normal numbers. {"1.00000000000008p0", 1.0, 18, std::errc(), hex}, {"1.00000000000018p0", 1.0000000000000004, 18, std::errc(), hex}, @@ -319,10 +409,7 @@ std::string random_hex_string(std::mt19937_64 &rng) { template void check_random(std::mt19937_64 &rng, size_t n) { for (size_t i = 0; i < n; i++) { std::string const s = random_hex_string(rng); - std::string prefixed = s; - size_t const sign = (s[0] == '-') ? 1 : 0; - prefixed.insert(sign, "0x"); - T const expected = reference_parse(prefixed); + T const expected = reference_parse(s); T result; auto answer = fast_float::from_chars(s.data(), s.data() + s.size(), result, hex); @@ -348,7 +435,8 @@ template void check_random(std::mt19937_64 &rng, size_t n) { // Put every byte value at every position of a run of digits, so that the // blocks of 8 digits see every kind of non-digit byte, and compare the value -// and the number of characters consumed with strtod. +// and the number of characters consumed with strtod (the value with our +// reference). void check_all_bytes() { std::string const base = "1234567890abcdefABCDEF0123456789"; for (int b = 0; b < 256; b++) { @@ -367,7 +455,7 @@ void check_all_bytes() { fast_float::from_chars(s.data(), s.data() + s.size(), result, hex); std::string prefixed = "0x" + s; char *end = nullptr; - double const expected = std::strtod(prefixed.c_str(), &end); + (void)std::strtod(prefixed.c_str(), &end); size_t const consumed = (end == prefixed.c_str()) ? 0 : size_t(end - prefixed.c_str()) - 2; // strtod reads "0x" as the number 0 when no digit follows. @@ -376,6 +464,8 @@ void check_all_bytes() { if (strtod_parsed_zero || consumed == 0) { ok = (answer.ec == std::errc::invalid_argument); } else { + double const expected = + reference_parse(s.substr(0, consumed)); // An exponent can follow the first digits ("1p345..."). std::errc const ec = (std::isinf(expected) || expected == 0) ? std::errc::result_out_of_range @@ -398,11 +488,13 @@ void check_all_bytes() { // it: 4 * 67108864 = 2^28, so 0.(67108863 zeros)1 is 2^-268435456. void check_long_exponent() { std::string const zeros(67108863, '0'); + struct long_case { std::string input; double expected; std::errc ec; }; + long_case const cases[] = { {"0." + zeros + "1p268435456", 1.0, std::errc()}, {"0." + zeros + "1p268435457", 2.0, std::errc()}, @@ -424,8 +516,8 @@ void check_long_exponent() { !same(result, c.expected)) { std::printf("FAIL: long input ending in %s -> %a (ec %d), expected %a " "(ec %d)\n", - c.input.c_str() + c.input.size() - 16, result, - int(answer.ec), c.expected, int(c.ec)); + c.input.c_str() + c.input.size() - 16, result, int(answer.ec), + c.expected, int(c.ec)); failures++; } } From 5aacb82d24a627ac5384daea98fd8a7c633f1c8d Mon Sep 17 00:00:00 2001 From: Daniel Lemire Date: Sat, 28 Nov 2026 09:26:14 -0500 Subject: [PATCH 3/3] hex_float_test: avoid a false GCC 12 -Wrestrict error on string insert --- tests/hex_float_test.cpp | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/tests/hex_float_test.cpp b/tests/hex_float_test.cpp index d3e5ab3c..30ef5cf3 100644 --- a/tests/hex_float_test.cpp +++ b/tests/hex_float_test.cpp @@ -438,22 +438,24 @@ template void check_random(std::mt19937_64 &rng, size_t n) { // and the number of characters consumed with strtod (the value with our // reference). void check_all_bytes() { - std::string const base = "1234567890abcdefABCDEF0123456789"; + // With the point first, after 3 digits, or absent. (Spelled out: GCC 12 + // warns falsely about std::string::insert in C++20, see GCC bug 105651.) + char const *const bases[] = {".1234567890abcdefABCDEF0123456789", + "123.4567890abcdefABCDEF0123456789", + "1234567890abcdefABCDEF0123456789"}; for (int b = 0; b < 256; b++) { for (size_t k = 0; k < 18; k++) { if (k == 0 && (b == '-' || b == '+')) { continue; // a sign, which strtod does not take after "0x" } - for (size_t point : {size_t(0), size_t(3), size_t(100)}) { - std::string s = base; - if (point < s.size()) { - s.insert(point, "."); - } + for (size_t which = 0; which < 3; which++) { + std::string s = bases[which]; s[k] = char(b); double result = 0; auto answer = fast_float::from_chars(s.data(), s.data() + s.size(), result, hex); - std::string prefixed = "0x" + s; + std::string prefixed = "0x"; + prefixed += s; char *end = nullptr; (void)std::strtod(prefixed.c_str(), &end); size_t const consumed = @@ -475,7 +477,7 @@ void check_all_bytes() { same(result, expected); } if (!ok) { - std::printf("FAIL: byte %d at %zu (point %zu)\n", b, k, point); + std::printf("FAIL: byte %d at %zu in %s\n", b, k, bases[which]); failures++; return; }