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
// This `dtoa` implementation is taken from `https://github.com/dtolnay/dtoa`.

//---------------------------------------------------------------------------------------------------- Use
#![allow(
    clippy::cast_lossless,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::doc_markdown,
    clippy::expl_impl_clone_on_copy,
    clippy::if_not_else,
    clippy::missing_errors_doc,
    clippy::must_use_candidate,
    clippy::needless_doctest_main,
    clippy::range_plus_one,
    clippy::semicolon_if_nothing_returned, // https://github.com/rust-lang/rust-clippy/issues/7768
    clippy::shadow_unrelated,
    clippy::suspicious_else_formatting,
    clippy::transmute_float_to_int,
    clippy::unreadable_literal,
    clippy::unseparated_literal_suffix
)]

use core::mem::{self, MaybeUninit};
use core::slice;
use core::str;

//----------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// ---
//
// The C++ implementation preserved here in comments is licensed as follows:
//
// Tencent is pleased to support the open source community by making RapidJSON
// available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All
// rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License
// at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

use core::ptr;

/*
inline unsigned CountDecimalDigit32(uint32_t n) {
    // Simple pure C++ implementation was faster than __builtin_clz version in this situation.
    if (n < 10) return 1;
    if (n < 100) return 2;
    if (n < 1000) return 3;
    if (n < 10000) return 4;
    if (n < 100000) return 5;
    if (n < 1000000) return 6;
    if (n < 10000000) return 7;
    if (n < 100000000) return 8;
    // Will not reach 10 digits in DigitGen()
    //if (n < 1000000000) return 9;
    //return 10;
    return 9;
}
*/

#[inline]
fn count_decimal_digit32(n: u32) -> usize {
    if n < 10 {
        1
    } else if n < 100 {
        2
    } else if n < 1000 {
        3
    } else if n < 10000 {
        4
    } else if n < 100000 {
        5
    } else if n < 1000000 {
        6
    } else if n < 10000000 {
        7
    } else if n < 100000000 {
        8
    }
    // Will not reach 10 digits in digit_gen()
    else {
        9
    }
}

/*
inline char* WriteExponent(int K, char* buffer) {
    if (K < 0) {
        *buffer++ = '-';
        K = -K;
    }

    if (K >= 100) {
        *buffer++ = static_cast<char>('0' + static_cast<char>(K / 100));
        K %= 100;
        const char* d = GetDigitsLut() + K * 2;
        *buffer++ = d[0];
        *buffer++ = d[1];
    }
    else if (K >= 10) {
        const char* d = GetDigitsLut() + K * 2;
        *buffer++ = d[0];
        *buffer++ = d[1];
    }
    else
        *buffer++ = static_cast<char>('0' + static_cast<char>(K));

    return buffer;
}
*/

#[inline]
unsafe fn write_exponent(mut k: isize, mut buffer: *mut u8) -> *mut u8 {
    if k < 0 {
        *buffer = b'-';
        buffer = buffer.offset(1);
        k = -k;
    }

    if k >= 100 {
        *buffer = b'0' + (k / 100) as u8;
        k %= 100;
        let d = DEC_DIGITS_LUT.as_ptr().offset(k * 2);
        ptr::copy_nonoverlapping(d, buffer.offset(1), 2);
        buffer.offset(3)
    } else if k >= 10 {
        let d = DEC_DIGITS_LUT.as_ptr().offset(k * 2);
        ptr::copy_nonoverlapping(d, buffer, 2);
        buffer.offset(2)
    } else {
        *buffer = b'0' + k as u8;
        buffer.offset(1)
    }
}

/*
inline char* Prettify(char* buffer, int length, int k, int maxDecimalPlaces) {
    const int kk = length + k;  // 10^(kk-1) <= v < 10^kk
*/

