sonic-number 0.1.3

Fast number parsing based on SIMD
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
#![no_std]

#[cfg(test)]
extern crate std;

mod arch;
mod common;
mod decimal;
mod float;
mod lemire;
mod slow;
pub mod swar;
mod table;

use self::{common::BiasedFp, float::RawFloat, table::POWER_OF_FIVE_128};
pub use crate::{arch::simd_str2int, swar::swar_str2int};

const FLOATING_LONGEST_DIGITS: usize = 17;
const FLOATING_LONGEST_DIGITS_F32: usize = 9;
const F64_BITS: u32 = 64;
const F64_SIG_BITS: u32 = 52;
const F64_SIG_FULL_BITS: u32 = 53;
const F64_EXP_BIAS: i32 = 1023;
const F64_SIG_MASK: u64 = 0x000F_FFFF_FFFF_FFFF;

#[derive(Debug)]
pub enum ParserNumber {
    Unsigned(u64),
    /// Always less than zero.
    Signed(i64),
    /// Always finite.
    Float(f64),
}

#[derive(Debug)]
pub enum Error {
    InvalidNumber,
    FloatMustBeFinite,
}

// Checked macros (with bounds check — safe for any buffer)
macro_rules! match_digit {
    ($data:expr, $i:expr, $pattern:pat) => {
        $i < $data.len() && matches!($data[$i], $pattern)
    };
}
macro_rules! is_digit {
    ($data:expr, $i:expr) => {
        $i < $data.len() && $data[$i].is_ascii_digit()
    };
}
macro_rules! digit {
    ($data:expr, $i:expr) => {
        ($data[$i] - b'0') as u64
    };
}
macro_rules! check_digit {
    ($data:expr, $i:expr) => {
        if !($i < $data.len() && $data[$i].is_ascii_digit()) {
            return Err(Error::InvalidNumber);
        }
    };
}

// Unchecked macros (no bounds check — requires >=64 bytes padding after data)
macro_rules! match_digit_u {
    ($data:expr, $i:expr, $pattern:pat) => {
        matches!(unsafe { *$data.get_unchecked($i) }, $pattern)
    };
}
macro_rules! is_digit_u {
    ($data:expr, $i:expr) => {
        unsafe { *$data.get_unchecked($i) }.is_ascii_digit()
    };
}
macro_rules! digit_u {
    ($data:expr, $i:expr) => {
        (unsafe { *$data.get_unchecked($i) } - b'0') as u64
    };
}
macro_rules! check_digit_u {
    ($data:expr, $i:expr) => {
        if !(unsafe { *$data.get_unchecked($i) }.is_ascii_digit()) {
            return Err(Error::InvalidNumber);
        }
    };
}

#[inline(always)]
fn parse_exponent(data: &[u8], index: &mut usize) -> Result<i32, Error> {
    let mut exponent: i32 = 0;
    let mut negative = false;

    if *index >= data.len() {
        return Err(Error::InvalidNumber);
    }

    match data[*index] {
        b'+' => *index += 1,
        b'-' => {
            negative = true;
            *index += 1;
        }
        _ => {}
    }

    check_digit!(data, *index);
    while exponent < 1000 && is_digit!(data, *index) {
        exponent = digit!(data, *index) as i32 + exponent * 10;
        *index += 1;
    }
    while is_digit!(data, *index) {
        *index += 1;
    }
    if negative {
        exponent = -exponent;
    }
    Ok(exponent)
}

const POW10_UINT: [u64; 18] = [
    1,
    10,
    100,
    1000,
    10000,
    100000,
    1000000,
    10000000,
    100000000,
    1000000000,
    10000000000,
    100000000000,
    1000000000000,
    10000000000000,
    100000000000000,
    1000000000000000,
    10000000000000000,
    100000000000000000,
];

