Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/alpine.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
56 changes: 56 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<UC> from_chars_resume(UC const *first, UC const *cursor, UC const *last,
uint64_t prefix, T &value, parse_options_t<UC> 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 <iostream>

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
Expand Down
25 changes: 22 additions & 3 deletions include/fast_float/ascii_number.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 <bool basic_json_fmt, bool basic_javascript_fmt, typename UC>
//
// 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 <bool basic_json_fmt, bool basic_javascript_fmt, typename UC,
bool resume = false>
fastfloat_really_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t<UC>
parse_number_string_impl(UC const *p, UC const *pend,
parse_options_t<UC> options,
bool store_spans) noexcept {
parse_options_t<UC> 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;

Expand Down Expand Up @@ -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:
Expand Down
18 changes: 18 additions & 0 deletions include/fast_float/fast_float.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,24 @@ FASTFLOAT_CONSTEXPR20 from_chars_result_t<UC>
from_chars_advanced(UC const *first, UC const *last, T &value,
parse_options_t<UC> 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 <typename T, typename UC = char>
FASTFLOAT_CONSTEXPR20 from_chars_result_t<UC>
from_chars_resume(UC const *first, UC const *cursor, UC const *last,
uint64_t prefix, T &value,
parse_options_t<UC> options = parse_options_t<UC>()) 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
Expand Down
25 changes: 19 additions & 6 deletions include/fast_float/parse_number.h
Original file line number Diff line number Diff line change
Expand Up @@ -385,10 +385,14 @@ from_chars_float_javascript(UC const *first, UC const *last, T &value,
return from_chars_advanced(pns, value);
}

template <typename T, typename UC>
// With resume, the caller has already read [first, cursor): see
// from_chars_resume.
template <typename T, typename UC, bool resume = false>
fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t<UC>
from_chars_float_advanced(UC const *first, UC const *last, T &value,
parse_options_t<UC> options) noexcept {
parse_options_t<UC> options,
UC const *cursor = nullptr,
uint64_t prefix = 0) noexcept {

static_assert(is_supported_float_type<T>::value,
"only some floating-point types are supported");
Expand Down Expand Up @@ -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<UC> pns =
bjf ? parse_number_string_impl<true, false, UC>(first, last, options,
false)
: parse_number_string_impl<false, false, UC>(first, last, options,
false);
bjf ? parse_number_string_impl<true, false, UC, resume>(
first, last, options, false, cursor, prefix)
: parse_number_string_impl<false, false, UC, resume>(
first, last, options, false, cursor, prefix);
if (!pns.valid) {
if (uint64_t(fmt & chars_format::no_infnan)) {
answer.ec = std::errc::invalid_argument;
Expand Down Expand Up @@ -495,6 +499,15 @@ from_chars_float_advanced(UC const *first, UC const *last, T &value,
return answer;
}

template <typename T, typename UC>
fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t<UC>
from_chars_resume(UC const *first, UC const *cursor, UC const *last,
uint64_t prefix, T &value,
parse_options_t<UC> options) noexcept {
return from_chars_float_advanced<T, UC, true>(first, last, value, options,
cursor, prefix);
}

template <typename T, typename UC, typename>
FASTFLOAT_CONSTEXPR20 from_chars_result_t<UC>
from_chars(UC const *first, UC const *last, T &value, int base) noexcept {
Expand Down
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
157 changes: 157 additions & 0 deletions tests/from_chars_resume_test.cpp
Original file line number Diff line number Diff line change
@@ -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 <cstdint>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <random>
#include <string>
#include <vector>

template <typename T> bool same_value(T a, T b) {
if (a != a) {
return b != b;
}
return std::memcmp(&a, &b, sizeof(T)) == 0;
}

template <typename T, typename UC>
bool check(std::basic_string<UC> const &s,
fast_float::parse_options_t<UC> 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<UC const *> 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 <typename UC> bool check_all(std::string const &s) {
using fast_float::chars_format;
std::basic_string<UC> 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<UC> const options{fmt, dp};
if (!check<double>(w, options) || !check<float>(w, options)) {
return false;
}
}
}
return true;
}

int main() {
std::vector<std::string> 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<char>(s) || !check_all<char16_t>(s)) {
return EXIT_FAILURE;
}
}
std::cout << "from_chars_resume: " << inputs.size() << " inputs checked\n";
return EXIT_SUCCESS;
}
Loading