#[inline]
unsafe fn prettify(buffer: *mut u8, length: isize, k: isize) -> *mut u8 {
    let kk = length + k; // 10^(kk-1) <= v < 10^kk

    /*
    if (0 <= k && kk <= 21) {
        // 1234e7 -> 12340000000
        for (int i = length; i < kk; i++)
            buffer[i] = '0';
        buffer[kk] = '.';
        buffer[kk + 1] = '0';
        return &buffer[kk + 2];
    }
    */
    if 0 <= k && kk <= 21 {
        // 1234e7 -> 12340000000
        for i in length..kk {
            *buffer.offset(i) = b'0';
        }
        *buffer.offset(kk) = b'.';
        *buffer.offset(kk + 1) = b'0';
        buffer.offset(kk + 2)
    }
    /*
    else if (0 < kk && kk <= 21) {
        // 1234e-2 -> 12.34
        std::memmove(&buffer[kk + 1], &buffer[kk], static_cast<size_t>(length - kk));
        buffer[kk] = '.';
        if (0 > k + maxDecimalPlaces) {
            // When maxDecimalPlaces = 2, 1.2345 -> 1.23, 1.102 -> 1.1
            // Remove extra trailing zeros (at least one) after truncation.
            for (int i = kk + maxDecimalPlaces; i > kk + 1; i--)
                if (buffer[i] != '0')
                    return &buffer[i + 1];
            return &buffer[kk + 2]; // Reserve one zero
        }
        else
            return &buffer[length + 1];
    }
    */
    else if 0 < kk && kk <= 21 {
        // 1234e-2 -> 12.34
        ptr::copy(
            buffer.offset(kk),
            buffer.offset(kk + 1),
            (length - kk) as usize,
        );
        *buffer.offset(kk) = b'.';
        if 0 > k + MAX_DECIMAL_PLACES {
            // When MAX_DECIMAL_PLACES = 2, 1.2345 -> 1.23, 1.102 -> 1.1
            // Remove extra trailing zeros (at least one) after truncation.
            for i in (kk + 2..kk + MAX_DECIMAL_PLACES + 1).rev() {
                if *buffer.offset(i) != b'0' {
                    return buffer.offset(i + 1);
                }
            }
            buffer.offset(kk + 2) // Reserve one zero
        } else {
            buffer.offset(length + 1)
        }
    }
    /*
    else if (-6 < kk && kk <= 0) {
        // 1234e-6 -> 0.001234
        const int offset = 2 - kk;
        std::memmove(&buffer[offset], &buffer[0], static_cast<size_t>(length));
        buffer[0] = '0';
        buffer[1] = '.';
        for (int i = 2; i < offset; i++)
            buffer[i] = '0';
        if (length - kk > maxDecimalPlaces) {
            // When maxDecimalPlaces = 2, 0.123 -> 0.12, 0.102 -> 0.1
            // Remove extra trailing zeros (at least one) after truncation.
            for (int i = maxDecimalPlaces + 1; i > 2; i--)
                if (buffer[i] != '0')
                    return &buffer[i + 1];
            return &buffer[3]; // Reserve one zero
        }
        else
            return &buffer[length + offset];
    }
    */
    else if -6 < kk && kk <= 0 {
        // 1234e-6 -> 0.001234
        let offset = 2 - kk;
        ptr::copy(buffer, buffer.offset(offset), length as usize);
        *buffer = b'0';
        *buffer.offset(1) = b'.';
        for i in 2..offset {
            *buffer.offset(i) = b'0';
        }
        if length - kk > MAX_DECIMAL_PLACES {
            // When MAX_DECIMAL_PLACES = 2, 0.123 -> 0.12, 0.102 -> 0.1
            // Remove extra trailing zeros (at least one) after truncation.
            for i in (3..MAX_DECIMAL_PLACES + 2).rev() {
                if *buffer.offset(i) != b'0' {
                    return buffer.offset(i + 1);
                }
            }
            buffer.offset(3) // Reserve one zero
        } else {
            buffer.offset(length + offset)
        }
    }
    /*
    else if (kk < -maxDecimalPlaces) {
        // Truncate to zero
        buffer[0] = '0';
        buffer[1] = '.';
        buffer[2] = '0';
        return &buffer[3];
    }
    */
    else if kk < -MAX_DECIMAL_PLACES {
        *buffer = b'0';
        *buffer.offset(1) = b'.';
        *buffer.offset(2) = b'0';
        buffer.offset(3)
    }
    /*
    else if (length == 1) {
        // 1e30
        buffer[1] = 'e';
        return WriteExponent(kk - 1, &buffer[2]);
    }
    */
    else if length == 1 {
        // 1e30
        *buffer.offset(1) = b'e';
        write_exponent(kk - 1, buffer.offset(2))
    }
    /*
    else {
        // 1234e30 -> 1.234e33
        std::memmove(&buffer[2], &buffer[1], static_cast<size_t>(length - 1));
        buffer[1] = '.';
        buffer[length + 1] = 'e';
        return WriteExponent(kk - 1, &buffer[0 + length + 2]);
    }
    */
    else {
        // 1234e30 -> 1.234e33
        ptr::copy(buffer.offset(1), buffer.offset(2), (length - 1) as usize);
        *buffer.offset(1) = b'.';
        *buffer.offset(length + 1) = b'e';
        write_exponent(kk - 1, buffer.offset(length + 2))
    }
}