// parse at most 16 digits for fraction, record the exponent.
// because we calcaute at least the first significant digit when both normal or subnormal float
// points
#[inline(always)]
fn parse_number_fraction(
    data: &[u8],
    index: &mut usize,
    significant: &mut u64,
    exponent: &mut i32,
    need: isize,
    dot_pos: usize,
) -> Result<bool, Error> {
    debug_assert!(need < FLOATING_LONGEST_DIGITS as isize);

    // Use SWAR (integer pipeline) instead of SSE simd_str2int (FP pipeline).
    // On AMD Zen, SSE maddubs/madd go through FP ports causing ALU saturation.
    // Two-step SWAR: 8-digit batch + tolerant SWAR for remaining 1-8 digits,
    // eliminating the scalar while-loop tail for float-heavy workloads.
    //
    // Note: `significant` may wrap on u64 overflow when the integer part has many
    // digits. This is harmless — wrapping makes the fast path in `parse_float` fail,
    // which falls back to `slow::parse_long_mantissa(raw_num)` for a correct result.
    if need > 0 {
        let need = need as usize;
        unsafe {
            let c = data.get_unchecked(*index..);
            if need >= 8 && c.len() >= 8 && swar::is_eight_digits(c) {
                let first8 = swar::parse_eight_digits(c) as u64;
                let remaining = need - 8;
                if remaining >= 8 && c.len() >= 16 && swar::is_eight_digits(&c[8..]) {
                    let second8 = swar::parse_eight_digits(&c[8..]) as u64;
                    *significant = *significant * POW10_UINT[16] + first8 * 100_000_000 + second8;
                    *index += 16;
                } else if remaining > 0 && c.len() >= 16 {
                    // Tolerant SWAR for remaining 1-8 digits (no scalar loop)
                    let (mut tail_val, tail_n) = swar::parse_digits_tolerant(&c[8..]);
                    let tail_n = if tail_n > remaining {
                        // Parsed more digits than needed — drop the excess trailing digits.
                        tail_val /= POW10_UINT[tail_n - remaining];
                        remaining
                    } else {
                        tail_n
                    };
                    let total = 8 + tail_n;
                    *significant =
                        *significant * POW10_UINT[total] + first8 * POW10_UINT[tail_n] + tail_val;
                    *index += total;
                } else {
                    // c.len() < 16: not enough bytes for tolerant SWAR on tail.
                    // Parse first 8 digits via SWAR, then scalar tail for remaining.
                    *significant = *significant * POW10_UINT[8] + first8;
                    *index += 8;
                    let mut rem = remaining;
                    while rem > 0 && is_digit!(data, *index) {
                        *significant = *significant * 10 + digit!(data, *index);
                        *index += 1;
                        rem -= 1;
                    }
                }
            } else {
                let (frac, ndigits) = swar::swar_str2int(c, need);
                *significant = *significant * POW10_UINT[ndigits] + frac;
                *index += ndigits;
            }
        }
    }

    *exponent -= *index as i32 - dot_pos as i32;
    let mut trunc = false;
    while is_digit!(data, *index) {
        trunc = true;
        *index += 1;
    }

    if match_digit!(data, *index, b'e' | b'E') {
        *index += 1;
        *exponent += parse_exponent(data, &mut *index)?;
    }
    Ok(trunc)
}

