bigdecimal/
impl_fmt.rs

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
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
//! Implementation of std::fmt traits & other stringification functions
//!

use crate::*;
use rounding::{NonDigitRoundingData, InsigData};
use stdlib::fmt::Write;
use stdlib::num::NonZeroUsize;


// const EXPONENTIAL_FORMAT_LEADING_ZERO_THRESHOLD: usize = ${RUST_BIGDECIMAL_FMT_EXPONENTIAL_LOWER_THRESHOLD} or 5;
// const EXPONENTIAL_FORMAT_TRAILING_ZERO_THRESHOLD: usize = ${RUST_BIGDECIMAL_FMT_EXPONENTIAL_UPPER_THRESHOLD} or 15;
// const FMT_MAX_INTEGER_PADDING: usize = = ${RUST_BIGDECIMAL_FMT_MAX_INTEGER_PADDING} or  1000;
include!(concat!(env!("OUT_DIR"), "/exponential_format_threshold.rs"));


impl fmt::Display for BigDecimal {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        dynamically_format_decimal(
            self.to_ref(),
            f,
            EXPONENTIAL_FORMAT_LEADING_ZERO_THRESHOLD,
            EXPONENTIAL_FORMAT_TRAILING_ZERO_THRESHOLD,
        )
    }
}

impl fmt::Display for BigDecimalRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        dynamically_format_decimal(
            *self,
            f,
            EXPONENTIAL_FORMAT_LEADING_ZERO_THRESHOLD,
            EXPONENTIAL_FORMAT_TRAILING_ZERO_THRESHOLD,
        )
    }
}


impl fmt::LowerExp for BigDecimal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::LowerExp::fmt(&self.to_ref(), f)
    }
}

impl fmt::LowerExp for BigDecimalRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let abs_int = self.digits.to_str_radix(10);
        format_exponential(*self, f, abs_int, "e")
    }
}


impl fmt::UpperExp for BigDecimal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::UpperExp::fmt(&self.to_ref(), f)
    }
}

impl fmt::UpperExp for BigDecimalRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let abs_int = self.digits.to_str_radix(10);
        format_exponential(*self, f, abs_int, "E")
    }
}


impl fmt::Debug for BigDecimal {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if f.alternate() {
            write!(f, "BigDecimal(\"{}e{:}\")", self.int_val, -self.scale)
        } else {
            write!(f,
                "BigDecimal(sign={:?}, scale={}, digits={:?})",
                self.sign(), self.scale, self.int_val.magnitude().to_u64_digits()
            )
        }
    }
}


fn dynamically_format_decimal(
    this: BigDecimalRef,
    f: &mut fmt::Formatter,
    leading_zero_threshold: usize,
    trailing_zero_threshold: usize,
) -> fmt::Result {
    // Acquire the absolute integer as a decimal string
    let abs_int = this.digits.to_str_radix(10);

    // number of zeros between most significant digit and decimal point
    let leading_zero_count = this.scale
                                 .to_u64()
                                 .and_then(|scale| scale.checked_sub(abs_int.len() as u64))
                                 .unwrap_or(0);

    // number of zeros between least significant digit and decimal point
    let trailing_zero_count = this.scale
                                  .checked_neg()
                                  .and_then(|d| d.to_u64());

    // this ignores scientific-formatting if precision is requested
    let trailing_zeros = f.precision().map(|_| 0)
                          .or(trailing_zero_count)
                          .unwrap_or(0);

    let leading_zero_threshold = leading_zero_threshold as u64;
    let trailing_zero_threshold = trailing_zero_threshold as u64;

    // use exponential form if decimal point is outside
    // the upper and lower thresholds of the decimal
    if leading_zero_threshold < leading_zero_count {
        format_exponential(this, f, abs_int, "E")
    } else if trailing_zero_threshold < trailing_zeros {
        // non-scientific notation
        format_dotless_exponential(f, abs_int, this.sign, this.scale, "e")
    } else {
        format_full_scale(this, f, abs_int)
    }
}


fn format_full_scale(
    this: BigDecimalRef,
    f: &mut fmt::Formatter,
    abs_int: String,
) -> fmt::Result {
    use stdlib::cmp::Ordering::*;

    let mut digits = abs_int.into_bytes();
    let mut exp = 0;
    let non_negative = matches!(this.sign, Sign::Plus | Sign::NoSign);

    debug_assert_ne!(digits.len(), 0);

    let rounder = NonDigitRoundingData::default_with_sign(this.sign);

    if this.scale <= 0 {
        exp = (this.scale as i128).neg();
        // format an integer value by adding trailing zeros to the right
        zero_right_pad_integer_ascii_digits(&mut digits, &mut exp, f.precision());
    } else {
        let scale = this.scale as u64;

        // std::fmt 'precision' has same meaning as bigdecimal 'scale'
        //
        // interpret 'no-precision' to mean the same as matching the scale
        // of the deicmal (i.e. no padding or rounding)
        let target_scale = f.precision().and_then(|prec| prec.to_u64()).unwrap_or(scale);

        if scale < digits.len() as u64 {
            // format both integer and fractional digits (always 'trim' to precision)
            format_ascii_digits_with_integer_and_fraction(&mut digits, scale, target_scale, rounder);
        } else {
            // format only fractional digits
            format_ascii_digits_no_integer(&mut digits, scale, target_scale, rounder);
        }
    }

    // move digits back into String form
    let mut buf = String::from_utf8(digits).unwrap();

    // add exp part to buffer (if not zero)
    if exp != 0 {
        write!(buf, "e{:+}", exp)?;
    }

    // write buffer to formatter
    f.pad_integral(non_negative, "", &buf)
}