macro_rules! dtoa_inner {
    (
        floating_type: $fty:ty,
        significand_type: $sigty:ty,
        exponent_type: $expty:ty,
        $($diyfp_param:ident: $diyfp_value:tt,)*
    ) => {
        diyfp! {
            floating_type: $fty,
            significand_type: $sigty,
            exponent_type: $expty,
            $($diyfp_param: $diyfp_value,)*
        };

        /*
        inline void GrisuRound(char* buffer, int len, uint64_t delta, uint64_t rest, uint64_t ten_kappa, uint64_t wp_w) {
            while (rest < wp_w && delta - rest >= ten_kappa &&
                (rest + ten_kappa < wp_w ||  /// closer
                    wp_w - rest > rest + ten_kappa - wp_w)) {
                buffer[len - 1]--;
                rest += ten_kappa;
            }
        }
        */

        #[inline]
    
        unsafe fn grisu_round(buffer: *mut u8, len: isize, delta: $sigty, mut rest: $sigty, ten_kappa: $sigty, wp_w: $sigty) {
            while rest < wp_w && delta - rest >= ten_kappa &&
                (rest + ten_kappa < wp_w || // closer
                    wp_w - rest > rest + ten_kappa - wp_w) {
                *buffer.offset(len - 1) -= 1;
                rest += ten_kappa;
            }
        }

        /*
        inline void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, char* buffer, int* len, int* K) {
            static const uint32_t kPow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
            const DiyFp one(uint64_t(1) << -Mp.e, Mp.e);
            const DiyFp wp_w = Mp - W;
            uint32_t p1 = static_cast<uint32_t>(Mp.f >> -one.e);
            uint64_t p2 = Mp.f & (one.f - 1);
            unsigned kappa = CountDecimalDigit32(p1); // kappa in [0, 9]
            *len = 0;
        */

        // Returns length and k.
        #[inline]
    
        unsafe fn digit_gen(w: DiyFp, mp: DiyFp, mut delta: $sigty, buffer: *mut u8, mut k: isize) -> (isize, isize) {
            static POW10: [$sigty; 10] = [ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 ];
            let one = DiyFp::new(1 << -mp.e, mp.e);
            let wp_w = mp - w;
            let mut p1 = (mp.f >> -one.e) as u32;
            let mut p2 = mp.f & (one.f - 1);
            let mut kappa = count_decimal_digit32(p1); // kappa in [0, 9]
            let mut len = 0;

            /*
            while (kappa > 0) {
                uint32_t d = 0;
                switch (kappa) {
                    case  9: d = p1 /  100000000; p1 %=  100000000; break;
                    case  8: d = p1 /   10000000; p1 %=   10000000; break;
                    case  7: d = p1 /    1000000; p1 %=    1000000; break;
                    case  6: d = p1 /     100000; p1 %=     100000; break;
                    case  5: d = p1 /      10000; p1 %=      10000; break;
                    case  4: d = p1 /       1000; p1 %=       1000; break;
                    case  3: d = p1 /        100; p1 %=        100; break;
                    case  2: d = p1 /         10; p1 %=         10; break;
                    case  1: d = p1;              p1 =           0; break;
                    default:;
                }
                if (d || *len)
                    buffer[(*len)++] = static_cast<char>('0' + static_cast<char>(d));
                kappa--;
                uint64_t tmp = (static_cast<uint64_t>(p1) << -one.e) + p2;
                if (tmp <= delta) {
                    *K += kappa;
                    GrisuRound(buffer, *len, delta, tmp, static_cast<uint64_t>(kPow10[kappa]) << -one.e, wp_w.f);
                    return;
                }
            }
            */
            while kappa > 0 {
                let mut d = 0u32;
                match kappa {
                    9 => { d = p1 /  100000000; p1 %=  100000000; }
                    8 => { d = p1 /   10000000; p1 %=   10000000; }
                    7 => { d = p1 /    1000000; p1 %=    1000000; }
                    6 => { d = p1 /     100000; p1 %=     100000; }
                    5 => { d = p1 /      10000; p1 %=      10000; }
                    4 => { d = p1 /       1000; p1 %=       1000; }
                    3 => { d = p1 /        100; p1 %=        100; }
                    2 => { d = p1 /         10; p1 %=         10; }
                    1 => { d = p1;              p1 =           0; }
                    _ => {}
                }
                if d != 0 || len != 0 {
                    *buffer.offset(len) = b'0' + d as u8;
                    len += 1;
                }
                kappa -= 1;
                let tmp = ((p1 as $sigty) << -one.e) + p2;
                if tmp <= delta {
                    k += kappa as isize;
                    grisu_round(buffer, len, delta, tmp, *POW10.get_unchecked(kappa) << -one.e, wp_w.f);
                    return (len, k);
                }
            }

            // kappa = 0
            /*
            for (;;) {
                p2 *= 10;
                delta *= 10;
                char d = static_cast<char>(p2 >> -one.e);
                if (d || *len)
                    buffer[(*len)++] = static_cast<char>('0' + d);
                p2 &= one.f - 1;
                kappa--;
                if (p2 < delta) {
                    *K += kappa;
                    int index = -static_cast<int>(kappa);
                    GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * (index < 9 ? kPow10[-static_cast<int>(kappa)] : 0));
                    return;
                }
            }
            */
            loop {
                p2 *= 10;
                delta *= 10;
                let d = (p2 >> -one.e) as u8;
                if d != 0 || len != 0 {
                    *buffer.offset(len) = b'0' + d;
                    len += 1;
                }
                p2 &= one.f - 1;
                kappa = kappa.wrapping_sub(1);
                if p2 < delta {
                    k += kappa as isize;
                    let index = -(kappa as isize);
                    grisu_round(
                        buffer,
                        len,
                        delta,
                        p2,
                        one.f,
                        wp_w.f * if index < 9 {
                            *POW10.get_unchecked(-(kappa as isize) as usize)
                        } else {
                            0
                        },
                    );
                    return (len, k);
                }
            }
        }

        /*
        inline void Grisu2(double value, char* buffer, int* length, int* K) {
            const DiyFp v(value);
            DiyFp w_m, w_p;
            v.NormalizedBoundaries(&w_m, &w_p);

            const DiyFp c_mk = GetCachedPower(w_p.e, K);
            const DiyFp W = v.Normalize() * c_mk;
            DiyFp Wp = w_p * c_mk;
            DiyFp Wm = w_m * c_mk;
            Wm.f++;
            Wp.f--;
            DigitGen(W, Wp, Wp.f - Wm.f, buffer, length, K);
        }
        */

        // Returns length and k.
        #[inline]
    
        unsafe fn grisu2(value: $fty, buffer: *mut u8) -> (isize, isize) {
            let v = DiyFp::from(value);
            let (w_m, w_p) = v.normalized_boundaries();

            let (c_mk, k) = get_cached_power(w_p.e);
            let w = v.normalize() * c_mk;
            let mut wp = w_p * c_mk;
            let mut wm = w_m * c_mk;
            wm.f += 1;
            wp.f -= 1;
            digit_gen(w, wp, wp.f - wm.f, buffer, k)
        }

        /*
        inline char* dtoa(double value, char* buffer, int maxDecimalPlaces = 324) {
            RAPIDJSON_ASSERT(maxDecimalPlaces >= 1);
            Double d(value);
            if (d.IsZero()) {
                if (d.Sign())
                    *buffer++ = '-';     // -0.0, Issue #289
                buffer[0] = '0';
                buffer[1] = '.';
                buffer[2] = '0';
                return &buffer[3];
            }
            else {
                if (value < 0) {
                    *buffer++ = '-';
                    value = -value;
                }
                int length, K;
                Grisu2(value, buffer, &length, &K);
                return Prettify(buffer, length, K, maxDecimalPlaces);
            }
        }
        */

        #[inline]
    
        unsafe fn dtoa(buf: &mut [MaybeUninit<u8>; 25], mut value: $fty) -> &str {
            if value == 0.0 {
                if value.is_sign_negative() {
                    "-0.0"
                } else {
                    "0.0"
                }
            } else {
                let start = buf.as_mut_ptr() as *mut u8;
                let mut buf_ptr = start;
                if value < 0.0 {
                    *buf_ptr = b'-';
                    buf_ptr = buf_ptr.offset(1);
                    value = -value;
                }
                let (length, k) = grisu2(value, buf_ptr);
                let end = prettify(buf_ptr, length, k);
                let len = end as usize - start as usize;
                str::from_utf8_unchecked(slice::from_raw_parts(start, len))
            }
        }
    };
}