#[inline(always)]
pub fn parse_number(data: &[u8], index: &mut usize, negative: bool) -> Result<ParserNumber, Error> {
    let mut significant: u64 = 0;
    let mut exponent: i32 = 0;
    let mut trunc = false;
    // Checked slice: validates *index <= data.len() (panics otherwise).
    // This bounds guarantee is relied upon by the unchecked slice at the SWAR branch below.
    let raw_num = &data[*index..];

    if match_digit!(data, *index, b'0') {
        *index += 1;

        if *index >= data.len() || !matches!(data[*index], b'.' | b'e' | b'E') {
            // view -0 as float number
            if negative {
                return Ok(ParserNumber::Float(0.0));
            }
            return Ok(ParserNumber::Unsigned(0));
        }

        // deal with 0e123 or 0.000e123
        match data[*index] {
            b'.' => {
                *index += 1;
                let dot_pos = *index;
                check_digit!(data, *index);
                while match_digit!(data, *index, b'0') {
                    *index += 1;
                }
                // special case: 0.000e123
                if match_digit!(data, *index, b'e' | b'E') {
                    *index += 1;
                    if match_digit!(data, *index, b'-' | b'+') {
                        *index += 1;
                    }
                    check_digit!(data, *index);
                    while is_digit!(data, *index) {
                        *index += 1;
                    }
                    return Ok(ParserNumber::Float(0.0));
                }

                // we calculate the first digit here for two reasons:
                // 1. fastpath for small float number
                // 2. we only need parse at most 16 digits in parse_number_fraction
                // and it is friendly for simd
                if !is_digit!(data, *index) {
                    return Ok(ParserNumber::Float(0.0));
                }

                significant = digit!(data, *index);
                *index += 1;

                if is_digit!(data, *index) {
                    let need = FLOATING_LONGEST_DIGITS as isize - 1;
                    trunc = parse_number_fraction(
                        data,
                        index,
                        &mut significant,
                        &mut exponent,
                        need,
                        dot_pos,
                    )?;
                } else {
                    exponent -= *index as i32 - dot_pos as i32;
                    if match_digit!(data, *index, b'e' | b'E') {
                        *index += 1;
                        exponent += parse_exponent(data, &mut *index)?;
                    }
                }
            }
            b'e' | b'E' => {
                *index += 1;
                if match_digit!(data, *index, b'-' | b'+') {
                    *index += 1;
                }
                check_digit!(data, *index);
                while is_digit!(data, *index) {
                    *index += 1;
                }
                return Ok(ParserNumber::Float(0.0));
            }
            _ => unreachable!("unreachable branch in parse_number_unchecked"),
        }
    } else {
        // SWAR-optimized integer digit parsing.
        let digit_start = *index;
        // Safety: *index <= data.len() is guaranteed by the checked slice `&data[*index..]`
        // above (line 223), which would have panicked on out-of-bounds.
        let remaining = unsafe { data.get_unchecked(*index..) };

        let digits_cnt;
        if remaining.len() >= 8 && swar::is_eight_digits(remaining) {
            // SWAR path: first 8 bytes are all digits.
            significant = swar::parse_eight_digits(remaining) as u64;
            *index += 8;

            // Try second 8-digit batch
            if data.len() - *index >= 8 && swar::is_eight_digits(&data[*index..]) {
                significant =
                    significant * 100_000_000 + swar::parse_eight_digits(&data[*index..]) as u64;
                *index += 8;
            }

            // Scalar tail for remaining digits (at most 3 more to stay within u64)
            while (*index - digit_start) < 19 && is_digit!(data, *index) {
                significant = significant * 10 + digit!(data, *index);
                *index += 1;
            }
            digits_cnt = *index - digit_start;

            // Handle overflow digits beyond 19
            while is_digit!(data, *index) {
                exponent += 1;
                *index += 1;
                trunc = true;
            }
        } else {
            // Scalar path: fewer than 8 leading digits or short input.
            // Includes single-digit fast path — if only one digit and not followed
            // by '.', 'e', 'E', return immediately without further checks.
            if !is_digit!(data, *index) {
                return Err(Error::InvalidNumber);
            }
            significant = digit!(data, *index);
            *index += 1;

            if is_digit!(data, *index) {
                // 2-7 digits: continue scalar loop
                while is_digit!(data, *index) {
                    significant = significant * 10 + digit!(data, *index);
                    *index += 1;
                }
                digits_cnt = *index - digit_start;
            } else if !match_digit!(data, *index, b'.' | b'e' | b'E') {
                // Single digit integer — fast return
                if negative {
                    return Ok(ParserNumber::Signed(-(significant as i64)));
                }
                return Ok(ParserNumber::Unsigned(significant));
            } else {
                digits_cnt = 1;
            }
        }
        if match_digit!(data, *index, b'e' | b'E') {
            // parse exponent
            *index += 1;
            exponent += parse_exponent(data, index)?;
        } else if match_digit!(data, *index, b'.') {
            *index += 1;
            check_digit!(data, *index);
            let dot_pos = *index;

            if digits_cnt < 8 {
                // Short integer part — continue scalar accumulation into fraction.
                // Avoids SIMD setup + POW10 table multiplication overhead.
                // yyjson uses this approach: sig = sig*10+digit continuously.
                let mut need = FLOATING_LONGEST_DIGITS as isize - digits_cnt as isize;
                while need > 0 && is_digit!(data, *index) {
                    significant = significant * 10 + digit!(data, *index);
                    *index += 1;
                    need -= 1;
                }
                exponent -= *index as i32 - dot_pos as i32;
                while is_digit!(data, *index) {
                    trunc = true;
                    *index += 1;
                }
                if match_digit!(data, *index, b'e' | b'E') {
                    *index += 1;
                    exponent += parse_exponent(data, &mut *index)?;
                }
            } else {
                // Long integer part — use SIMD fraction parsing
                let need = FLOATING_LONGEST_DIGITS as isize - digits_cnt as isize;
                trunc = parse_number_fraction(
                    data,
                    index,
                    &mut significant,
                    &mut exponent,
                    need,
                    dot_pos,
                )?;
            }
        } else {
            // parse integer, all parse has finished.
            if exponent == 0 {
                if negative {
                    if significant > (1u64 << 63) {
                        return Ok(ParserNumber::Float(-(significant as f64)));
                    } else {
                        // if significant is 0x8000_0000_0000_0000, it will overflow here.
                        // so, we must use wrapping_sub here.
                        return Ok(ParserNumber::Signed(0_i64.wrapping_sub(significant as i64)));
                    }
                } else {
                    return Ok(ParserNumber::Unsigned(significant));
                }
            } else if exponent == 1 {
                // now we get 20 digits, it maybe overflow for uint64
                let last = digit!(data, *index - 1);
                let (out, ov0) = significant.overflowing_mul(10);
                let (out, ov1) = out.overflowing_add(last);
                if !ov0 && !ov1 {
                    // negative must be overflow here.
                    significant = out;
                    if negative {
                        return Ok(ParserNumber::Float(-(significant as f64)));
                    } else {
                        return Ok(ParserNumber::Unsigned(significant));
                    }
                }
            }
            trunc = true;
        }
    }

    // raw_num is pass-through for fallback parsing logic
    parse_float(significant, exponent, negative, trunc, raw_num)
}

