smarter_csv 1.17.4 → 1.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,6 +7,14 @@
7
7
  #include <stdlib.h>
8
8
  #include <errno.h>
9
9
 
10
+ #ifdef __ARM_NEON
11
+ #include <arm_neon.h>
12
+ #elif defined(__SSE2__)
13
+ #include <immintrin.h>
14
+ #endif
15
+
16
+ #include "vendor/eisel_lemire.h" /* Eisel-Lemire decimal->double, correctly rounded (fast_float) */
17
+
10
18
  #ifndef bool
11
19
  #define bool int
12
20
  #define false ((bool)0)
@@ -41,6 +49,8 @@ static ID id_only, id_except, id_quote_boundary;
41
49
  static ID id_only_headers, id_except_headers, id_keep_cols, id_strict;
42
50
  static ID id_keep_bitmap, id_keep_extra_cols, id_early_exit_after_sym;
43
51
  static ID id_backslash, id_standard;
52
+ static ID id_decimal_precision, id_float, id_bigdecimal;
53
+ static ID id_BigDecimal; /* the Kernel#BigDecimal() method (require 'bigdecimal' done in Ruby) */
44
54
 
45
55
  /* ================================================================================
46
56
  * ParseContext — wraps all per-file parse options as a GC-managed TypedData object.
@@ -70,6 +80,9 @@ typedef struct {
70
80
  /* Numeric conversion: 0=off, 1=all, 2=only listed keys, 3=except listed keys */
71
81
  int numeric_mode;
72
82
 
83
+ /* Decimal handling: 0=float, 1=auto (BigDecimal above 16 sig digits), 2=bigdecimal */
84
+ int decimal_precision;
85
+
73
86
  /* Column filter bitmap (xmalloc'd; NULL when no filtering active) */
74
87
  bool *keep_bitmap;
75
88
  long keep_bitmap_len;
@@ -133,6 +146,51 @@ static const rb_data_type_t parse_context_type = {
133
146
  RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
134
147
  };
135
148
 