//---------------------------------------------------------------------------------------------------- Const
const NAN:          &str = "NaN";
const INFINITY:     &str = "inf";
const NEG_INFINITY: &str = "-inf";

//---------------------------------------------------------------------------------------------------- Dtoa
/// Fast float to string conversion
///
/// This struct represents a stack-based string converted from an [`IntoDtoa`] (number).
///
/// It internally uses [`dtoa`](https://docs.rs/dtoa) by `dtolnay`,
/// however [`Dtoa`] stores the string computation and can be turned into a [`&str`]
/// again and again after construction.
///
/// This does not do any `readable`-style formatting (adding commas), it simply
/// converts an integer into a string (but is much faster than [`format!()`]).
///
/// ## Example
/// ```rust
/// # use readable::Dtoa;
/// let dtoa = Dtoa::new(0.0);
/// assert_eq!(dtoa, "0.0");
///
/// let copy = dtoa;
/// assert_eq!(dtoa.as_str(), copy.as_str());
/// ```
///
/// ## Size
/// ```rust
/// assert_eq!(std::mem::size_of::<readable::Dtoa>(), 26);
/// ```
#[derive(Copy, Clone, Debug)]
pub struct Dtoa {
	len: u8,
    bytes: [MaybeUninit<u8>; 25],
}

impl Default for Dtoa {
    #[inline]
    fn default() -> Dtoa {
        Dtoa::new_finite(0.0)
    }
}

impl Dtoa {
	/// Create a new [`Dtoa`].
	///
	/// Takes any [`IntoDtoa`] ([`f32`], [`f64`]).
	///
	/// This function will properly format non-finite floats.
	///
	/// See [`Dtoa::new_finite()`] if you know your float is finite
	/// (not [`f32::NAN`], [`f32::INFINITY`], [`f32::NEG_INFINITY`]).
	///
	/// ```rust
	/// # use readable::Dtoa;
	/// let dtoa = Dtoa::new(1.0);
	/// assert_eq!(dtoa, "1.0");
	///
	/// let dtoa = Dtoa::new(f64::NAN);
	/// assert_eq!(dtoa, "NaN");
	/// let dtoa = Dtoa::new(f64::INFINITY);
	/// assert_eq!(dtoa, "inf");
	/// let dtoa = Dtoa::new(f64::NEG_INFINITY);
	/// assert_eq!(dtoa, "-inf");
	/// ```

    pub fn new<N: IntoDtoa>(num: N) -> Self {
        if num.is_nonfinite() {
			let mut bytes = [MaybeUninit::<u8>::uninit(); 25];
            let string = num.format_nonfinite();
			for (i, byte) in string.as_bytes().into_iter().enumerate() {
				bytes[i].write(*byte);
			}
			Self {
				len: string.len() as u8,
				bytes,
			}
        } else {
            Self::new_finite(num)
        }
    }