#[allow(unused_assignments)]
#[inline(always)]
pub fn parse_float32(data: &[u8], index: &mut usize, negative: bool) -> Result<f32, Error> {
    let mut significant: u64 = 0;
    let mut exponent: i32 = 0;
    let mut trunc = false;
    let raw_num = &data[*index..];

    if match_digit!(data, *index, b'0') {
        *index += 1;

        if *index >= data.len() || !matches!(data[*index], b'.' | b'e' | b'E') {
            let zero = 0.0f32;
            return Ok(if negative { -zero } else { zero });
        }

        match data[*index] {
            b'.' => {
                *index += 1;
                let dot_pos = *index;
                check_digit!(data, *index);
                while match_digit!(data, *index, b'0') {
                    *index += 1;
                }

                if match_digit!(data, *index, b'e' | b'E') {
                    *index += 1;
                    if match_digit!(data, *index, b'-' | b'+') {
                        *index += 1;
                    }
                    check_digit!(data, *index);
                    while is_digit!(data, *index) {
                        *index += 1;
                    }
                    let zero = 0.0f32;
                    return Ok(if negative { -zero } else { zero });
                }

                if !is_digit!(data, *index) {
                    let zero = 0.0f32;
                    return Ok(if negative { -zero } else { zero });
                }

                significant = digit!(data, *index);
                *index += 1;

                if is_digit!(data, *index) {
                    let need = FLOATING_LONGEST_DIGITS_F32 as isize - 1;
                    trunc = parse_number_fraction(
                        data,
                        index,
                        &mut significant,
                        &mut exponent,
                        need,
                        dot_pos,
                    )?;
                } else {
                    exponent -= *index as i32 - dot_pos as i32;
                    if match_digit!(data, *index, b'e' | b'E') {
                        *index += 1;
                        exponent += parse_exponent(data, &mut *index)?;
                    }
                }
            }
            b'e' | b'E' => {
                *index += 1;
                if match_digit!(data, *index, b'-' | b'+') {
                    *index += 1;
                }
                check_digit!(data, *index);
                while is_digit!(data, *index) {
                    *index += 1;
                }
                let zero = 0.0f32;
                return Ok(if negative { -zero } else { zero });
            }
            _ => unreachable!("unreachable branch in parse_float32"),
        }
    } else {
        let digit_start = *index;
        let remaining = unsafe { data.get_unchecked(*index..) };

        let digits_cnt;
        if remaining.len() >= 8 && swar::is_eight_digits(remaining) {
            significant = swar::parse_eight_digits(remaining) as u64;
            *index += 8;

            if data.len() - *index >= 8 && swar::is_eight_digits(&data[*index..]) {
                significant =
                    significant * 100_000_000 + swar::parse_eight_digits(&data[*index..]) as u64;
                *index += 8;
            }

            while (*index - digit_start) < 19 && is_digit!(data, *index) {
                significant = significant * 10 + digit!(data, *index);
                *index += 1;
            }
            digits_cnt = *index - digit_start;

            while is_digit!(data, *index) {
                exponent += 1;
                *index += 1;
                trunc = true;
            }
        } else {
            if !is_digit!(data, *index) {
                return Err(Error::InvalidNumber);
            }
            significant = digit!(data, *index);
            *index += 1;

            if is_digit!(data, *index) {
                while is_digit!(data, *index) {
                    significant = significant * 10 + digit!(data, *index);
                    *index += 1;
                }
                digits_cnt = *index - digit_start;
            } else if !match_digit!(data, *index, b'.' | b'e' | b'E') {
                let mut float = significant as f32;
                if negative {
                    float = -float;
                }
                return Ok(float);
            } else {
                digits_cnt = 1;
            }
        }

        if match_digit!(data, *index, b'e' | b'E') {
            *index += 1;
            exponent += parse_exponent(data, index)?;
        } else if match_digit!(data, *index, b'.') {
            *index += 1;
            check_digit!(data, *index);
            let dot_pos = *index;

            if digits_cnt < 8 {
                let mut need = FLOATING_LONGEST_DIGITS_F32 as isize - digits_cnt as isize;
                while need > 0 && is_digit!(data, *index) {
                    significant = significant * 10 + digit!(data, *index);
                    *index += 1;
                    need -= 1;
                }
                exponent -= *index as i32 - dot_pos as i32;
                while is_digit!(data, *index) {
                    trunc = true;
                    *index += 1;
                }
                if match_digit!(data, *index, b'e' | b'E') {
                    *index += 1;
                    exponent += parse_exponent(data, &mut *index)?;
                }
            } else {
                let need = FLOATING_LONGEST_DIGITS_F32 as isize - digits_cnt as isize;
                trunc = parse_number_fraction(
                    data,
                    index,
                    &mut significant,
                    &mut exponent,
                    need,
                    dot_pos,
                )?;
            }
        } else {
            if exponent == 0 {
                let mut float = significant as f32;
                if negative {
                    float = -float;
                }
                return Ok(float);
            } else if exponent == 1 {
                let last = digit!(data, *index - 1);
                let (out, ov0) = significant.overflowing_mul(10);
                let (out, ov1) = out.overflowing_add(last);
                if !ov0 && !ov1 {
                    significant = out;
                    let mut float = significant as f32;
                    if negative {
                        float = -float;
                    }
                    return Ok(float);
                }
            }
            trunc = true;
        }
    }

    parse_float_generic::<f32>(significant, exponent, negative, trunc, raw_num)
}

