diff --git a/.github/workflows/alpine.yml b/.github/workflows/alpine.yml index 842313b7..6d641d3c 100644 --- a/.github/workflows/alpine.yml +++ b/.github/workflows/alpine.yml @@ -6,7 +6,9 @@ on: jobs: build: name: Build on Alpine ${{ matrix.arch }} - runs-on: ubuntu-latest + # setup-alpine v1 runs its script with "sudo -E", and the sudo of Ubuntu 26.04 + # ignores -E, so the action loses its inputs. + runs-on: ubuntu-24.04 strategy: matrix: arch: diff --git a/README.md b/README.md index d9d0b04e..e167df4b 100644 --- a/README.md +++ b/README.md @@ -441,6 +441,62 @@ int main() { } ``` +### Resuming after a prefix you have already read + +Some parsers read small integers by themselves, because most numbers in their +inputs are small integers, and call fast_float only for the other numbers. For +example, V8 (the JavaScript engine in Chrome) parses `JSON.parse` input this +way. When the number goes on (`1700000000000` or `12.5`), fast_float would read +again the digits that the parser has already read. The function +`from_chars_resume` avoids this work: + +```C++ +from_chars_result_t from_chars_resume(UC const *first, UC const *cursor, UC const *last, + uint64_t prefix, T &value, parse_options_t options); +``` + +It works as follows. + +1. The number starts at `first` and the input ends at `last`, as with + `from_chars_advanced`. +2. You read an optional sign (`-`, or `+` if the options allow it), followed by + some digits. You stop at `cursor`, the first character you did not read. +3. You compute `prefix`, the value of the digits you read (ignoring the sign). + E.g., if you read `-170`, then `prefix` is 170. +4. If the number ends at `cursor`, you have its value and you are done. + Otherwise, you call `from_chars_resume(first, cursor, last, prefix, value, options)`. + It continues parsing from `cursor`. + +The result (`value`, `ec` and `ptr`) is the same as with +`from_chars_advanced(first, last, value, options)`. If you have read nothing, +pass `cursor == first` and `prefix == 0`. + +```C++ +#include "fast_float/fast_float.h" +#include + +int main() { + std::string input = "-1700000000000.25"; + char const *first = input.data(); + char const *last = input.data() + input.size(); + // Step 2: read the sign and up to 9 digits. + char const *cursor = first; + if (*cursor == '-') { cursor++; } + // Step 3: compute the value of the digits. + uint64_t prefix = 0; + for (int n = 0; cursor != last && n < 9 && *cursor >= '0' && *cursor <= '9'; n++, cursor++) { + prefix = 10 * prefix + uint64_t(*cursor - '0'); + } + // Here, cursor points at the tenth digit and prefix is 170000000. + // Step 4: the number goes on, so let fast_float finish the work. + double result; + fast_float::parse_options options{fast_float::chars_format::json}; + auto answer = fast_float::from_chars_resume(first, cursor, last, prefix, result, options); + if (answer.ec != std::errc() || result != -1700000000000.25) { std::cerr << "parsing failure\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/include/fast_float/ascii_number.h b/include/fast_float/ascii_number.h index cd69e933..bf53f84c 100644 --- a/include/fast_float/ascii_number.h +++ b/include/fast_float/ascii_number.h @@ -348,11 +348,17 @@ 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 +// +// With resume (see from_chars_resume), the caller has already read the digits +// in [start of the integer part, resume_p), and their value is resume_i (modulo +// 2^64): the scan of the integer part continues from resume_p. +template fastfloat_really_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t parse_number_string_impl(UC const *p, UC const *pend, - parse_options_t options, - bool store_spans) noexcept { + parse_options_t options, bool store_spans, + UC const *resume_p = nullptr, + uint64_t resume_i = 0) noexcept { chars_format const fmt = detail::adjust_for_feature_macros(options.format); UC const decimal_point = options.decimal_point; @@ -388,6 +394,19 @@ parse_number_string_impl(UC const *p, UC const *pend, uint64_t i = 0; // an unsigned int avoids signed overflows (which are bad) + FASTFLOAT_IF_CONSTEXPR17(resume) { + // resume_p may be before p when the caller has read no digit (e.g., it + // passed the start of the input, and we skipped a sign or spaces). + if (resume_p > p) { + p = resume_p; + i = resume_i; + } + while ((p != pend) && is_integer(*p)) { + i = 10 * i + uint64_t(*p - UC('0')); // might overflow, handled later + ++p; + } + // The scan below then finds no digit and leaves p and i as they are. + } // Straight-line unroll of the integer-part scan: most integer parts are // 1-5 digits, so peeling the first iterations eliminates the loop back-edge // for the common case. Semantics are identical to the original `while` loop: diff --git a/include/fast_float/fast_float.h b/include/fast_float/fast_float.h index 1e79ac61..b4ee85d5 100644 --- a/include/fast_float/fast_float.h +++ b/include/fast_float/fast_float.h @@ -45,6 +45,24 @@ 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 for floating-point types, but for callers that have + * already read the start of the number: [first, cursor) must hold an optional + * sign followed by zero or more digits, and `prefix` must be the value of these + * digits (modulo 2^64). The sign is '-', or '+' when the options allow it + * (chars_format::allow_leading_plus, outside of JSON). The parsing continues + * from `cursor`, and the result is the same as from_chars_advanced(first, last, + * value, options). Passing cursor == first and prefix == 0 is always allowed. + * + * For example, a JSON parser may read short integers by itself and fall back to + * from_chars_resume when the number does not end after the digits. + */ +template +FASTFLOAT_CONSTEXPR20 from_chars_result_t +from_chars_resume(UC const *first, UC const *cursor, UC const *last, + uint64_t prefix, T &value, + parse_options_t options = parse_options_t()) 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 diff --git a/include/fast_float/parse_number.h b/include/fast_float/parse_number.h index 0006fc4c..31a13540 100644 --- a/include/fast_float/parse_number.h +++ b/include/fast_float/parse_number.h @@ -385,10 +385,14 @@ from_chars_float_javascript(UC const *first, UC const *last, T &value, return from_chars_advanced(pns, value); } -template +// With resume, the caller has already read [first, cursor): see +// from_chars_resume. +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 { + parse_options_t options, + UC const *cursor = nullptr, + uint64_t prefix = 0) noexcept { static_assert(is_supported_float_type::value, "only some floating-point types are supported"); @@ -432,10 +436,10 @@ from_chars_float_advanced(UC const *first, UC const *last, T &value, // parsed_number_string_t off the hot path. store_spans is a runtime argument, // so this reuses the single parse_number_string_impl instantiation. parsed_number_string_t pns = - bjf ? parse_number_string_impl(first, last, options, - false) - : parse_number_string_impl(first, last, options, - false); + bjf ? parse_number_string_impl( + first, last, options, false, cursor, prefix) + : parse_number_string_impl( + first, last, options, false, cursor, prefix); if (!pns.valid) { if (uint64_t(fmt & chars_format::no_infnan)) { answer.ec = std::errc::invalid_argument; @@ -495,6 +499,15 @@ from_chars_float_advanced(UC const *first, UC const *last, T &value, return answer; } +template +fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t +from_chars_resume(UC const *first, UC const *cursor, UC const *last, + uint64_t prefix, T &value, + parse_options_t options) noexcept { + return from_chars_float_advanced(first, last, value, options, + cursor, prefix); +} + template FASTFLOAT_CONSTEXPR20 from_chars_result_t from_chars(UC const *first, UC const *last, T &value, int base) noexcept { diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index a8cc62be..b33f3caf 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -88,6 +88,7 @@ target_compile_features(fast_int 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(from_chars_resume_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/from_chars_resume_test.cpp b/tests/from_chars_resume_test.cpp new file mode 100644 index 00000000..e7cd4b54 --- /dev/null +++ b/tests/from_chars_resume_test.cpp @@ -0,0 +1,157 @@ +// from_chars_resume must give the same result as from_chars_advanced, whatever +// prefix of digits the caller has already read. +#include "fast_float/fast_float.h" +#include +#include +#include +#include +#include +#include +#include + +template bool same_value(T a, T b) { + if (a != a) { + return b != b; + } + return std::memcmp(&a, &b, sizeof(T)) == 0; +} + +template +bool check(std::basic_string const &s, + fast_float::parse_options_t options) { + UC const *first = s.data(); + UC const *last = s.data() + s.size(); + T expected = T(1.5); + auto const want = + fast_float::from_chars_advanced(first, last, expected, options); + // Every cursor such that [first, cursor) is an optional sign followed by + // digits, and cursor == first in any case. + UC const *start = first; + bool const plus = + uint64_t(options.format & fast_float::chars_format::allow_leading_plus) && + !uint64_t(options.format & fast_float::detail::basic_json_fmt); + if (start != last && (*start == UC('-') || (plus && *start == UC('+')))) { + ++start; + } + std::vector cursors{first}; + for (UC const *c = start;; ++c) { + if (c != first) { + cursors.push_back(c); + } + if (c == last || !fast_float::is_integer(*c)) { + break; + } + } + for (UC const *cursor : cursors) { + uint64_t prefix = 0; + for (UC const *c = start; c < cursor; ++c) { + prefix = 10 * prefix + uint64_t(*c - UC('0')); + } + T got = T(1.5); + auto const r = fast_float::from_chars_resume(first, cursor, last, prefix, + got, options); + if (r.ec != want.ec || r.ptr != want.ptr || !same_value(got, expected)) { + std::cerr << "mismatch on \""; + for (UC c : s) { + std::cerr << char(c); + } + std::cerr << "\" (format " << uint64_t(options.format) << ", cursor at " + << (cursor - first) << ", sizeof(T) " << sizeof(T) + << ", sizeof(UC) " << sizeof(UC) << ")\n"; + return false; + } + } + return true; +} + +template bool check_all(std::string const &s) { + using fast_float::chars_format; + std::basic_string const w(s.begin(), s.end()); + chars_format const formats[] = { + chars_format::general, + chars_format::fixed, + chars_format::scientific, + chars_format::json, + chars_format::json_or_infnan, + chars_format::fortran, + chars_format::javascript, + 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::allow_leading_plus, + }; + for (chars_format fmt : formats) { + for (UC dp : {UC('.'), UC(',')}) { + fast_float::parse_options_t const options{fmt, dp}; + if (!check(w, options) || !check(w, options)) { + return false; + } + } + } + return true; +} + +int main() { + std::vector inputs = { + "", + "-", + "+", + "0", + "-0", + "00", + "01", + "0.5", + "1", + "123", + "123456789", + "1234567890", + "1700000000000", + "-1700000000000.5", + "1.5", + "-12.25e3", + "12e", + "12.", + ".5", + "-.5", + "1,5", + "3.14159265358979323846264338327950288", + "123456789012345678901234567890", + "18446744073709551615", + "18446744073709551616", + "99999999999999999999.5", + "9007199254740993", + "2.2250738585072011e-308", + "1e400", + "-1e400", + "1e-400", + "123abc", + "12 ", + " 12", + " -3.5", + "+12", + "-+1", + "inf", + "-infinity", + "nan", + "12d3", + "0x10", + "017", + }; + std::mt19937_64 rng(435); + char const alphabet[] = "0123456789000.-+e, "; + for (int k = 0; k < 20000; k++) { + std::string s; + size_t const len = size_t(rng() % 32); + for (size_t j = 0; j < len; j++) { + s += alphabet[rng() % (sizeof(alphabet) - 1)]; + } + inputs.push_back(s); + } + for (auto const &s : inputs) { + if (!check_all(s) || !check_all(s)) { + return EXIT_FAILURE; + } + } + std::cout << "from_chars_resume: " << inputs.size() << " inputs checked\n"; + return EXIT_SUCCESS; +}