	/// Create a new [`Dtoa`].
	///
	/// Takes any [`IntoDtoa`].
	///
	/// This function **will not** properly format non-finite floats.
	///
	/// See [`Dtoa::new()`] for non-finite float formatting
	/// (not [`f32::NAN`], [`f32::INFINITY`], [`f32::NEG_INFINITY`]).
	///
	/// ```rust
	/// # use readable::Dtoa;
	/// let dtoa = Dtoa::new(18.425);
	/// assert_eq!(dtoa, "18.425");
	/// let dtoa = Dtoa::new(19.0918);
	/// assert_eq!(dtoa, "19.0918");
	///
	/// // This is safe, but the output strings will be incorrect.
	/// let dtoa = Dtoa::new_finite(f64::NAN);
	/// assert_eq!(dtoa, "2.696539702293474e308");
	/// let dtoa = Dtoa::new_finite(f64::INFINITY);
	/// assert_eq!(dtoa, "1.797693134862316e308");
	/// let dtoa = Dtoa::new_finite(f64::NEG_INFINITY);
	/// assert_eq!(dtoa, "-1.797693134862316e308");
	/// ```

    pub fn new_finite<N: IntoDtoa>(num: N) -> Self {
		let mut input = [MaybeUninit::<u8>::uninit(); 25];
		let string = num.write(&mut input);

		let mut bytes = [MaybeUninit::<u8>::uninit(); 25];

		for (i, byte) in string.as_bytes().into_iter().enumerate() {
			bytes[i].write(*byte);
		}

		Self {
			len: string.len() as u8,
			bytes,
		}
    }

	#[inline]
	/// Turns [`Dtoa`] into a `&str`.
	///
	/// ```rust
	/// # use readable::Dtoa;
	/// let dtoa:   Dtoa = Dtoa::new(123.456);
	/// let string: &str = dtoa.as_str();
	/// assert_eq!(string, "123.456");
	/// ```
	pub const fn as_str(&self) -> &str {
		// Safety: Constructors must set state correctly.
		unsafe {
			let slice = slice::from_raw_parts(
				self.bytes.as_ptr() as *const u8,
				self.len as usize
			);
			std::str::from_utf8_unchecked(slice)
		}
	}
}

//---------------------------------------------------------------------------------------------------- DtoaTmp
/// A short-lived version of [`Dtoa`]
///
/// This version doesn't save the formatting
/// computation, and is meant for cases where the
/// lifetime of the formatted output [`&str`] is very brief.
///
/// This version has less overhead, but the string
/// must be formatted everytime you need it.
///
/// See [`crate::dtoa!()`] for a quick 1-line format macro.
///
/// ```rust
/// # use readable::DtoaTmp;
/// assert_eq!(DtoaTmp::new().format(1.0), "1.0");
/// ```
///
/// You could keep a [`DtoaTmp`] around to use it
/// as a factory to keep formatting new strings,
/// as it will reuse the inner buffer:
/// ```rust
/// # use readable::DtoaTmp;
/// let mut dtoa = DtoaTmp::new();
///
/// assert_eq!(dtoa.format(1.0), "1.0");
/// assert_eq!(dtoa.format(2.0), "2.0");
/// assert_eq!(dtoa.format(3.0), "3.0");
/// ```
///
/// ## Size
/// ```rust
/// assert_eq!(std::mem::size_of::<readable::DtoaTmp>(), 25);
/// ```
#[derive(Copy, Clone, Debug)]
pub struct DtoaTmp {
	bytes: [MaybeUninit<u8>; 25],
}

impl DtoaTmp {
	/// Create a new [`DtoaTmp`].
	#[inline]
	pub const fn new() -> Self {
		Self { bytes: [MaybeUninit::<u8>::uninit(); 25] }
	}

	/// Format an [`IntoDtoa`] into a [`&str`] with an existing [`DtoaTmp`]
	///
	/// This function will properly format non-finite floats.
	///
	/// See [`DtoaTmp::format_finite()`] if you know your float is finite
	/// (not [`f32::NAN`], [`f32::INFINITY`], [`f32::NEG_INFINITY`]).
	///
	/// ```rust
	/// # use readable::DtoaTmp;
	/// // We can cheaply reuse this.
	/// let mut dtoa = DtoaTmp::new();
	///
	/// assert_eq!(dtoa.format(18.425),  "18.425");
	/// assert_eq!(dtoa.format(19.0918), "19.0918");
	/// assert_eq!(dtoa.format(1.0),     "1.0");
	///
	/// assert_eq!(dtoa.format(f32::NAN),          "NaN");
	/// assert_eq!(dtoa.format(f32::INFINITY),     "inf");
	/// assert_eq!(dtoa.format(f32::NEG_INFINITY), "-inf");
	/// ```
	pub fn format<N: IntoDtoa>(&mut self, num: N) -> &str {
		if num.is_nonfinite() {
			num.format_nonfinite()
		} else {
			num.write(&mut self.bytes)
		}
	}

	#[inline]
	/// Format an [`IntoDtoa`] into a [`&str`] with an existing [`DtoaTmp`]
	///
	/// This function **will not** properly format non-finite floats.
	///
	/// See [`DtoaTmp::format()`] for non-finite float formatting
	/// (not [`f32::NAN`], [`f32::INFINITY`], [`f32::NEG_INFINITY`]).
	///
	/// ```rust
	/// # use readable::DtoaTmp;
	/// // We can cheaply reuse this.
	/// let mut dtoa = DtoaTmp::new();
	///
	/// assert_eq!(dtoa.format_finite(18.425),  "18.425");
	/// assert_eq!(dtoa.format_finite(19.0918), "19.0918");
	///
	/// // This is safe, but the output strings will be incorrect.
	/// assert_eq!(dtoa.format_finite(f64::NAN),          "2.696539702293474e308");
	/// assert_eq!(dtoa.format_finite(f64::INFINITY),     "1.797693134862316e308");
	/// assert_eq!(dtoa.format_finite(f64::NEG_INFINITY), "-1.797693134862316e308");
	/// ```
	pub fn format_finite<N: IntoDtoa>(&mut self, num: N) -> &str {
		num.write(&mut self.bytes)
	}
}