/// Unchecked version — caller must ensure data has >=64 bytes padding.
#[inline(always)]
pub unsafe fn parse_number_unchecked(
    data: &[u8],
    index: &mut usize,
    negative: bool,
) -> Result<ParserNumber, Error> {
    let mut significant: u64 = 0;
    let mut exponent: i32 = 0;
    let mut trunc = false;
    let raw_num = unsafe { data.get_unchecked(*index..) };

    if match_digit_u!(data, *index, b'0') {
        *index += 1;

        if !match_digit_u!(data, *index, b'.' | b'e' | b'E') {
            // view -0 as float number
            if negative {
                return Ok(ParserNumber::Float(0.0));
            }
            return Ok(ParserNumber::Unsigned(0));
        }

        // deal with 0e123 or 0.000e123
        match data[*index] {
            b'.' => {
                *index += 1;
                let dot_pos = *index;
                check_digit_u!(data, *index);
                while match_digit_u!(data, *index, b'0') {
                    *index += 1;
                }
                // special case: 0.000e123
                if match_digit_u!(data, *index, b'e' | b'E') {
                    *index += 1;
                    if match_digit_u!(data, *index, b'-' | b'+') {
                        *index += 1;
                    }
                    check_digit_u!(data, *index);
                    while is_digit_u!(data, *index) {
                        *index += 1;
                    }
                    return Ok(ParserNumber::Float(0.0));
                }

                // we calculate the first digit here for two reasons:
                // 1. fastpath for small float number
                // 2. we only need parse at most 16 digits in parse_number_fraction
                // and it is friendly for simd
                if !is_digit_u!(data, *index) {
                    return Ok(ParserNumber::Float(0.0));
                }

                significant = digit_u!(data, *index);
                *index += 1;

                if is_digit_u!(data, *index) {
                    let need = FLOATING_LONGEST_DIGITS as isize - 1;
                    trunc = parse_number_fraction(
                        data,
                        index,
                        &mut significant,
                        &mut exponent,
                        need,
                        dot_pos,
                    )?;
                } else {
                    exponent -= *index as i32 - dot_pos as i32;
                    if match_digit_u!(data, *index, b'e' | b'E') {
                        *index += 1;
                        exponent += parse_exponent(data, &mut *index)?;
                    }
                }
            }
            b'e' | b'E' => {
                *index += 1;
                if match_digit_u!(data, *index, b'-' | b'+') {
                    *index += 1;
                }
                check_digit_u!(data, *index);
                while is_digit_u!(data, *index) {
                    *index += 1;
                }
                return Ok(ParserNumber::Float(0.0));
            }
            _ => unreachable!("unreachable branch in parse_number_unchecked"),
        }
    } else {
        // SWAR-optimized integer digit parsing.
        let digit_start = *index;
        let remaining = unsafe { data.get_unchecked(*index..) };

        let digits_cnt;
        if remaining.len() >= 8 && swar::is_eight_digits(remaining) {
            // SWAR path: first 8 bytes are all digits.
            significant = swar::parse_eight_digits(remaining) as u64;
            *index += 8;

            // Try second 8-digit batch
            if data.len() - *index >= 8
                && swar::is_eight_digits(unsafe { data.get_unchecked(*index..) })
            {
                significant = significant * 100_000_000
                    + swar::parse_eight_digits(unsafe { data.get_unchecked(*index..) }) as u64;
                *index += 8;
            }

            // Scalar tail for remaining digits (at most 3 more to stay within u64)
            while (*index - digit_start) < 19 && is_digit_u!(data, *index) {
                significant = significant * 10 + digit_u!(data, *index);
                *index += 1;
            }
            digits_cnt = *index - digit_start;

            // Handle overflow digits beyond 19
            while is_digit_u!(data, *index) {
                exponent += 1;
                *index += 1;
                trunc = true;
            }
        } else {
            // Scalar path: fewer than 8 leading digits or short input.
            // Includes single-digit fast path — if only one digit and not followed
            // by '.', 'e', 'E', return immediately without further checks.
            if !is_digit_u!(data, *index) {
                return Err(Error::InvalidNumber);
            }
            significant = digit_u!(data, *index);
            *index += 1;

            if is_digit_u!(data, *index) {
                // 2-7 digits: continue scalar loop
                while is_digit_u!(data, *index) {
                    significant = significant * 10 + digit_u!(data, *index);
                    *index += 1;
                }
                digits_cnt = *index - digit_start;
            } else if !match_digit_u!(data, *index, b'.' | b'e' | b'E') {
                // Single digit integer — fast return
                if negative {
                    return Ok(ParserNumber::Signed(-(significant as i64)));
                }
                return Ok(ParserNumber::Unsigned(significant));
            } else {
                digits_cnt = 1;
            }
        }
        if match_digit_u!(data, *index, b'e' | b'E') {
            // parse exponent
            *index += 1;
            exponent += parse_exponent(data, index)?;
        } else if match_digit_u!(data, *index, b'.') {
            *index += 1;
            check_digit_u!(data, *index);
            let dot_pos = *index;

            // parse fraction
            let need = FLOATING_LONGEST_DIGITS as isize - digits_cnt as isize;
            trunc =
                parse_number_fraction(data, index, &mut significant, &mut exponent, need, dot_pos)?;
        } else {
            // parse integer, all parse has finished.
            if exponent == 0 {
                if negative {
                    if significant > (1u64 << 63) {
                        return Ok(ParserNumber::Float(-(significant as f64)));
                    } else {
                        // if significant is 0x8000_0000_0000_0000, it will overflow here.
                        // so, we must use wrapping_sub here.
                        return Ok(ParserNumber::Signed(0_i64.wrapping_sub(significant as i64)));
                    }
                } else {
                    return Ok(ParserNumber::Unsigned(significant));
                }
            } else if exponent == 1 {
                // now we get 20 digits, it maybe overflow for uint64
                let last = digit_u!(data, *index - 1);
                let (out, ov0) = significant.overflowing_mul(10);
                let (out, ov1) = out.overflowing_add(last);
                if !ov0 && !ov1 {
                    // negative must be overflow here.
                    significant = out;
                    if negative {
                        return Ok(ParserNumber::Float(-(significant as f64)));
                    } else {
                        return Ok(ParserNumber::Unsigned(significant));
                    }
                }
            }
            trunc = true;
        }
    }

    // raw_num is pass-through for fallback parsing logic
    parse_float(significant, exponent, negative, trunc, raw_num)
}