/// Fill appropriate number of zeros and decimal point into Vec of (ascii/utf-8) digits
///
/// Exponent is set to zero if zeros were added
///
fn zero_right_pad_integer_ascii_digits(
    digits: &mut Vec<u8>,
    exp: &mut i128,
    // number of zeros after the decimal point
    target_scale: Option<usize>,
) {
    debug_assert!(*exp >= 0);
    debug_assert_ne!(digits.len(), 0);

    let integer_zero_count = match exp.to_usize() {
        Some(n) => n,
        None => { return; }
    };

    // did not explicitly request precision, so we'll only
    // implicitly right-pad if less than this threshold.
    if matches!(target_scale, None) && integer_zero_count > 20 {
        // no padding
        return;
    }

    let fraction_zero_char_count;
    let decimal_place_idx;

    if let Some(frac_zero_count) = target_scale.and_then(NonZeroUsize::new) {
        // add one char for '.' if target_scale is not zero
        fraction_zero_char_count = frac_zero_count.get() + 1;
        // indicate we'll need to add a decimal point
        decimal_place_idx = Some(digits.len() + integer_zero_count);
    } else {
        fraction_zero_char_count = 0;
        decimal_place_idx = None;
    }

    let total_additional_zeros = integer_zero_count.saturating_add(fraction_zero_char_count);

    // no padding if out of bounds
    if total_additional_zeros > FMT_MAX_INTEGER_PADDING {
        return;
    }

    digits.resize(digits.len() + total_additional_zeros, b'0');
    if let Some(decimal_place_idx) = decimal_place_idx {
        digits[decimal_place_idx] = b'.';
    }

    // set exp to zero so it won't be written in `format_full_scale`
    *exp = 0;
}


/// Insert decimal point into digits_ascii_be, rounding or padding with zeros when necessary
///
/// (digits_ascii_be, scale) represents a decimal with both integer and fractional digits.
///
fn format_ascii_digits_with_integer_and_fraction(
    digits_ascii_be: &mut Vec<u8>,
    scale: u64,
    target_scale: u64,
    rounder: NonDigitRoundingData,
) {
    debug_assert!(scale < digits_ascii_be.len() as u64, "No integer digits");
    let mut digit_scale = scale;

    // decimal has more fractional digits than requested: round (trimming insignificant digits)
    if target_scale < scale {
        let digit_count_to_remove = (scale - target_scale)
                                    .to_usize()
                                    .expect("Precision exceeds maximum usize");

        let rounding_idx = NonZeroUsize::new(digits_ascii_be.len() - digit_count_to_remove)
                           .expect("decimal must have integer digits");

        // round and trim the digits at the 'rounding index'
        let scale_diff = round_ascii_digits(digits_ascii_be, rounding_idx, rounder);

        match scale_diff.checked_sub(digit_scale as usize) {
            None | Some(0) => {
                digit_scale -= scale_diff as u64;
            }
            Some(zeros_to_add) => {
                debug_assert_eq!(zeros_to_add, 1);
                digits_ascii_be.resize(digits_ascii_be.len() + zeros_to_add, b'0');
                digit_scale = 0;
            }
        }
    }

    // ignore the decimal point if the target scale is zero
    if target_scale != 0 {
        // there are both integer and fractional digits
        let integer_digit_count = (digits_ascii_be.len() as u64 - digit_scale)
                                  .to_usize()
                                  .expect("Number of digits exceeds maximum usize");


        digits_ascii_be.insert(integer_digit_count, b'.');
    }

    if digit_scale < target_scale {
        let trailing_zero_count = (target_scale - digit_scale)
                                  .to_usize()
                                  .expect("Too Big");

        // precision required beyond scale
        digits_ascii_be.resize(digits_ascii_be.len() + trailing_zero_count, b'0');
        digit_scale += trailing_zero_count as u64;
    }

    debug_assert_eq!(digit_scale, target_scale);
}


/// Insert decimal point into digits_ascii_be, rounding or padding with zeros when necessary
///
/// (digits_ascii_be, scale) represents a decimal with only fractional digits.
///
fn format_ascii_digits_no_integer(
    digits_ascii_be: &mut Vec<u8>,
    scale: u64,
    target_scale: u64,
    rounder: NonDigitRoundingData,
) {
    use stdlib::cmp::Ordering::*;

    debug_assert!(scale >= digits_ascii_be.len() as u64);
    let leading_zeros = scale - digits_ascii_be.len() as u64;

    match arithmetic::diff(target_scale, leading_zeros) {
        // handle rounding point before the start of digits
        (Less, intermediate_zeros) | (Equal, intermediate_zeros)  => {
            // get insignificant digit
            let (insig_digit, trailing_digits) = if intermediate_zeros > 0 {
                (0, digits_ascii_be.as_slice())
            } else {
                (digits_ascii_be[0] - b'0', &digits_ascii_be[1..])
            };

            let insig_data = InsigData::from_digit_and_lazy_trailing_zeros(
                rounder, insig_digit, || trailing_digits.iter().all(|&d| d == b'0')
            );

            let rounded_digit = insig_data.round_digit(0);
            debug_assert_ne!(rounded_digit, 10);

            digits_ascii_be.clear();

            if target_scale > 0 {
                digits_ascii_be.resize(target_scale as usize + 1, b'0');
            }

            digits_ascii_be.push(rounded_digit + b'0');

            if target_scale > 0 {
                digits_ascii_be[1] = b'.';
            }
        }
        (Greater, sig_digit_count) => {
            let significant_digit_count = sig_digit_count
                                          .to_usize()
                                          .and_then(NonZeroUsize::new)
                                          .expect("Request overflow in sig_digit_count");

            let mut digit_scale = scale;

            // if 'digits_ascii_be' has more digits than requested, round
            if significant_digit_count.get() < digits_ascii_be.len() {
                let removed_digit_count = round_ascii_digits(
                    digits_ascii_be, significant_digit_count, rounder
                );

                digit_scale -= removed_digit_count as u64;
            }

            // number of zeros to keep after the significant digits
            let trailing_zeros = target_scale - digit_scale;

            // expected length is target scale (number of digits after decimal point) + "0."
            let dest_len = target_scale as usize + 2;

            // number of significant digits is whatever is left in the digit vector
            let sig_digit_count = digits_ascii_be.len();

            // index where to store significant digits
            let sig_digit_idx = dest_len - trailing_zeros as usize - sig_digit_count;

            // fill output with zeros
            digits_ascii_be.resize(dest_len, b'0');

            // very likely case where there are digits after the decimal point
            if digit_scale != 0 {
                // copy significant digits to their index location
                digits_ascii_be.copy_within(..sig_digit_count, sig_digit_idx);

                // clear copied values
                fill_slice(&mut digits_ascii_be[..sig_digit_count.min(sig_digit_idx)], b'0');
            } else {
                debug_assert_eq!(sig_digit_count, 1);
            }

            // add decimal point
            digits_ascii_be[1] = b'.';
        }
    }
}

#[cfg(rust_1_50)]
fn fill_slice<T: Clone>(v: &mut [T], value: T) {
    v.fill(value);
}

#[cfg(not(rust_1_50))]
fn fill_slice<T: Clone>(v: &mut [T], value: T) {
    for i in v.iter_mut() {
        *i = value.clone();
    }
}