#[macro_export]
/// Quickly format a float to a [`&str`]
///
/// This creates a [`DtoaTmp`] from an [`IntoDtoa`], returns the output [`&str`], and immediately goes out of scope.
///
/// The function signature would look something like:
/// ```rust,ignore
/// fn dtoa<N: IntoDtoa>(num: N) -> &'tmp str
/// where
/// 	'tmp: FreedAtEndOfStatement
/// ```
///
/// [`DtoaTmp`] is created and immediately dropped, thus it cannot be stored:
/// ```rust,ignore
/// # use readable::dtoa;
/// let x = dtoa!(1.0);
///         ^^^^^^^^^^- temporary value is freed at the end of this statement
///
/// assert_eq!(x, "1.0");
/// -------------------- compile error: borrow later used here
/// ```
///
/// You must use the [`&str`] in 1 single statement:
/// ```rust
/// # use readable::dtoa;
/// assert_eq!(dtoa!(1.0), "1.0"); // ok
///
/// if dtoa!(f32::NAN) == "NaN" {
/// 	// ok
/// }
///
/// // ok
/// let string: String = dtoa!(f32::INFINITY).to_string();
/// assert_eq!(string, "inf");
/// ```
///
/// The macro expands to `DtoaTmp::new().format(x)`:
/// ```rust
/// # use readable::dtoa;
/// // These are the same.
///
/// dtoa!(1.0);
///
/// readable::DtoaTmp::new().format(1.0);
/// ```
macro_rules! dtoa {
	($into_dtoa:expr) => {{
		$crate::DtoaTmp::new().format($into_dtoa)
	}};
}

//---------------------------------------------------------------------------------------------------- Dtoa Traits
impl std::ops::Deref for Dtoa {
	type Target = str;

	fn deref(&self) -> &Self::Target {
		self.as_str()
	}
}

impl AsRef<str> for Dtoa {
	fn as_ref(&self) -> &str {
		self.as_str()
	}
}

impl std::borrow::Borrow<str> for Dtoa {
	fn borrow(&self) -> &str {
		self.as_str()
	}
}

impl PartialEq<str> for Dtoa {
	fn eq(&self, other: &str) -> bool {
		self.as_str() == other
	}
}

impl PartialEq<&str> for Dtoa {
	fn eq(&self, other: &&str) -> bool {
		self.as_str() == *other
	}
}

impl PartialEq<String> for Dtoa {
	fn eq(&self, other: &String) -> bool {
		self.as_str() == other
	}
}

impl<T: IntoDtoa> std::convert::From<T> for Dtoa {
	fn from(float: T) -> Self {
		Self::new(float)
	}
}

impl std::fmt::Display for Dtoa {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "{}", self.as_str())
	}
}

//---------------------------------------------------------------------------------------------------- IntoDtoa
/// Numbers that can losslessly be written into a [`Dtoa`].
///
/// Non-floating point numbers (not [`f32`] or [`f64`]) will be casted with `as` before creation.
///
/// Precision is 100% lossless for any integer that is 32 bits or less.
///
/// 64/128-bit integers may be lossy, so they aren't implemented for [`IntoDtoa`].
///
/// ```rust
/// # use readable::Dtoa;
/// let dtoa_from_float = Dtoa::new(-2147483648.0_f64);
/// assert_eq!(dtoa_from_float, "-2147483648.0");
///
/// // Casted to `f64` before creation.
/// let dtoa_from_int = Dtoa::new(-2147483648_i32);
/// assert_eq!(dtoa_from_int, "-2147483648.0");
///
/// // This code is basically the same as the above.
/// let dtoa = Dtoa::new(-2147483648_i32 as f64);
/// assert_eq!(dtoa, "-2147483648.0");
///
/// // u32 conversion is lossless.
/// let mut i = 1_u64;
/// while i <= u32::MAX as u64 {
/// 	let dtoa   = Dtoa::new(i as u32);
/// 	let string = format!("{i}.0");
/// 	assert_eq!(dtoa, string);
/// 	i *= 10;
/// }
///
/// // i32 conversion is lossless.
/// let mut i = -1_i64;
/// while i >= i32::MIN as i64 {
/// 	let dtoa   = Dtoa::new(i as i32);
/// 	let string = format!("{i}.0");
/// 	assert_eq!(dtoa, string);
/// 	i *= 10;
/// }
///
/// // NonZero types work too.
/// let dtoa = Dtoa::new(std::num::NonZeroU32::new(1000).unwrap());
/// assert_eq!(dtoa, "1000.0");
///
/// // ⚠️ Manual lossy conversion.
///	let dtoa = Dtoa::new(u64::MAX as f64);
/// assert_ne!(dtoa, format!("{}.0", u64::MAX)) // not equal
/// ```
pub trait IntoDtoa: private::Sealed {}