#[inline(always)]
fn parse_float(
    significant: u64,
    exponent: i32,
    negative: bool,
    trunc: bool,
    raw_num: &[u8],
) -> Result<ParserNumber, Error> {
    // parse double fast
    if significant < (1u64 << F64_SIG_FULL_BITS) && (-22..=(22 + 15)).contains(&exponent) {
        if let Some(mut float) = parse_float_fast(exponent, significant) {
            if negative {
                float = -float;
            }
            return Ok(ParserNumber::Float(float));
        }
    }

    if !trunc && exponent > (-308 + 1) && exponent < (308 - 20) {
        if let Some(raw) = parse_floating_normal_fast(exponent, significant) {
            let mut float = f64::from_u64_bits(raw);
            if negative {
                float = -float;
            }
            return Ok(ParserNumber::Float(float));
        }
    }

    // If significant digits were truncated, then we can have rounding error
    // only if `mantissa + 1` produces a different result. We also avoid
    // redundantly using the Eisel-Lemire algorithm if it was unable to
    // correctly round on the first pass.
    let exponent = exponent as i64;
    let mut fp = lemire::compute_float::<f64>(exponent, significant);
    if trunc && fp.e >= 0 && fp != lemire::compute_float::<f64>(exponent, significant + 1) {
        fp.e = -1;
    }

    // Unable to correctly round the float using the Eisel-Lemire algorithm.
    // Fallback to a slower, but always correct algorithm.
    if fp.e < 0 {
        fp = slow::parse_long_mantissa::<f64>(raw_num);
    }

    let mut float = biased_fp_to_float::<f64>(fp);
    if negative {
        float = -float;
    }

    // check inf for float
    if float.is_infinite() {
        return Err(Error::FloatMustBeFinite);
    }
    Ok(ParserNumber::Float(float))
}

#[inline(always)]
fn parse_float_generic<T: RawFloat>(
    significant: u64,
    exponent: i32,
    negative: bool,
    trunc: bool,
    raw_num: &[u8],
) -> Result<T, Error> {
    if let Some(mut float) = parse_float_fast_generic::<T>(exponent, significant) {
        if negative {
            float = -float;
        }
        return Ok(float);
    }

    let exponent = exponent as i64;
    let mut fp = lemire::compute_float::<T>(exponent, significant);
    if trunc && fp.e >= 0 && fp != lemire::compute_float::<T>(exponent, significant + 1) {
        fp.e = -1;
    }

    if fp.e < 0 {
        fp = slow::parse_long_mantissa::<T>(raw_num);
    }

    let mut float = biased_fp_to_float::<T>(fp);
    if negative {
        float = -float;
    }

    if matches!(float.classify(), core::num::FpCategory::Infinite) {
        return Err(Error::FloatMustBeFinite);
    }
    Ok(float)
}

// This function is modified from yyjson
#[inline(always)]
fn parse_floating_normal_fast(exp10: i32, man: u64) -> Option<u64> {
    let (mut hi, lo, hi2, add, bits);
    let mut exp2: i32;
    let mut exact = false;
    let idx = exp10 + 342;
    let sig2_ext = POWER_OF_FIVE_128[idx as usize].1;
    let sig2 = POWER_OF_FIVE_128[idx as usize].0;

    let mut lz = man.leading_zeros();
    let sig1 = man << lz;
    exp2 = ((217706 * exp10 - 4128768) >> 16) - lz as i32;

    (lo, hi) = lemire::full_multiplication(sig1, sig2);

    bits = hi & ((1u64 << (64 - 54 - 1)) - 1);
    if bits.wrapping_sub(1) < ((1u64 << (64 - 54 - 1)) - 2) {
        exact = true;
    } else {
        (_, hi2) = lemire::full_multiplication(sig1, sig2_ext);
        // not need warring overflow here
        add = lo.wrapping_add(hi2);
        if add + 1 > 1u64 {
            let carry = add < lo || add < hi2;
            hi += carry as u64;
            exact = true;
        }
    }

    if exact {
        lz = if hi < (1u64 << 63) { 1 } else { 0 };
        hi <<= lz;
        exp2 -= lz as i32;
        exp2 += 64;

        let round_up = (hi & (1u64 << (64 - 54))) > 0;
        hi = hi.wrapping_add(if round_up { 1u64 << (64 - 54) } else { 0 });

        if hi < (1u64 << (64 - 54)) {
            hi = 1u64 << 63;
            exp2 += 1;
        }

        hi >>= F64_BITS - F64_SIG_FULL_BITS;
        exp2 += F64_BITS as i32 - F64_SIG_FULL_BITS as i32 + F64_SIG_BITS as i32;
        exp2 += F64_EXP_BIAS;
        let raw = ((exp2 as u64) << F64_SIG_BITS) | (hi & F64_SIG_MASK);
        return Some(raw);
    }
    None
}

#[inline(always)]
/// Converts a `BiasedFp` to the closest machine float type.
fn biased_fp_to_float<T: RawFloat>(x: BiasedFp) -> T {
    let mut word = x.f;
    word |= (x.e as u64) << T::MANTISSA_EXPLICIT_BITS;
    T::from_u64_bits(word)
}

