Repository navigation
Expand file tree
/
Copy pathreadFloatText.cpp
More file actions
1138 lines (996 loc) · 42.2 KB
/
Copy pathreadFloatText.cpp
File metadata and controls
1138 lines (996 loc) · 42.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <IO/readFloatText.h>
#include <IO/ReadHelpers.h>
#include <IO/ReadBufferFromMemory.h>
#include <Core/Defines.h>
#include <base/shift10.h>
#include <base/sanitizer_defs.h>
#include <base/unaligned.h>
#include <Common/StringUtils.h>
#include <Common/intExp.h>
#include <bit>
#include <cstring>
#include <limits>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunneeded-internal-declaration"
#include <fast_float/fast_float.h>
#pragma clang diagnostic pop
/// The analyzer chases fast_float's flag-enum operators (chars_format) and ascii number parsing
/// through every call site below, so the suppression spans the whole file.
// NOLINTBEGIN(clang-analyzer-core.UndefinedBinaryOperatorResult,clang-analyzer-optin.core.EnumCastOutOfRange)
namespace DB
{
namespace ErrorCodes
{
extern const int CANNOT_PARSE_NUMBER;
extern const int CANNOT_PARSE_INPUT_ASSERTION_FAILED;
}
/** Must successfully parse inf, INF and Infinity.
* All other variants in different cases are also parsed for simplicity.
*/
bool parseInfinity(ReadBuffer & buf)
{
if (!checkStringCaseInsensitive("inf", buf))
return false;
/// Just inf.
if (buf.eof() || !isWordCharASCII(*buf.position()))
return true;
/// If word characters after inf, it should be infinity.
return checkStringCaseInsensitive("inity", buf);
}
/** Must successfully parse nan, NAN and NaN.
* All other variants in different cases are also parsed for simplicity.
*/
bool parseNaN(ReadBuffer & buf)
{
return checkStringCaseInsensitive("nan", buf);
}
void assertInfinity(ReadBuffer & buf)
{
if (!parseInfinity(buf))
throw Exception(ErrorCodes::CANNOT_PARSE_INPUT_ASSERTION_FAILED, "Cannot parse infinity.");
}
void assertNaN(ReadBuffer & buf)
{
if (!parseNaN(buf))
throw Exception(ErrorCodes::CANNOT_PARSE_INPUT_ASSERTION_FAILED, "Cannot parse NaN.");
}
namespace
{
template <bool throw_exception>
bool assertOrParseInfinity(ReadBuffer & buf)
{
if constexpr (throw_exception)
{
assertInfinity(buf);
return true;
}
else
return parseInfinity(buf);
}
template <bool throw_exception>
bool assertOrParseNaN(ReadBuffer & buf)
{
if constexpr (throw_exception)
{
assertNaN(buf);
return true;
}
else
return parseNaN(buf);
}
// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/
/// The addition of the magic constant carries between the packed bytes on purpose - that is what
/// makes this a branchless test of all eight at once.
NO_SANITIZE_UNSIGNED_OVERFLOW inline bool is_made_of_eight_digits_fast(uint64_t val) noexcept
{
return (((val & 0xF0F0F0F0F0F0F0F0) | (((val + 0x0606060606060606) & 0xF0F0F0F0F0F0F0F0) >> 4)) == 0x3333333333333333);
}
inline bool is_made_of_eight_digits_fast(const char * chars) noexcept
{
uint64_t val = 0;
::memcpy(&val, chars, 8);
return is_made_of_eight_digits_fast(val);
}
/// Convert 8 ASCII decimal digits (read as a little-endian uint64) into their integer value. credit: @aqrit
inline uint32_t NO_SANITIZE_UNSIGNED_OVERFLOW parse_eight_digits_unrolled(uint64_t val) noexcept
{
const uint64_t mask = 0x000000FF000000FF;
const uint64_t mul1 = 0x000F424000000064; // 100 + (1000000ULL << 32)
const uint64_t mul2 = 0x0000271000000001; // 1 + (10000ULL << 32)
val -= 0x3030303030303030;
val = (val * 10) + (val >> 8);
val = (((val & mask) * mul1) + (((val >> 16) & mask) * mul2)) >> 32;
return static_cast<uint32_t>(val);
}
#if defined(__x86_64__) || defined(__aarch64__)
/// Classifying 16 bytes at once finds where a short token ends without a branch per character, which
/// mispredicts when the lengths of the values vary. Written with clang vector extensions rather than
/// intrinsics so that the same code compiles for x86 and aarch64.
#if defined(__aarch64__)
constexpr unsigned mask_bits_per_byte = 4;
#else
constexpr unsigned mask_bits_per_byte = 1;
#endif
/// Bit mask of the true bytes of a 16-byte comparison result, `mask_bits_per_byte` bits per byte.
template <typename Vector>
inline uint64_t byteMask16(Vector bytes)
{
#if defined(__aarch64__)
/// NEON has no movemask. Narrowing each 16-bit lane by 4 bits (`shrn`) keeps 4 bits of every byte, which
/// is as good for counting bytes with countr_zero / popcount. Credit: Danila Kutenin, "Porting x86 vector
/// bitmask optimizations to Arm NEON", Arm Community blog, 2022.
using U16x8 = uint16_t __attribute__((vector_size(16)));
using U8x8 = uint8_t __attribute__((vector_size(8)));
return __builtin_bit_cast(uint64_t, __builtin_convertvector(__builtin_bit_cast(U16x8, bytes) >> 4, U8x8));
#else
/// Clang lowers this to `pmovmskb` on x86.
using Bool16 = bool __attribute__((ext_vector_type(16)));
return __builtin_bit_cast(uint16_t, __builtin_convertvector(bytes, Bool16));
#endif
}
/// Value of the `n` <= 15 decimal digits at `p`, reading 16 bytes.
/// Uses parse_eight_digits_unrolled above (credit: @aqrit), which needs exactly 8 digits. Right-aligning a
/// shorter run behind leading zeros lets one or two such conversions handle any length without a loop.
inline uint64_t NO_SANITIZE_UNSIGNED_OVERFLOW parseDigits16(const char * p, unsigned n)
{
if (n == 0)
return 0;
/// Subtract '0' (0x30) from every byte, then shift the digits to the end so that zeros enter at the start.
/// Borrows only go up from the bytes after the digits, which are shifted out.
/// parse_eight_digits_unrolled subtracts '0' itself, so it is added back (the compiler folds both).
/// Runs of at most 8 digits, the common case, need a single 64-bit conversion.
if (n <= 8)
return parse_eight_digits_unrolled(((unalignedLoad<uint64_t>(p) - 0x3030303030303030) << (8 * (8 - n))) + 0x3030303030303030);
const unsigned __int128 zeros = (static_cast<unsigned __int128>(0x3030303030303030) << 64) | 0x3030303030303030;
const unsigned __int128 digits = (unalignedLoad<unsigned __int128>(p) - zeros) << (8 * (16 - n));
return parse_eight_digits_unrolled(static_cast<uint64_t>(digits) + 0x3030303030303030) * 100000000ULL
+ parse_eight_digits_unrolled(static_cast<uint64_t>(digits >> 64) + 0x3030303030303030);
}
/// Bytes that parseUnsignedFloatFromBuffer may read from the start of a token. The fraction's 16-byte load
/// starts at most 15 bytes in (at most 14 integer digits and the dot), so it ends at most 31 bytes in.
constexpr ptrdiff_t short_decimal_read_bytes = 31;
#endif
/// A pure decimal integer of up to 38 digits fits exactly in unsigned __int128, and the conversion
/// to double/float is correctly rounded. That is far cheaper than fast_float's big-integer path for
/// long inputs (e.g. 19-20 digit integers), and exactly as correct.
/// Returns true (and sets @x and @parse_end) on a pure integer; false to fall back otherwise
/// (decimal point, exponent, or more than 38 digits).
constexpr int max_u128_integer_digits = 38;
/// A value of at most this many characters has at most this many significant digits, so
/// fast_float's default from_chars (store_spans=false) never hits the too_many_digits double-parse
/// and is fastest. Longer inputs use the unsigned __int128 integer path or fromCharsLong.
constexpr ptrdiff_t max_short_float_chars = 19;
template <typename T>
inline bool tryReadLongIntegerToFloat(T & x, const char * first, const char * last, const char *& parse_end)
{
const char * p = first;
const char * const digits_begin = p;
unsigned __int128 value = 0;
/// Accumulate 8 digits at a time via SWAR (byteswap on big-endian; see parse_eight_digits_unrolled).
while (p + 8 <= last && is_made_of_eight_digits_fast(p))
{
/// Eight more digits would exceed what fits exactly, and the tail loop below rejects it.
if (p - digits_begin + 8 > max_u128_integer_digits)
break;
uint64_t chunk = 0;
::memcpy(&chunk, p, 8);
if constexpr (std::endian::native == std::endian::big)
chunk = std::byteswap(chunk);
value = value * 100000000ULL + parse_eight_digits_unrolled(chunk);
p += 8;
}
while (p < last && isNumericASCII(*p))
{
/// One digit too many: the value cannot be represented exactly, so stop before it overflows.
if (p - digits_begin >= max_u128_integer_digits)
return false;
value = value * 10 + static_cast<unsigned>(*p - '0');
++p;
}
const auto num_digits = p - digits_begin;
/// Not a pure integer (fraction/exponent follows), empty, or too many digits to fit exactly.
if (num_digits == 0 || num_digits > max_u128_integer_digits)
return false;
if (p < last && (*p == '.' || *p == 'e' || *p == 'E'))
return false;
x = static_cast<T>(value);
parse_end = p;
return true;
}
/// Correctly-rounded parse of a pure decimal integer with MORE than 38 significant digits (does not
/// fit in unsigned __int128). Such an input goes through fast_float's big-integer path, but
/// fast_float wastefully accumulates every digit and then recomputes the mantissa from the first 19.
/// Instead, build the parsed_number_string_t ourselves: accumulate only the first 19 significant
/// digits, then SWAR-skip (count) the rest, and hand the result to fast_float::from_chars_advanced,
/// which keeps the proven Eisel-Lemire + digit_comp rounding. Returns false (fall back) for
/// non-integers. This mirrors parse_number_string's too_many_digits semantics for an integer.
template <typename T>
inline bool tryReadBigIntegerToFloat(T & x, const char * first, const char * last, fast_float::from_chars_result_t<char> & result)
{
const char * p = first;
const char * const integer_begin = p;
while (p < last && *p == '0') /// leading zeros are part of the integer span but not significant
++p;
uint64_t mantissa = 0;
int significant = 0;
while (p < last && significant < 19 && isNumericASCII(*p))
{
mantissa = mantissa * 10 + static_cast<unsigned>(*p - '0');
++p;
++significant;
}
/// Count (do not accumulate) the remaining significant digits, 8 at a time.
const char * const rest_begin = p;
while (p + 8 <= last && is_made_of_eight_digits_fast(p))
p += 8;
while (p < last && isNumericASCII(*p))
++p;
/// Pure integer only; a fraction/exponent must go through the general parser.
if (p < last && (*p == '.' || *p == 'e' || *p == 'E'))
return false;
const auto total_significant = significant + (p - rest_begin);
if (total_significant <= max_u128_integer_digits) /// handled by the exact unsigned __int128 path
return false;
fast_float::parsed_number_string_t<char> pns;
pns.valid = true;
pns.too_many_digits = true;
pns.negative = false;
pns.mantissa = mantissa; /// first 19 significant digits, truncated
pns.exponent = total_significant - 19; /// integer scaling, matching parse_number_string
pns.lastmatch = p;
pns.integer = fast_float::span<const char>(integer_begin, static_cast<size_t>(p - integer_begin));
pns.fraction = fast_float::span<const char>(p, 0);
/// Return the backend result directly, including result_out_of_range (e.g. a >38-digit
/// integer that overflows Float32) — falling back to fromCharsLong would just re-scan and
/// reach the same error more slowly.
result = fast_float::from_chars_advanced(pns, x);
return true;
}
/// Variant of fast_float::from_chars tuned for inputs known to have many significant digits.
/// Built on fast_float's existing primitives (no fork of the library): parse once with the
/// integer/fraction spans materialized (store_spans=true) and run the full algorithm, so the
/// >19-significant-digit case is handled in one pass instead of from_chars's store_spans=false
/// hot path re-parsing the whole string.
template <typename T>
fast_float::from_chars_result_t<char>
fromCharsLong(const char * first, const char * last, T & value, fast_float::chars_format fmt)
{
const fast_float::parse_options_t<char> options(fmt);
const fast_float::chars_format adjusted = fast_float::detail::adjust_for_feature_macros(fmt);
auto pns = fast_float::parse_number_string<false, char>(first, last, options, /*store_spans=*/true);
if (!pns.valid)
{
if (uint64_t(adjusted & fast_float::chars_format::no_infnan))
{
fast_float::from_chars_result_t<char> answer{};
answer.ec = std::errc::invalid_argument;
answer.ptr = first;
return answer;
}
return fast_float::detail::parse_infnan(first, last, value, adjusted);
}
return fast_float::from_chars_advanced(pns, value);
}
/// Length, capped just past the 38-digit boundary, of the leading integer run at [first, last) --
/// i.e. the size of the integer token, NOT of the whole remaining buffer. The dispatch below must
/// classify by the token: a short token like "1" sitting in a large buffer (e.g. "1.5 GiB", or any
/// non-exact ReadBuffer) must still take the fast from_chars path. A '.', 'e' or 'E' right after the
/// digits means it is a fraction/exponent, not an integer, so we return max_short_float_chars to send
/// it to from_chars directly. The cap is enough to tell short / <=38-digit / longer integers apart;
/// the chosen parser still receives the real `last` and consumes the full token.
inline ptrdiff_t floatTokenClassLength(const char * first, const char * last)
{
const char * const scan_end = (last - first > max_u128_integer_digits + 2) ? first + (max_u128_integer_digits + 2) : last;
const char * p = first;
while (scan_end - p >= 8)
{
if (!is_made_of_eight_digits_fast(p))
{
/// A failure in either of the first two blocks implies a short integer run.
if (p - first < 16)
return max_short_float_chars;
break;
}
p += 8;
}
while (p < scan_end && isNumericASCII(*p))
++p;
/// A '.', 'e' or 'E' means this is not a pure integer, so neither integer fast path applies.
/// Classify it as short so the dispatch hands it to from_chars for a single-pass parse.
if (p < scan_end && (*p == '.' || *p == 'e' || *p == 'E'))
return max_short_float_chars;
return p - first;
}
/// The whole length-based dispatch for parsing a float from a contiguous [first, last) range,
/// shared by the no-copy and copy paths of readFloatTextPreciseImpl (inlined). Picks:
/// - short token (<= max_short_float_chars) -> fast_float::from_chars,
/// - long pure integer (<= 38 digits) -> unsigned __int128 (correctly rounded, cheap),
/// - otherwise (long fraction / huge integer) -> fromCharsLong (single parse).
/// On big-endian, fast_float parsing directly to float can misbehave, so parse as double and
/// narrow (the unsigned __int128 path is endian-independent and needs no such workaround).
/// The token must not have a sign: callers apply it themselves (see parseFloatFromBuffer).
template <typename T>
inline fast_float::from_chars_result_t<char>
parseFloatFromRange(T & x, const char * first, const char * last)
{
constexpr auto fmt = fast_float::chars_format::general;
/// Classify by the token length, but only scan when the buffer holds more than a short token's
/// worth of bytes (so short inputs cost nothing extra).
const auto length = (last - first <= max_short_float_chars) ? (last - first) : floatTokenClassLength(first, last);
if (length > max_short_float_chars)
{
/// <= 38-digit integer: exact via unsigned __int128 (always in range, so a plain success).
if (length <= max_u128_integer_digits + 1)
{
const char * int_end = nullptr;
if (tryReadLongIntegerToFloat(x, first, last, int_end))
{
fast_float::from_chars_result_t<char> answer{};
answer.ptr = int_end;
answer.ec = std::errc();
return answer;
}
}
/// Longer integer: build the parsed_number_string_t directly (lean wide scan) and use
/// fast_float's rounding backend; its result (incl. out-of-range) is returned as-is.
else
{
fast_float::from_chars_result_t<char> answer{};
if (tryReadBigIntegerToFloat(x, first, last, answer))
return answer;
}
}
const bool is_short = length <= max_short_float_chars;
if constexpr (std::endian::native == std::endian::little)
return is_short ? fast_float::from_chars(first, last, x, fmt)
: fromCharsLong(first, last, x, fmt);
else
{
Float64 wide = 0.0;
auto answer = is_short ? fast_float::from_chars(first, last, wide, fmt)
: fromCharsLong(first, last, wide, fmt);
x = static_cast<T>(wide);
return answer;
}
}
/// Sets the sign with a bit flip: a conditional negation compiles to a branch that mispredicts on columns
/// with mixed signs.
template <typename T>
ALWAYS_INLINE inline T withSign(T value, bool negative)
{
using Bits = std::conditional_t<sizeof(T) == 8, uint64_t, uint32_t>;
return std::bit_cast<T>(std::bit_cast<Bits>(value) ^ (Bits(negative) << (sizeof(T) * 8 - 1)));
}
/// Parses a float without a sign at the start of [first, last), which may continue far past the token.
/// A `digits[.digits]` token of at most 15 digits (7 for float) is parsed here. Such a mantissa and its power
/// of ten are exact in the type (10^15 < 2^53 for double, 10^7 < 2^24 for float), so one division is
/// correctly rounded: Clinger's fast path (William D. Clinger, "How to Read Floating Point Numbers
/// Accurately", PLDI 1990), with the same bounds as fast_float's clinger_fast_path_impl. It skips fast_float's
/// scan, which is a branch per digit. Anything else goes to fast_float directly, except a token starting with
/// 16 digits, which may be a long integer for the unsigned __int128 paths of parseFloatFromRange.
/// `padded` means at least 15 bytes after `last` are readable (ReadBuffer::isPadded), as in column data.
template <typename T>
ALWAYS_INLINE inline fast_float::from_chars_result_t<char>
parseUnsignedFloatFromBuffer(T & x, const char * first, const char * last, [[maybe_unused]] bool padded)
{
#if defined(__x86_64__) || defined(__aarch64__)
/// The byte masks assume little-endian lane order.
if (std::endian::native != std::endian::little || unlikely(last - first < short_decimal_read_bytes && !padded))
return parseFloatFromRange(x, first, last);
/// The token is the run of digits and dots at `first`.
using U8x16 = uint8_t __attribute__((vector_size(16)));
const auto bytes = unalignedLoad<U8x16>(first);
uint64_t digit_mask = byteMask16((bytes - '0') < 10);
uint64_t dot_mask = byteMask16(bytes == '.');
/// Bytes past `last` belong to the next value (e.g. the next row of a column): drop them from the token.
/// With them gone every later load ends within 15 bytes after `last`.
if (last - first < 16)
{
const uint64_t inside = (uint64_t(1) << ((last - first) * mask_bits_per_byte)) - 1;
digit_mask &= inside;
dot_mask &= inside;
}
const unsigned len = std::countr_zero(~(digit_mask | dot_mask)) / mask_bits_per_byte;
if (len >= 16)
{
/// Integers longer than max_short_float_chars are where the unsigned __int128 paths beat fast_float,
/// and they all start with 16 digits. Other long tokens have a dot early, and fast_float is faster
/// for them than parseFloatFromRange's own scan of the token.
constexpr uint64_t all_digits = mask_bits_per_byte == 1 ? 0xFFFF : ~uint64_t(0);
if (digit_mask == all_digits)
return parseFloatFromRange(x, first, last);
return fast_float::from_chars(first, last, x, fast_float::chars_format::general);
}
const unsigned num_digits = std::popcount(digit_mask & ((uint64_t(1) << (len * mask_bits_per_byte)) - 1)) / mask_bits_per_byte;
const unsigned int_len = std::countr_zero(~digit_mask) / mask_bits_per_byte;
const unsigned frac_len = num_digits - int_len;
const char * const end = first + len;
/// At most one dot (`len - num_digits` counts the dots; "1.2.3" is left to fast_float), at least one
/// digit, and no exponent (`| 0x20` maps 'E' to 'e').
constexpr unsigned max_digits = std::is_same_v<T, double> ? 15 : 7;
if (len - num_digits > 1 || num_digits == 0 || num_digits > max_digits || (end < last && (*end | 0x20) == 'e'))
return fast_float::from_chars(first, last, x, fast_float::chars_format::general);
const uint64_t mantissa = parseDigits16(first, int_len) * common::exp10_i64(frac_len) + parseDigits16(first + int_len + 1, frac_len);
x = static_cast<T>(static_cast<int64_t>(mantissa)) / static_cast<T>(common::exp10_i64(frac_len));
return {end, std::errc()};
#else
/// Elsewhere the vector comparisons are untested or do not compile (`vector bool` with AltiVec on ppc64le).
return parseFloatFromRange(x, first, last);
#endif
}
/// Parses a float at the start of [first, last), which may continue far past the token. The sign is taken
/// off before parsing and applied afterwards: fast_float's own sign test was the most mispredicted branch
/// parsing mixed-sign decimals (seen with `perf record -b`), and plain `general` (no `allow_leading_plus`)
/// selects fast_float's instantiation specialized for that format (fast_float PR 413).
template <typename T>
ALWAYS_INLINE inline fast_float::from_chars_result_t<char> parseFloatFromBuffer(T & x, const char * first, const char * last, bool padded)
{
const bool negative = *first == '-';
const char * const begin = first + (negative || *first == '+');
/// A lone sign or a second sign ("+-5", "--5") is invalid. Without a sign `*begin` is `*first`, which is
/// not a sign either, so this does not depend on whether there is one.
if (unlikely(begin == last || *begin == '-' || *begin == '+'))
return {first, std::errc::invalid_argument};
auto res = parseUnsignedFloatFromBuffer(x, begin, last, padded);
/// On a parse failure `x` is left as the caller passed it.
if (likely(res.ec == std::errc() || res.ec == std::errc::result_out_of_range))
x = withSign(x, negative);
return res;
}
constexpr int MAX_LENGTH = 316;
/// Out of line, so that building the message does not cost a stack frame on the fast path.
[[noreturn]] NO_INLINE void throwCannotParseFloat(const char * begin, const char * end)
{
throw Exception(ErrorCodes::CANNOT_PARSE_NUMBER, "Cannot read floating point value here: {}", String(begin, end - begin));
}
/// Slow path. Copy characters that may be present in floating point number to temporary buffer.
/// Out of line, so that the buffer does not cost a stack frame on the fast path.
template <typename T, typename ReturnType>
NO_INLINE ReturnType readFloatTextPreciseSlow(T & x, ReadBuffer & buf)
{
static constexpr bool throw_exception = std::is_same_v<ReturnType, void>;
bool negative = false;
/// We check eof here because we can parse +inf +nan
while (!buf.eof())
{
switch (*buf.position())
{
case '+':
++buf.position();
continue;
case '-':
{
negative = true;
++buf.position();
continue;
}
case 'i': [[fallthrough]];
case 'I':
{
if (assertOrParseInfinity<throw_exception>(buf))
{
x = std::numeric_limits<T>::infinity();
if (negative)
x = -x;
return ReturnType(true);
}
return ReturnType(false);
}
case 'n': [[fallthrough]];
case 'N':
{
if (assertOrParseNaN<throw_exception>(buf))
{
x = std::numeric_limits<T>::quiet_NaN();
if (negative)
x = -x;
return ReturnType(true);
}
return ReturnType(false);
}
default:
break;
}
break;
}
char tmp_buf[MAX_LENGTH];
int num_copied_chars = 0;
while (!buf.eof() && num_copied_chars < MAX_LENGTH)
{
char c = *buf.position();
if (!(isNumericASCII(c) || c == '-' || c == '+' || c == '.' || c == 'e' || c == 'E'))
break;
tmp_buf[num_copied_chars] = c;
++buf.position();
++num_copied_chars;
}
/// Sign was already consumed above (tracked in `negative`), so tmp_buf holds no leading sign.
auto res = parseFloatFromRange(x, tmp_buf, tmp_buf + num_copied_chars);
if (unlikely((res.ec != std::errc() && res.ec != std::errc::result_out_of_range) || res.ptr - tmp_buf != num_copied_chars))
{
if constexpr (throw_exception)
throw Exception(
ErrorCodes::CANNOT_PARSE_NUMBER, "Cannot read floating point value here: {}", String(tmp_buf, num_copied_chars));
else
return ReturnType(false);
}
if (negative)
x = -x;
return ReturnType(true);
}
template <typename T, typename ReturnType>
ReturnType readFloatTextPreciseImpl(T & x, ReadBuffer & buf)
{
static_assert(std::is_same_v<T, double> || std::is_same_v<T, float>, "Argument for readFloatTextPreciseImpl must be float or double");
static_assert('a' > '.' && 'A' > '.' && '\n' < '.' && '\t' < '.' && '\'' < '.' && '"' < '.', "Layout of char is not like ASCII");
static constexpr bool throw_exception = std::is_same_v<ReturnType, void>;
/// Fast path (avoid copying) if the buffer has at least MAX_LENGTH bytes or the whole input is in memory.
/// The bounds check comes first, so the virtual isMemoryBuffer() is only called near the end of the buffer.
if (likely(!buf.eof() && (buf.buffer().end() - buf.position() >= MAX_LENGTH || buf.isMemoryBuffer())))
{
auto * initial_position = buf.position();
auto * const buf_end = buf.buffer().end();
auto res = parseFloatFromBuffer(x, initial_position, buf_end, buf.isPadded());
/// result_out_of_range means overflow/underflow: fast_float has already set x to +-inf or +-0,
/// matching strtod semantics. Only a genuine parse failure is an error.
if (unlikely(res.ec != std::errc() && res.ec != std::errc::result_out_of_range))
{
if constexpr (throw_exception)
throwCannotParseFloat(initial_position, buf_end);
else
return ReturnType(false);
}
buf.position() += res.ptr - initial_position;
return ReturnType(true);
}
return readFloatTextPreciseSlow<T, ReturnType>(x, buf);
}
template <size_t N, typename T>
inline void readUIntTextUpToNSignificantDigits(T & x, ReadBuffer & buf)
{
/// In optimistic case we can skip bound checking for first loop.
if (buf.position() + N <= buf.buffer().end())
{
for (size_t i = 0; i < N; ++i)
{
if (isNumericASCII(*buf.position()))
{
x *= 10;
x += *buf.position() & 0x0F;
++buf.position();
}
else
return;
}
}
else
{
for (size_t i = 0; i < N; ++i)
{
if (!buf.eof() && isNumericASCII(*buf.position()))
{
x *= 10;
x += *buf.position() & 0x0F;
++buf.position();
}
else
return;
}
}
while (!buf.eof() && (buf.position() + 8 <= buf.buffer().end()) && is_made_of_eight_digits_fast(buf.position()))
buf.position() += 8;
while (!buf.eof() && isNumericASCII(*buf.position()))
++buf.position();
}
template <typename T, typename ReturnType, bool allow_exponent = true>
ReturnType NO_SANITIZE_UNSIGNED_OVERFLOW readFloatTextFastImpl(T & x, ReadBuffer & in, bool & has_fractional)
{
static_assert(std::is_same_v<T, double> || std::is_same_v<T, float>, "Argument for readFloatTextImpl must be float or double");
static_assert('a' > '.' && 'A' > '.' && '\n' < '.' && '\t' < '.' && '\'' < '.' && '"' < '.', "Layout of char is not like ASCII");
has_fractional = false;
static constexpr bool throw_exception = std::is_same_v<ReturnType, void>;
bool negative = false;
x = 0;
UInt64 before_point = 0;
UInt64 after_point = 0;
int after_point_exponent = 0;
int exponent = 0;
if (in.eof())
{
if constexpr (throw_exception)
throw Exception(ErrorCodes::CANNOT_PARSE_NUMBER, "Cannot read floating point value");
else
return false;
}
if (*in.position() == '-')
{
negative = true;
++in.position();
}
else if (*in.position() == '+')
++in.position();
auto count_after_sign = in.count();
constexpr int significant_digits = std::numeric_limits<UInt64>::digits10;
readUIntTextUpToNSignificantDigits<significant_digits>(before_point, in);
size_t read_digits = in.count() - count_after_sign;
if (unlikely(read_digits > significant_digits))
{
int before_point_additional_exponent = static_cast<int>(read_digits) - significant_digits;
x = static_cast<T>(shift10(before_point, before_point_additional_exponent));
}
else
{
x = static_cast<T>(before_point);
/// Shortcut for the common case when there is an integer that fit in Int64.
if (read_digits && (in.eof() || *in.position() < '.'))
{
if (negative)
x = -x;
return ReturnType(true);
}
}
if (checkChar('.', in))
{
has_fractional = true;
auto after_point_count = in.count();
while (!in.eof() && *in.position() == '0')
++in.position();
auto after_leading_zeros_count = in.count();
int after_point_num_leading_zeros = static_cast<int>(after_leading_zeros_count - after_point_count);
readUIntTextUpToNSignificantDigits<significant_digits>(after_point, in);
read_digits = in.count() - after_leading_zeros_count;
after_point_exponent = (read_digits > significant_digits ? -significant_digits : static_cast<int>(-read_digits)) - after_point_num_leading_zeros;
}
if constexpr (allow_exponent)
{
if (checkChar('e', in) || checkChar('E', in))
{
has_fractional = true;
if (in.eof())
{
if constexpr (throw_exception)
throw Exception(ErrorCodes::CANNOT_PARSE_NUMBER, "Cannot read floating point value: nothing after exponent");
else
return false;
}
bool exponent_negative = false;
if (*in.position() == '-')
{
exponent_negative = true;
++in.position();
}
else if (*in.position() == '+')
{
++in.position();
}
readUIntTextUpToNSignificantDigits<4>(exponent, in);
if (exponent_negative)
exponent = -exponent;
}
}
if (after_point)
{
x += static_cast<T>(shift10(after_point, after_point_exponent));
}
if (exponent)
{
x = static_cast<T>(shift10(x, exponent));
}
if (negative)
x = -x;
auto num_characters_without_sign = in.count() - count_after_sign;
/// Denormals. At most one character is read before denormal and it is '-'.
if (num_characters_without_sign == 0)
{
if (in.eof())
{
if constexpr (throw_exception)
throw Exception(ErrorCodes::CANNOT_PARSE_NUMBER, "Cannot read floating point value: no digits read");
else
return false;
}
if (*in.position() == '+')
{
++in.position();
if (in.eof())
{
if constexpr (throw_exception)
throw Exception(ErrorCodes::CANNOT_PARSE_NUMBER, "Cannot read floating point value: nothing after plus sign");
else
return false;
}
else if (negative)
{
if constexpr (throw_exception)
throw Exception(ErrorCodes::CANNOT_PARSE_NUMBER, "Cannot read floating point value: plus after minus sign");
else
return false;
}
}
if (*in.position() == 'i' || *in.position() == 'I')
{
if (assertOrParseInfinity<throw_exception>(in))
{
x = std::numeric_limits<T>::infinity();
if (negative)
x = -x;
return ReturnType(true);
}
return ReturnType(false);
}
if (*in.position() == 'n' || *in.position() == 'N')
{
if (assertOrParseNaN<throw_exception>(in))
{
x = std::numeric_limits<T>::quiet_NaN();
if (negative)
x = -x;
return ReturnType(true);
}
return ReturnType(false);
}
}
return ReturnType(true);
}
template <typename T, typename ReturnType>
ReturnType readFloatTextSimpleImpl(T & x, ReadBuffer & buf)
{
static constexpr bool throw_exception = std::is_same_v<ReturnType, void>;
bool negative = false;
x = 0;
bool after_point = false;
T power_of_ten = 1;
if (buf.eof())
throwReadAfterEOF();
while (!buf.eof())
{
switch (*buf.position())
{
case '+':
break;
case '-':
negative = true;
break;
case '.':
after_point = true;
break;
case '0': [[fallthrough]];
case '1': [[fallthrough]];
case '2': [[fallthrough]];
case '3': [[fallthrough]];
case '4': [[fallthrough]];
case '5': [[fallthrough]];
case '6': [[fallthrough]];
case '7': [[fallthrough]];
case '8': [[fallthrough]];
case '9':
if (after_point)
{
power_of_ten /= 10;
x += (*buf.position() - '0') * power_of_ten;
}
else
{
x *= 10;
x += *buf.position() - '0';
}
break;
case 'e': [[fallthrough]];
case 'E':
{
++buf.position();
Int32 exponent = 0;
readIntText(exponent, buf);
x = shift10(x, exponent);
if (negative)
x = -x;
return ReturnType(true);
}
case 'i': [[fallthrough]];
case 'I':
{
if (assertOrParseInfinity<throw_exception>(buf))
{
x = std::numeric_limits<T>::infinity();
if (negative)
x = -x;
return ReturnType(true);
}
return ReturnType(false);
}
case 'n': [[fallthrough]];
case 'N':
{
if (assertOrParseNaN<throw_exception>(buf))
{
x = std::numeric_limits<T>::quiet_NaN();
if (negative)
x = -x;
return ReturnType(true);
}
return ReturnType(false);
}
default:
{
if (negative)
x = -x;
return ReturnType(true);
}
}
++buf.position();
}
if (negative)
x = -x;
return ReturnType(true);
}
}
template <typename T> void readFloatTextPrecise(T & x, ReadBuffer & in)
{
if constexpr (std::is_same_v<T, BFloat16>)
{
Float32 tmp = 0;
readFloatTextPreciseImpl<Float32, void>(tmp, in);
x = BFloat16(tmp);
}
else
readFloatTextPreciseImpl<T, void>(x, in);
}
template <typename T> bool tryReadFloatTextPrecise(T & x, ReadBuffer & in)
{
if constexpr (std::is_same_v<T, BFloat16>)
{
Float32 tmp = 0;
bool res = readFloatTextPreciseImpl<Float32, bool>(tmp, in);
if (res)
x = BFloat16(tmp);
return res;
}
else
return readFloatTextPreciseImpl<T, bool>(x, in);
}
template <typename T> void readFloatImpreciseForCompatibility(T & x, ReadBuffer & in)
{
bool has_fractional = false;
if constexpr (std::is_same_v<T, BFloat16>)
{
Float32 tmp = 0;
readFloatTextFastImpl<Float32, void>(tmp, in, has_fractional);
x = BFloat16(tmp);
}
else
readFloatTextFastImpl<T, void>(x, in, has_fractional);
}
template <typename T> bool tryReadFloatImpreciseForCompatibility(T & x, ReadBuffer & in)
{
bool has_fractional = false;
if constexpr (std::is_same_v<T, BFloat16>)
{
Float32 tmp = 0;
bool res = readFloatTextFastImpl<Float32, bool>(tmp, in, has_fractional);
if (res)
x = BFloat16(tmp);
return res;
}
else
return readFloatTextFastImpl<T, bool>(x, in, has_fractional);