use std::num::{
	NonZeroI8,
	NonZeroI16,
	NonZeroI32,
	NonZeroU8,
	NonZeroU16,
	NonZeroU32,
};

macro_rules! impl_float {
	($( $target_type:ty ),* $(,)?) => {
		$(
			impl IntoDtoa for $target_type {}
		)*
	};
}
impl_float! {
	f32,f64,u8,u16,u32,i8,i16,i32,
	NonZeroI8,
	NonZeroI16,
	NonZeroI32,
	NonZeroU8,
	NonZeroU16,
	NonZeroU32,
}

//---------------------------------------------------------------------------------------------------- Impl
// Seal to prevent downstream implementations of IntoDtoa trait.
mod private {
    pub trait Sealed: Copy {
        fn is_nonfinite(self) -> bool;
        fn format_nonfinite(self) -> &'static str;
        fn write(self, buf: &mut [core::mem::MaybeUninit<u8>; 25]) -> &str;
    }
}

macro_rules! impl_int {
	($( $int:ty => $target_float:ty ),* $(,)?) => {$(
		impl private::Sealed for $int {
			#[inline]
			fn is_nonfinite(self) -> bool {
				false // Integer can't be NaN
			}

			#[cold]
			fn format_nonfinite(self) -> &'static str {
				// private::Sealed::format_nonfinite(self as $target_float)
				unreachable!() // Integer can't be NaN
			}

			#[inline]
			fn write(self, buf: &mut [core::mem::MaybeUninit<u8>; 25]) -> &str {
				private::Sealed::write(self as $target_float, buf)
			}
		}
	)*};
}
macro_rules! impl_non_zero {
	($( $int:ty => $target_float:ty ),* $(,)?) => {$(
		impl private::Sealed for $int {
			#[inline]
			fn is_nonfinite(self) -> bool {
				false // Integer can't be NaN
			}

			#[cold]
			fn format_nonfinite(self) -> &'static str {
				// private::Sealed::format_nonfinite(self.get() as $target_float)
				unreachable!() // Integer can't be NaN
			}

			#[inline]
			fn write(self, buf: &mut [core::mem::MaybeUninit<u8>; 25]) -> &str {
				private::Sealed::write(self.get() as $target_float, buf)
			}
		}
	)*};
}
impl_int! {
	u8  => f32,
	u16 => f32,
	u32 => f64,
	i8  => f32,
	i16 => f32,
	i32 => f64,
}
impl_non_zero! {
	NonZeroI8  => f32,
	NonZeroI16 => f32,
	NonZeroI32 => f64,
	NonZeroU8  => f32,
	NonZeroU16 => f32,
	NonZeroU32 => f64,
}

impl private::Sealed for f32 {
    #[inline]
    fn is_nonfinite(self) -> bool {
        const EXP_MASK: u32 = 0x7f800000;
        let bits = self.to_bits();
        bits & EXP_MASK == EXP_MASK
    }

    #[cold]
    fn format_nonfinite(self) -> &'static str {
        const MANTISSA_MASK: u32 = 0x007fffff;
        const SIGN_MASK: u32 = 0x80000000;
        let bits = self.to_bits();
        if bits & MANTISSA_MASK != 0 {
            NAN
        } else if bits & SIGN_MASK != 0 {
            NEG_INFINITY
        } else {
            INFINITY
        }
    }

    #[inline]
    fn write(self, buf: &mut [MaybeUninit<u8>; 25]) -> &str {
        dtoa_inner! {
            floating_type: f32,
            significand_type: u32,
            exponent_type: i32,

            diy_significand_size: 32,
            significand_size: 23,
            exponent_bias: 0x7F,
            mask_type: u32,
            exponent_mask: 0x7F800000,
            significand_mask: 0x007FFFFF,
            hidden_bit: 0x00800000,
            cached_powers_f: CACHED_POWERS_F_32,
            cached_powers_e: CACHED_POWERS_E_32,
            min_power: (-36),
        };
        unsafe { dtoa(buf, self) }
    }
}

impl private::Sealed for f64 {
    #[inline]
    fn is_nonfinite(self) -> bool {
        const EXP_MASK: u64 = 0x7ff0000000000000;
        let bits = self.to_bits();
        bits & EXP_MASK == EXP_MASK
    }

    #[cold]
    fn format_nonfinite(self) -> &'static str {
        const MANTISSA_MASK: u64 = 0x000fffffffffffff;
        const SIGN_MASK: u64 = 0x8000000000000000;
        let bits = self.to_bits();
        if bits & MANTISSA_MASK != 0 {
            NAN
        } else if bits & SIGN_MASK != 0 {
            NEG_INFINITY
        } else {
            INFINITY
        }
    }

    #[inline]
    fn write(self, buf: &mut [MaybeUninit<u8>; 25]) -> &str {
        dtoa_inner! {
            floating_type: f64,
            significand_type: u64,
            exponent_type: isize,

            diy_significand_size: 64,
            significand_size: 52,
            exponent_bias: 0x3FF,
            mask_type: u64,
            exponent_mask: 0x7FF0000000000000,
            significand_mask: 0x000FFFFFFFFFFFFF,
            hidden_bit: 0x0010000000000000,
            cached_powers_f: CACHED_POWERS_F_64,
            cached_powers_e: CACHED_POWERS_E_64,
            min_power: (-348),
        };
        unsafe { dtoa(buf, self) }
    }
}