#[inline(always)]
fn parse_float_fast_generic<T: RawFloat>(mut exp10: i32, mut significant: u64) -> Option<T> {
    if significant > T::MAX_MANTISSA_FAST_PATH {
        return None;
    }

    let exp10_i64 = exp10 as i64;
    if exp10_i64 < T::MIN_EXPONENT_FAST_PATH || exp10_i64 > T::MAX_EXPONENT_DISGUISED_FAST_PATH {
        return None;
    }

    if exp10_i64 > T::MAX_EXPONENT_FAST_PATH {
        let shift = (exp10_i64 - T::MAX_EXPONENT_FAST_PATH) as usize;
        let pow10 = *POW10_UINT.get(shift)?;
        significant = significant.checked_mul(pow10)?;
        if significant > T::MAX_MANTISSA_FAST_PATH {
            return None;
        }
        exp10 = T::MAX_EXPONENT_FAST_PATH as i32;
    }

    let mut float = T::from_u64(significant);
    if exp10 > 0 {
        float = float * T::pow10_fast_path(exp10 as usize);
    } else if exp10 < 0 {
        float = float / T::pow10_fast_path((-exp10) as usize);
    }
    Some(float)
}

#[inline(always)]
fn parse_float_fast(exp10: i32, significant: u64) -> Option<f64> {
    let mut d = significant as f64;
    if exp10 > 0 {
        if exp10 > 22 {
            d *= POW10_FLOAT[exp10 as usize - 22];
            if (-1e15..=1e15).contains(&d) {
                Some(d * POW10_FLOAT[22])
            } else {
                None
            }
        } else {
            Some(d * POW10_FLOAT[exp10 as usize])
        }
    } else {
        Some(d / POW10_FLOAT[(-exp10) as usize])
    }
}

const POW10_FLOAT: [f64; 23] = [
    /* <= the connvertion to double is not exact when less than 1 => */ 1e-000, 1e+001,
    1e+002, 1e+003, 1e+004, 1e+005, 1e+006, 1e+007, 1e+008, 1e+009, 1e+010, 1e+011, 1e+012, 1e+013,
    1e+014, 1e+015, 1e+016, 1e+017, 1e+018, 1e+019, 1e+020, 1e+021,
    1e+022, /* <= the connvertion to double is not exact when larger,  => */
];

#[cfg(test)]
mod test {
    use crate::{parse_float32, parse_number, ParserNumber};

    fn test_parse_ok(input: &str, expect: f64) {
        assert_eq!(input.parse::<f64>().unwrap(), expect);

        let mut data = input.as_bytes().to_vec();
        data.push(b' ');
        let mut index = 0;
        let num = parse_number(&data, &mut index, false).unwrap();
        assert!(
            matches!(num, ParserNumber::Float(f) if f == expect),
            "parsed is {:?} failed num is {}",
            num,
            input
        );
        assert_eq!(data[index], b' ', "failed num is {}", input);
    }

    fn test_parse_int_ok(input: &str, expected: u64) {
        let mut data = input.as_bytes().to_vec();
        data.push(b' ');
        let mut index = 0;
        let num = parse_number(&data, &mut index, false).unwrap();
        assert!(
            matches!(num, ParserNumber::Unsigned(v) if v == expected),
            "input {} parsed as {:?}, expected Unsigned({})",
            input,
            num,
            expected
        );
        assert_eq!(data[index], b' ', "trailing byte for {}", input);
    }

    fn test_parse_f32_ok(input: &str, expect: f32) {
        assert_eq!(input.parse::<f32>().unwrap().to_bits(), expect.to_bits());

        let mut data = input.as_bytes().to_vec();
        data.push(b' ');
        let mut index = if input.starts_with('-') { 1 } else { 0 };
        let num = parse_float32(&data, &mut index, input.starts_with('-')).unwrap();
        assert_eq!(
            num.to_bits(),
            expect.to_bits(),
            "parsed is {:?} failed num is {}",
            num,
            input
        );
        assert_eq!(data[index], b' ', "failed num is {}", input);
    }

    fn test_parse_f32_finite_err(input: &str) {
        let mut data = input.as_bytes().to_vec();
        data.push(b' ');
        let mut index = if input.starts_with('-') { 1 } else { 0 };
        let err = parse_float32(&data, &mut index, input.starts_with('-')).unwrap_err();
        assert!(
            matches!(err, crate::Error::FloatMustBeFinite),
            "input {} returned {:?}",
            input,
            err
        );
    }

    fn test_parse_signed_ok(input: &str, expected: i64) {
        let mut data = input.as_bytes().to_vec();
        data.push(b' ');
        let mut index = 1; // skip '-'
        let num = parse_number(&data, &mut index, true).unwrap();
        assert!(
            matches!(num, ParserNumber::Signed(v) if v == expected),
            "input {} parsed as {:?}, expected Signed({})",
            input,
            num,
            expected
        );
    }

