From 765bd16183d7c9cddbb93bfe11f3aff4a767fe2a Mon Sep 17 00:00:00 2001 From: Daniel Lemire Date: Mon, 9 Nov 2026 23:03:07 -0500 Subject: [PATCH 1/5] Add performance hints: unpredictable_sign, assume_round_to_nearest, short_numbers --- README.md | 163 +++++++++++++-- benchmarks/CMakeLists.txt | 2 +- benchmarks/benchmark.cpp | 72 ++++++- benchmarks/benchmark_hints.cpp | 41 ++++ benchmarks/benchmark_rtn.cpp | 49 ----- include/fast_float/ascii_number.h | 103 ++++++++- include/fast_float/fast_float.h | 53 +++++ include/fast_float/float_common.h | 114 +++++++++- include/fast_float/parse_number.h | 282 ++++++++++++++++++++++--- tests/CMakeLists.txt | 3 +- tests/example_formatted.cpp | 99 +++++++++ tests/performance_hints_test.cpp | 337 ++++++++++++++++++++++++++++++ tests/rounds_to_nearest_test.cpp | 107 ---------- 13 files changed, 1198 insertions(+), 227 deletions(-) create mode 100644 benchmarks/benchmark_hints.cpp delete mode 100644 benchmarks/benchmark_rtn.cpp create mode 100644 tests/example_formatted.cpp create mode 100644 tests/performance_hints_test.cpp delete mode 100644 tests/rounds_to_nearest_test.cpp diff --git a/README.md b/README.md index b78da99a..7ddab93c 100644 --- a/README.md +++ b/README.md @@ -514,8 +514,136 @@ float: 12345678 * 10^23 = 1.23456782e+30 (==expected) Overloads of `fast_float::integer_times_pow10()` are provided for signed and unsigned integer types up to 64 bits: `int64_t`, `uint64_t`, etc. +### Parsing formatted numbers in one pass -## Assuming the default rounding mode +`fast_float::from_chars()` does not accept formatted numbers such as +`$1,234.56` or `-12.5%`. You could remove the extra characters and then call +`fast_float::from_chars()`, but that takes two passes over the input. Instead, +you can accumulate the digits yourself as you skip the extra characters, and +let `fast_float::integer_times_pow10()` produce the correctly rounded result: + +```C++ +bool parse_formatted(std::string const &s, double &out) { + uint64_t mantissa = 0; + int significant_digits = 0; // leading zeros excluded + int exponent = 0; // minus the number of digits after the point + bool negative = false, seen_dot = false, seen_digit = false, started = false; + for (char c : s) { + if (c >= '0' && c <= '9') { + seen_digit = started = true; + if (mantissa != 0 || c != '0') { + significant_digits++; + } + // overflows beyond 19 significant digits, handled below + mantissa = 10 * mantissa + uint64_t(c - '0'); + exponent -= seen_dot; + } else if (c == ',' || c == '$' || c == '%') { + continue; + } else if (c == '.' && !seen_dot) { + seen_dot = started = true; + } else if (c == '-' && !started) { + negative = started = true; + } else { + return false; + } + } + if (!seen_digit) { + return false; + } + if (significant_digits > 19) { + // Rare: the mantissa does not fit in 64 bits, let from_chars do it. + std::string clean; + for (char c : s) { + if ((c >= '0' && c <= '9') || c == '.' || c == '-') { + clean += c; + } + } + return fast_float::from_chars(clean.data(), clean.data() + clean.size(), + out) + .ec == std::errc(); + } + out = fast_float::integer_times_pow10(mantissa, exponent); + if (negative) { + out = -out; + } + return true; +} +``` + +See [tests/example_formatted.cpp](tests/example_formatted.cpp) for a complete +example. + + +## Performance hints + +You may tell fast_float what to expect, from your input or from your program, +so that it parses faster. Pass one or more `fast_float::performance_hints` as a +template argument; everything else stays the same: + +```C++ +using fast_float::performance_hints; + +double result; +auto answer = fast_float::from_chars( + input.data(), input.data() + input.size(), result); + +// combine them with | +constexpr auto hints = performance_hints::unpredictable_sign | + performance_hints::assume_round_to_nearest; +answer = fast_float::from_chars( + input.data(), input.data() + input.size(), result, + fast_float::chars_format::fixed); + +// from_chars_advanced and integer_times_pow10 take them too +fast_float::parse_options options{fast_float::chars_format::general, ','}; +answer = fast_float::from_chars_advanced( + input.data(), input.data() + input.size(), result, options); +double d = fast_float::integer_times_pow10(int64_t(-123456), -2); +float f = fast_float::integer_times_pow10(uint64_t(123456), -2); +``` + +The hints apply to floating-point types. Use them only when they hold: a wrong +`unpredictable_sign` or `short_numbers` only makes parsing slower, but a wrong +`assume_round_to_nearest` gives wrong results (see below). + +### Signs that are hard to predict + +By default, the parser checks for a sign with a branch. The branch is nearly +free when the processor predicts its outcome: when all numbers are positive, or +when the signs follow a pattern. When positive and negative numbers come in +random order (e.g., gains and losses), the processor mispredicts it often. Then +you may pass `fast_float::performance_hints::unpredictable_sign`: the parser +handles the sign without a branch. + +The results do not change. Do not use it when the signs are predictable, since +parsing is then slower. The JSON and JavaScript formats ignore it. + +### Short numbers of varying shapes + +When you parse short numbers whose shapes vary unpredictably, such as `7`, +`-12.5`, `0.375` and `1042` in random order, the parser mispredicts its +branches on the number of digits and the position of the decimal point. If +most of your numbers have at most 8 characters (sign and decimal point +included) and you pass each number alone (the range `[first, last)` holds just +the number, as when you parse fields already split from a CSV line), you may +pass `fast_float::performance_hints::short_numbers`: such numbers are then +parsed with a few bitwise operations, without branches that depend on their +shape. + +```C++ +double result; +auto answer = fast_float::from_chars( + field.data(), field.data() + field.size(), result); +``` + +The results do not change. Other inputs (longer numbers, exponents, a range +holding more than the number, etc.) are parsed as usual, only a bit more +slowly. Do not use it when the shapes are predictable (e.g., mostly `0`, `1.0` +and `0.75` in a regular pattern): the usual parser is then faster, since the +processor predicts its branches. It only applies to `char` inputs and to the +`float` and `double` types; the JSON and JavaScript formats ignore it. + +### Assuming the default rounding mode The C and C++ languages let a program change the floating-point rounding mode of a thread with `std::fesetround` (e.g., `FE_UPWARD`). fast_float @@ -532,18 +660,18 @@ loop, it can be a noticeable fraction of the time, depending on your compiler and processor. If your program never changes the rounding mode, you can skip the check by -defining the `FASTFLOAT_ROUNDS_TO_NEAREST` macro: +passing `fast_float::performance_hints::assume_round_to_nearest`: ```C++ -#define FASTFLOAT_ROUNDS_TO_NEAREST -#include "fast_float/fast_float.h" +double result; +auto answer = fast_float::from_chars< + fast_float::performance_hints::assume_round_to_nearest>( + input.data(), input.data() + input.size(), result); ``` -It affects `from_chars`, `from_chars_advanced` and `integer_times_pow10`. - -Before you define it, consider the tradeoff: +Before you use it, consider the tradeoff: -* **You make a promise.** With the macro, fast_float trusts that the rounding +* **You make a promise.** With the hint, fast_float trusts that the rounding mode is `FE_TONEAREST`. If some code in your process (yours, or a library you call) sets another mode, the numbers that take the fast path are rounded according to that mode, while the other numbers are still rounded @@ -551,19 +679,15 @@ Before you define it, consider the tradeoff: even consistent with one another. For example, with `FE_UPWARD`, `0.3` becomes `0.30000000000000004` but `0.30000000000000000000001` becomes `0.29999999999999999`: the larger input gives the smaller value. Nothing - crashes and nothing warns you. Without the macro, fast_float is correct in + crashes and nothing warns you. Without the hint, fast_float is correct in every rounding mode. * **It is only a speedup on short inputs.** Long numbers (more than about 15 significant digits, or large exponents) never take the fast path, so they gain nothing. -* **Define it the same way everywhere.** The macro changes inline functions, - so every translation unit that includes fast_float should see the same - definition. The simplest is to set it for the whole build - (`-DFASTFLOAT_ROUNDS_TO_NEAREST`, or - `target_compile_definitions(myapp PRIVATE FASTFLOAT_ROUNDS_TO_NEAREST)` in - CMake) rather than in a source file. +* **It applies call by call.** Only the calls with the hint skip the check: + the other calls in your program keep it. -If in doubt, leave the macro undefined: the default is always correct. +If in doubt, leave the hint out: the default is always correct. ## Users and Related Work @@ -710,9 +834,10 @@ cmake --build build Importantly, by default, the benchmark is built in Release mode. -The lines marked `assume nearest` time the same code compiled with -`FASTFLOAT_ROUNDS_TO_NEAREST` (see [Assuming the default rounding -mode](#assuming-the-default-rounding-mode)). +The lines marked `assume nearest` and `unpredictable sign` time the same code +with the performance hints `fast_float::performance_hints::assume_round_to_nearest` +and `fast_float::performance_hints::unpredictable_sign` (see [Performance +hints](#performance-hints)). The instructions are similar under Windows. diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index 79b403d6..5df12aee 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -8,7 +8,7 @@ FetchContent_Declare( FetchContent_MakeAvailable(counters) -add_executable(realbenchmark benchmark.cpp benchmark_rtn.cpp) +add_executable(realbenchmark benchmark.cpp benchmark_hints.cpp) target_link_libraries(realbenchmark PRIVATE counters::counters) add_executable(bench_ip bench_ip.cpp) add_executable(bench_uint16 bench_uint16.cpp) diff --git a/benchmarks/benchmark.cpp b/benchmarks/benchmark.cpp index 04afb9d1..bba2b2d2 100644 --- a/benchmarks/benchmark.cpp +++ b/benchmarks/benchmark.cpp @@ -50,11 +50,17 @@ double findmax_fastfloat32(std::vector> &s) { return answer; } -// Defined in benchmark_rtn.cpp, with FASTFLOAT_ROUNDS_TO_NEAREST. -template -double findmax_fastfloat64_rtn(std::vector> &s); -template -double findmax_fastfloat32_rtn(std::vector> &s); +// Defined in benchmark_hints.cpp: the same loops, with performance hints. They +// are in their own translation unit: with them, this file would hold many more +// instantiations of the parser, and GCC would stop inlining it into the loops +// above. +template +double findmax_fastfloat_hints(std::vector> &s); + +constexpr fast_float::performance_hints unpredictable_sign = + fast_float::performance_hints::unpredictable_sign; +constexpr fast_float::performance_hints assume_nearest = + fast_float::performance_hints::assume_round_to_nearest; counters::event_collector collector{}; @@ -199,12 +205,21 @@ void process(std::vector &lines, size_t volume) { std::cout << "ASCII volume = " << volumeMB << " MB " << std::endl; pretty_print(volume, lines.size(), "fastfloat (64)", time_it_ns(lines, findmax_fastfloat64, repeat)); + pretty_print( + volume, lines.size(), "fastfloat (64, unpredictable sign)", + time_it_ns(lines, + findmax_fastfloat_hints, + repeat)); pretty_print(volume, lines.size(), "fastfloat (64, assume nearest)", - time_it_ns(lines, findmax_fastfloat64_rtn, repeat)); + time_it_ns(lines, + findmax_fastfloat_hints, + repeat)); pretty_print(volume, lines.size(), "fastfloat (32)", time_it_ns(lines, findmax_fastfloat32, repeat)); pretty_print(volume, lines.size(), "fastfloat (32, assume nearest)", - time_it_ns(lines, findmax_fastfloat32_rtn, repeat)); + time_it_ns(lines, + findmax_fastfloat_hints, + repeat)); std::vector lines16 = widen(lines); volume = 2 * volume; @@ -212,12 +227,23 @@ void process(std::vector &lines, size_t volume) { std::cout << "UTF-16 volume = " << volumeMB << " MB " << std::endl; pretty_print(volume, lines.size(), "fastfloat (64)", time_it_ns(lines16, findmax_fastfloat64, repeat)); - pretty_print(volume, lines.size(), "fastfloat (64, assume nearest)", - time_it_ns(lines16, findmax_fastfloat64_rtn, repeat)); + pretty_print( + volume, lines.size(), "fastfloat (64, unpredictable sign)", + time_it_ns(lines16, + findmax_fastfloat_hints, + repeat)); + pretty_print( + volume, lines.size(), "fastfloat (64, assume nearest)", + time_it_ns(lines16, + findmax_fastfloat_hints, + repeat)); pretty_print(volume, lines.size(), "fastfloat (32)", time_it_ns(lines16, findmax_fastfloat32, repeat)); - pretty_print(volume, lines.size(), "fastfloat (32, assume nearest)", - time_it_ns(lines16, findmax_fastfloat32_rtn, repeat)); + pretty_print( + volume, lines.size(), "fastfloat (32, assume nearest)", + time_it_ns(lines16, + findmax_fastfloat_hints, + repeat)); } void fileload(std::string filename) { @@ -241,6 +267,29 @@ void fileload(std::string filename) { process(lines, volume); } +// Prices with two decimals and a random sign, e.g., "-731271.51", as in a +// column of gains and losses. The sign is unpredictable, unlike in canada.txt +// (where it alternates) or mesh.txt (where there is none). Inspired by +// https://simonwillison.net/2026/Nov/8/sqlite-parse-number-c-vs-rust/ +void process_prices(size_t count) { + std::mt19937_64 gen(1234); // fixed seed: the same data on every run + std::uniform_real_distribution dis(-1e6, 1e6); + std::vector lines; + lines.reserve(count); + size_t volume = 0; + char buffer[64]; + for (size_t i = 0; i < count; i++) { + int len = std::snprintf(buffer, sizeof(buffer), "%.2f", dis(gen)); + lines.emplace_back(buffer, size_t(len)); + volume += size_t(len); + } + std::cout << "#### " << std::endl; + std::cout << "# " << count << " prices (random sign, two decimals)" + << std::endl; + std::cout << "#### " << std::endl; + process(lines, volume); +} + int main(int argc, char **argv) { if (collector.has_events()) { std::cout << "# Using hardware counters" << std::endl; @@ -257,5 +306,6 @@ int main(int argc, char **argv) { } fileload(std::string(BENCHMARK_DATA_DIR) + "/canada.txt"); fileload(std::string(BENCHMARK_DATA_DIR) + "/mesh.txt"); + process_prices(100000); return EXIT_SUCCESS; } diff --git a/benchmarks/benchmark_hints.cpp b/benchmarks/benchmark_hints.cpp new file mode 100644 index 00000000..dffe630c --- /dev/null +++ b/benchmarks/benchmark_hints.cpp @@ -0,0 +1,41 @@ +// The parsing loops of benchmark.cpp, with performance hints (see +// findmax_fastfloat_hints in benchmark.cpp). +#include +#include +#include + +#include "fast_float/fast_float.h" + +// With performance hints. +template +double findmax_fastfloat_hints(std::vector> &s) { + T answer = 0; + T x = 0; + for (auto &st : s) { + auto [p, ec] = + fast_float::from_chars(st.data(), st.data() + st.size(), x); + if (p == st.data()) { + throw std::runtime_error("bug in findmax_fastfloat_hints"); + } + answer = answer > x ? answer : x; + } + return answer; +} + +constexpr fast_float::performance_hints unpredictable_sign = + fast_float::performance_hints::unpredictable_sign; +constexpr fast_float::performance_hints assume_nearest = + fast_float::performance_hints::assume_round_to_nearest; + +template double findmax_fastfloat_hints( + std::vector &); +template double findmax_fastfloat_hints( + std::vector &); +template double findmax_fastfloat_hints( + std::vector &); +template double findmax_fastfloat_hints( + std::vector &); +template double findmax_fastfloat_hints( + std::vector &); +template double findmax_fastfloat_hints( + std::vector &); diff --git a/benchmarks/benchmark_rtn.cpp b/benchmarks/benchmark_rtn.cpp deleted file mode 100644 index 18921612..00000000 --- a/benchmarks/benchmark_rtn.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// The same parsing loops as findmax_fastfloat64 and findmax_fastfloat32 in -// benchmark.cpp, but compiled with FASTFLOAT_ROUNDS_TO_NEAREST: fast_float -// assumes the default rounding mode and skips its check before the fast path. -// -// We rename the fast_float namespace in this file. Otherwise, the two -// configurations would define the same inline functions differently, and the -// linker could keep either one (an ODR violation). -#include -#include -#include - -#define FASTFLOAT_ROUNDS_TO_NEAREST -#define fast_float fast_float_rtn -#include "fast_float/fast_float.h" - -template -double findmax_fastfloat64_rtn(std::vector> &s) { - double answer = 0; - double x = 0; - for (auto &st : s) { - auto [p, ec] = fast_float::from_chars(st.data(), st.data() + st.size(), x); - if (p == st.data()) { - throw std::runtime_error("bug in findmax_fastfloat_rtn"); - } - answer = answer > x ? answer : x; - } - return answer; -} - -template -double findmax_fastfloat32_rtn(std::vector> &s) { - float answer = 0; - float x = 0; - for (auto &st : s) { - auto [p, ec] = fast_float::from_chars(st.data(), st.data() + st.size(), x); - if (p == st.data()) { - throw std::runtime_error("bug in findmax_fastfloat_rtn"); - } - answer = answer > x ? answer : x; - } - return answer; -} - -template double findmax_fastfloat64_rtn(std::vector &); -template double findmax_fastfloat32_rtn(std::vector &); -template double -findmax_fastfloat64_rtn(std::vector &); -template double -findmax_fastfloat32_rtn(std::vector &); diff --git a/include/fast_float/ascii_number.h b/include/fast_float/ascii_number.h index 80b08cfa..594c6ef5 100644 --- a/include/fast_float/ascii_number.h +++ b/include/fast_float/ascii_number.h @@ -352,6 +352,81 @@ report_parse_error(UC const *p, parse_error error) { return answer; } +// Parses short inputs such as "-12.5" or "731" in a few bitwise operations, +// without any branch that depends on the content: the sign, the position of +// the decimal point and the number of digits are often unpredictable. The input +// [p, pend) must have between 1 and 8 characters. It must be made only of +// digits, with at most one decimal point and an optional leading sign, and have +// at least one digit; otherwise we return false and the caller falls back to +// the general parser (which handles exponents, errors, infinity, etc.). +template +fastfloat_really_inline bool +parse_short_number(UC const *p, UC const *pend, UC decimal_point, + bool allow_plus, uint64_t &mantissa, int64_t &exponent, + bool &negative) noexcept { + if (!std::is_same::value) { + return false; + } + uint64_t const ones = 0x0101010101010101; + uint64_t const high = 0x8080808080808080; + uint32_t const n = uint32_t(pend - p); // in [1, 8] + // We load the n characters in w (first character in the least significant + // byte), padded with zeros, using at most three loads and no loop. + uint64_t w; + if (n >= 4) { + uint32_t lo, hi; + ::memcpy(&lo, p, 4); + ::memcpy(&hi, pend - 4, 4); // overlaps lo when n < 8 +#if FASTFLOAT_IS_BIG_ENDIAN == 1 + lo = byteswap_32(lo); + hi = byteswap_32(hi); +#endif + w = uint64_t(lo) | (uint64_t(hi) << (8 * (n - 4))); + } else { + w = uint64_t(uint8_t(p[0])) | + (uint64_t(uint8_t(p[n / 2])) << (8 * (n / 2))) | + (uint64_t(uint8_t(p[n - 1])) << (8 * (n - 1))); + } + // Per byte, the high bit tells us whether it is one of our n characters. + uint64_t const in_range = (~uint64_t(0) >> (64 - 8 * n)) & high; + // Setting the high bit of each byte prevents borrows between bytes. + uint64_t const x = w | high; + uint64_t const digits = + ((x - 0x30 * ones) & ~(x - 0x3a * ones) & high) & in_range; + uint64_t const z = w ^ (uint64_t(uint8_t(decimal_point)) * ones); + uint64_t const dot = ~(((z & ~high) + ~high) | z) & high & in_range; + uint8_t const first = uint8_t(w); + bool const has_sign = + (first == uint8_t('-')) || (allow_plus && first == uint8_t('+')); + // the high bit of the last decimal point (or 0 if there is none) + int const lz = leading_zeroes(dot | 1); + int const last_dot_bit = 63 - lz; + // We need at least one digit, at most one decimal point (once the last + // one is shifted to the top bit, no other remains), and nothing else. + if (((digits | dot | (uint64_t(has_sign) << 7)) ^ in_range) | + ((dot << lz) & 0x7fffffffffffffff) | uint64_t(digits == 0)) { + return false; + } + negative = (first == uint8_t('-')); + // We remove the decimal point: the bytes after it move down by one. + uint64_t const before_dot = (dot >> 7) - 1; // all ones if there is no dot + uint64_t c = (w & before_dot) | ((w >> 8) & ~before_dot); + // The sign becomes a leading zero. + c ^= uint64_t(has_sign) * (first ^ uint8_t('0')); + uint32_t const length = n - uint32_t(dot != 0); // in [1, 8] + // The digit values, right-aligned so that the missing leading digits are + // zeros: the bytes after the last digit are shifted out. + uint64_t d = (c ^ 0x3030303030303030) << (8 * (8 - length)); + // as in parse_eight_digits_unrolled, after the subtraction of '0' + d = (d * 10) + (d >> 8); + mantissa = (((d & 0x000000FF000000FF) * (100 + (1000000ULL << 32))) + + (((d >> 16) & 0x000000FF000000FF) * (1 + (10000ULL << 32)))) >> + 32; + // minus the number of digits after the decimal point + exponent = (dot != 0) ? -int64_t(n - 1 - uint32_t(last_dot_bit) / 8) : 0; + return true; +} + // Assuming that you use no more than 19 digits, this will // parse an ASCII string. // @@ -361,7 +436,12 @@ report_parse_error(UC const *p, parse_error error) { // spans (read only by the rare digit_comp slow path) are not materialized, // which keeps the fat parsed_number_string_t off the hot path. The caller // re-parses with store_spans=true if the slow path is actually reached. -template +// +// branchless_sign is set with performance_hints::unpredictable_sign. It is a +// template parameter so that the sign skip is chosen at compile time: given an +// ordinary if, GCC turns the skip back into a branch on the sign. +template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t parse_number_string_impl(UC const *p, UC const *pend, parse_options_t options, @@ -375,8 +455,20 @@ parse_number_string_impl(UC const *p, UC const *pend, // assume p < pend, so dereference without checks; answer.negative = (*p == UC('-')); // C++17 20.19.3.(7.1) explicitly forbids '+' sign here - if ((*p == UC('-')) || (uint64_t(fmt & chars_format::allow_leading_plus) && - !basic_json_fmt && *p == UC('+'))) { + bool const has_sign = + (*p == UC('-')) || (uint64_t(fmt & chars_format::allow_leading_plus) && + !basic_json_fmt && *p == UC('+')); + FASTFLOAT_IF_CONSTEXPR17(branchless_sign && !basic_json_fmt && + !basic_javascript_fmt) { + uint64_t const c = + uint64_t(static_cast::type>(*p)); + uint64_t skip = (((c ^ uint64_t('-')) - 1) >> 63); + if (uint64_t(fmt & chars_format::allow_leading_plus)) { + skip |= (((c ^ uint64_t('+')) - 1) >> 63); + } + p += skip; + } + else if (has_sign) { ++p; if (p == pend) { return report_parse_error( @@ -500,6 +592,11 @@ parse_number_string_impl(UC const *p, UC const *pend, } } else if (digit_count == 0) { // we must have encountered at least one integer! + // Without a digit or a dot after the sign, we report the sign. + if (has_sign && !has_decimal_point) { + return report_parse_error( + start_digits, parse_error::missing_integer_or_dot_after_sign); + } return report_parse_error(p, parse_error::no_digits_in_mantissa); } int64_t exp_number = 0; // explicit exponential part diff --git a/include/fast_float/fast_float.h b/include/fast_float/fast_float.h index 47998ded..3b0fe230 100644 --- a/include/fast_float/fast_float.h +++ b/include/fast_float/fast_float.h @@ -38,6 +38,19 @@ FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars(UC const *first, UC const *last, T &value, chars_format fmt = chars_format::general) noexcept; +/** + * Like from_chars, with performance hints (see `fast_float::performance_hints`) + * as a template argument: + * + * fast_float::from_chars( + * first, last, value); + */ +template ::value)> +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t +from_chars(UC const *first, UC const *last, T &value, + chars_format fmt = chars_format::general) noexcept; + /** * Like from_chars, but accepts an `options` argument to govern number parsing. * Both for floating-point types and integer types. @@ -47,6 +60,17 @@ FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars_advanced(UC const *first, UC const *last, T &value, parse_options_t options) noexcept; +/** + * Like from_chars_advanced, with performance hints (see + * `fast_float::performance_hints`) as a template argument. For floating-point + * types only. + */ +template ::value)> +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t +from_chars_advanced(UC const *first, UC const *last, T &value, + parse_options_t options) noexcept; + /** * This function multiplies an integer number by a power of 10 and returns * the result as a double precision floating-point value that is correctly @@ -79,6 +103,35 @@ FASTFLOAT_CONSTEXPR20 typename std::enable_if::value, T>::type integer_times_pow10(int64_t mantissa, int decimal_exponent) noexcept; +/** + * integer_times_pow10 with performance hints (see + * `fast_float::performance_hints`) as a template argument, for any integer + * type up to 64 bits. This one returns a value of type `T`: + * + * fast_float::integer_times_pow10(m, e); + */ +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 + typename std::enable_if::value && + std::is_integral::value && + sizeof(Int) <= sizeof(uint64_t), + T>::type + integer_times_pow10(Int mantissa, int decimal_exponent) noexcept; + +/** + * Same, returning a double: + * + * fast_float::integer_times_pow10< + * fast_float::performance_hints::assume_round_to_nearest>(m, e); + */ +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 + typename std::enable_if::value && + sizeof(Int) <= sizeof(uint64_t), + double>::type + integer_times_pow10(Int mantissa, int decimal_exponent) noexcept; + /** * from_chars for integer types. */ diff --git a/include/fast_float/float_common.h b/include/fast_float/float_common.h index ad93836f..389d1dd2 100644 --- a/include/fast_float/float_common.h +++ b/include/fast_float/float_common.h @@ -76,6 +76,35 @@ enum class chars_format : uint64_t { scientific | no_infnan, }; +// Performance hints, passed as a template argument, e.g., +// fast_float::from_chars( +// first, last, value); +// They tell the parser what to expect from the input, or from the program, so +// that it can parse faster. Combine them with |. +enum class performance_hints : uint64_t { + none = 0, + // The sign is hard to predict (e.g., gains and losses), so it is handled + // without a branch. The results do not change. Without the hint, + // predictable signs (e.g., all positive) are parsed faster. The JSON and + // JavaScript formats ignore it. + unpredictable_sign = 1 << 0, + // The floating-point rounding mode is always the default (round to + // nearest), so it is not checked. The results are wrong if the program + // parses while another rounding mode is set (see fesetround). + assume_round_to_nearest = 1 << 1, + // The numbers are short, at most 8 characters (sign and decimal point + // included), such as 12.5 or -3.75, and their shapes vary unpredictably + // (length, position of the decimal point). Each number must be given alone: + // the range [first, last) holds just the number. Such numbers are then + // parsed with a few bitwise operations, without branches that depend on + // their shape. Do not use it when the numbers have predictable shapes (e.g., + // mostly 0, 1.0 and 0.75 in a regular pattern): the usual parser is then + // faster. Other inputs are parsed as usual, only a bit more slowly. The + // results do not change. Only for char inputs and the float and double + // types; the JSON and JavaScript formats ignore it. + short_numbers = 1 << 2, +}; + template struct from_chars_result_t { UC const *ptr; std::errc ec; @@ -634,6 +663,10 @@ template struct binary_format : binary_format_lookup_tables { static constexpr int largest_power_of_ten(); static constexpr int smallest_power_of_ten(); static constexpr T exact_power_of_ten(int64_t power); + // Returns -10^power if negative is true, and 10^power otherwise, for + // 0 <= power <= max_exponent_fast_path(). Selecting the sign by indexing + // avoids a branch on the sign, which is often unpredictable. + static constexpr T signed_exact_power_of_ten(int64_t power, bool negative); static constexpr size_t max_digits(); static constexpr equiv_uint exponent_mask(); static constexpr equiv_uint mantissa_mask(); @@ -641,9 +674,14 @@ template struct binary_format : binary_format_lookup_tables { }; template struct binary_format_lookup_tables { + // The exact powers of ten, then their negations (see + // signed_exact_power_of_ten). static constexpr double powers_of_ten[] = { - 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, - 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22}; + 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, + 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, + 1e20, 1e21, 1e22, -1e0, -1e1, -1e2, -1e3, -1e4, -1e5, -1e6, + -1e7, -1e8, -1e9, -1e10, -1e11, -1e12, -1e13, -1e14, -1e15, -1e16, + -1e17, -1e18, -1e19, -1e20, -1e21, -1e22}; // Largest integer value v so that (5**index * v) <= 1<<53. // 0x20000000000000 == 1 << 53 @@ -692,8 +730,10 @@ constexpr uint64_t binary_format_lookup_tables::max_mantissa[]; #endif template struct binary_format_lookup_tables { - static constexpr float powers_of_ten[] = {1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, - 1e6f, 1e7f, 1e8f, 1e9f, 1e10f}; + static constexpr float powers_of_ten[] = { + 1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f, 1e7f, + 1e8f, 1e9f, 1e10f, -1e0f, -1e1f, -1e2f, -1e3f, -1e4f, + -1e5f, -1e6f, -1e7f, -1e8f, -1e9f, -1e10f}; // Largest integer value v so that (5**index * v) <= 1<<24. // 0x1000000 == 1<<24 @@ -817,8 +857,9 @@ inline constexpr uint64_t binary_format::max_mantissa_fast_path() { // credit: Jakub Jelínek #ifdef __STDCPP_FLOAT16_T__ template struct binary_format_lookup_tables { - static constexpr std::float16_t powers_of_ten[] = {1e0f16, 1e1f16, 1e2f16, - 1e3f16, 1e4f16}; + static constexpr std::float16_t powers_of_ten[] = { + 1e0f16, 1e1f16, 1e2f16, 1e3f16, 1e4f16, + -1e0f16, -1e1f16, -1e2f16, -1e3f16, -1e4f16}; // Largest integer value v so that (5**index * v) <= 1<<11. // 0x800 == 1<<11 @@ -872,6 +913,15 @@ inline constexpr int binary_format::max_exponent_fast_path() { return 4; } +template <> +inline constexpr std::float16_t +binary_format::signed_exact_power_of_ten(int64_t power, + bool negative) { + // Work around clang bug https://godbolt.org/z/zedh7rrhc + return static_cast(powers_of_ten[0]), + powers_of_ten[power + (negative ? max_exponent_fast_path() + 1 : 0)]; +} + template <> inline constexpr int binary_format::mantissa_explicit_bits() { return 10; @@ -948,8 +998,9 @@ inline constexpr size_t binary_format::max_digits() { // credit: Jakub Jelínek #ifdef __STDCPP_BFLOAT16_T__ template struct binary_format_lookup_tables { - static constexpr std::bfloat16_t powers_of_ten[] = {1e0bf16, 1e1bf16, 1e2bf16, - 1e3bf16}; + static constexpr std::bfloat16_t powers_of_ten[] = { + 1e0bf16, 1e1bf16, 1e2bf16, 1e3bf16, + -1e0bf16, -1e1bf16, -1e2bf16, -1e3bf16}; // Largest integer value v so that (5**index * v) <= 1<<8. // 0x100 == 1<<8 @@ -982,6 +1033,15 @@ inline constexpr int binary_format::max_exponent_fast_path() { return 3; } +template <> +inline constexpr std::bfloat16_t +binary_format::signed_exact_power_of_ten(int64_t power, + bool negative) { + // Work around clang bug https://godbolt.org/z/zedh7rrhc + return static_cast(powers_of_ten[0]), + powers_of_ten[power + (negative ? max_exponent_fast_path() + 1 : 0)]; +} + template <> inline constexpr binary_format::equiv_uint binary_format::exponent_mask() { @@ -1116,12 +1176,28 @@ binary_format::exact_power_of_ten(int64_t power) { return static_cast(powers_of_ten[0]), powers_of_ten[power]; } +template <> +inline constexpr double +binary_format::signed_exact_power_of_ten(int64_t power, bool negative) { + // Work around clang bug https://godbolt.org/z/zedh7rrhc + return static_cast(powers_of_ten[0]), + powers_of_ten[power + (negative ? max_exponent_fast_path() + 1 : 0)]; +} + template <> inline constexpr float binary_format::exact_power_of_ten(int64_t power) { // Work around clang bug https://godbolt.org/z/zedh7rrhc return static_cast(powers_of_ten[0]), powers_of_ten[power]; } +template <> +inline constexpr float +binary_format::signed_exact_power_of_ten(int64_t power, bool negative) { + // Work around clang bug https://godbolt.org/z/zedh7rrhc + return static_cast(powers_of_ten[0]), + powers_of_ten[power + (negative ? max_exponent_fast_path() + 1 : 0)]; +} + template <> inline constexpr int binary_format::largest_power_of_ten() { return 308; } @@ -1437,6 +1513,28 @@ operator|=(chars_format &lhs, chars_format rhs) noexcept { return lhs = (lhs | rhs); } +constexpr performance_hints operator&(performance_hints lhs, + performance_hints rhs) noexcept { + using int_type = std::underlying_type::type; + return static_cast(static_cast(lhs) & + static_cast(rhs)); +} + +constexpr performance_hints operator|(performance_hints lhs, + performance_hints rhs) noexcept { + using int_type = std::underlying_type::type; + return static_cast(static_cast(lhs) | + static_cast(rhs)); +} + +namespace detail { +// Whether hints include hint. +constexpr bool has_hint(performance_hints hints, + performance_hints hint) noexcept { + return uint64_t(hints & hint) != 0; +} +} // namespace detail + fastfloat_really_inline FASTFLOAT_CONSTEXPR14 chars_format & operator^=(chars_format &lhs, chars_format rhs) noexcept { return lhs = (lhs ^ rhs); diff --git a/include/fast_float/parse_number.h b/include/fast_float/parse_number.h index 5ae2871a..f23f1a69 100644 --- a/include/fast_float/parse_number.h +++ b/include/fast_float/parse_number.h @@ -75,19 +75,21 @@ from_chars_result_t * It is the default on most system. This function is meant to be inexpensive. * Credit : @mwalcott3 * - * If FASTFLOAT_ROUNDS_TO_NEAREST is defined, we trust the user that the - * rounding mode is always 'nearest' and we skip the check (see README). + * With assume_nearest (performance_hints::assume_round_to_nearest), we trust + * the user that the rounding mode is always 'nearest' and we skip the check. */ +template fastfloat_really_inline bool rounds_to_nearest() noexcept { // https://lemire.me/blog/2020/06/26/gcc-not-nearest/ #if (FLT_EVAL_METHOD != 1) && (FLT_EVAL_METHOD != 0) // The arithmetic may be carried out with excess precision (e.g., x87): - // Clinger's fast path could then round twice. FASTFLOAT_ROUNDS_TO_NEAREST - // does not change this. + // Clinger's fast path could then round twice. assume_nearest does not + // change this. return false; -#elif defined(FASTFLOAT_ROUNDS_TO_NEAREST) - return true; #else + if (assume_nearest) { + return true; + } // See // A fast function to check your floating-point rounding mode // https://lemire.me/blog/2022/11/16/a-fast-function-to-check-your-floating-point-rounding-mode/ @@ -141,11 +143,18 @@ fastfloat_really_inline bool rounds_to_nearest() noexcept { #elif defined(__GNUC__) #pragma GCC diagnostic pop #endif -#endif // FASTFLOAT_ROUNDS_TO_NEAREST +#endif } } // namespace detail +// Hints holds the performance hints (see performance_hints). +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t +from_chars_float_advanced(UC const *first, UC const *last, T &value, + parse_options_t options) noexcept; + template struct from_chars_caller { template fastfloat_clang_really_inline @@ -154,6 +163,17 @@ template struct from_chars_caller { parse_options_t options) noexcept { return from_chars_advanced(first, last, value, options); } + + // Like call, for floating-point types, with performance hints. As with + // call, GCC inlines it on its own, folding the format when it is a + // constant. + template + fastfloat_clang_really_inline + FASTFLOAT_CONSTEXPR20 static from_chars_result_t + call_hinted(UC const *first, UC const *last, T &value, + parse_options_t options) noexcept { + return from_chars_float_advanced(first, last, value, options); + } }; #ifdef __STDCPP_FLOAT32_T__ @@ -173,6 +193,20 @@ template <> struct from_chars_caller { } return ret; } + + template + FASTFLOAT_CONSTEXPR20 static from_chars_result_t + call_hinted(UC const *first, UC const *last, std::float32_t &value, + parse_options_t options) noexcept { + float val = 0.0f; + auto ret = + from_chars_float_advanced(first, last, val, options); + // If no characters match the pattern, value must be left unmodified. + if (ret.ec != std::errc::invalid_argument) { + value = val; + } + return ret; + } }; #endif @@ -193,6 +227,20 @@ template <> struct from_chars_caller { } return ret; } + + template + FASTFLOAT_CONSTEXPR20 static from_chars_result_t + call_hinted(UC const *first, UC const *last, std::float64_t &value, + parse_options_t options) noexcept { + double val = 0.0; + auto ret = + from_chars_float_advanced(first, last, val, options); + // If no characters match the pattern, value must be left unmodified. + if (ret.ec != std::errc::invalid_argument) { + value = val; + } + return ret; + } }; #endif @@ -207,6 +255,15 @@ from_chars_fixed_format(UC const *first, UC const *last, T &value) noexcept { return from_chars_caller::call(first, last, value, parse_options_t(Fmt)); } + +// Same, with performance hints. +template +FASTFLOAT_CONSTEXPR20 from_chars_result_t +from_chars_fixed_format_hinted(UC const *first, UC const *last, + T &value) noexcept { + return from_chars_caller::template call_hinted( + first, last, value, parse_options_t(Fmt)); +} #endif template @@ -223,7 +280,8 @@ from_chars(UC const *first, UC const *last, T &value, parse_options_t(fmt)); } -template +// Hints holds the performance hints (see performance_hints). +template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool clinger_fast_path_impl(uint64_t mantissa, int64_t exponent, bool is_negative, T &value) noexcept { @@ -248,9 +306,34 @@ clinger_fast_path_impl(uint64_t mantissa, int64_t exponent, bool is_negative, // We could check it first (before the previous branch), but // there might be performance advantages at having the check // be last. - if (!cpp20_and_in_constexpr() && detail::rounds_to_nearest()) { + constexpr bool assume_nearest = + detail::has_hint(Hints, performance_hints::assume_round_to_nearest); + if (!cpp20_and_in_constexpr() && + detail::rounds_to_nearest()) { // We have that fegetround() == FE_TONEAREST. // Next is Clinger's fast path. + FASTFLOAT_IF_CONSTEXPR17( + detail::has_hint(Hints, performance_hints::unpredictable_sign)) { + // The sign comes with the power of ten: (-10^k) * m and m / (-10^k) + // are exactly -(10^k * m) and -(m / 10^k), including -0 when m = 0. + // Thus no branch on the sign. + value = T(mantissa); + if (exponent < 0) { + value = value / binary_format::signed_exact_power_of_ten( + -exponent, is_negative); + } else { + value = value * binary_format::signed_exact_power_of_ten( + exponent, is_negative); + // Only std::float16_t can overflow here (e.g., "656e2"); let the + // slow path report result_out_of_range. + if (binary_format::fast_path_can_overflow() && + (value > (std::numeric_limits::max)() || + value < std::numeric_limits::lowest())) { + return false; + } + } + return true; + } value = T(mantissa); if (exponent < 0) { value = value / binary_format::exact_power_of_ten(-exponent); @@ -291,6 +374,86 @@ clinger_fast_path_impl(uint64_t mantissa, int64_t exponent, bool is_negative, return false; } +namespace detail { +// performance_hints::short_numbers. Returns false if the input does not fit. +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool +from_chars_short(UC const *first, UC const *last, T &value, chars_format fmt, + UC decimal_point, from_chars_result_t &answer) noexcept { + if (!(std::is_same::value || std::is_same::value) || + !std::is_same::value || cpp20_and_in_constexpr()) { + return false; + } + fmt = adjust_for_feature_macros(fmt); + // JSON and JavaScript have stricter rules (e.g., no "01" or "5."). + if (!uint64_t(fmt & chars_format::fixed) || + uint64_t(fmt & (basic_json_fmt | basic_javascript_fmt)) || + (last - first) > 8 || first == last) { + return false; + } + uint64_t mantissa; + int64_t exponent; + bool negative; + if (!parse_short_number(first, last, decimal_point, + uint64_t(fmt & chars_format::allow_leading_plus) != 0, + mantissa, exponent, negative) || + !clinger_fast_path_impl(mantissa, exponent, negative, value)) { + return false; + } + answer.ec = std::errc(); + answer.ptr = last; + return true; +} + +template +FASTFLOAT_CONSTEXPR20 from_chars_result_t +from_chars_hinted(UC const *first, UC const *last, T &value, + chars_format fmt) noexcept { +#ifdef __clang__ + if (fmt == chars_format::general) { + return from_chars_fixed_format_hinted( + first, last, value); + } +#endif + return from_chars_caller::template call_hinted( + first, last, value, parse_options_t(fmt)); +} +} // namespace detail + +// With performance hints. Only the short path (short_numbers) is inlined in +// the caller; the rest is the usual parser. +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t +from_chars(UC const *first, UC const *last, T &value, + chars_format fmt /*= chars_format::general*/) noexcept { + FASTFLOAT_IF_CONSTEXPR17( + detail::has_hint(Hints, performance_hints::short_numbers)) { + from_chars_result_t answer; + if (detail::from_chars_short(first, last, value, fmt, UC('.'), + answer)) { + return answer; + } + } + return detail::from_chars_hinted(first, last, value, fmt); +} + +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t +from_chars_advanced(UC const *first, UC const *last, T &value, + parse_options_t options) noexcept { + FASTFLOAT_IF_CONSTEXPR17( + detail::has_hint(Hints, performance_hints::short_numbers)) { + from_chars_result_t answer; + if (detail::from_chars_short(first, last, value, + options.format, + options.decimal_point, answer)) { + return answer; + } + } + return from_chars_caller::template call_hinted(first, last, value, + options); +} + /** * This function overload takes parsed_number_string_t structure that is created * and populated either by from_chars_advanced function taking chars range and @@ -667,7 +830,7 @@ from_chars_float_hex(UC const *first, UC const *last, T &value, return answer; } -template +template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars_float_advanced(UC const *first, UC const *last, T &value, parse_options_t options) noexcept { @@ -717,11 +880,13 @@ from_chars_float_advanced(UC const *first, UC const *last, T &value, // only by the rare slow paths). Skipping their stores keeps the fat // parsed_number_string_t off the hot path. store_spans is a runtime argument, // so this reuses the single parse_number_string_impl instantiation. + constexpr bool branchless_sign = + detail::has_hint(Hints, performance_hints::unpredictable_sign); parsed_number_string_t pns = bjf ? parse_number_string_impl(first, last, options, false) - : parse_number_string_impl(first, last, options, - false); + : parse_number_string_impl( + first, last, options, false); if (!pns.valid) { if (uint64_t(fmt & chars_format::no_infnan)) { answer.ec = std::errc::invalid_argument; @@ -752,7 +917,8 @@ from_chars_float_advanced(UC const *first, UC const *last, T &value, answer.ec = std::errc(); // be optimistic answer.ptr = pns.lastmatch; - if (clinger_fast_path_impl(pns.mantissa, pns.exponent, pns.negative, value)) { + if (clinger_fast_path_impl(pns.mantissa, pns.exponent, pns.negative, + value)) { return answer; } @@ -795,22 +961,36 @@ from_chars(UC const *first, UC const *last, T &value, int base) noexcept { return from_chars_advanced(first, last, value, options); } +namespace detail { +// The part of integer_times_pow10 that does not fit Clinger's fast path. template -FASTFLOAT_CONSTEXPR20 - typename std::enable_if::value, T>::type - integer_times_pow10(uint64_t mantissa, int decimal_exponent) noexcept { +FASTFLOAT_CONSTEXPR20 T integer_times_pow10_slow(uint64_t mantissa, + int decimal_exponent, + bool is_negative) noexcept { T value; - if (clinger_fast_path_impl(mantissa, decimal_exponent, false, value)) - return value; - adjusted_mantissa am = compute_float>(decimal_exponent, mantissa); - to_float(false, am, value); + to_float(is_negative, am, value); return value; } +} // namespace detail +// integer_times_pow10 is meant to be called in the loop of a hand-written +// parser: we force the inlining of Clinger's fast path, which is short, so that +// the common case does not pay for a function call. template -FASTFLOAT_CONSTEXPR20 +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 + typename std::enable_if::value, T>::type + integer_times_pow10(uint64_t mantissa, int decimal_exponent) noexcept { + T value; + if (clinger_fast_path_impl(mantissa, decimal_exponent, false, value)) { + return value; + } + return detail::integer_times_pow10_slow(mantissa, decimal_exponent, false); +} + +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 typename std::enable_if::value, T>::type integer_times_pow10(int64_t mantissa, int decimal_exponent) noexcept { const bool is_negative = mantissa < 0; @@ -819,24 +999,70 @@ FASTFLOAT_CONSTEXPR20 : static_cast(mantissa); T value; - if (clinger_fast_path_impl(m, decimal_exponent, is_negative, value)) + if (clinger_fast_path_impl(m, decimal_exponent, is_negative, value)) { return value; - - adjusted_mantissa am = compute_float>(decimal_exponent, m); - to_float(is_negative, am, value); - return value; + } + return detail::integer_times_pow10_slow(m, decimal_exponent, is_negative); } -FASTFLOAT_CONSTEXPR20 inline double +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 double integer_times_pow10(uint64_t mantissa, int decimal_exponent) noexcept { return integer_times_pow10(mantissa, decimal_exponent); } -FASTFLOAT_CONSTEXPR20 inline double +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 double integer_times_pow10(int64_t mantissa, int decimal_exponent) noexcept { return integer_times_pow10(mantissa, decimal_exponent); } +namespace detail { +// Whether an integer is negative, without comparing an unsigned value to 0. +template +constexpr typename std::enable_if::value, bool>::type +is_negative_integer(Int value) noexcept { + return value < 0; +} + +template +constexpr typename std::enable_if::value, bool>::type +is_negative_integer(Int) noexcept { + return false; +} +} // namespace detail + +// integer_times_pow10 with performance hints, for any integer type up to 64 +// bits: integer_times_pow10(mantissa, exponent) returns a T, and +// integer_times_pow10(mantissa, exponent) returns a double. +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 + typename std::enable_if::value && + std::is_integral::value && + sizeof(Int) <= sizeof(uint64_t), + T>::type + integer_times_pow10(Int mantissa, int decimal_exponent) noexcept { + bool const is_negative = detail::is_negative_integer(mantissa); + // Negate as unsigned: -mantissa overflows for the most negative value. + uint64_t const m = + is_negative + ? uint64_t(0) - static_cast(static_cast(mantissa)) + : static_cast(mantissa); + T value; + if (clinger_fast_path_impl(m, decimal_exponent, is_negative, + value)) { + return value; + } + return detail::integer_times_pow10_slow(m, decimal_exponent, is_negative); +} + +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 + typename std::enable_if::value && + sizeof(Int) <= sizeof(uint64_t), + double>::type + integer_times_pow10(Int mantissa, int decimal_exponent) noexcept { + return integer_times_pow10(mantissa, decimal_exponent); +} + // the following overloads are here to avoid surprising ambiguity for int, // unsigned, etc. template diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index cb5ad6d4..b14b3045 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -67,7 +67,8 @@ fast_float_add_cpp_test(supported_chars_test) fast_float_add_cpp_test(example_test) fast_float_add_cpp_test(example_comma_test) fast_float_add_cpp_test(example_integer_times_pow10) -fast_float_add_cpp_test(rounds_to_nearest_test) +fast_float_add_cpp_test(performance_hints_test) +fast_float_add_cpp_test(example_formatted) fast_float_add_cpp_test(basictest) option(FASTFLOAT_CONSTEXPR_TESTS "Require constexpr tests (build will fail if the compiler won't support it)" OFF) if (FASTFLOAT_CONSTEXPR_TESTS) diff --git a/tests/example_formatted.cpp b/tests/example_formatted.cpp new file mode 100644 index 00000000..691cc335 --- /dev/null +++ b/tests/example_formatted.cpp @@ -0,0 +1,99 @@ +#include "fast_float/fast_float.h" + +#include +#include +#include +#include +#include +#include + +// Parses formatted numbers such as "$1,234.56", "-12.5%" or "1,000" in one +// pass: we skip ',', '$' and '%' while accumulating the digits, and +// fast_float::integer_times_pow10 does the conversion. The result is correctly +// rounded. Returns false if the input is not a number. +bool parse_formatted(std::string const &s, double &out) { + uint64_t mantissa = 0; + int significant_digits = 0; // leading zeros excluded + int exponent = 0; // minus the number of digits after the point + bool negative = false, seen_dot = false, seen_digit = false, started = false; + for (char c : s) { + if (c >= '0' && c <= '9') { + seen_digit = started = true; + if (mantissa != 0 || c != '0') { + significant_digits++; + } + // overflows beyond 19 significant digits, handled below + mantissa = 10 * mantissa + uint64_t(c - '0'); + exponent -= seen_dot; + } else if (c == ',' || c == '$' || c == '%') { + continue; + } else if (c == '.' && !seen_dot) { + seen_dot = started = true; + } else if (c == '-' && !started) { + negative = started = true; + } else { + return false; + } + } + if (!seen_digit) { + return false; + } + if (significant_digits > 19) { + // Rare: the mantissa does not fit in 64 bits, let from_chars do it. + std::string clean; + for (char c : s) { + if ((c >= '0' && c <= '9') || c == '.' || c == '-') { + clean += c; + } + } + return fast_float::from_chars(clean.data(), clean.data() + clean.size(), + out) + .ec == std::errc(); + } + out = fast_float::integer_times_pow10(mantissa, exponent); + if (negative) { + out = -out; + } + return true; +} + +int main() { + struct test_case { + char const *input; + bool valid; + double expected; + }; + + test_case const cases[] = { + {"$1,234.56", true, 1234.56}, + {"$-1,234.56", true, -1234.56}, + {"-12.5%", true, -12.5}, + {"1,000", true, 1000}, + {"0.1", true, 0.1}, + {"-0", true, -0.0}, + {"123,456,789,012,345,678,901.5", true, 123456789012345678901.5}, + {"0.00000000000000000000000000001234", true, 1.234e-29}, + {"", false, 0}, + {"-", false, 0}, + {"n/a", false, 0}, + {"1.2.3", false, 0}, + {"12abc", false, 0}, + }; + bool ok = true; + for (test_case const &t : cases) { + double result = 0; + bool const valid = parse_formatted(t.input, result); + bool const good = + (valid == t.valid) && + (!valid || std::memcmp(&result, &t.expected, sizeof(double)) == 0); + std::cout.precision(17); + std::cout << (good ? "ok " : "FAIL ") << '"' << t.input << "\" -> "; + if (valid) { + std::cout << result << "\n"; + } else { + std::cout << "not a number\n"; + } + ok = ok && good; + } + return ok ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/tests/performance_hints_test.cpp b/tests/performance_hints_test.cpp new file mode 100644 index 00000000..3fe526be --- /dev/null +++ b/tests/performance_hints_test.cpp @@ -0,0 +1,337 @@ +// Performance hints (fast_float::performance_hints) must not change the value, +// the error or the end pointer. We also check that the overloads taking hints +// do not disturb the other overloads. +#include "fast_float/fast_float.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using fast_float::chars_format; +using fast_float::performance_hints; + +constexpr performance_hints sign = performance_hints::unpredictable_sign; +constexpr performance_hints nearest = + performance_hints::assume_round_to_nearest; +constexpr performance_hints short_numbers = performance_hints::short_numbers; +constexpr performance_hints all = sign | nearest | short_numbers; + +chars_format const formats[] = { + chars_format::general, + chars_format::general | chars_format::allow_leading_plus, + chars_format::general | chars_format::skip_white_space, + chars_format::scientific, + chars_format::fixed, + chars_format::json, + chars_format::json_or_infnan, + chars_format::fortran, + chars_format::javascript, + chars_format::javascript | chars_format::allow_leading_plus}; + +template void print(std::basic_string const &s) { + for (UC c : s) { + std::cerr << char(c); + } +} + +template +bool same(std::basic_string const &s, + fast_float::from_chars_result_t r1, T expected, + fast_float::from_chars_result_t r2, T actual, char const *what, + chars_format fmt) { + if (r1.ec != r2.ec || r1.ptr != r2.ptr || + std::memcmp(&expected, &actual, sizeof(T)) != 0) { + std::cerr << what << ": mismatch on \""; + print(s); + std::cerr << "\" (format " << uint64_t(fmt) << ", size " << sizeof(T) + << ", char size " << sizeof(UC) << ")\n"; + return false; + } + return true; +} + +// from_chars and from_chars_advanced against the same calls +// without hints. +template +bool same_result(std::basic_string const &s, chars_format fmt) { + UC const *first = s.data(); + UC const *last = s.data() + s.size(); + T expected = T(-12345); + T actual = T(-12345); + auto r1 = fast_float::from_chars(first, last, expected, fmt); + auto r2 = fast_float::from_chars(first, last, actual, fmt); + if (!same(s, r1, expected, r2, actual, "from_chars", fmt)) { + return false; + } + fast_float::parse_options_t const options(fmt, UC(',')); + expected = T(-12345); + actual = T(-12345); + r1 = fast_float::from_chars_advanced(first, last, expected, options); + r2 = fast_float::from_chars_advanced(first, last, actual, options); + return same(s, r1, expected, r2, actual, "from_chars_advanced", fmt); +} + +// The parser's own result also tells which error it found, and where. +template +bool same_parse(std::basic_string const &s, chars_format fmt) { + UC const *first = s.data(); + UC const *last = s.data() + s.size(); + fast_float::parse_options_t const options(fmt); + auto const a = fast_float::parse_number_string_impl( + first, last, options, true); + auto const b = fast_float::parse_number_string_impl( + first, last, options, true); + bool const ok = + a.valid == b.valid && a.error == b.error && a.lastmatch == b.lastmatch && + (!a.valid || + (a.negative == b.negative && a.mantissa == b.mantissa && + a.exponent == b.exponent && a.too_many_digits == b.too_many_digits)); + if (!ok) { + std::cerr << "parse mismatch on \""; + print(s); + std::cerr << "\" (format " << uint64_t(fmt) << ", char size " << sizeof(UC) + << ")\n"; + } + return ok; +} + +template bool check(std::string const &ascii) { + std::basic_string const s(ascii.begin(), ascii.end()); + // The JavaScript formats have their own parser: no parse-level check. + if (!same_parse(s, chars_format::general) || + !same_parse(s, chars_format::general | + chars_format::allow_leading_plus) || + !same_parse(s, chars_format::json)) { + return false; + } + for (chars_format fmt : formats) { + if (!same_result(s, fmt) || + !same_result(s, fmt) || + !same_result(s, fmt) || + !same_result(s, fmt) || + !same_result(s, fmt) || + !same_result(s, fmt) || + !same_result(s, fmt) || !same_result(s, fmt)) { + return false; + } + } + return true; +} + +bool check_all(std::string const &s) { + return check(s) && check(s) && check(s); +} + +// With assume_round_to_nearest, the results must still be those of strtod in +// the default rounding mode. +bool check_nearest_double(char const *s) { + double const expected = std::strtod(s, nullptr); + double result = 0; + auto const answer = + fast_float::from_chars(s, s + std::strlen(s), result); + if (answer.ec != std::errc() || + std::memcmp(&result, &expected, sizeof(double)) != 0) { + std::cerr << "nearest: mismatch on " << s << "\n"; + return false; + } + return true; +} + +bool check_nearest_float(char const *s) { + float const expected = std::strtof(s, nullptr); + float result = 0; + auto const answer = + fast_float::from_chars(s, s + std::strlen(s), result); + if (answer.ec != std::errc() || + std::memcmp(&result, &expected, sizeof(float)) != 0) { + std::cerr << "nearest: mismatch on " << s << " (float)\n"; + return false; + } + return true; +} + +bool check_nearest() { +#if (FLT_EVAL_METHOD == 0) || (FLT_EVAL_METHOD == 1) + if (!fast_float::detail::rounds_to_nearest()) { + std::cerr << "assume_round_to_nearest is ignored\n"; + return false; + } +#endif + char const *cases[] = {"0", + "-0", + "1", + "-1", + "0.1", + "-0.1", + "1e10", + "-1e10", + "1e-10", + "16777216", + "16777217", + "9007199254740992", + "9007199254740993", + "123456.789", + "-1234.56", + "1e23"}; + for (char const *s : cases) { + if (!check_nearest_double(s) || !check_nearest_float(s)) { + return false; + } + } + std::mt19937_64 gen(1234); + std::uniform_real_distribution prices(-1e6, 1e6); + std::uniform_int_distribution bits; + char buffer[64]; + for (size_t i = 0; i < 100000; i++) { + // short decimals: they take Clinger's fast path + std::snprintf(buffer, sizeof(buffer), "%.2f", prices(gen)); + if (!check_nearest_double(buffer) || !check_nearest_float(buffer)) { + return false; + } + // arbitrary doubles: most take the other paths + uint64_t const word = bits(gen); + double d; + std::memcpy(&d, &word, sizeof(d)); + if (d != d || d - d != 0) { // NaN or infinity + continue; + } + std::snprintf(buffer, sizeof(buffer), "%.17g", d); + if (!check_nearest_double(buffer)) { + return false; + } + } + return true; +} + +template bool same_bits(T a, T b) { + return std::memcmp(&a, &b, sizeof(T)) == 0; +} + +// integer_times_pow10 against integer_times_pow10. +template bool check_integer_times_pow10() { + std::mt19937_64 gen(5678); + for (size_t i = 0; i < 200000; i++) { + uint64_t const word = gen(); + // mostly short mantissas, which take Clinger's fast path + uint64_t const u = (i % 2 == 0) ? word % 100000000 : word; + int64_t const s = (word & 1) ? -int64_t(u >> 1) : int64_t(u >> 1); + int const e = int(gen() % 80) - 40; + if (!same_bits(fast_float::integer_times_pow10(u, e), + fast_float::integer_times_pow10(u, e)) || + !same_bits(fast_float::integer_times_pow10(s, e), + fast_float::integer_times_pow10(s, e)) || + !same_bits(fast_float::integer_times_pow10(u, e), + fast_float::integer_times_pow10(u, e)) || + !same_bits(fast_float::integer_times_pow10(s, e), + fast_float::integer_times_pow10(s, e)) || + !same_bits(fast_float::integer_times_pow10(int(s % 1000), e), + fast_float::integer_times_pow10(int(s % 1000), e)) || + !same_bits(fast_float::integer_times_pow10(uint16_t(u), e), + fast_float::integer_times_pow10(uint16_t(u), e))) { + std::cerr << "integer_times_pow10 mismatch on " << u << " or " << s + << " times 10^" << e << " (hints " << uint64_t(Hints) << ")\n"; + return false; + } + } + int64_t const most_negative = (std::numeric_limits::min)(); + if (fast_float::integer_times_pow10(most_negative, 0) != + double(most_negative)) { + std::cerr << "integer_times_pow10 mismatch on the most negative value\n"; + return false; + } + return true; +} + +// The other overloads still resolve as before. +bool check_overloads() { + std::string const input = "-12.5"; + char const *first = input.data(); + char const *last = input.data() + input.size(); + double d = 0; + // explicit types + fast_float::from_chars(first, last, d); + fast_float::from_chars(first, last, d, chars_format::fixed); + fast_float::from_chars_advanced(first, last, d, + fast_float::parse_options()); + // the address of an overload + fast_float::from_chars_result_t (*pointer)(char const *, char const *, + double &, chars_format) = + &fast_float::from_chars; + if (pointer(first, last, d, chars_format::general).ec != std::errc() || + d != -12.5) { + std::cerr << "function pointer to from_chars failed\n"; + return false; + } + // integers + std::string const integer = "-125"; + int i = 0; + fast_float::from_chars(integer.data(), integer.data() + integer.size(), i); + long l = 0; + fast_float::from_chars(integer.data(), integer.data() + integer.size(), + l, 10); + if (i != -125 || l != -125) { + std::cerr << "integer from_chars failed\n"; + return false; + } + // integer_times_pow10 + if (fast_float::integer_times_pow10(-125, -1) != -12.5 || + fast_float::integer_times_pow10(125u, -1) != 12.5 || + fast_float::integer_times_pow10(int64_t(-125), -1) != -12.5f || + fast_float::integer_times_pow10(uint64_t(125), -1) != 12.5) { + std::cerr << "integer_times_pow10 failed\n"; + return false; + } + return true; +} + +} // namespace + +int main() { + if (!check_overloads() || !check_nearest() || + !check_integer_times_pow10() || + !check_integer_times_pow10() || + !check_integer_times_pow10() || + !check_integer_times_pow10()) { + return EXIT_FAILURE; + } + std::vector const cases = { + "-", "+", "-.", "+.", "-.5", "+.5", "-5", "+5", "--5", "-+5", "+-5", + "-e5", "-5e", "-5e-3", "-0", "+0", "-0.0", "-1e400", "-1e-400", "-inf", + "+inf", "-nan", "-infinity", "- 1", " -1", " +1", "-,5", "-1,5", "-x", + "-1.5x", "-123456789012345678901234567890", "-0x1p3", "-9007199254740993", + "-2.2250738585072014e-308", "-1.7976931348623157e308", "-1d5", "-1+5", + // around 8 characters + "12345678", "123456789", "-1234567", "-12345678", "+1234567", "1234.567", + "1234.5678", "-123.456", ".1234567", "1234567.", "0000000.", "-0000000", + "99999999", "9.999999", "1.2.3", "12..3", "1,234", "12 34"}; + for (std::string const &s : cases) { + if (!check_all(s)) { + return EXIT_FAILURE; + } + } + // Short random strings over an alphabet rich in signs, digits and dots. + char const alphabet[] = "0123456789000.-+e ,xn"; + std::mt19937_64 gen(1234); + for (size_t i = 0; i < 100000; i++) { + size_t const length = 1 + gen() % 10; + std::string s; + for (size_t k = 0; k < length; k++) { + s += alphabet[gen() % (sizeof(alphabet) - 1)]; + } + if (!check_all(s)) { + return EXIT_FAILURE; + } + } + std::cout << "ok\n"; + return EXIT_SUCCESS; +} diff --git a/tests/rounds_to_nearest_test.cpp b/tests/rounds_to_nearest_test.cpp deleted file mode 100644 index 1c56b92f..00000000 --- a/tests/rounds_to_nearest_test.cpp +++ /dev/null @@ -1,107 +0,0 @@ -// Checks that defining FASTFLOAT_ROUNDS_TO_NEAREST does not change the results -// when the rounding mode is the default (round to nearest). -#define FASTFLOAT_ROUNDS_TO_NEAREST -#include "fast_float/fast_float.h" - -#include -#include -#include -#include -#include -#include -#include - -namespace { - -bool check_double(char const *s) { - double const expected = std::strtod(s, nullptr); - double result = 0; - auto const answer = fast_float::from_chars(s, s + std::strlen(s), result); - if (answer.ec != std::errc() || - std::memcmp(&result, &expected, sizeof(double)) != 0) { - std::cerr << "mismatch on " << s << "\n"; - return false; - } - return true; -} - -bool check_float(char const *s) { - float const expected = std::strtof(s, nullptr); - float result = 0; - auto const answer = fast_float::from_chars(s, s + std::strlen(s), result); - if (answer.ec != std::errc() || - std::memcmp(&result, &expected, sizeof(float)) != 0) { - std::cerr << "mismatch on " << s << " (float)\n"; - return false; - } - return true; -} - -} // namespace - -int main() { -#if (FLT_EVAL_METHOD == 0) || (FLT_EVAL_METHOD == 1) - if (!fast_float::detail::rounds_to_nearest()) { - std::cerr << "FASTFLOAT_ROUNDS_TO_NEAREST is ignored\n"; - return EXIT_FAILURE; - } -#endif - char const *cases[] = {"0", - "-0", - "1", - "-1", - "0.1", - "-0.1", - "1e10", - "-1e10", - "1e-10", - "16777216", - "16777217", - "9007199254740992", - "9007199254740993", - "123456.789", - "-1234.56", - "1e23"}; - for (char const *s : cases) { - if (!check_double(s) || !check_float(s)) { - return EXIT_FAILURE; - } - } - char const *double_cases[] = {"1e22", "-1e22", "1e-22", - "2.2250738585072014e-308", - "1.7976931348623157e308"}; - for (char const *s : double_cases) { - if (!check_double(s)) { - return EXIT_FAILURE; - } - } - std::mt19937_64 gen(1234); - std::uniform_real_distribution prices(-1e6, 1e6); - std::uniform_int_distribution bits; - char buffer[64]; - for (size_t i = 0; i < 100000; i++) { - // short decimals: they take Clinger's fast path - std::snprintf(buffer, sizeof(buffer), "%.2f", prices(gen)); - if (!check_double(buffer) || !check_float(buffer)) { - return EXIT_FAILURE; - } - // arbitrary doubles: most take the other paths - uint64_t const word = bits(gen); - double d; - std::memcpy(&d, &word, sizeof(d)); - if (d != d || d - d != 0) { // NaN or infinity - continue; - } - std::snprintf(buffer, sizeof(buffer), "%.17g", d); - if (!check_double(buffer)) { - return EXIT_FAILURE; - } - } - if (fast_float::integer_times_pow10(uint64_t(123456), -2) != 1234.56 || - fast_float::integer_times_pow10(int64_t(-123456), -2) != -1234.56) { - std::cerr << "integer_times_pow10 mismatch\n"; - return EXIT_FAILURE; - } - std::cout << "ok\n"; - return EXIT_SUCCESS; -} From 883b630c8c5bdc68dd3b7e762f764742281afc47 Mon Sep 17 00:00:00 2001 From: Daniel Lemire Date: Tue, 10 Nov 2026 00:03:31 -0500 Subject: [PATCH 2/5] Fix narrowing conversions in performance_hints_test on 32-bit targets --- tests/performance_hints_test.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/performance_hints_test.cpp b/tests/performance_hints_test.cpp index 3fe526be..1800281d 100644 --- a/tests/performance_hints_test.cpp +++ b/tests/performance_hints_test.cpp @@ -323,10 +323,10 @@ int main() { char const alphabet[] = "0123456789000.-+e ,xn"; std::mt19937_64 gen(1234); for (size_t i = 0; i < 100000; i++) { - size_t const length = 1 + gen() % 10; + size_t const length = 1 + size_t(gen() % 10); std::string s; for (size_t k = 0; k < length; k++) { - s += alphabet[gen() % (sizeof(alphabet) - 1)]; + s += alphabet[size_t(gen() % (sizeof(alphabet) - 1))]; } if (!check_all(s)) { return EXIT_FAILURE; From 537ad0da9d7afe8726254840387275ab7030f2bf Mon Sep 17 00:00:00 2001 From: Daniel Lemire Date: Wed, 18 Nov 2026 16:25:35 -0500 Subject: [PATCH 3/5] short_numbers: reject inputs that cannot start a number at once With short_numbers, an input that failed the short parser fell back to the usual parser. Words such as "auto" or "undefined" thus paid for both, which made them about six times slower than without the hint. In a JavaScript engine, most strings converted to numbers can be such words (see #435). We now test the first character before anything else: unless it is a digit, a sign or the decimal point, the input is rejected as the usual parser would reject it (leading spaces, infinity and NaN are still left to the usual parser). --- include/fast_float/float_common.h | 3 ++- include/fast_float/parse_number.h | 24 +++++++++++++++++++++++- tests/performance_hints_test.cpp | 14 ++++++++++++-- 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/include/fast_float/float_common.h b/include/fast_float/float_common.h index 389d1dd2..898713d2 100644 --- a/include/fast_float/float_common.h +++ b/include/fast_float/float_common.h @@ -99,7 +99,8 @@ enum class performance_hints : uint64_t { // parsed with a few bitwise operations, without branches that depend on // their shape. Do not use it when the numbers have predictable shapes (e.g., // mostly 0, 1.0 and 0.75 in a regular pattern): the usual parser is then - // faster. Other inputs are parsed as usual, only a bit more slowly. The + // faster. Inputs that cannot start a number (e.g., "auto") are rejected at + // once; other inputs are parsed as usual, only a bit more slowly. The // results do not change. Only for char inputs and the float and double // types; the JSON and JavaScript formats ignore it. short_numbers = 1 << 2, diff --git a/include/fast_float/parse_number.h b/include/fast_float/parse_number.h index f23f1a69..0defcefa 100644 --- a/include/fast_float/parse_number.h +++ b/include/fast_float/parse_number.h @@ -388,7 +388,29 @@ from_chars_short(UC const *first, UC const *last, T &value, chars_format fmt, // JSON and JavaScript have stricter rules (e.g., no "01" or "5."). if (!uint64_t(fmt & chars_format::fixed) || uint64_t(fmt & (basic_json_fmt | basic_javascript_fmt)) || - (last - first) > 8 || first == last) { + first == last) { + return false; + } + // A number starts with a digit, a sign or the decimal point. Other inputs, + // such as "auto", are rejected here as the usual parser would reject them: + // falling back would cost them a full parse, and such inputs can be common + // (e.g., in a JavaScript engine, most strings converted to numbers are not + // numbers). We test before the length so that long words (e.g., "undefined") + // take the same branch. + UC const c = *first; + if (!is_integer(c) && c != UC('-') && c != decimal_point && + !(uint64_t(fmt & chars_format::allow_leading_plus) && c == UC('+'))) { + // Leading spaces, infinity and NaN are left to the usual parser. + bool const maybe_infnan = !uint64_t(fmt & chars_format::no_infnan) && + ((c | 0x20) == 'i' || (c | 0x20) == 'n'); + if (uint64_t(fmt & chars_format::skip_white_space) || maybe_infnan) { + return false; + } + answer.ec = std::errc::invalid_argument; + answer.ptr = first; + return true; + } + if ((last - first) > 8) { return false; } uint64_t mantissa; diff --git a/tests/performance_hints_test.cpp b/tests/performance_hints_test.cpp index 1800281d..1b40314d 100644 --- a/tests/performance_hints_test.cpp +++ b/tests/performance_hints_test.cpp @@ -30,6 +30,12 @@ chars_format const formats[] = { chars_format::general, chars_format::general | chars_format::allow_leading_plus, chars_format::general | chars_format::skip_white_space, + chars_format::general | chars_format::no_infnan, + chars_format::general | chars_format::no_infnan | + chars_format::allow_leading_plus, + chars_format::general | chars_format::no_infnan | + chars_format::skip_white_space, + chars_format::fixed | chars_format::no_infnan, chars_format::scientific, chars_format::fixed, chars_format::json, @@ -313,14 +319,18 @@ int main() { // around 8 characters "12345678", "123456789", "-1234567", "-12345678", "+1234567", "1234.567", "1234.5678", "-123.456", ".1234567", "1234567.", "0000000.", "-0000000", - "99999999", "9.999999", "1.2.3", "12..3", "1,234", "12 34"}; + "99999999", "9.999999", "1.2.3", "12..3", "1,234", "12 34", + // not numbers + "auto", "none", "px", "x", "a1", "e5", "E5", "true", "undefined", + "inherit", "Infinity", "infinity", "INF", "inf", "NaN", "nan", "nan(1)", + "i", "n", "Nope", "infx", " 1", "\t1", "_1", "(1)", "#1"}; for (std::string const &s : cases) { if (!check_all(s)) { return EXIT_FAILURE; } } // Short random strings over an alphabet rich in signs, digits and dots. - char const alphabet[] = "0123456789000.-+e ,xn"; + char const alphabet[] = "0123456789000.-+e ,xniaf"; std::mt19937_64 gen(1234); for (size_t i = 0; i < 100000; i++) { size_t const length = 1 + size_t(gen() % 10); From 0b081d3dbb619e28a13a4760ece867358f06efd4 Mon Sep 17 00:00:00 2001 From: Daniel Lemire Date: Wed, 18 Nov 2026 16:36:56 -0500 Subject: [PATCH 4/5] short_numbers: do not take the short path when the decimal point is a digit The short parser cannot tell such a decimal point from the digit itself: with '0' as decimal point, "30" gave 3. V8 passes '0' so that parseInt stops after the integer part. The test now also uses '0' and '5' as decimal points. --- include/fast_float/parse_number.h | 6 ++++-- tests/performance_hints_test.cpp | 19 +++++++++++++------ 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/include/fast_float/parse_number.h b/include/fast_float/parse_number.h index 0defcefa..1a2da082 100644 --- a/include/fast_float/parse_number.h +++ b/include/fast_float/parse_number.h @@ -385,10 +385,12 @@ from_chars_short(UC const *first, UC const *last, T &value, chars_format fmt, return false; } fmt = adjust_for_feature_macros(fmt); - // JSON and JavaScript have stricter rules (e.g., no "01" or "5."). + // JSON and JavaScript have stricter rules (e.g., no "01" or "5."). The + // short parser cannot tell a decimal point that is a digit (e.g., V8 passes + // '0' so that parseInt stops after the integer part) from the digit itself. if (!uint64_t(fmt & chars_format::fixed) || uint64_t(fmt & (basic_json_fmt | basic_javascript_fmt)) || - first == last) { + is_integer(decimal_point) || first == last) { return false; } // A number starts with a digit, a sign or the decimal point. Other inputs, diff --git a/tests/performance_hints_test.cpp b/tests/performance_hints_test.cpp index 1b40314d..d127f198 100644 --- a/tests/performance_hints_test.cpp +++ b/tests/performance_hints_test.cpp @@ -79,12 +79,19 @@ bool same_result(std::basic_string const &s, chars_format fmt) { if (!same(s, r1, expected, r2, actual, "from_chars", fmt)) { return false; } - fast_float::parse_options_t const options(fmt, UC(',')); - expected = T(-12345); - actual = T(-12345); - r1 = fast_float::from_chars_advanced(first, last, expected, options); - r2 = fast_float::from_chars_advanced(first, last, actual, options); - return same(s, r1, expected, r2, actual, "from_chars_advanced", fmt); + // A comma as decimal point, and a digit: V8 passes '0' so that parseInt + // stops after the integer part. + for (UC const decimal_point : {UC(','), UC('0'), UC('5')}) { + fast_float::parse_options_t const options(fmt, decimal_point); + expected = T(-12345); + actual = T(-12345); + r1 = fast_float::from_chars_advanced(first, last, expected, options); + r2 = fast_float::from_chars_advanced(first, last, actual, options); + if (!same(s, r1, expected, r2, actual, "from_chars_advanced", fmt)) { + return false; + } + } + return true; } // The parser's own result also tells which error it found, and where. From 5f61b3f07afded95062038b44f2d3737184f4b27 Mon Sep 17 00:00:00 2001 From: Daniel Lemire Date: Tue, 1 Dec 2026 01:06:33 +0100 Subject: [PATCH 5/5] short_numbers: leave hexadecimal input to the hex parser With chars_format::hex | chars_format::fixed (or general), the short path parsed "10" as ten instead of sixteen, and rejected "ff" as not starting a number. The hinted tests now also run the hex formats. --- include/fast_float/parse_number.h | 10 ++++++---- tests/performance_hints_test.cpp | 7 ++++++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/include/fast_float/parse_number.h b/include/fast_float/parse_number.h index 1a2da082..d985af93 100644 --- a/include/fast_float/parse_number.h +++ b/include/fast_float/parse_number.h @@ -385,11 +385,13 @@ from_chars_short(UC const *first, UC const *last, T &value, chars_format fmt, return false; } fmt = adjust_for_feature_macros(fmt); - // JSON and JavaScript have stricter rules (e.g., no "01" or "5."). The - // short parser cannot tell a decimal point that is a digit (e.g., V8 passes - // '0' so that parseInt stops after the integer part) from the digit itself. + // JSON and JavaScript have stricter rules (e.g., no "01" or "5."), and + // hexadecimal numbers have their own parser. The short parser cannot tell a + // decimal point that is a digit (e.g., V8 passes '0' so that parseInt stops + // after the integer part) from the digit itself. if (!uint64_t(fmt & chars_format::fixed) || - uint64_t(fmt & (basic_json_fmt | basic_javascript_fmt)) || + uint64_t(fmt & + (basic_json_fmt | basic_javascript_fmt | chars_format::hex)) || is_integer(decimal_point) || first == last) { return false; } diff --git a/tests/performance_hints_test.cpp b/tests/performance_hints_test.cpp index d127f198..9429d863 100644 --- a/tests/performance_hints_test.cpp +++ b/tests/performance_hints_test.cpp @@ -39,6 +39,9 @@ chars_format const formats[] = { chars_format::scientific, chars_format::fixed, chars_format::json, + chars_format::hex, + chars_format::hex | chars_format::general, + chars_format::hex | chars_format::fixed, chars_format::json_or_infnan, chars_format::fortran, chars_format::javascript, @@ -330,7 +333,9 @@ int main() { // not numbers "auto", "none", "px", "x", "a1", "e5", "E5", "true", "undefined", "inherit", "Infinity", "infinity", "INF", "inf", "NaN", "nan", "nan(1)", - "i", "n", "Nope", "infx", " 1", "\t1", "_1", "(1)", "#1"}; + "i", "n", "Nope", "infx", " 1", "\t1", "_1", "(1)", "#1", + // hexadecimal digits + "10", "ff", "1.8", "a.b", "1p4", "-1p-1", "dead.bee", "FFFFFFFF"}; for (std::string const &s : cases) { if (!check_all(s)) { return EXIT_FAILURE;