////////////////////////////////////////////////////////////////////////////////

const MAX_DECIMAL_PLACES: isize = 324;

static DEC_DIGITS_LUT: [u8; 200] = *b"\
    0001020304050607080910111213141516171819\
    2021222324252627282930313233343536373839\
    4041424344454647484950515253545556575859\
    6061626364656667686970717273747576777879\
    8081828384858687888990919293949596979899";

// 10^-36, 10^-28, ..., 10^52
#[rustfmt::skip]
static CACHED_POWERS_F_32: [u32; 12] = [
    0xaa242499, 0xfd87b5f3, 0xbce50865, 0x8cbccc09,
    0xd1b71759, 0x9c400000, 0xe8d4a510, 0xad78ebc6,
    0x813f3979, 0xc097ce7c, 0x8f7e32ce, 0xd5d238a5,
];

#[rustfmt::skip]
static CACHED_POWERS_E_32: [i16; 12] = [
    -151, -125, -98, -71, -45, -18, 8, 35, 62, 88, 115, 141,
];

// 10^-348, 10^-340, ..., 10^340
#[rustfmt::skip]
static CACHED_POWERS_F_64: [u64; 87] = [
    0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76,
    0x8b16fb203055ac76, 0xcf42894a5dce35ea,
    0x9a6bb0aa55653b2d, 0xe61acf033d1a45df,
    0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f,
    0xbe5691ef416bd60c, 0x8dd01fad907ffc3c,
    0xd3515c2831559a83, 0x9d71ac8fada6c9b5,
    0xea9c227723ee8bcb, 0xaecc49914078536d,
    0x823c12795db6ce57, 0xc21094364dfb5637,
    0x9096ea6f3848984f, 0xd77485cb25823ac7,
    0xa086cfcd97bf97f4, 0xef340a98172aace5,
    0xb23867fb2a35b28e, 0x84c8d4dfd2c63f3b,
    0xc5dd44271ad3cdba, 0x936b9fcebb25c996,
    0xdbac6c247d62a584, 0xa3ab66580d5fdaf6,
    0xf3e2f893dec3f126, 0xb5b5ada8aaff80b8,
    0x87625f056c7c4a8b, 0xc9bcff6034c13053,
    0x964e858c91ba2655, 0xdff9772470297ebd,
    0xa6dfbd9fb8e5b88f, 0xf8a95fcf88747d94,
    0xb94470938fa89bcf, 0x8a08f0f8bf0f156b,
    0xcdb02555653131b6, 0x993fe2c6d07b7fac,
    0xe45c10c42a2b3b06, 0xaa242499697392d3,
    0xfd87b5f28300ca0e, 0xbce5086492111aeb,
    0x8cbccc096f5088cc, 0xd1b71758e219652c,
    0x9c40000000000000, 0xe8d4a51000000000,
    0xad78ebc5ac620000, 0x813f3978f8940984,
    0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70,
    0xd5d238a4abe98068, 0x9f4f2726179a2245,
    0xed63a231d4c4fb27, 0xb0de65388cc8ada8,
    0x83c7088e1aab65db, 0xc45d1df942711d9a,
    0x924d692ca61be758, 0xda01ee641a708dea,
    0xa26da3999aef774a, 0xf209787bb47d6b85,
    0xb454e4a179dd1877, 0x865b86925b9bc5c2,
    0xc83553c5c8965d3d, 0x952ab45cfa97a0b3,
    0xde469fbd99a05fe3, 0xa59bc234db398c25,
    0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece,
    0x88fcf317f22241e2, 0xcc20ce9bd35c78a5,
    0x98165af37b2153df, 0xe2a0b5dc971f303a,
    0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c,
    0xbb764c4ca7a44410, 0x8bab8eefb6409c1a,
    0xd01fef10a657842c, 0x9b10a4e5e9913129,
    0xe7109bfba19c0c9d, 0xac2820d9623bf429,
    0x80444b5e7aa7cf85, 0xbf21e44003acdd2d,
    0x8e679c2f5e44ff8f, 0xd433179d9c8cb841,
    0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9,
    0xaf87023b9bf0ee6b,
];

#[rustfmt::skip]
static CACHED_POWERS_E_64: [i16; 87] = [
    -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007,  -980,
    -954,   -927,  -901,  -874,  -847,  -821,  -794,  -768,  -741,  -715,
    -688,   -661,  -635,  -608,  -582,  -555,  -529,  -502,  -475,  -449,
    -422,   -396,  -369,  -343,  -316,  -289,  -263,  -236,  -210,  -183,
    -157,   -130,  -103,   -77,   -50,   -24,     3,    30,    56,    83,
     109,    136,   162,   189,   216,   242,   269,   295,   322,   348,
     375,    402,   428,   455,   481,   508,   534,   561,   588,   614,
     641,    667,   694,   720,   747,   774,   800,   827,   853,   880,
     907,    933,   960,   986,  1013,  1039,  1066,
];