/// Format integer as {int}e+{exp}
///
/// Slightly different than scientific notation,
///
fn format_dotless_exponential(
    f: &mut fmt::Formatter,
    mut abs_int: String,
    sign: Sign,
    scale: i64,
    e_symbol: &str,
) -> fmt::Result {
    debug_assert!(scale <= 0);

    write!(abs_int, "{}{:+}", e_symbol, -scale).unwrap();
    let non_negative = matches!(sign, Sign::Plus | Sign::NoSign);
    f.pad_integral(non_negative, "", &abs_int)
}

fn format_exponential(
    this: BigDecimalRef,
    f: &mut fmt::Formatter,
    abs_int: String,
    e_symbol: &str,
) -> fmt::Result {
    // Steps:
    //  1. Truncate integer based on precision
    //  2. calculate exponent from the scale and the length of the internal integer
    //  3. Place decimal point after a single digit of the number, or omit if there is only a single digit
    //  4. Append `E{exponent}` and format the resulting string based on some `Formatter` flags

    let exp = (this.scale as i128).neg();
    let digits = abs_int.into_bytes();

    format_exponential_bigendian_ascii_digits(
        digits, this.sign, exp, f, e_symbol
    )
}


fn format_exponential_bigendian_ascii_digits(
    mut digits: Vec<u8>,
    sign: Sign,
    mut exp: i128,
    f: &mut fmt::Formatter,
    e_symbol: &str,
) -> fmt::Result {
    // how many zeros to pad at the end of the decimal
    let mut extra_trailing_zero_count = 0;

    if let Some(prec) = f.precision() {
        // 'prec' is number of digits after the decimal point
        let total_prec = prec + 1;

        if total_prec < digits.len() {
            // round to smaller precision
            let rounder = NonDigitRoundingData::default_with_sign(sign);
            let target_scale = NonZeroUsize::new(total_prec).unwrap();
            let delta_exp = round_ascii_digits(&mut digits, target_scale, rounder);
            exp += delta_exp as i128;
        }

        extra_trailing_zero_count = total_prec - digits.len();
    }

    let needs_decimal_point = digits.len() > 1 || extra_trailing_zero_count > 0;

    let mut abs_int = String::from_utf8(digits).unwrap();

    // Determine the exponent value based on the scale
    //
    // # First case: the integer representation falls completely behind the
    //   decimal point.
    //
    //   Example of this.scale > abs_int.len():
    //   0.000001234509876
    //   abs_int.len() = 10
    //   scale = 15
    //   target is 1.234509876
    //   exponent = -6
    //
    //   Example of this.scale == abs_int.len():
    //   0.333333333333333314829616256247390992939472198486328125
    //   abs_int.len() = 54
    //   scale = 54
    //   target is 3.33333333333333314829616256247390992939472198486328125
    //   exponent = -1
    //
    // # Second case: the integer representation falls around, or before the
    //   decimal point
    //
    //   ## Case 2.1, entirely before the decimal point.
    //     Example of (abs_int.len() - this.scale) > abs_int.len():
    //     123450987600000
    //     abs_int.len() = 10
    //     scale = -5
    //     location = 15
    //     target is 1.234509876
    //     exponent = 14
    //
    //   ## Case 2.2, somewhere around the decimal point.
    //     Example of (abs_int.len() - this.scale) < abs_int.len():
    //     12.339999999999999857891452847979962825775146484375
    //     abs_int.len() = 50
    //     scale = 48
    //     target is 1.2339999999999999857891452847979962825775146484375
    //     exponent = 1
    //
    //     For the (abs_int.len() - this.scale) == abs_int.len() I couldn't
    //     come up with an example
    let exponent = abs_int.len() as i128 + exp - 1;

    if needs_decimal_point {
        // only add decimal point if there is more than 1 decimal digit
        abs_int.insert(1, '.');
    }

    if extra_trailing_zero_count > 0 {
        abs_int.extend(stdlib::iter::repeat('0').take(extra_trailing_zero_count));
    }

    // always print exponent in exponential mode
    write!(abs_int, "{}{:+}", e_symbol, exponent)?;

    let non_negative = matches!(sign, Sign::Plus | Sign::NoSign);
    //pad_integral does the right thing although we have a decimal
    f.pad_integral(non_negative, "", &abs_int)
}


/// Round big-endian ascii digits to given significant digit count,
/// updating the scale appropriately
///
/// Returns the number of digits removed; this should be treated as the
/// change in the decimal's scale, and should be subtracted from the scale
/// when appropriate.
///
fn round_ascii_digits(
    // bigendian ascii digits
    digits_ascii_be: &mut Vec<u8>,
    // number of significant digits to keep
    significant_digit_count: NonZeroUsize,
    // how to round
    rounder: NonDigitRoundingData,
) -> usize {
    debug_assert!(significant_digit_count.get() < digits_ascii_be.len());

    let (sig_digits, insig_digits) = digits_ascii_be.split_at(significant_digit_count.get());
    let (&insig_digit, trailing_digits) = insig_digits.split_first().unwrap_or((&b'0', &[]));

    let insig_data = InsigData::from_digit_and_lazy_trailing_zeros(
        rounder, insig_digit - b'0', || trailing_digits.iter().all(|&d| d == b'0')
    );

    let rounding_digit_pos = significant_digit_count.get() - 1;
    let sig_digit = sig_digits[rounding_digit_pos] - b'0';
    let rounded_digit = insig_data.round_digit(sig_digit);

    // record how many digits to remove (changes the 'scale')
    let mut removed_digit_count = insig_digits.len();

    // discard insignificant digits (and rounding digit)
    digits_ascii_be.truncate(rounding_digit_pos);

    if rounded_digit < 10 {
        // simple case: no carrying/overflow, push rounded digit
        digits_ascii_be.push(rounded_digit + b'0');
        return removed_digit_count;
    }

    // handle carrying the 1
    debug_assert!(rounded_digit == 10);

    // carry the one past trailing 9's: replace them with zeros
    let next_non_nine_rev_pos = digits_ascii_be.iter().rev().position(|&d| d != b'9');
    match next_non_nine_rev_pos {
        // number of nines to remove
        Some(backwards_nine_count) => {
            let digits_to_trim = backwards_nine_count + 1;
            let idx = digits_ascii_be.len() - digits_to_trim;
            // increment least significant non-nine zero
            digits_ascii_be[idx] += 1;
            // remove trailing nines
            digits_ascii_be.truncate(idx + 1);
            // count truncation
            removed_digit_count += digits_to_trim;
        }
        // all nines! overflow to 1.000
        None => {
            digits_ascii_be.clear();
            digits_ascii_be.push(b'1');
            // count digit clearning
            removed_digit_count += significant_digit_count.get();
        }
    }

    // return the number of removed digits
    return removed_digit_count;
}