149
+ /* Scan [p, end) for the first `quote` char or backslash; returns a pointer to it,
150
+ * or `end` if neither occurs. NEON (arm64) or SSE2 (x86-64) processes 16 bytes per
151
+ * iteration; scalar fallback elsewhere. Ported from smarter_json's fj_scan_str.
152
+ *
153
+ * Used by the quoted-field slow path in :backslash escaping mode, where the only bytes
154
+ * that can change parser state inside a quoted field are the quote char (closing /
155
+ * doubled) and the backslash (escape). Bulk-skipping the plain content between them
156
+ * keeps the byte-by-byte state machine's behavior but avoids stepping every byte.
157
+ * In RFC mode the slow path uses a plain memchr-to-quote instead (only one byte class
158
+ * matters there), so this two-class scan is reserved for backslash mode. */
159
+ static inline const char *scan_quote_or_backslash(const char *p, const char *end, char quote) {
160
+ #ifdef __ARM_NEON
161
+ const uint8x16_t vq = vdupq_n_u8((uint8_t)quote);
162
+ const uint8x16_t vbs = vdupq_n_u8((uint8_t)'\\');
163
+ while (p + 16 <= end) {
164
+ uint8x16_t chunk = vld1q_u8((const uint8_t *)p);
165
+ uint8x16_t m = vorrq_u8(vceqq_u8(chunk, vq), vceqq_u8(chunk, vbs));
166
+ /* movemask emulation (Oj's technique): pack to 4 bits/byte, then ctz/4. */
167
+ uint8x8_t res = vshrn_n_u16(vreinterpretq_u16_u8(m), 4);
168
+ uint64_t mask = vget_lane_u64(vreinterpret_u64_u8(res), 0);
169
+ if (__builtin_expect(mask != 0, 0)) { /* most 16-byte chunks contain neither */
170
+ mask &= 0x8888888888888888ull;
171
+ return p + (__builtin_ctzll(mask) >> 2);
172
+ }
173
+ p += 16;
174
+ }
175
+ #elif defined(__SSE2__)
176
+ const __m128i vq = _mm_set1_epi8(quote);
177
+ const __m128i vbs = _mm_set1_epi8('\\');
178
+ while (p + 16 <= end) {
179
+ __m128i chunk = _mm_loadu_si128((const __m128i *)p);
180
+ __m128i m = _mm_or_si128(_mm_cmpeq_epi8(chunk, vq), _mm_cmpeq_epi8(chunk, vbs));
181
+ int mask = _mm_movemask_epi8(m); /* one bit per byte that matched */
182
+ if (__builtin_expect(mask != 0, 0)) { /* most 16-byte chunks contain neither */
183
+ return p + __builtin_ctz(mask);
184
+ }
185
+ p += 16;
186
+ }
187
+ #endif
188
+ for (; p < end; p++) {
189
+ if (*p == quote || *p == '\\') return p;
190
+ }
191
+ return end;
192
+ }
193
+
136
194
  static VALUE unescape_quotes(char *str, long len, char quote_char, rb_encoding *encoding) {
137
195
  // Fast path: scan for any doubled quote pair. If none present, the field has
138
196
  // nothing to unescape — emit it directly via rb_enc_str_new and skip the
@@ -386,6 +444,20 @@ static VALUE rb_parse_csv_line(VALUE self, VALUE line, VALUE col_sep, VALUE quot
386
444
  backslash_count = 0;
387
445
  field_started = false; // reset for next field
388
446
  } else {
447
+ /* Backslash mode: NEON scan-ahead to the next quote OR backslash (Opt #7).
448
+ * Inside a quoted field the only state-changing bytes are the quote char and the
449
+ * backslash; bulk-skip the plain content between them. Skipped bytes are plain
450
+ * content, which the byte-by-byte loop resets backslash_count to 0 on, so reset
451
+ * it here whenever we actually move p. */
452
+ if (allow_escaped_quotes && in_quotes) {
453
+ const char *hit = scan_quote_or_backslash(p, endP, quote_char_val);
454
+ if (hit != p) {
455
+ backslash_count = 0;
456
+ p = (char *)hit;
457
+ if (p == endP) continue; /* no quote/backslash before end → unclosed */
458
+ }
459
+ }
460
+
389
461
  if (allow_escaped_quotes && *p == '\\') {
390
462
  backslash_count++;
391
463
  if (__builtin_expect(quote_boundary_standard, 1) && !in_quotes) field_started = true;
@@ -525,47 +597,101 @@ static inline VALUE get_key_for_index(long index, VALUE headers, long headers_le
525
597
  * Handles overflow: if strtol overflows (ERANGE), falls back to rb_cstr_to_inum
526
598
  * which produces a Ruby Bignum.
527
599
  */
528
- static inline VALUE try_numeric_conversion(char *trim_start, long trimmed_len) {
529
- // Quick pre-check: first char must be digit, +, -, or .
530
- char first = trim_start[0];
531
- if (!((first >= '0' && first <= '9') || first == '+' || first == '-' || first == '.')) {
600
+ static inline VALUE try_numeric_conversion(char *s, long n, int decimal_precision) {
601
+ // Quick pre-check: first char must be a digit or a sign.
602
+ char first = s[0];
603
+ if (!((first >= '0' && first <= '9') || first == '+' || first == '-')) {
532
604
  return Qundef;
533
605
  }
534
606
 
535
- // Need null-terminated string for strtol/strtod; use stack buffer for typical fields
536
- if (trimmed_len >= 63) return Qundef; // very long fields are unlikely to be simple numbers
537
-
538
- char num_buf[64];
539
- memcpy(num_buf, trim_start, trimmed_len);
540
- num_buf[trimmed_len] = '\0';
541
-
542
- char *endptr;
543
-
544
- // Try integer first (most common numeric type in CSV)
545
- // Don't try integer if field starts with '.' (e.g., ".5")
546
- if (first != '.') {
547
- errno = 0;
548
- long int_val = strtol(num_buf, &endptr, 10);
549
- if (endptr == num_buf + trimmed_len) {
550
- // Entire string was consumed valid integer
551
- if (errno == ERANGE) {
552
- // Overflow: fall back to Ruby Bignum
553
- return rb_cstr_to_inum(num_buf, 10, false);
607
+ /* Single pass: validate the token against the same grammar as the Ruby path's
608
+ * NUMERIC_REGEX = /\A[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\z/ and, in the same pass,
609
+ * extract everything the fast paths need:
610
+ * - mantissa value m10 (exact for <= 18 digits; `overflow` flags beyond)
611
+ * - significant-digit count `sig` (leading zeros excluded; matches the Ruby
612
+ * significant_digits helper / Oj dec_cnt) — drives the :auto Float/BigDecimal split
613
+ * - base-10 exponent e10 (from the fraction length and any explicit exponent)
614
+ * Anything the grammar rejects returns Qundef (stays a String), keeping the C and
615
+ * Ruby paths byte-identical on what does and does not convert. */
616
+ long i = 0;
617
+ int neg = 0;
618
+ if (s[i] == '+' || s[i] == '-') { neg = (s[i] == '-'); i++; }
619
+
620
+ uint64_t m10 = 0;
621
+ int m10digits = 0; /* mantissa digits accumulated into m10 (capped at 19) */
622
+ long sig = 0; /* significant digits (leading zeros excluded) */
623
+ int sig_started = 0;
624
+ bool overflow = false;
625
+ long int_digits = 0, frac_digits = 0;
626
+ bool seen_dot = false, seen_exp = false, any_digit = false, exp_any = false;
627
+ int64_t exp_val = 0; int exp_neg = 0;
628
+
629
+ for (; i < n; i++) {
630
+ char c = s[i];
631
+ if (c >= '0' && c <= '9') {
632
+ any_digit = true;
633
+ if (!seen_exp) {
634
+ if (seen_dot) frac_digits++; else int_digits++;
635
+ if (sig_started) sig++;
636
+ else if (c != '0') { sig_started = 1; sig = 1; }
637
+ if (m10digits < 19) { m10 = m10 * 10 + (uint64_t)(c - '0'); m10digits++; }
638
+ else overflow = true;
639
+ } else {
640
+ exp_any = true;
641
+ exp_val = exp_val * 10 + (c - '0');
642
+ if (exp_val > 1000000) overflow = true; /* extreme exponent → strtod fallback */
554
643
  }
555
- return LONG2NUM(int_val);
644
+ } else if (c == '.' && !seen_dot && !seen_exp) {
645
+ seen_dot = true;
646
+ } else if ((c == 'e' || c == 'E') && !seen_exp && any_digit) {
647
+ seen_exp = true;
648
+ if (i + 1 < n && (s[i + 1] == '+' || s[i + 1] == '-')) { exp_neg = (s[i + 1] == '-'); i++; }
649
+ } else {
650
+ return Qundef; /* invalid char for a number → not numeric */
556
651
  }
557
652
  }
558
653
 
559
- // Try float (only if contains '.')
560
- if (memchr(num_buf, '.', trimmed_len)) {
561
- errno = 0;
562
- double float_val = strtod(num_buf, &endptr);
563
- if (endptr == num_buf + trimmed_len && errno != ERANGE) {
564
- return DBL2NUM(float_val);
654
+ /* Enforce NUMERIC_REGEX exactly: an integer part is required; a dot requires a
655
+ * fraction digit; an exponent requires an exponent digit. */
656
+ if (int_digits == 0) return Qundef;
657
+ if (seen_dot && frac_digits == 0) return Qundef;
658
+ if (seen_exp && !exp_any) return Qundef;
659
+
660
+ bool is_decimal = seen_dot || seen_exp;
661
+
662
+ if (!is_decimal) {
663
+ /* Integer. Fast path when it fits in a long; otherwise a Ruby Integer/Bignum. */
664
+ if (!overflow && m10digits <= 18) {
665
+ long v = (long)m10;
666
+ return LONG2NUM(neg ? -v : v);
565
667
  }
668
+ VALUE str = rb_str_new(s, n);
669
+ return rb_cstr_to_inum(RSTRING_PTR(str), 10, false);
566
670
  }
567
671
 
568
- return Qundef; // not numeric
672
+ /* Decimal (has a '.' or an exponent) — honor decimal_precision. 0=float, 1=auto, 2=bigdecimal */
673
+ if (decimal_precision == 2 || (decimal_precision == 1 && sig > 16)) {
674
+ VALUE str = rb_str_new(s, n);
675
+ return rb_funcall(rb_cObject, id_BigDecimal, 1, str);
676
+ }
677
+
678
+ /* Float. base-10 exponent = explicit exponent minus the fraction length. */
679
+ int64_t e10 = (exp_neg ? -exp_val : exp_val) - (int64_t)frac_digits;
680
+ double d;
681
+ if (!overflow && m10digits >= 1 && m10digits <= 19 && ((long)m10digits + e10) >= -307) {
682
+ /* Eisel-Lemire is correctly-rounded for any nonzero mantissa that fits exactly in a
683
+ * uint64 — i.e. up to 19 significant digits (the max 19-digit value ~1.0e19 is below
684
+ * UINT64_MAX ~1.8e19). Verified bit-for-bit vs the stdlib over 1..19-digit ties. */
685
+ d = (m10 == 0) ? (neg ? -0.0 : 0.0) : fj_eisel_lemire_s2d(e10, m10, neg);
686
+ } else {
687
+ /* >19 digits / extreme or subnormal exponent: fall back to Ruby's own correctly-rounded
688
+ * strtod (rb_cstr_to_dbl) — the exact conversion String#to_f uses — so the C path and the
689
+ * Ruby path produce the identical double on every platform, not just where the system
690
+ * strtod happens to be correctly rounded. The token is pre-validated, so badcheck=0. */
691
+ VALUE str = rb_str_new(s, n);
692
+ d = rb_cstr_to_dbl(RSTRING_PTR(str), 0);
693
+ }
694
+ return DBL2NUM(d);
569
695
  }
570
696
 
571
697
  /*
@@ -614,6 +740,7 @@ typedef struct {
614
740
  long headers_len;
615
741
  long hash_capa; // Pre-computed capacity for lazy hash allocation
616
742
  int numeric_mode; // 0=off, 1=all, 2=only, 3=except
743
+ int decimal_precision; // 0=float, 1=auto (BigDecimal above 16 sig digits), 2=bigdecimal
617
744
  bool remove_empty_values;
618
745
  bool remove_zero_values;
619
746
  } field_transform_opts;
@@ -705,7 +832,7 @@ static inline __attribute__((always_inline)) bool insert_field_into_hash(
705
832
  (opts->numeric_mode == 2 && rb_ary_includes(opts->numeric_keys, key) == Qtrue) ||
706
833
  (opts->numeric_mode == 3 && rb_ary_includes(opts->numeric_keys, key) != Qtrue);
707
834
  if (do_convert) {
708
- VALUE numeric = try_numeric_conversion(trim_start, trimmed_len);
835
+ VALUE numeric = try_numeric_conversion(trim_start, trimmed_len, opts->decimal_precision);
709
836
  if (numeric != Qundef) {
710
837
  ensure_hash_allocated(opts);
711
838
  rb_hash_aset(opts->hash, key, numeric);
@@ -752,6 +879,18 @@ void parse_numeric_option(VALUE options_hash, int *out_mode, VALUE *out_keys) {
752
879
  }
753
880
  }
754
881
 
882
+ /* Read decimal_precision into 0=float, 1=auto, 2=bigdecimal. Default :auto (1).
883
+ * The option is validated and coerced to a symbol on the Ruby side before we get here. */
884
+ static inline int parse_decimal_precision(VALUE options_hash) {
885
+ VALUE v = rb_hash_aref(options_hash, ID2SYM(id_decimal_precision));
886
+ if (RB_TYPE_P(v, T_SYMBOL)) {
887
+ ID s = SYM2ID(v);
888
+ if (s == id_float) return 0;
889
+ if (s == id_bigdecimal) return 2;
890
+ }
891
+ return 1; // :auto (also the default when unset)
892
+ }
893
+
755
894
  /*
756
895
  * ================================================================================
757
896
  * rb_parse_line_to_hash - Parse CSV line directly into a Ruby Hash
@@ -826,6 +965,7 @@ __attribute__((hot)) static VALUE rb_parse_line_to_hash(VALUE self, VALUE line,
826
965
  int numeric_mode = 0;
827
966
  VALUE numeric_keys = Qnil;
828
967
  parse_numeric_option(options_hash, &numeric_mode, &numeric_keys);
968
+ int decimal_precision = parse_decimal_precision(options_hash);
829
969
 
830
970
  // quote_escaping and quote_boundary are only needed in Section 5 (quoted/slow path).
831
971
  // They are declared here as forward declarations so Section 5 can set them lazily.
@@ -990,6 +1130,7 @@ __attribute__((hot)) static VALUE rb_parse_line_to_hash(VALUE self, VALUE line,
990
1130
  .headers_len = headers_len,
991
1131
  .hash_capa = hash_size,
992
1132
  .numeric_mode = numeric_mode,
1133
+ .decimal_precision = decimal_precision,
993
1134
  .remove_empty_values = remove_empty_values,
994
1135
  .remove_zero_values = remove_zero_values,
995
1136
  };
@@ -1160,6 +1301,20 @@ __attribute__((hot)) static VALUE rb_parse_line_to_hash(VALUE self, VALUE line,
1160
1301
  p = next_quote; /* jump to quote char; fall through to quote-handling code */
1161
1302
  }
1162
1303
 
1304
+ /* Backslash mode: NEON scan-ahead to the next quote OR backslash (Opt #7).
1305
+ * The RFC memchr skip above only matters for one byte class; with escaping on
1306
+ * a backslash also changes state, so scan for both. Skipped bytes are plain
1307
+ * content (the byte-by-byte loop resets backslash_count to 0 on them), so reset
1308
+ * it here whenever we actually move p. */
1309
+ if (allow_escaped_quotes && in_quotes) {
1310
+ const char *hit = scan_quote_or_backslash(p, endP, quote_char_val);
1311
+ if (hit != p) {
1312
+ backslash_count = 0;
1313
+ p = (char *)hit;
1314
+ if (p == endP) continue; /* no quote/backslash before end → unclosed */
1315
+ }
1316
+ }
1317
+
1163
1318
  if (allow_escaped_quotes && *p == '\\') {
1164
1319
  // Count consecutive backslashes for escape sequence detection
1165
1320
  backslash_count++;
@@ -1354,6 +1509,7 @@ __attribute__((cold)) static VALUE rb_new_parse_context(VALUE self, VALUE header
1354
1509
 
1355
1510
  /* Numeric conversion */
1356
1511
  parse_numeric_option(options_hash, &ctx->numeric_mode, &ctx->numeric_keys);
1512
+ ctx->decimal_precision = parse_decimal_precision(options_hash);
1357
1513
 
1358
1514
  /* quote_escaping → allow_escaped_quotes */
1359
1515
  VALUE quote_escaping_val = rb_hash_aref(options_hash, ID2SYM(id_quote_escaping));
@@ -1474,6 +1630,7 @@ __attribute__((hot)) static VALUE rb_parse_line_to_hash_ctx(VALUE self, VALUE li
1474
1630
  bool remove_empty_values = ctx->remove_empty_values;
1475
1631
  bool remove_zero_values = ctx->remove_zero_values;
1476
1632
  int numeric_mode = ctx->numeric_mode;
1633
+ int decimal_precision = ctx->decimal_precision;
1477
1634
  VALUE numeric_keys = ctx->numeric_keys;
1478
1635
  bool *keep_bitmap = ctx->keep_bitmap;
1479
1636
  /* keep_bitmap is cached in the context (xmalloc'd once at construction, sized to the header count
@@ -1525,6 +1682,7 @@ __attribute__((hot)) static VALUE rb_parse_line_to_hash_ctx(VALUE self, VALUE li
1525
1682
  .headers_len = headers_len,
1526
1683
  .hash_capa = hash_size,
1527
1684
  .numeric_mode = numeric_mode,
1685
+ .decimal_precision = decimal_precision,
1528
1686
  .remove_empty_values = remove_empty_values,
1529
1687
  .remove_zero_values = remove_zero_values,
1530
1688
  };
@@ -1654,6 +1812,16 @@ __attribute__((hot)) static VALUE rb_parse_line_to_hash_ctx(VALUE self, VALUE li
1654
1812
  p = next_quote; /* fall through to quote-handling code */
1655
1813
  }
1656
1814
 
1815
+ /* Backslash mode: NEON scan-ahead to the next quote OR backslash (Opt #7). */
1816
+ if (allow_escaped_quotes && in_quotes) {
1817
+ const char *hit = scan_quote_or_backslash(p, endP, quote_char_val);
1818
+ if (hit != p) {
1819
+ backslash_count = 0;
1820
+ p = (char *)hit;
1821
+ if (p == endP) continue; /* no quote/backslash before end → unclosed */
1822
+ }
1823
+ }
1824
+
1657
1825
  if (allow_escaped_quotes && *p == '\\') {
1658
1826
  backslash_count++;
1659
1827
  if (__builtin_expect(quote_boundary_standard, 1) && !in_quotes) field_started = true;
@@ -1878,6 +2046,10 @@ void Init_smarter_csv(void) {
1878
2046
  id_strict = rb_intern("strict");
1879
2047
  id_backslash = rb_intern("backslash");
1880
2048
  id_standard = rb_intern("standard");
2049
+ id_decimal_precision = rb_intern("decimal_precision");
2050
+ id_float = rb_intern("float");
2051
+ id_bigdecimal = rb_intern("bigdecimal");
2052
+ id_BigDecimal = rb_intern("BigDecimal"); /* Kernel#BigDecimal(); 'bigdecimal' is required in lib/smarter_csv.rb */
1881
2053
 
1882
2054
  rb_define_module_function(Parser, "parse_csv_line_c", rb_parse_csv_line, 9);
1883
2055
  rb_define_module_function(Parser, "count_quote_chars_c", rb_count_quote_chars, 4);
@@ -0,0 +1,27 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 The fast_float authors
4
+
5
+ Permission is hereby granted, free of charge, to any
6
+ person obtaining a copy of this software and associated
7
+ documentation files (the "Software"), to deal in the
8
+ Software without restriction, including without
9
+ limitation the rights to use, copy, modify, merge,
10
+ publish, distribute, sublicense, and/or sell copies of
11
+ the Software, and to permit persons to whom the Software
12
+ is furnished to do so, subject to the following
13
+ conditions:
14
+
15
+ The above copyright notice and this permission notice
16
+ shall be included in all copies or substantial portions
17
+ of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
20
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
21
+ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
22
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
23
+ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
24
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
26
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27
+ DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,117 @@
1
+ /* Eisel-Lemire decimal->double, ported from fast_float:
2
+ * include/fast_float/decimal_to_binary.h, the compute_float<binary_format<double>>
3
+ * + compute_product_approximation routines.
4
+ *
5
+ * Algorithm authors: Michael Eisel (original approach) and Daniel Lemire
6
+ * (formalization, proof, and the fast_float implementation) — hence "Eisel-Lemire".
7
+ *
8
+ * Copyright (c) 2021 The fast_float authors. Tri-licensed Apache-2.0 / MIT / BSL-1.0;
9
+ * used here under MIT — see LICENSE-fast_float-MIT in this directory.
10
+ *
11
+ * This is the "without fallback" variant (Noble Mushtak & Daniel Lemire, "Fast
12
+ * Number Parsing Without Fallback"): for ANY nonzero mantissa w that fits exactly
13
+ * in a uint64 (i.e. <= 19 significant digits, not truncated) and decimal exponent
14
+ * q, it returns the correctly-rounded binary64 with no slow-path needed.
15
+ *
16
+ * smarter_json uses it as THE decimal->double path for mantissas up to 18 digits
17
+ * (everything wider / overflowed / with an extreme exponent goes to the strtod
18
+ * round-to-odd fallback). It is correctly-rounded across that whole range, with no
19
+ * round-to-even tie loss, and is fast on the common short-mantissa case.
20
+ * Verified bit-for-bit vs JSON.parse. See eisel_lemire.md for provenance. */
21
+ #ifndef FJ_EISEL_LEMIRE_H
22
+ #define FJ_EISEL_LEMIRE_H
23
+
24
+ #include <stdint.h>
25
+ #include <string.h>
26
+ #include "eisel_lemire_powers.h"
27
+
28
+ /* binary_format<double> constants from fast_float. */
29
+ #define FJ_EL_MANTISSA_BITS 52
30
+ #define FJ_EL_MIN_EXPONENT (-1023)
31
+ #define FJ_EL_INFINITE_POWER 0x7FF
32
+ #define FJ_EL_SMALLEST_POW10 (-342)
33
+ #define FJ_EL_LARGEST_POW10 308
34
+ #define FJ_EL_MIN_RTE (-4) /* min_exponent_round_to_even */
35
+ #define FJ_EL_MAX_RTE 23 /* max_exponent_round_to_even */
36
+
37
+ /* (((152170 + 65536) * q) >> 16) + 63 == floor(log2(10^q)) + q + 63, see paper. */
38
+ static inline int32_t fj_el_power(int32_t q) {
39
+ return (((152170 + 65536) * q) >> 16) + 63;
40
+ }
41
+
42
+ static inline void fj_el_mul128(uint64_t a, uint64_t b, uint64_t *hi, uint64_t *lo) {
43
+ #if defined(__SIZEOF_INT128__)
44
+ __uint128_t p = (__uint128_t)a * (__uint128_t)b;
45
+ *lo = (uint64_t)p;
46
+ *hi = (uint64_t)(p >> 64);
47
+ #else
48
+ uint64_t a0 = (uint32_t)a, a1 = a >> 32, b0 = (uint32_t)b, b1 = b >> 32;
49
+ uint64_t p00 = a0 * b0, p01 = a0 * b1, p10 = a1 * b0, p11 = a1 * b1;
50
+ uint64_t mid = p10 + (p00 >> 32) + (uint32_t)p01;
51
+ *hi = p11 + (mid >> 32) + (p01 >> 32);
52
+ *lo = (mid << 32) | (uint32_t)p00;
53
+ #endif
54
+ }
55
+
56
+ static inline double fj_el_bits2double(uint64_t bits) {
57
+ double d;
58
+ memcpy(&d, &bits, sizeof(d));
59
+ return d;
60
+ }
61
+
62
+ /* q = power of ten, w = mantissa (NONZERO, exact, fits in uint64). neg = sign. */
63
+ static inline double fj_eisel_lemire_s2d(int64_t q, uint64_t w, int neg) {
64
+ const uint64_t sign = (uint64_t)(neg != 0) << 63;
65
+ uint64_t mantissa, prod_hi, prod_lo, sp_hi, sp_lo;
66
+ int32_t power2;
67
+ int lz, upperbit, shift, index;
68
+
69
+ if (q < FJ_EL_SMALLEST_POW10) return fj_el_bits2double(sign); /* underflow -> 0 */
70
+ if (q > FJ_EL_LARGEST_POW10)
71
+ return fj_el_bits2double(sign | ((uint64_t)FJ_EL_INFINITE_POWER << FJ_EL_MANTISSA_BITS));
72
+
73
+ lz = __builtin_clzll(w);
74
+ w <<= lz;
75
+
76
+ /* compute_product_approximation<mantissa_bits + 3 = 55>: precision_mask = 0x1FF. */
77
+ index = 2 * (int)(q - FJ_EL_SMALLEST_POWER_OF_FIVE);
78
+ fj_el_mul128(w, fj_power_of_five_128[index], &prod_hi, &prod_lo);
79
+ if ((prod_hi & 0x1FF) == 0x1FF) {
80
+ fj_el_mul128(w, fj_power_of_five_128[index + 1], &sp_hi, &sp_lo);
81
+ prod_lo += sp_hi;
82
+ if (sp_hi > prod_lo) prod_hi++;
83
+ }
84
+
85
+ upperbit = (int)(prod_hi >> 63);
86
+ shift = upperbit + 64 - FJ_EL_MANTISSA_BITS - 3; /* upperbit + 9 */
87
+ mantissa = prod_hi >> shift;
88
+ power2 = (int32_t)(fj_el_power((int32_t)q) + upperbit - lz - FJ_EL_MIN_EXPONENT);
89
+
90
+ if (power2 <= 0) { /* subnormal */
91
+ if (-power2 + 1 >= 64) return fj_el_bits2double(sign); /* far below min -> 0 */
92
+ mantissa >>= (-power2 + 1);
93
+ mantissa += (mantissa & 1);
94
+ mantissa >>= 1;
95
+ power2 = (mantissa < ((uint64_t)1 << FJ_EL_MANTISSA_BITS)) ? 0 : 1;
96
+ return fj_el_bits2double(sign | ((uint64_t)power2 << FJ_EL_MANTISSA_BITS) | mantissa);
97
+ }
98
+
99
+ /* round-to-even: if we land exactly between two doubles, round down. */
100
+ if ((prod_lo <= 1) && (q >= FJ_EL_MIN_RTE) && (q <= FJ_EL_MAX_RTE) &&
101
+ ((mantissa & 3) == 1) && ((mantissa << shift) == prod_hi)) {
102
+ mantissa &= ~(uint64_t)1;
103
+ }
104
+
105
+ mantissa += (mantissa & 1);
106
+ mantissa >>= 1;
107
+ if (mantissa >= ((uint64_t)2 << FJ_EL_MANTISSA_BITS)) {
108
+ mantissa = (uint64_t)1 << FJ_EL_MANTISSA_BITS;
109
+ power2++;
110
+ }
111
+ mantissa &= ~((uint64_t)1 << FJ_EL_MANTISSA_BITS); /* drop implicit bit */
112
+ if (power2 >= FJ_EL_INFINITE_POWER)
113
+ return fj_el_bits2double(sign | ((uint64_t)FJ_EL_INFINITE_POWER << FJ_EL_MANTISSA_BITS));
114
+ return fj_el_bits2double(sign | ((uint64_t)power2 << FJ_EL_MANTISSA_BITS) | mantissa);
115
+ }
116
+
117
+ #endif
@@ -0,0 +1,29 @@
1
+ # Eisel-Lemire decimal→double, from fast_float
2
+
3
+ - The algorithm is **Eisel-Lemire**, named for **Michael Eisel** (who proposed/motivated the original approach) and **Daniel Lemire** (who formalized it, proved its bounds, and wrote the fast_float implementation). We use the later "without fallback" form proven by **Noble Mushtak & Daniel Lemire, _Fast Number Parsing Without Fallback_**. It converts a decimal mantissa+exponent to a correctly-rounded binary64 with no slow path, for any nonzero mantissa that fits exactly in a `uint64` (≤ 19 significant digits).
4
+ - Vendored from **fastfloat/fast_float** — https://github.com/fastfloat/fast_float — license Apache-2.0 / MIT / Boost-1.0 (your choice).
5
+
6
+ ## What smarter_json uses it for
7
+
8
+ `try_numeric_conversion` (in `smarter_csv.c`) routes decimal tokens with `m10digits ≤ 19 → fj_eisel_lemire_s2d`, and `> 19 / overflow / extreme exponent → strtod`. Eisel-Lemire is correctly-rounded across the whole ≤19-digit range — every mantissa that fits exactly in a uint64, no round-to-even tie loss — **and** fast on the common short-mantissa case. (smarter_json uses it the same way via `fj_float_from_parts`.)
9
+
10
+ ## These two files are DERIVED, not verbatim copies
11
+
12
+ - **`eisel_lemire_powers.h`** — the `power_of_five_128` table (1302 × `uint64`), extracted **verbatim** (the constants are byte-for-byte) from fast_float `include/fast_float/fast_table.h`, but **rewrapped**: a plain C `static const uint64_t fj_power_of_five_128[...]` array instead of fast_float's C++ `powers_template` struct. `FJ_EL_SMALLEST_POWER_OF_FIVE` / `FJ_EL_LARGEST_POWER_OF_FIVE` are the `-342` / `308` bounds.
13
+ - **`eisel_lemire.h`** — a C **port** of `compute_float<binary_format<double>>` + `compute_product_approximation` from fast_float `include/fast_float/decimal_to_binary.h`. Adapted to: (a) plain C (no templates), (b) take our already-extracted `(q, w)` = `(e10, m10)` instead of re-parsing a string, (c) the binary64 constants inlined as `FJ_EL_*` macros, (d) a portable `fj_el_mul128` (`__uint128_t` when available, else a 32×32 split). The control flow — `compute_product_approximation<55>`, the `0x1FF` precision mask, `upperbit`/`shift`, the subnormal branch, and the round-to-even "land exactly between two doubles → round down" check — mirrors the source.
14
+
15
+ Because they're derived (rewrapped table, ported algorithm), they're named after the **algorithm** (Eisel-Lemire) rather than their upstream source (`fast_float`). The verification that they faithfully reproduce upstream is the bit-for-bit stress vs `JSON.parse` (8–10M random numbers incl. ties / subnormals / near-overflow, 0 mismatches).
16
+
17
+ ## To refresh from upstream
18
+
19
+ Re-pull the two source files and re-derive:
20
+
21
+ - table: `curl -L https://raw.githubusercontent.com/fastfloat/fast_float/main/include/fast_float/fast_table.h` — copy the `power_of_five_128[...] = { ... };` body into `eisel_lemire_powers.h`'s array (constants only).
22
+ - algorithm: `curl -L https://raw.githubusercontent.com/fastfloat/fast_float/main/include/fast_float/decimal_to_binary.h` — re-check `compute_float` / `compute_product_approximation` against the port in `eisel_lemire.h`.
23
+
24
+ Then re-run the bit-exact stress (≥ several million random 1–19-digit numbers, with forced round-to-even ties and exponents spanning subnormal → overflow) vs `JSON.parse` before trusting it.
25
+
26
+ - origin: Eisel-Lemire (`fastfloat/fast_float`)
27
+ - vendored from: fast_float (upstream `main`)
28
+ - copyright: (c) 2021 The fast_float authors
29
+ - license: tri-licensed Apache-2.0 / MIT / BSL-1.0; vendored here under **MIT**, full text in `LICENSE-fast_float-MIT` (this directory)