    #[test]
    fn test_parse_number_integers() {
        // Small integers (scalar fallback path, remaining < 8)
        test_parse_int_ok("0", 0);
        test_parse_int_ok("1", 1);
        test_parse_int_ok("42", 42);
        test_parse_int_ok("123", 123);
        test_parse_int_ok("1234", 1234);
        test_parse_int_ok("12345", 12345);
        test_parse_int_ok("123456", 123456);
        test_parse_int_ok("1234567", 1234567);
        // 8-digit (first SWAR batch boundary)
        test_parse_int_ok("12345678", 12345678);
        test_parse_int_ok("99999999", 99999999);
        // 9-15 digits (SWAR + scalar tail)
        test_parse_int_ok("123456789", 123456789);
        test_parse_int_ok("1234567890", 1234567890);
        test_parse_int_ok("123456789012345", 123456789012345);
        // 16 digits (two SWAR batches)
        test_parse_int_ok("1234567890123456", 1234567890123456);
        // 17-19 digits (two SWAR + scalar tail)
        test_parse_int_ok("12345678901234567", 12345678901234567);
        test_parse_int_ok("123456789012345678", 123456789012345678);
        test_parse_int_ok("1234567890123456789", 1234567890123456789);
        // u64::MAX
        test_parse_int_ok("18446744073709551615", u64::MAX);
        // Negative integers
        test_parse_signed_ok("-1", -1);
        test_parse_signed_ok("-12345678", -12345678);
        test_parse_signed_ok("-1234567890123456789", -1234567890123456789);
        test_parse_signed_ok("-9223372036854775808", i64::MIN);
    }

    #[test]
    fn test_parse_number_overflow_to_float() {
        // > 20 digits → float
        test_parse_ok("33333333333333333333", 3.333333333333333e19);
        test_parse_ok("123456789012345678901", 1.2345678901234568e20);
        // Truncated integer without dot
        test_parse_ok("12448139190673828122020e-47", 1.244813919067383e-25);
        test_parse_ok(
            "3469446951536141862700000000000000000e-62",
            3.469446951536142e-26,
        );
    }

    #[test]
    fn test_parse_float() {
        test_parse_ok("0.0", 0.0);
        test_parse_ok("0.01", 0.01);
        test_parse_ok("0.1", 0.1);
        test_parse_ok("0.12", 0.12);
        test_parse_ok("0.123", 0.123);
        test_parse_ok("0.1234", 0.1234);
        test_parse_ok("0.12345", 0.12345);
        test_parse_ok("0.123456", 0.123456);
        test_parse_ok("0.1234567", 0.1234567);
        test_parse_ok("0.12345678", 0.12345678);
        test_parse_ok("0.123456789", 0.123456789);
        test_parse_ok("0.1234567890", 0.1234567890);
        test_parse_ok("0.10000000149011612", 0.10000000149011612);
        test_parse_ok("0.06411743306171047", 0.06411743306171047);

        test_parse_ok("0e-1", 0e-1);
        test_parse_ok("0e+1000000", 0e+1000000);
        test_parse_ok("0.001e-1", 0.001e-1);
        test_parse_ok("0.001e+123", 0.001e+123);
        test_parse_ok(
            "0.000000000000000000000000001e+123",
            0.000000000000000000000000001e+123,
        );

        test_parse_ok("1.0", 1.0);
        test_parse_ok("1350.0", 1350.0);
        test_parse_ok("1.10000000149011612", 1.1000000014901161);

        // 8+ integer digits + fraction: exercises parse_number_fraction
        // with digits_cnt >= 8, need <= 9, fraction slice may be < 16 bytes.
        test_parse_ok("12345678.123456789", 12345678.123456789);
        test_parse_ok("12345678.1", 12345678.1);
        test_parse_ok("12345678.12345678", 12345678.12345678);
        test_parse_ok("123456789.123456", 123456789.123456);
        test_parse_ok("1234567890.1234567", 1234567890.1234567);
        test_parse_ok("99999999.99999999", 99999999.99999999);

        test_parse_ok("1e0", 1e0);
        test_parse_ok("1.0e0", 1.0e0);
        test_parse_ok("1.0e+0", 1.0e+0);
        test_parse_ok("1.001e-123", 1.001e-123);
        test_parse_ok("10000000149011610000.0e-123", 1.000_000_014_901_161e-104);
        test_parse_ok(
            "10000000149011612123.001e-123",
            1.000_000_014_901_161_2e-104,
        );
        test_parse_ok("33333333333333333333", 3.333333333333333e19);
        test_parse_ok("135e-12", 135e-12);

        // test truncated float number without dot
        test_parse_ok("12448139190673828122020e-47", 1.244813919067383e-25);
        test_parse_ok(
            "3469446951536141862700000000000000000e-62",
            3.469446951536142e-26,
        );
    }

    #[test]
    fn test_parse_float32() {
        test_parse_f32_ok("0", 0.0);
        test_parse_f32_ok("-0", -0.0);
        test_parse_f32_ok("1", 1.0);
        test_parse_f32_ok("0.1", 0.1);
        test_parse_f32_ok("1.23", 1.23);
        test_parse_f32_ok("100e11", "100e11".parse().unwrap());
        test_parse_f32_ok(
            "17005001.000000000000130",
            "17005001.000000000000130".parse().unwrap(),
        );
        test_parse_f32_ok("3.4028235e38", "3.4028235e38".parse().unwrap());
        test_parse_f32_ok("1.17549435e-38", "1.17549435e-38".parse().unwrap());
        test_parse_f32_ok(
            "12448139190673828122020e-47",
            "12448139190673828122020e-47".parse().unwrap(),
        );
        test_parse_f32_finite_err("3.4028236e38");
        test_parse_f32_finite_err("1e39");
    }
}