Debian Codegraph @

include/fast_float/ascii_number.h

raw
1 #ifndef FASTFLOAT_ASCII_NUMBER_H
2 #define FASTFLOAT_ASCII_NUMBER_H
3
4 #include <cctype>
5 #include <cstdint>
6 #include <cstring>
7 #include <iterator>
8 #include <limits>
9 #include <type_traits>
10
11 #include "float_common.h"
12
13 #ifdef FASTFLOAT_SSE2
14 #include <emmintrin.h>
15 #endif
16
17 #ifdef FASTFLOAT_NEON
18 #include <arm_neon.h>
19 #endif
20
21 namespace fast_float {
22
23 template <typename UC> fastfloat_really_inline constexpr bool has_simd_opt() {
24 #ifdef FASTFLOAT_HAS_SIMD
25 return std::is_same<UC, char16_t>::value;
26 #else
27 return false;
28 #endif
29 }
30
31 // Next function can be micro-optimized, but compilers are entirely
32 // able to optimize it well.
33 template <typename UC>
34 fastfloat_really_inline constexpr bool is_integer(UC c) noexcept {
35 return !(c > UC('9') || c < UC('0'));
36 }
37
38 fastfloat_really_inline constexpr uint64_t byteswap(uint64_t val) {
39 return (val & 0xFF00000000000000) >> 56 | (val & 0x00FF000000000000) >> 40 |
40 (val & 0x0000FF0000000000) >> 24 | (val & 0x000000FF00000000) >> 8 |
41 (val & 0x00000000FF000000) << 8 | (val & 0x0000000000FF0000) << 24 |
42 (val & 0x000000000000FF00) << 40 | (val & 0x00000000000000FF) << 56;
43 }
44
45 // Read 8 UC into a u64. Truncates UC if not char.
46 template <typename UC>
47 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint64_t
48 read8_to_u64(UC const *chars) {
49 if (cpp20_and_in_constexpr() || !std::is_same<UC, char>::value) {
50 uint64_t val = 0;
51 for (int i = 0; i < 8; ++i) {
52 val |= uint64_t(uint8_t(*chars)) << (i * 8);
53 ++chars;
54 }
55 return val;
56 }
57 uint64_t val;
58 ::memcpy(&val, chars, sizeof(uint64_t));
59 #if FASTFLOAT_IS_BIG_ENDIAN == 1
60 // Need to read as-if the number was in little-endian order.
61 val = byteswap(val);
62 #endif
63 return val;
64 }
65
66 #ifdef FASTFLOAT_SSE2
67
68 fastfloat_really_inline uint64_t simd_read8_to_u64(__m128i const data) {
69 FASTFLOAT_SIMD_DISABLE_WARNINGS
70 __m128i const packed = _mm_packus_epi16(data, data);
71 #ifdef FASTFLOAT_64BIT
72 return uint64_t(_mm_cvtsi128_si64(packed));
73 #else
74 uint64_t value;
75 // Visual Studio + older versions of GCC don't support _mm_storeu_si64
76 _mm_storel_epi64(reinterpret_cast<__m128i *>(&value), packed);
77 return value;
78 #endif
79 FASTFLOAT_SIMD_RESTORE_WARNINGS
80 }
81
82 fastfloat_really_inline uint64_t simd_read8_to_u64(char16_t const *chars) {
83 FASTFLOAT_SIMD_DISABLE_WARNINGS
84 return simd_read8_to_u64(
85 _mm_loadu_si128(reinterpret_cast<__m128i const *>(chars)));
86 FASTFLOAT_SIMD_RESTORE_WARNINGS
87 }
88
89 #elif defined(FASTFLOAT_NEON)
90
91 fastfloat_really_inline uint64_t simd_read8_to_u64(uint16x8_t const data) {
92 FASTFLOAT_SIMD_DISABLE_WARNINGS
93 uint8x8_t utf8_packed = vmovn_u16(data);
94 return vget_lane_u64(vreinterpret_u64_u8(utf8_packed), 0);
95 FASTFLOAT_SIMD_RESTORE_WARNINGS
96 }
97
98 fastfloat_really_inline uint64_t simd_read8_to_u64(char16_t const *chars) {
99 FASTFLOAT_SIMD_DISABLE_WARNINGS
100 return simd_read8_to_u64(
101 vld1q_u16(reinterpret_cast<uint16_t const *>(chars)));
102 FASTFLOAT_SIMD_RESTORE_WARNINGS
103 }
104
105 #endif // FASTFLOAT_SSE2
106
107 // MSVC SFINAE is broken pre-VS2017
108 #if defined(_MSC_VER) && _MSC_VER <= 1900
109 template <typename UC>
110 #else
111 template <typename UC, FASTFLOAT_ENABLE_IF(!has_simd_opt<UC>()) = 0>
112 #endif
113 // dummy for compile
114 uint64_t simd_read8_to_u64(UC const *) {
115 return 0;
116 }
117
118 // credit @aqrit
119 fastfloat_really_inline FASTFLOAT_CONSTEXPR14 uint32_t
120 parse_eight_digits_unrolled(uint64_t val) {
121 uint64_t const mask = 0x000000FF000000FF;
122 uint64_t const mul1 = 0x000F424000000064; // 100 + (1000000ULL << 32)
123 uint64_t const mul2 = 0x0000271000000001; // 1 + (10000ULL << 32)
124 val -= 0x3030303030303030;
125 val = (val * 10) + (val >> 8); // val = (val * 2561) >> 8;
126 val = (((val & mask) * mul1) + (((val >> 16) & mask) * mul2)) >> 32;
127 return uint32_t(val);
128 }
129
130 // Call this if chars are definitely 8 digits.
131 template <typename UC>
132 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 uint32_t
133 parse_eight_digits_unrolled(UC const *chars) noexcept {
134 if (cpp20_and_in_constexpr() || !has_simd_opt<UC>()) {
135 return parse_eight_digits_unrolled(read8_to_u64(chars)); // truncation okay
136 }
137 return parse_eight_digits_unrolled(simd_read8_to_u64(chars));
138 }
139
140 // credit @aqrit
141 fastfloat_really_inline constexpr bool
142 is_made_of_eight_digits_fast(uint64_t val) noexcept {
143 return !((((val + 0x4646464646464646) | (val - 0x3030303030303030)) &
144 0x8080808080808080));
145 }
146
147 #ifdef FASTFLOAT_HAS_SIMD
148
149 // Call this if chars might not be 8 digits.
150 // Using this style (instead of is_made_of_eight_digits_fast() then
151 // parse_eight_digits_unrolled()) ensures we don't load SIMD registers twice.
152 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 bool
153 simd_parse_if_eight_digits_unrolled(char16_t const *chars,
154 uint64_t &i) noexcept {
155 if (cpp20_and_in_constexpr()) {
156 return false;
157 }
158 #ifdef FASTFLOAT_SSE2
159 FASTFLOAT_SIMD_DISABLE_WARNINGS
160 __m128i const data =
161 _mm_loadu_si128(reinterpret_cast<__m128i const *>(chars));
162
163 // (x - '0') <= 9
164 // http://0x80.pl/articles/simd-parsing-int-sequences.html
165 __m128i const t0 = _mm_add_epi16(data, _mm_set1_epi16(32720));
166 __m128i const t1 = _mm_cmpgt_epi16(t0, _mm_set1_epi16(-32759));
167
168 if (_mm_movemask_epi8(t1) == 0) {
169 i = i * 100000000 + parse_eight_digits_unrolled(simd_read8_to_u64(data));
170 return true;
171 } else
172 return false;
173 FASTFLOAT_SIMD_RESTORE_WARNINGS
174 #elif defined(FASTFLOAT_NEON)
175 FASTFLOAT_SIMD_DISABLE_WARNINGS
176 uint16x8_t const data = vld1q_u16(reinterpret_cast<uint16_t const *>(chars));
177
178 // (x - '0') <= 9
179 // http://0x80.pl/articles/simd-parsing-int-sequences.html
180 uint16x8_t const t0 = vsubq_u16(data, vmovq_n_u16('0'));
181 uint16x8_t const mask = vcltq_u16(t0, vmovq_n_u16('9' - '0' + 1));
182
183 if (vminvq_u16(mask) == 0xFFFF) {
184 i = i * 100000000 + parse_eight_digits_unrolled(simd_read8_to_u64(data));
185 return true;
186 } else
187 return false;
188 FASTFLOAT_SIMD_RESTORE_WARNINGS
189 #else
190 (void)chars;
191 (void)i;
192 return false;
193 #endif // FASTFLOAT_SSE2
194 }
195
196 #endif // FASTFLOAT_HAS_SIMD
197
198 // MSVC SFINAE is broken pre-VS2017
199 #if defined(_MSC_VER) && _MSC_VER <= 1900
200 template <typename UC>
201 #else
202 template <typename UC, FASTFLOAT_ENABLE_IF(!has_simd_opt<UC>()) = 0>
203 #endif
204 // dummy for compile
205 bool simd_parse_if_eight_digits_unrolled(UC const *, uint64_t &) {
206 return 0;
207 }
208
209 template <typename UC, FASTFLOAT_ENABLE_IF(!std::is_same<UC, char>::value) = 0>
210 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void
211 loop_parse_if_eight_digits(UC const *&p, UC const *const pend, uint64_t &i) {
212 if (!has_simd_opt<UC>()) {
213 return;
214 }
215 while ((std::distance(p, pend) >= 8) &&
216 simd_parse_if_eight_digits_unrolled(
217 p, i)) { // in rare cases, this will overflow, but that's ok
218 p += 8;
219 }
220 }
221
222 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 void
223 loop_parse_if_eight_digits(char const *&p, char const *const pend,
224 uint64_t &i) {
225 // optimizes better than parse_if_eight_digits_unrolled() for UC = char.
226 while ((std::distance(p, pend) >= 8) &&
227 is_made_of_eight_digits_fast(read8_to_u64(p))) {
228 i = i * 100000000 +
229 parse_eight_digits_unrolled(read8_to_u64(
230 p)); // in rare cases, this will overflow, but that's ok
231 p += 8;
232 }
233 }
234
235 enum class parse_error {
236 no_error,
237 // [JSON-only] The minus sign must be followed by an integer.
238 missing_integer_after_sign,
239 // A sign must be followed by an integer or dot.
240 missing_integer_or_dot_after_sign,
241 // [JSON-only] The integer part must not have leading zeros.
242 leading_zeros_in_integer_part,
243 // [JSON-only] The integer part must have at least one digit.
244 no_digits_in_integer_part,
245 // [JSON-only] If there is a decimal point, there must be digits in the
246 // fractional part.
247 no_digits_in_fractional_part,
248 // The mantissa must have at least one digit.
249 no_digits_in_mantissa,
250 // Scientific notation requires an exponential part.
251 missing_exponential_part,
252 };
253
254 template <typename UC> struct parsed_number_string_t {
255 int64_t exponent{0};
256 uint64_t mantissa{0};
257 UC const *lastmatch{nullptr};
258 bool negative{false};
259 bool valid{false};
260 bool too_many_digits{false};
261 // contains the range of the significant digits
262 span<UC const> integer{}; // non-nullable
263 span<UC const> fraction{}; // nullable
264 parse_error error{parse_error::no_error};
265 };
266
267 using byte_span = span<char const>;
268 using parsed_number_string = parsed_number_string_t<char>;
269
270 template <typename UC>
271 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t<UC>
272 report_parse_error(UC const *p, parse_error error) {
273 parsed_number_string_t<UC> answer;
274 answer.valid = false;
275 answer.lastmatch = p;
276 answer.error = error;
277 return answer;
278 }
279
280 // Assuming that you use no more than 19 digits, this will
281 // parse an ASCII string.
282 template <bool basic_json_fmt, typename UC>
283 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 parsed_number_string_t<UC>
284 parse_number_string(UC const *p, UC const *pend,
285 parse_options_t<UC> options) noexcept {
286 chars_format const fmt = detail::adjust_for_feature_macros(options.format);
287 UC const decimal_point = options.decimal_point;
288
289 parsed_number_string_t<UC> answer;
290 answer.valid = false;
291 answer.too_many_digits = false;
292 // assume p < pend, so dereference without checks;
293 answer.negative = (*p == UC('-'));
294 // C++17 20.19.3.(7.1) explicitly forbids '+' sign here
295 if ((*p == UC('-')) || (uint64_t(fmt & chars_format::allow_leading_plus) &&
296 !basic_json_fmt && *p == UC('+'))) {
297 ++p;
298 if (p == pend) {
299 return report_parse_error<UC>(
300 p, parse_error::missing_integer_or_dot_after_sign);
301 }
302 FASTFLOAT_IF_CONSTEXPR17(basic_json_fmt) {
303 if (!is_integer(*p)) { // a sign must be followed by an integer
304 return report_parse_error<UC>(p,
305 parse_error::missing_integer_after_sign);
306 }
307 }
308 else {
309 if (!is_integer(*p) &&
310 (*p !=
311 decimal_point)) { // a sign must be followed by an integer or the dot
312 return report_parse_error<UC>(
313 p, parse_error::missing_integer_or_dot_after_sign);
314 }
315 }
316 }
317 UC const *const start_digits = p;
318
319 uint64_t i = 0; // an unsigned int avoids signed overflows (which are bad)
320
321 while ((p != pend) && is_integer(*p)) {
322 // a multiplication by 10 is cheaper than an arbitrary integer
323 // multiplication
324 i = 10 * i +
325 uint64_t(*p -
326 UC('0')); // might overflow, we will handle the overflow later
327 ++p;
328 }
329 UC const *const end_of_integer_part = p;
330 int64_t digit_count = int64_t(end_of_integer_part - start_digits);
331 answer.integer = span<UC const>(start_digits, size_t(digit_count));
332 FASTFLOAT_IF_CONSTEXPR17(basic_json_fmt) {
333 // at least 1 digit in integer part, without leading zeros
334 if (digit_count == 0) {
335 return report_parse_error<UC>(p, parse_error::no_digits_in_integer_part);
336 }
337 if ((start_digits[0] == UC('0') && digit_count > 1)) {
338 return report_parse_error<UC>(start_digits,
339 parse_error::leading_zeros_in_integer_part);
340 }
341 }
342
343 int64_t exponent = 0;
344 bool const has_decimal_point = (p != pend) && (*p == decimal_point);
345 if (has_decimal_point) {
346 ++p;
347 UC const *before = p;
348 // can occur at most twice without overflowing, but let it occur more, since
349 // for integers with many digits, digit parsing is the primary bottleneck.
350 loop_parse_if_eight_digits(p, pend, i);
351
352 while ((p != pend) && is_integer(*p)) {
353 uint8_t digit = uint8_t(*p - UC('0'));
354 ++p;
355 i = i * 10 + digit; // in rare cases, this will overflow, but that's ok
356 }
357 exponent = before - p;
358 answer.fraction = span<UC const>(before, size_t(p - before));
359 digit_count -= exponent;
360 }
361 FASTFLOAT_IF_CONSTEXPR17(basic_json_fmt) {
362 // at least 1 digit in fractional part
363 if (has_decimal_point && exponent == 0) {
364 return report_parse_error<UC>(p,
365 parse_error::no_digits_in_fractional_part);
366 }
367 }
368 else if (digit_count == 0) { // we must have encountered at least one integer!
369 return report_parse_error<UC>(p, parse_error::no_digits_in_mantissa);
370 }
371 int64_t exp_number = 0; // explicit exponential part
372 if ((uint64_t(fmt & chars_format::scientific) && (p != pend) &&
373 ((UC('e') == *p) || (UC('E') == *p))) ||
374 (uint64_t(fmt & detail::basic_fortran_fmt) && (p != pend) &&
375 ((UC('+') == *p) || (UC('-') == *p) || (UC('d') == *p) ||
376 (UC('D') == *p)))) {
377 UC const *location_of_e = p;
378 if ((UC('e') == *p) || (UC('E') == *p) || (UC('d') == *p) ||
379 (UC('D') == *p)) {
380 ++p;
381 }
382 bool neg_exp = false;
383 if ((p != pend) && (UC('-') == *p)) {
384 neg_exp = true;
385 ++p;
386 } else if ((p != pend) &&
387 (UC('+') ==
388 *p)) { // '+' on exponent is allowed by C++17 20.19.3.(7.1)
389 ++p;
390 }
391 if ((p == pend) || !is_integer(*p)) {
392 if (!uint64_t(fmt & chars_format::fixed)) {
393 // The exponential part is invalid for scientific notation, so it must
394 // be a trailing token for fixed notation. However, fixed notation is
395 // disabled, so report a scientific notation error.
396 return report_parse_error<UC>(p, parse_error::missing_exponential_part);
397 }
398 // Otherwise, we will be ignoring the 'e'.
399 p = location_of_e;
400 } else {
401 while ((p != pend) && is_integer(*p)) {
402 uint8_t digit = uint8_t(*p - UC('0'));
403 if (exp_number < 0x10000000) {
404 exp_number = 10 * exp_number + digit;
405 }
406 ++p;
407 }
408 if (neg_exp) {
409 exp_number = -exp_number;
410 }
411 exponent += exp_number;
412 }
413 } else {
414 // If it scientific and not fixed, we have to bail out.
415 if (uint64_t(fmt & chars_format::scientific) &&
416 !uint64_t(fmt & chars_format::fixed)) {
417 return report_parse_error<UC>(p, parse_error::missing_exponential_part);
418 }
419 }
420 answer.lastmatch = p;
421 answer.valid = true;
422
423 // If we frequently had to deal with long strings of digits,
424 // we could extend our code by using a 128-bit integer instead
425 // of a 64-bit integer. However, this is uncommon.
426 //
427 // We can deal with up to 19 digits.
428 if (digit_count > 19) { // this is uncommon
429 // It is possible that the integer had an overflow.
430 // We have to handle the case where we have 0.0000somenumber.
431 // We need to be mindful of the case where we only have zeroes...
432 // E.g., 0.000000000...000.
433 UC const *start = start_digits;
434 while ((start != pend) && (*start == UC('0') || *start == decimal_point)) {
435 if (*start == UC('0')) {
436 digit_count--;
437 }
438 start++;
439 }
440
441 if (digit_count > 19) {
442 answer.too_many_digits = true;
443 // Let us start again, this time, avoiding overflows.
444 // We don't need to call if is_integer, since we use the
445 // pre-tokenized spans from above.
446 i = 0;
447 p = answer.integer.ptr;
448 UC const *int_end = p + answer.integer.len();
449 uint64_t const minimal_nineteen_digit_integer{1000000000000000000};
450 while ((i < minimal_nineteen_digit_integer) && (p != int_end)) {
451 i = i * 10 + uint64_t(*p - UC('0'));
452 ++p;
453 }
454 if (i >= minimal_nineteen_digit_integer) { // We have a big integer
455 exponent = end_of_integer_part - p + exp_number;
456 } else { // We have a value with a fractional component.
457 p = answer.fraction.ptr;
458 UC const *frac_end = p + answer.fraction.len();
459 while ((i < minimal_nineteen_digit_integer) && (p != frac_end)) {
460 i = i * 10 + uint64_t(*p - UC('0'));
461 ++p;
462 }
463 exponent = answer.fraction.ptr - p + exp_number;
464 }
465 // We have now corrected both exponent and i, to a truncated value
466 }
467 }
468 answer.exponent = exponent;
469 answer.mantissa = i;
470 return answer;
471 }
472
473 template <typename T, typename UC>
474 fastfloat_really_inline FASTFLOAT_CONSTEXPR20 from_chars_result_t<UC>
475 parse_int_string(UC const *p, UC const *pend, T &value,
476 parse_options_t<UC> options) {
477 chars_format const fmt = detail::adjust_for_feature_macros(options.format);
478 int const base = options.base;
479
480 from_chars_result_t<UC> answer;
481
482 UC const *const first = p;
483
484 bool const negative = (*p == UC('-'));
485 #ifdef FASTFLOAT_VISUAL_STUDIO
486 #pragma warning(push)
487 #pragma warning(disable : 4127)
488 #endif
489 if (!std::is_signed<T>::value && negative) {
490 #ifdef FASTFLOAT_VISUAL_STUDIO
491 #pragma warning(pop)
492 #endif
493 answer.ec = std::errc::invalid_argument;
494 answer.ptr = first;
495 return answer;
496 }
497 if ((*p == UC('-')) ||
498 (uint64_t(fmt & chars_format::allow_leading_plus) && (*p == UC('+')))) {
499 ++p;
500 }
501
502 UC const *const start_num = p;
503
504 while (p != pend && *p == UC('0')) {
505 ++p;
506 }
507
508 bool const has_leading_zeros = p > start_num;
509
510 UC const *const start_digits = p;
511
512 uint64_t i = 0;
513 if (base == 10) {
514 loop_parse_if_eight_digits(p, pend, i); // use SIMD if possible
515 }
516 while (p != pend) {
517 uint8_t digit = ch_to_digit(*p);
518 if (digit >= base) {
519 break;
520 }
521 i = uint64_t(base) * i + digit; // might overflow, check this later
522 p++;
523 }
524
525 size_t digit_count = size_t(p - start_digits);
526
527 if (digit_count == 0) {
528 if (has_leading_zeros) {
529 value = 0;
530 answer.ec = std::errc();
531 answer.ptr = p;
532 } else {
533 answer.ec = std::errc::invalid_argument;
534 answer.ptr = first;
535 }
536 return answer;
537 }
538
539 answer.ptr = p;
540
541 // check u64 overflow
542 size_t max_digits = max_digits_u64(base);
543 if (digit_count > max_digits) {
544 answer.ec = std::errc::result_out_of_range;
545 return answer;
546 }
547 // this check can be eliminated for all other types, but they will all require
548 // a max_digits(base) equivalent
549 if (digit_count == max_digits && i < min_safe_u64(base)) {
550 answer.ec = std::errc::result_out_of_range;
551 return answer;
552 }
553
554 // check other types overflow
555 if (!std::is_same<T, uint64_t>::value) {
556 if (i > uint64_t(std::numeric_limits<T>::max()) + uint64_t(negative)) {
557 answer.ec = std::errc::result_out_of_range;
558 return answer;
559 }
560 }
561
562 if (negative) {
563 #ifdef FASTFLOAT_VISUAL_STUDIO
564 #pragma warning(push)
565 #pragma warning(disable : 4146)
566 #endif
567 // this weird workaround is required because:
568 // - converting unsigned to signed when its value is greater than signed max
569 // is UB pre-C++23.
570 // - reinterpret_casting (~i + 1) would work, but it is not constexpr
571 // this is always optimized into a neg instruction (note: T is an integer
572 // type)
573 value = T(-std::numeric_limits<T>::max() -
574 T(i - uint64_t(std::numeric_limits<T>::max())));
575 #ifdef FASTFLOAT_VISUAL_STUDIO
576 #pragma warning(pop)
577 #endif
578 } else {
579 value = T(i);
580 }
581
582 answer.ec = std::errc();
583 return answer;
584 }
585
586 } // namespace fast_float
587
588 #endif