#[inline(never)]
pub(crate) fn write_scientific_notation<W: Write>(n: &BigDecimal, w: &mut W) -> fmt::Result {
    if n.is_zero() {
        return w.write_str("0e0");
    }

    if n.int_val.sign() == Sign::Minus {
        w.write_str("-")?;
    }

    let digits = n.int_val.magnitude();

    let dec_str = digits.to_str_radix(10);
    let (first_digit, remaining_digits) = dec_str.as_str().split_at(1);
    w.write_str(first_digit)?;
    if !remaining_digits.is_empty() {
        w.write_str(".")?;
        w.write_str(remaining_digits)?;
    }
    write!(w, "e{}", remaining_digits.len() as i128 - n.scale as i128)
}


#[inline(never)]
pub(crate) fn write_engineering_notation<W: Write>(n: &BigDecimal, out: &mut W) -> fmt::Result {
    if n.is_zero() {
        return out.write_str("0e0");
    }

    if n.int_val.sign() == Sign::Minus {
        out.write_char('-')?;
    }

    let digits = n.int_val.magnitude();

    let dec_str = digits.to_str_radix(10);
    let digit_count = dec_str.len();

    let top_digit_exponent = digit_count as i128 - n.scale as i128;

    let shift_amount = match top_digit_exponent.rem_euclid(3) {
        0 => 3,
        i => i as usize,
    };

    let exp = top_digit_exponent - shift_amount as i128;

    // handle adding zero padding
    if let Some(padding_zero_count) = shift_amount.checked_sub(dec_str.len()) {
        let zeros = &"000"[..padding_zero_count];
        out.write_str(&dec_str)?;
        out.write_str(zeros)?;
        return write!(out, "e{}", exp);
    }

    let (head, rest) = dec_str.split_at(shift_amount);
    debug_assert_eq!(exp % 3, 0);

    out.write_str(head)?;

    if !rest.is_empty() {
        out.write_char('.')?;
        out.write_str(rest)?;
    }

    return write!(out, "e{}", exp);
}


#[cfg(test)]
#[allow(non_snake_case)]
mod test {
    use super::*;
    use paste::*;

    /// test case builder for mapping decimal-string to formatted-string
    /// define test_fmt_function! macro to test your function
    #[cfg(test)]
    macro_rules! impl_case {
        ($name:ident : $in:literal => $ex:literal) => {
            #[test]
            fn $name() {
                let n: BigDecimal = $in.parse().unwrap();
                let s = test_fmt_function!(n);
                assert_eq!(&s, $ex);
            }
        };
    }

    /// "Mock" Formatter
    ///
    /// Given callable, forwards formatter to callable.
    /// Required work-around due to lack of constructor in fmt::Formatter
    ///
    struct Fmt<F>(F)
        where F: Fn(&mut fmt::Formatter) -> fmt::Result;

    impl<F> fmt::Display for Fmt<F>
        where F: Fn(&mut fmt::Formatter) -> fmt::Result
    {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            // call closure with given formatter
            (self.0)(f)
        }
    }

    impl<F> fmt::Debug for Fmt<F>
        where F: Fn(&mut fmt::Formatter) -> fmt::Result
    {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            (self.0)(f)
        }
    }

    mod dynamic_fmt {
        use super::*;

        macro_rules! test_fmt_function {
            ($n:ident) => {{
                format!("{}", Fmt(|f| dynamically_format_decimal($n.to_ref(), f, 2, 9)))
            }};
        }

        impl_case!(case_0d123: "0.123" => "0.123");
        impl_case!(case_0d0123: "0.0123" => "0.0123");
        impl_case!(case_0d00123: "0.00123" => "0.00123");
        impl_case!(case_0d000123: "0.000123" => "1.23E-4");

        impl_case!(case_123d: "123." => "123");
        impl_case!(case_123de1: "123.e1" => "1230");
    }

    mod fmt_options {
        use super::*;

        macro_rules! impl_case {
            ($name:ident: $fmt:literal => $expected:literal) => {
                #[test]
                fn $name() {
                    let x = test_input();
                    let y = format!($fmt, x);
                    assert_eq!(y, $expected);
                }
            };
        }

        mod dec_1 {
            use super::*;

            fn test_input() -> BigDecimal {
                "1".parse().unwrap()
            }

            impl_case!(fmt_default:      "{}" => "1");
            impl_case!(fmt_d1:        "{:.1}" => "1.0");
            impl_case!(fmt_d4:        "{:.4}" => "1.0000");
            impl_case!(fmt_4d1:      "{:4.1}" => " 1.0");
            impl_case!(fmt_r4d1:    "{:>4.1}" => " 1.0");
            impl_case!(fmt_l4d1:    "{:<4.1}" => "1.0 ");
            impl_case!(fmt_p05d1:  "{:+05.1}" => "+01.0");

            impl_case!(fmt_e:      "{:e}" => "1e+0");
            impl_case!(fmt_E:      "{:E}" => "1E+0");
        }

        mod dec_1e1 {
            use super::*;

            fn test_input() -> BigDecimal {
                BigDecimal::new(1.into(), -1)
            }

            impl_case!(fmt_default:      "{}" => "10");
            impl_case!(fmt_debug:      "{:?}" => "BigDecimal(sign=Plus, scale=-1, digits=[1])");
            impl_case!(fmt_debug_alt: "{:#?}" => "BigDecimal(\"1e1\")");
            impl_case!(fmt_d0:        "{:.0}" => "10");
            impl_case!(fmt_d1:        "{:.1}" => "10.0");
            impl_case!(fmt_d2:        "{:.2}" => "10.00");
        }

        mod dec_1en1 {
            use super::*;

            fn test_input() -> BigDecimal {
                BigDecimal::new(1.into(), 1)
            }

            impl_case!(fmt_default:      "{}" => "0.1");
            impl_case!(fmt_d0:        "{:.0}" => "0");
            impl_case!(fmt_d1:        "{:.1}" => "0.1");
            impl_case!(fmt_d2:        "{:.2}" => "0.10");
        }

        mod dec_9en1 {
            use super::*;

            fn test_input() -> BigDecimal {
                BigDecimal::new(9.into(), 1)
            }

            impl_case!(fmt_default:      "{}" => "0.9");
            impl_case!(fmt_d0:        "{:.0}" => "1");
            impl_case!(fmt_d1:        "{:.1}" => "0.9");
            impl_case!(fmt_d4:        "{:.4}" => "0.9000");
        }

        mod dec_800en3 {
            use super::*;

            fn test_input() -> BigDecimal {
                BigDecimal::new(800.into(), 3)
            }

            impl_case!(fmt_default:      "{}" => "0.800");
            impl_case!(fmt_d0:        "{:.0}" => "1");
            impl_case!(fmt_d1:        "{:.1}" => "0.8");
            impl_case!(fmt_d3:        "{:.3}" => "0.800");
            impl_case!(fmt_d9:        "{:.9}" => "0.800000000");
        }

        mod dec_123456 {
            use super::*;

            fn test_input() -> BigDecimal {
                "123456".parse().unwrap()
            }

            impl_case!(fmt_default:      "{}" => "123456");
            impl_case!(fmt_d1:        "{:.1}" => "123456.0");
            impl_case!(fmt_d4:        "{:.4}" => "123456.0000");
            impl_case!(fmt_4d1:      "{:4.1}" => "123456.0");
            impl_case!(fmt_15d2:    "{:15.2}" => "      123456.00");
            impl_case!(fmt_r15d2:  "{:>15.2}" => "      123456.00");
            impl_case!(fmt_l15d2:  "{:<15.2}" => "123456.00      ");
            impl_case!(fmt_p05d1:  "{:+05.7}" => "+123456.0000000");
        }

        mod dec_d099995 {
            use super::*;

            fn test_input() -> BigDecimal {
                ".099995".parse().unwrap()
            }

            impl_case!(fmt_default:  "{}" => "0.099995");
            impl_case!(fmt_d0:  "{:.0}" => "0");
            impl_case!(fmt_d1:  "{:.1}" => "0.1");
            impl_case!(fmt_d3:  "{:.3}" => "0.100");
        }

        mod dec_d9999999 {
            use super::*;

            fn test_input() -> BigDecimal {
                ".9999999".parse().unwrap()
            }

            impl_case!(fmt_default:  "{}" => "0.9999999");
            impl_case!(fmt_d0:  "{:.0}" => "1");
            impl_case!(fmt_d1:  "{:.1}" => "1.0");
            impl_case!(fmt_d3:  "{:.3}" => "1.000");
        }

        mod dec_9999999 {
            use super::*;

            fn test_input() -> BigDecimal {
                "9999999".parse().unwrap()
            }

            impl_case!(fmt_default:  "{}" => "9999999");
            impl_case!(fmt_d8:  "{:.8}" => "9999999.00000000");

            impl_case!(fmt_e:  "{:e}" => "9.999999e+6");
            impl_case!(fmt_E:  "{:E}" => "9.999999E+6");
            impl_case!(fmt_d0e:  "{:.0e}" => "1e+7");
            impl_case!(fmt_d1e:  "{:.1e}" => "1.0e+7");
            impl_case!(fmt_d2e:  "{:.2e}" => "1.00e+7");
            impl_case!(fmt_d4e:  "{:.4e}" => "1.0000e+7");
            impl_case!(fmt_d6e:  "{:.6e}" => "9.999999e+6");
            impl_case!(fmt_d7e:  "{:.7e}" => "9.9999990e+6");
            impl_case!(fmt_d10e:  "{:.10e}" => "9.9999990000e+6");
        }

        mod dec_19073d97235939614856 {
            use super::*;

            fn test_input() -> BigDecimal {
                "19073.97235939614856".parse().unwrap()
            }

            impl_case!(fmt_default:      "{}" => "19073.97235939614856");
            impl_case!(fmt_pd7:      "{:+.7}" => "+19073.9723594");
            impl_case!(fmt_d0:        "{:.0}" => "19074");
            impl_case!(fmt_d1:        "{:.1}" => "19074.0");
            impl_case!(fmt_d3:        "{:.3}" => "19073.972");
            impl_case!(fmt_d4:        "{:.4}" => "19073.9724");
            impl_case!(fmt_8d3:      "{:8.3}" => "19073.972");
            impl_case!(fmt_10d3:    "{:10.3}" => " 19073.972");
            impl_case!(fmt_010d3:  "{:010.3}" => "019073.972");
        }

        mod dec_n90037659d6902 {
            use super::*;

            fn test_input() -> BigDecimal {
                "-90037659.6905".parse().unwrap()
            }

            impl_case!(fmt_default:      "{}" => "-90037659.6905");
            impl_case!(fmt_debug:      "{:?}" => "BigDecimal(sign=Minus, scale=4, digits=[900376596905])");
            impl_case!(fmt_debug_alt: "{:#?}" => "BigDecimal(\"-900376596905e-4\")");
            impl_case!(fmt_pd7:      "{:+.7}" => "-90037659.6905000");
            impl_case!(fmt_d0:        "{:.0}" => "-90037660");
            impl_case!(fmt_d3:        "{:.3}" => "-90037659.690");
            impl_case!(fmt_d4:        "{:.4}" => "-90037659.6905");
            impl_case!(fmt_14d4:    "{:14.4}" => "-90037659.6905");
            impl_case!(fmt_15d4:    "{:15.4}" => " -90037659.6905");
            impl_case!(fmt_l17d5:  "{:<17.5}" => "-90037659.69050  ");
        }

        mod dec_0d0002394899999500 {
            use super::*;

            fn test_input() -> BigDecimal {
                "0.0002394899999500".parse().unwrap()
            }

            impl_case!(fmt_default:    "{}" => "0.0002394899999500");
            impl_case!(fmt_d0:      "{:.0}" => "0");
            impl_case!(fmt_d1:      "{:.1}" => "0.0");
            impl_case!(fmt_d3:      "{:.3}" => "0.000");
            impl_case!(fmt_d4:      "{:.4}" => "0.0002");
            impl_case!(fmt_d5:      "{:.5}" => "0.00024");
            impl_case!(fmt_d10:    "{:.10}" => "0.0002394900");
            impl_case!(fmt_d13:    "{:.13}" => "0.0002394900000");
            impl_case!(fmt_d14:    "{:.14}" => "0.00023948999995");
            impl_case!(fmt_d20:    "{:.20}" => "0.00023948999995000000");

        }

        mod dec_1764031078en13 {
            use super::*;

            fn test_input() -> BigDecimal {
                BigDecimal::new(1764031078.into(), 13)
            }

            impl_case!(fmt_default:    "{}" => "0.0001764031078");
            impl_case!(fmt_d1:      "{:.1}" => "0.0");
            impl_case!(fmt_d3:      "{:.3}" => "0.000");
            impl_case!(fmt_d4:      "{:.4}" => "0.0002");
            impl_case!(fmt_d5:      "{:.5}" => "0.00018");
            impl_case!(fmt_d13:    "{:.13}" => "0.0001764031078");
            impl_case!(fmt_d20:    "{:.20}" => "0.00017640310780000000");

        }

        mod dec_1e15 {
            use super::*;

            fn test_input() -> BigDecimal {
                "1e15".parse().unwrap()
            }

            impl_case!(fmt_default:        "{}" => "1000000000000000");
            impl_case!(fmt_d0:          "{:.0}" => "1000000000000000");
            impl_case!(fmt_d1:          "{:.1}" => "1000000000000000.0");
        }

        mod dec_1e16 {
            use super::*;

            fn test_input() -> BigDecimal {
                "1e16".parse().unwrap()
            }

            impl_case!(fmt_default:        "{}" => "1e+16");
            impl_case!(fmt_d0:          "{:.0}" => "10000000000000000");
            impl_case!(fmt_d2:          "{:.2}" => "10000000000000000.00");
        }


        mod dec_491326en12 {
            use super::*;

            fn test_input() -> BigDecimal {
                "491326e-12".parse().unwrap()
            }

            impl_case!(fmt_default:        "{}" => "4.91326E-7");
            impl_case!(fmt_d0:          "{:.0}" => "5E-7");
            impl_case!(fmt_d1:          "{:.1}" => "4.9E-7");
            impl_case!(fmt_d3:          "{:.3}" => "4.913E-7");
            impl_case!(fmt_d5:          "{:.5}" => "4.91326E-7");
            impl_case!(fmt_d6:          "{:.6}" => "4.913260E-7");

            impl_case!(fmt_d9:          "{:.9}" => "4.913260000E-7");
            impl_case!(fmt_d20:        "{:.20}" => "4.91326000000000000000E-7");
        }

        mod dec_0d00003102564500 {
            use super::*;

            fn test_input() -> BigDecimal {
                "0.00003102564500".parse().unwrap()
            }

            impl_case!(fmt_default: "{}" => "0.00003102564500");
            impl_case!(fmt_d0:   "{:.0}" => "0");
            impl_case!(fmt_d1:   "{:.1}" => "0.0");
            impl_case!(fmt_d2:   "{:.2}" => "0.00");
            impl_case!(fmt_d4:   "{:.4}" => "0.0000");
            impl_case!(fmt_d5:   "{:.5}" => "0.00003");
            impl_case!(fmt_d10:  "{:.10}" => "0.0000310256");
            impl_case!(fmt_d14:  "{:.14}" => "0.00003102564500");
            impl_case!(fmt_d17:  "{:.17}" => "0.00003102564500000");

            impl_case!(fmt_e:      "{:e}" => "3.102564500e-5");
            impl_case!(fmt_de:    "{:.e}" => "3.102564500e-5");
            impl_case!(fmt_d0e:  "{:.0e}" => "3e-5");
            impl_case!(fmt_d1e:  "{:.1e}" => "3.1e-5");
            impl_case!(fmt_d4e:  "{:.4e}" => "3.1026e-5");
        }

        mod dec_1en100000 {
            use super::*;

            fn test_input() -> BigDecimal {
                "1E-10000".parse().unwrap()
            }

            impl_case!(fmt_default: "{}" => "1E-10000");
            impl_case!(fmt_d1: "{:.1}" => "1.0E-10000");
            impl_case!(fmt_d4: "{:.4}" => "1.0000E-10000");
        }

        mod dec_1e100000 {
            use super::*;

            fn test_input() -> BigDecimal {
                "1e100000".parse().unwrap()
            }

            impl_case!(fmt_default: "{}" => "1e+100000");
            impl_case!(fmt_d1: "{:.1}" => "1e+100000");
            impl_case!(fmt_d4: "{:.4}" => "1e+100000");
        }


        mod dec_1234506789E5 {
            use super::*;

            fn test_input() -> BigDecimal {
                BigDecimal::new(1234506789.into(), -5)
            }

            impl_case!(fmt_default: "{}" => "123450678900000");
            impl_case!(fmt_d1: "{:.1}" => "123450678900000.0");
            impl_case!(fmt_d3: "{:.3}" => "123450678900000.000");
            impl_case!(fmt_d4: "{:.4}" => "123450678900000.0000");
            impl_case!(fmt_l13d4: "{:<23.4}" => "123450678900000.0000   ");
            impl_case!(fmt_r13d4: "{:>23.4}" => "   123450678900000.0000");
        }

        mod dec_1234506789E15 {
            use super::*;

            fn test_input() -> BigDecimal {
                BigDecimal::new(1234506789.into(), -15)
            }

            impl_case!(fmt_default: "{}" => "1234506789000000000000000");
            impl_case!(fmt_d1: "{:.1}" => "1234506789000000000000000.0");
            impl_case!(fmt_d3: "{:.3}" => "1234506789000000000000000.000");
            impl_case!(fmt_l13d4: "{:<+32.2}" => "+1234506789000000000000000.00   ");
            impl_case!(fmt_r13d4: "{:>+32.2}" => "   +1234506789000000000000000.00");
        }

        mod dec_13400476439814628800E2502 {
            use super::*;

            fn test_input() -> BigDecimal {
                BigDecimal::new(13400476439814628800u64.into(), -2502)
            }

            impl_case!(fmt_default: "{}" => "13400476439814628800e+2502");
            impl_case!(fmt_d1: "{:.1}" => "13400476439814628800e+2502");
        }

        mod dec_d9999 {
            use super::*;

            fn test_input() -> BigDecimal {
                "0.9999".parse().unwrap()
            }

            impl_case!(fmt_default:      "{}" => "0.9999");
            impl_case!(fmt_d0:        "{:.0}" => "1");
            impl_case!(fmt_d1:        "{:.1}" => "1.0");
            impl_case!(fmt_d2:        "{:.2}" => "1.00");
            impl_case!(fmt_d3:        "{:.3}" => "1.000");
            impl_case!(fmt_d4:        "{:.4}" => "0.9999");
            impl_case!(fmt_d6:        "{:.6}" => "0.999900");
        }

        mod dec_9d99 {
            use super::*;

            fn test_input() -> BigDecimal {
                "9.99".parse().unwrap()
            }

            impl_case!(fmt_default:      "{}" => "9.99");
            impl_case!(fmt_d0:        "{:.0}" => "10");
            impl_case!(fmt_d1:        "{:.1}" => "10.0");
            impl_case!(fmt_d2:        "{:.2}" => "9.99");
            impl_case!(fmt_d3:        "{:.3}" => "9.990");
        }
    }

    mod fmt_boundaries {
        use super::*;

        macro_rules! impl_case {
            ( $name:ident: $src:expr => $expected:literal ) => {
                #[test]
                fn $name() {
                    let src = $src;
                    let bd: BigDecimal = src.parse().unwrap();
                    let result = bd.to_string();
                    assert_eq!(result, $expected);

                    let round_trip = BigDecimal::from_str(&result).unwrap();
                    assert_eq!(round_trip, bd);

                    let sci = bd.to_scientific_notation();
                    let sci_round_trip = BigDecimal::from_str(&sci).unwrap();
                    assert_eq!(sci_round_trip, bd);

                    let eng = bd.to_engineering_notation();
                    let eng_round_trip = BigDecimal::from_str(&eng).unwrap();
                    assert_eq!(eng_round_trip, bd);
                }
            };
            ( (eng-check-invalid) $name:ident: $src:expr => $expected:literal ) => {
                #[test]
                fn $name() {
                    let src = $src;
                    let bd: BigDecimal = src.parse().unwrap();
                    let result = bd.to_string();
                    assert_eq!(result, $expected);

                    let round_trip = BigDecimal::from_str(&result).unwrap();
                    assert_eq!(round_trip, bd);

                    let sci = bd.to_scientific_notation();
                    let sci_round_trip = BigDecimal::from_str(&sci).unwrap();
                    assert_eq!(sci_round_trip, bd);

                    let eng = bd.to_engineering_notation();
                    let eng_round_trip = BigDecimal::from_str(&eng);
                    assert!(eng_round_trip.is_err());
                }
            };
            ( (panics) $name:ident: $src:expr ) => {
                #[test]
                #[should_panic]
                fn $name() {
                    let src = $src;
                    let _bd: BigDecimal = src.parse().unwrap();
                }
            };
        }


        impl_case!(test_max: format!("1E{}", i64::MAX) => "1e+9223372036854775807");
        impl_case!(test_max_multiple_digits: format!("314156E{}", i64::MAX) => "314156e+9223372036854775807");
        impl_case!(test_min_scale: "1E9223372036854775807" => "1e+9223372036854775807");

        impl_case!((eng-check-invalid) test_max_scale: "1E-9223372036854775807" => "1E-9223372036854775807");
        impl_case!(test_min_multiple_digits: format!("271828182E-{}", i64::MAX) => "2.71828182E-9223372036854775799");

        impl_case!((panics) test_max_exp_overflow: "1E9223372036854775809");
        impl_case!((panics) test_min_exp_overflow: "1E-9223372036854775808");
    }

    #[test]
    fn test_fmt() {
        let vals = vec![
            // b  s (      {}     {:.1}        {:.4}    {:4.1}   {:+05.1}   {:<4.1}
            (1, 0,  (     "1",    "1.0",    "1.0000",   " 1.0",   "+01.0",   "1.0 " )),
            (1, 1,  (   "0.1",    "0.1",    "0.1000",   " 0.1",   "+00.1",   "0.1 " )),
            (1, 2,  (  "0.01",    "0.0",    "0.0100",   " 0.0",   "+00.0",   "0.0 " )),
            (1, -2, (   "100",  "100.0",  "100.0000",  "100.0",  "+100.0",  "100.0" )),
            (-1, 0, (    "-1",   "-1.0",   "-1.0000",   "-1.0",   "-01.0",   "-1.0" )),
            (-1, 1, (  "-0.1",   "-0.1",   "-0.1000",   "-0.1",   "-00.1",   "-0.1" )),
            (-1, 2, ( "-0.01",   "-0.0",   "-0.0100",   "-0.0",   "-00.0",   "-0.0" )),
        ];
        for (i, scale, results) in vals {
            let x = BigDecimal::new(num_bigint::BigInt::from(i), scale);
            assert_eq!(format!("{}", x), results.0);
            assert_eq!(format!("{:.1}", x), results.1);
            assert_eq!(format!("{:.4}", x), results.2);
            assert_eq!(format!("{:4.1}", x), results.3);
            assert_eq!(format!("{:+05.1}", x), results.4);
            assert_eq!(format!("{:<4.1}", x), results.5);
        }
    }


    mod fmt_debug {
        use super::*;

        macro_rules! impl_case {
            ($name:ident: $input:literal => $expected:literal => $expected_alt:literal) => {
                paste! {
                    #[test]
                    fn $name() {
                        let x: BigDecimal = $input.parse().unwrap();
                        let y = format!("{:?}", x);
                        assert_eq!(y, $expected);
                    }

                    #[test]
                    fn [< $name _alt >]() {
                        let x: BigDecimal = $input.parse().unwrap();
                        let y = format!("{:#?}", x);
                        assert_eq!(y, $expected_alt);
                    }
                }
            }
        }

        impl_case!(case_0: "0" => r#"BigDecimal(sign=NoSign, scale=0, digits=[])"#
                               => r#"BigDecimal("0e0")"#);

        impl_case!(case_n0: "-0" => r#"BigDecimal(sign=NoSign, scale=0, digits=[])"#
                               => r#"BigDecimal("0e0")"#);

        impl_case!(case_1: "1" => r#"BigDecimal(sign=Plus, scale=0, digits=[1])"#
                               => r#"BigDecimal("1e0")"#);

        impl_case!(case_123_400: "123.400" => r#"BigDecimal(sign=Plus, scale=3, digits=[123400])"#
                                           => r#"BigDecimal("123400e-3")"#);

        impl_case!(case_123_4en2: "123.4e-2" => r#"BigDecimal(sign=Plus, scale=3, digits=[1234])"#
                                             => r#"BigDecimal("1234e-3")"#);

        impl_case!(case_123_456:   "123.456" => r#"BigDecimal(sign=Plus, scale=3, digits=[123456])"#
                                             => r#"BigDecimal("123456e-3")"#);

        impl_case!(case_01_20:       "01.20" => r#"BigDecimal(sign=Plus, scale=2, digits=[120])"#
                                             => r#"BigDecimal("120e-2")"#);

        impl_case!(case_1_20:         "1.20" => r#"BigDecimal(sign=Plus, scale=2, digits=[120])"#
                                             => r#"BigDecimal("120e-2")"#);
        impl_case!(case_01_2e3:     "01.2E3" => r#"BigDecimal(sign=Plus, scale=-2, digits=[12])"#
                                             => r#"BigDecimal("12e2")"#);

        impl_case!(case_avagadro: "6.02214076e1023" => r#"BigDecimal(sign=Plus, scale=-1015, digits=[602214076])"#
                                                    => r#"BigDecimal("602214076e1015")"#);

        impl_case!(case_1e99999999999999 : "1e99999999999999" => r#"BigDecimal(sign=Plus, scale=-99999999999999, digits=[1])"#
                                                              => r#"BigDecimal("1e99999999999999")"#);

        impl_case!(case_n144d3308279 : "-144.3308279" => r#"BigDecimal(sign=Minus, scale=7, digits=[1443308279])"#
                                                      => r#"BigDecimal("-1443308279e-7")"#);

        impl_case!(case_n349983058835858339619e2 : "-349983058835858339619e2"
                                                      => r#"BigDecimal(sign=Minus, scale=-2, digits=[17941665509086410531, 18])"#
                                                      => r#"BigDecimal("-349983058835858339619e2")"#);
    }

    mod write_scientific_notation {
        use super::*;

        macro_rules! test_fmt_function {
            ($n:expr) => { $n.to_scientific_notation() };
        }

        impl_case!(case_4_1592480782835e9 : "4159248078.2835" => "4.1592480782835e9");
        impl_case!(case_1_234e_5 : "0.00001234" => "1.234e-5");
        impl_case!(case_0 : "0" => "0e0");
        impl_case!(case_1 : "1" => "1e0");
        impl_case!(case_2_00e0 : "2.00" => "2.00e0");
        impl_case!(case_neg_5_70e1 : "-57.0" => "-5.70e1");
    }

    mod write_engineering_notation {
        use super::*;

        macro_rules! test_fmt_function {
            ($n:expr) => { $n.to_engineering_notation() };
        }

        impl_case!(case_4_1592480782835e9 : "4159248078.2835" => "4.1592480782835e9");
        impl_case!(case_12_34e_6 : "0.00001234" => "12.34e-6");
        impl_case!(case_0 : "0" => "0e0");
        impl_case!(case_1 : "1" => "1e0");
        impl_case!(case_2_00e0 : "2.00" => "2.00e0");
        impl_case!(case_neg_5_70e1 : "-57.0" => "-57.0e0");
        impl_case!(case_5_31e4 : "5.31e4" => "53.1e3");
        impl_case!(case_5_31e5 : "5.31e5" => "531e3");
        impl_case!(case_5_31e6 : "5.31e6" => "5.31e6");
        impl_case!(case_5_31e7 : "5.31e7" => "53.1e6");

        impl_case!(case_1e2 : "1e2" => "100e0");
        impl_case!(case_1e119 : "1e19" => "10e18");
        impl_case!(case_1e3000 : "1e3000" => "1e3000");
        impl_case!(case_4_2e7 : "4.2e7" => "42e6");
        impl_case!(case_4_2e8 : "4.2e8" => "420e6");

        impl_case!(case_4e99999999999999 : "4e99999999999999" => "4e99999999999999");
        impl_case!(case_4e99999999999998 : "4e99999999999998" => "400e99999999999996");
        impl_case!(case_44e99999999999998 : "44e99999999999998" => "4.4e99999999999999");
        impl_case!(case_4e99999999999997 : "4e99999999999997" => "40e99999999999996");
        impl_case!(case_41e99999999999997 : "41e99999999999997" => "410e99999999999996");
        impl_case!(case_413e99999999999997 : "413e99999999999997" => "4.13e99999999999999");
        // impl_case!(case_413e99999999999997 : "413e99999999999997" => "4.13e99999999999999");
    }
}


#[cfg(all(test, property_tests))]
mod proptests {
    use super::*;
    use paste::paste;
    use proptest::prelude::*;

    macro_rules! impl_parsing_test {
        ($t:ty) => {
            paste! { proptest! {
                #[test]
                fn [< roudtrip_to_str_and_back_ $t >](n: $t) {
                    let original = BigDecimal::from(n);
                    let display = format!("{}", original);
                    let parsed = display.parse::<BigDecimal>().unwrap();

                    prop_assert_eq!(&original, &parsed);
                }
            } }
        };
        (from-float $t:ty) => {
            paste! { proptest! {
                #[test]
                fn [< roudtrip_to_str_and_back_ $t >](n: $t) {
                    let original = BigDecimal::try_from(n).unwrap();
                    let display = format!("{}", original);
                    let parsed = display.parse::<BigDecimal>().unwrap();

                    prop_assert_eq!(&original, &parsed);
                }
            } }
        };
    }

    impl_parsing_test!(u8);
    impl_parsing_test!(u16);
    impl_parsing_test!(u32);
    impl_parsing_test!(u64);
    impl_parsing_test!(u128);

    impl_parsing_test!(i8);
    impl_parsing_test!(i16);
    impl_parsing_test!(i32);
    impl_parsing_test!(i64);
    impl_parsing_test!(i128);

    impl_parsing_test!(from-float f32);
    impl_parsing_test!(from-float f64);

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(1000))]

        #[test]
        fn scientific_notation_roundtrip(f: f64) {
            prop_assume!(!f.is_nan() && !f.is_infinite());
            let n = BigDecimal::from_f64(f).unwrap();
            let s = n.to_scientific_notation();
            let m: BigDecimal = s.parse().unwrap();
            prop_assert_eq!(n, m);
        }

        #[test]
        fn engineering_notation_roundtrip(f: f64) {
            prop_assume!(!f.is_nan() && !f.is_infinite());
            let n = BigDecimal::from_f64(f).unwrap();
            let s = n.to_engineering_notation();
            let m: BigDecimal = s.parse().unwrap();
            prop_assert_eq!(n, m);
        }
    }
}