fin_decimal 0.4.0

A high-performance decimal fixed-point arithmetic library for financial applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
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
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
//! 256-bit backed decimal fixed-point type.
//!
//! [`Decimal256`] extends the power-of-10 scaling design to a 256-bit signed
//! backing integer ([`I256`]). Addition and subtraction are two native
//! add/adc (sub/sbb) pairs; multiplication produces a 512-bit intermediate
//! from 64-bit limbs and re-scales with a single word-based long division
//! (10^DIGITS always fits one limb); division scales the dividend up and
//! uses Knuth's algorithm D with the same 128-by-64 division primitive.

use crate::AmountErrorKind;
use crate::AmountSign;
use crate::EvenSplit;
use crate::Rounding;
use crate::limbs::{
    cmp_twice_rem_u64, dec_div, dec_mul, dec_mul_div, div_mag_by_word, div_words_by_pow10,
    isqrt_u128_with_rem, isqrt_words, mul_add_word, mul_words, parse_decimal_mag_rounded, rem_mag,
    round_mag_to_step, round_up_by_cmp, sig_limbs, split_mag_even, sqrt_round_up, str_mag, upow10,
};
use core::cmp::Ordering;
use core::fmt;
use core::ops::*;

/// A 256-bit signed integer in two's complement form, used as the backing
/// storage of [`Decimal256`]. Only the operations the decimal type needs are
/// provided; it is not a general-purpose big integer.
#[derive(Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct I256 {
    lo: u128,
    hi: i128,
}

impl I256 {
    /// Constant equal to zero.
    pub const ZERO: Self = I256 { lo: 0, hi: 0 };
    /// The largest representable value, 2^255 - 1.
    pub const MAX: Self = I256 {
        lo: u128::MAX,
        hi: i128::MAX,
    };
    /// The smallest value used by the decimal types: `-MAX` (symmetric range).
    pub const MIN: Self = I256 {
        lo: 1,
        hi: i128::MIN,
    };

    /// Sign-extends an `i128` into an `I256`.
    #[inline]
    pub const fn from_i128(v: i128) -> Self {
        I256 {
            lo: v as u128,
            hi: v >> 127,
        }
    }

    /// Returns `true` if the value is negative.
    #[inline]
    pub const fn is_negative(self) -> bool {
        self.hi < 0
    }

    /// Returns `true` if the value is zero.
    #[inline]
    pub const fn is_zero(self) -> bool {
        self.hi == 0 && self.lo == 0
    }

    /// Two's complement negation (wrapping).
    #[inline]
    pub const fn wrapping_neg(self) -> Self {
        let lo = (!self.lo).wrapping_add(1);
        let hi = (!self.hi).wrapping_add((lo == 0) as i128);
        I256 { lo, hi }
    }

    /// Checked addition, `None` on signed overflow.
    #[inline]
    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
        let (lo, carry) = self.lo.overflowing_add(rhs.lo);
        let (hi, o1) = self.hi.overflowing_add(rhs.hi);
        let (hi, o2) = hi.overflowing_add(carry as i128);
        if o1 != o2 {
            None
        } else {
            Some(I256 { lo, hi })
        }
    }

    /// Checked subtraction, `None` on signed overflow.
    #[inline]
    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
        let (lo, borrow) = self.lo.overflowing_sub(rhs.lo);
        let (hi, o1) = self.hi.overflowing_sub(rhs.hi);
        let (hi, o2) = hi.overflowing_sub(borrow as i128);
        if o1 != o2 {
            None
        } else {
            Some(I256 { lo, hi })
        }
    }

    /// Decomposes into a sign and a 4-limb little-endian magnitude.
    #[inline]
    pub(crate) const fn to_sign_mag(self) -> (bool, [u64; 4]) {
        let neg = self.hi < 0;
        let v = if neg { self.wrapping_neg() } else { self };
        (
            neg,
            [
                v.lo as u64,
                (v.lo >> 64) as u64,
                v.hi as u64,
                ((v.hi as u128) >> 64) as u64,
            ],
        )
    }

    /// Builds a value from a sign and a 4-limb magnitude. Returns `None` if
    /// the magnitude exceeds 2^255 - 1 (the symmetric range bound).
    #[inline]
    pub(crate) const fn from_sign_mag(neg: bool, mag: [u64; 4]) -> Option<Self> {
        if mag[3] >> 63 != 0 {
            return None;
        }
        let v = I256 {
            lo: (mag[0] as u128) | ((mag[1] as u128) << 64),
            hi: ((mag[2] as u128) | ((mag[3] as u128) << 64)) as i128,
        };
        Some(if neg { v.wrapping_neg() } else { v })
    }

    /// Returns the memory representation as 32 bytes in little-endian order.
    #[inline]
    pub const fn to_le_bytes(self) -> [u8; 32] {
        let lo = self.lo.to_le_bytes();
        let hi = self.hi.to_le_bytes();
        let mut out = [0u8; 32];
        let mut i = 0;
        while i < 16 {
            out[i] = lo[i];
            out[i + 16] = hi[i];
            i += 1;
        }
        out
    }

    /// Creates a value from its 32-byte little-endian representation.
    #[inline]
    pub const fn from_le_bytes(bytes: [u8; 32]) -> Self {
        let mut lo = [0u8; 16];
        let mut hi = [0u8; 16];
        let mut i = 0;
        while i < 16 {
            lo[i] = bytes[i];
            hi[i] = bytes[i + 16];
            i += 1;
        }
        I256 {
            lo: u128::from_le_bytes(lo),
            hi: i128::from_le_bytes(hi),
        }
    }
}

impl Ord for I256 {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        match self.hi.cmp(&other.hi) {
            Ordering::Equal => self.lo.cmp(&other.lo),
            o => o,
        }
    }
}

impl PartialOrd for I256 {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl fmt::Debug for I256 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut buf = [0u8; 96];
        let (neg, mag) = self.to_sign_mag();
        match str_mag(&mag, neg, 0, None, AmountSign::Negative, &mut buf) {
            Some(s) => f.write_str(s),
            None => f.write_str("I256::ERROR"),
        }
    }
}

/// Decimal fixed-point number backed by a 256-bit signed integer, with
/// `DIGITS` fractional decimal digits (`DIGITS <= 19`).
///
/// Same decimal semantics as [`Decimal`](crate::Decimal) and
/// [`Decimal128`](crate::Decimal128), with a range of about
/// ±5.8 * 10^(76 - DIGITS).
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Decimal256<const DIGITS: u8>(pub I256);

/// Amount256 is a 256-bit integer based decimal type with 4 decimal digits precision.
pub type Amount256 = Decimal256<4>;
/// Rate256 is a 256-bit integer based decimal type with 8 decimal digits precision.
pub type Rate256 = Decimal256<8>;

/// Remainder of the backing integers (sign follows the dividend, like `%` on
/// primitive integers). `b` must be non-zero.
#[inline]
fn i256_rem(a: I256, b: I256) -> I256 {
    let (an, am) = a.to_sign_mag();
    let (_, bm) = b.to_sign_mag();
    // The remainder magnitude is < |b| <= MAX, so this cannot fail.
    I256::from_sign_mag(an, rem_mag(&am, &bm)).unwrap()
}

impl<const DIGITS: u8> Decimal256<DIGITS> {
    /// The decimal scale: the number of fractional digits.
    pub const SCALE: i32 = DIGITS as i32;

    /// The multiplier used to scale values up, as a single 64-bit word.
    /// Constrains `DIGITS <= 19` at compile time.
    pub(crate) const SCALE_U64: u64 = upow10(DIGITS as u32);

    /// The multiplier used to scale values up. Equal to 10^DIGITS.
    pub const SCALE_INT: i128 = Self::SCALE_U64 as i128;

    /// Half of the scaling factor, used for rounding.
    pub const SCALE_INT_HALF: i128 = Self::SCALE_INT / 2;

    /// The largest value that can be represented by this type.
    pub const MAX: Self = Decimal256::<DIGITS>(I256::MAX);
    /// The smallest value that can be represented by this type (`-MAX`).
    pub const MIN: Self = Decimal256::<DIGITS>(I256::MIN);

    /// Constant equal to '1'
    pub const ONE: Self = Decimal256::<DIGITS>(I256::from_i128(Self::SCALE_INT));
    /// Constant equal to '-1'
    pub const MINUS_ONE: Self = Decimal256::<DIGITS>(I256::from_i128(-Self::SCALE_INT));
    /// Constant equal to '0'
    pub const ZERO: Self = Decimal256::<DIGITS>(I256::ZERO);

    /// The multiplier used to scale values up, as f64.
    pub const SCALE_F64: f64 = Self::SCALE_INT as f64;

    /// 2^128 as f64, used to assemble/split wide float conversions.
    const TWO_POW_128: f64 = 340282366920938463463374607431768211456.0;

    /// The largest f64 value that can be represented, about 5.8e76 / 10^DIGITS.
    pub const F64_MAX: f64 =
        ((i128::MAX as f64) * Self::TWO_POW_128 + (u128::MAX as f64)) / Self::SCALE_F64;
    /// The smallest f64 value that can be represented.
    pub const F64_MIN: f64 = -Self::F64_MAX;

    /// Constructs a new decimal integer with value 0.
    ///
    /// # Examples
    /// ```rust
    /// use fin_decimal::Amount256;
    /// let i = Amount256::new();
    /// assert_eq!(i, Amount256::ZERO);
    /// ```
    #[inline]
    pub fn new() -> Self {
        Self::ZERO
    }

    /// Tries to convert a f32 to a Decimal256.
    #[inline]
    pub fn from_f32(val: f32) -> Result<Self, AmountErrorKind> {
        Self::from_f64(val as f64)
    }

    /// Tries to convert a f64 to a Decimal256.
    pub fn from_f64(val: f64) -> Result<Self, AmountErrorKind> {
        if !(Self::F64_MIN..=Self::F64_MAX).contains(&val) {
            return Err(AmountErrorKind::Overflow);
        }
        let x = val * Self::SCALE_F64;
        // Values within i128 take the exact native cast; wider ones are split
        // into 2^128-sized halves (f64 has only 53 mantissa bits, so the
        // split loses nothing that the input still carried).
        const TWO_POW_127: f64 = 170141183460469231731687303715884105728.0;
        if (-TWO_POW_127..TWO_POW_127).contains(&x) {
            Ok(Decimal256::<DIGITS>(I256::from_i128(x as i128)))
        } else {
            let two128 = Self::TWO_POW_128;
            // floor(x / 2^128) without std: the cast truncates toward zero,
            // so step down once when the remainder comes out negative.
            let mut hi = (x / two128) as i128;
            let mut lo = x - (hi as f64) * two128;
            if lo < 0.0 {
                hi -= 1;
                lo += two128;
            }
            Ok(Decimal256::<DIGITS>(I256 { lo: lo as u128, hi }))
        }
    }

    /// Converts an i128 to a Decimal256. Always exact: every i128 fits.
    #[inline]
    pub const fn from_i128(val: i128) -> Self {
        let neg = val < 0;
        let m = val.unsigned_abs();
        let mut mag = [m as u64, (m >> 64) as u64, 0, 0];
        // |i128| * 10^19 < 2^191: never overflows four limbs.
        mul_add_word(&mut mag, Self::SCALE_U64, 0);
        match I256::from_sign_mag(neg, mag) {
            Some(v) => Decimal256::<DIGITS>(v),
            None => unreachable!(),
        }
    }

    /// Converts an i64 to a Decimal256. Always exact.
    #[inline]
    pub const fn from_i64(val: i64) -> Self {
        Self::from_i128(val as i128)
    }

    /// Converts the Decimal256 back into an f64 (approximate for values wider
    /// than the f64 mantissa).
    pub fn to_f64(self) -> f64 {
        ((self.0.hi as f64) * Self::TWO_POW_128 + self.0.lo as f64) / Self::SCALE_F64
    }

    /// Converts the Decimal256 back into an i128, truncating the fractional
    /// part and saturating to `i128::MIN`/`i128::MAX` when out of range.
    pub const fn to_i128(self) -> i128 {
        let (neg, mag) = self.0.to_sign_mag();
        let mut q = mag;
        div_words_by_pow10::<DIGITS>(&mut q);
        if q[2] != 0 || q[3] != 0 || ((q[0] as u128) | ((q[1] as u128) << 64)) > i128::MAX as u128 {
            return if neg { i128::MIN } else { i128::MAX };
        }
        let v = ((q[0] as u128) | ((q[1] as u128) << 64)) as i128;
        if neg { -v } else { v }
    }

    /// Parses a decimal string, rounding any fractional digits beyond this
    /// type's scale with the given [`Rounding`] mode.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::{Amount256, Rounding};
    /// assert_eq!(
    ///     Amount256::from_str_rounded("1.00005", Rounding::HalfEven),
    ///     Ok(Amount256::from(1)),
    /// );
    /// ```
    pub const fn from_str_rounded(src: &str, mode: Rounding) -> Result<Self, AmountErrorKind> {
        let (neg, mag) = match parse_decimal_mag_rounded::<4>(src, DIGITS, mode) {
            Ok(v) => v,
            Err(e) => return Err(e),
        };
        match I256::from_sign_mag(neg, mag) {
            Some(v) => Ok(Decimal256::<DIGITS>(v)),
            None => Err(AmountErrorKind::Overflow),
        }
    }

    /// Parses a decimal string with [`Rounding::HalfUp`], panicking on invalid
    /// input — intended for compile-time constants, where the panic becomes a
    /// compile error.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::Amount256;
    /// const BUDGET: Amount256 = Amount256::from_str_const("1000000000000000000000000.25");
    /// assert_eq!(BUDGET.to_string(), "1000000000000000000000000.25");
    /// ```
    pub const fn from_str_const(src: &str) -> Self {
        match Self::from_str_rounded(src, Rounding::HalfUp) {
            Ok(v) => v,
            Err(_) => panic!("invalid decimal literal"),
        }
    }

    /// Sign and 4-limb magnitude, for the shared formatting code in
    /// [`common`](crate::common).
    #[inline]
    pub(crate) const fn sign_mag4(self) -> (bool, [u64; 4]) {
        self.0.to_sign_mag()
    }

    /// Computes the absolute value of self.
    #[inline]
    pub const fn abs(self) -> Self {
        if self.0.is_negative() {
            Decimal256::<DIGITS>(self.0.wrapping_neg())
        } else {
            self
        }
    }

    /// Checked addition. Computes `self + rhs`, returning `None` if overflow occurred.
    #[inline]
    pub const fn checked_add(self, rhs: Self) -> Option<Self> {
        match self.0.checked_add(rhs.0) {
            Some(v) => Some(Decimal256::<DIGITS>(v)),
            None => None,
        }
    }

    /// Checked subtraction. Computes `self - rhs`, returning `None` if overflow occurred.
    #[inline]
    pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
        match self.0.checked_sub(rhs.0) {
            Some(v) => Some(Decimal256::<DIGITS>(v)),
            None => None,
        }
    }

    /// Checked multiplication. Computes `self * rhs`, returning `None` if overflow occurred.
    #[inline]
    pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
        let (an, am) = self.0.to_sign_mag();
        let (bn, bm) = rhs.0.to_sign_mag();
        match dec_mul::<DIGITS, 4, 8>(an, &am, bn, &bm, Rounding::HalfUp) {
            Some((neg, mag)) => match I256::from_sign_mag(neg, mag) {
                Some(v) => Some(Decimal256::<DIGITS>(v)),
                None => unreachable!(),
            },
            None => None,
        }
    }

    /// Checked division. Computes `self / rhs`, returning `None` if `rhs == 0`
    /// or the division results in overflow.
    #[inline]
    pub fn checked_div(self, rhs: Self) -> Option<Self> {
        let (an, am) = self.0.to_sign_mag();
        let (bn, bm) = rhs.0.to_sign_mag();
        dec_div::<DIGITS, 4, 5>(an, &am, bn, &bm, Rounding::HalfUp)
            .map(|(neg, mag)| Decimal256::<DIGITS>(I256::from_sign_mag(neg, mag).unwrap()))
    }

    /// Checked remainder. Computes `self % rhs`, returning `None` if
    /// `rhs == 0`. (The remainder itself cannot overflow: its magnitude
    /// never exceeds the divisor's.)
    #[inline]
    pub fn checked_rem(self, rhs: Self) -> Option<Self> {
        if rhs.0.is_zero() {
            None
        } else {
            Some(Decimal256::<DIGITS>(i256_rem(self.0, rhs.0)))
        }
    }

    /// Takes the reciprocal (inverse) of a number, 1/x.
    #[inline]
    ///
    /// # Panics
    /// Panics if `self` is zero (like core's `/`);
    /// [`checked_recip`](Self::checked_recip) is the non-panicking form.
    pub fn recip(self) -> Self {
        match self.checked_recip() {
            Some(v) => v,
            // `checked_recip` can only fail for zero on this backing: the
            // reciprocal's mantissa is at most 10^(2 * DIGITS) <= 10^38,
            // inside the range.
            None => panic!("attempt to divide by zero"),
        }
    }

    /// Checked reciprocal: `None` if `self` is zero. (The result cannot
    /// overflow on this backing: its mantissa is at most
    /// `10^(2 * DIGITS) <= 10^38`, well inside the 256-bit range.)
    #[inline]
    pub fn checked_recip(self) -> Option<Self> {
        Self::ONE.checked_div(self)
    }

    /// Returns the integer part of a number (rounding toward zero).
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::Amount256;
    /// assert_eq!(Amount256::from_f64(-3.7).unwrap().trunc(), Amount256::from(-3));
    /// ```
    pub const fn trunc(self) -> Self {
        let (neg, mag) = self.0.to_sign_mag();
        let mut q = mag;
        div_words_by_pow10::<DIGITS>(&mut q);
        // q * scale <= mag: cannot overflow or exceed range.
        mul_add_word(&mut q, Self::SCALE_U64, 0);
        match I256::from_sign_mag(neg, q) {
            Some(v) => Decimal256::<DIGITS>(v),
            None => unreachable!(),
        }
    }

    /// Returns the fractional part of a number.
    #[inline]
    pub const fn fract(self) -> Self {
        // |fract| < 1: the subtraction cannot overflow.
        match self.0.checked_sub(self.trunc().0) {
            Some(v) => Decimal256::<DIGITS>(v),
            None => unreachable!(),
        }
    }

    /// Returns the largest integer less than or equal to a number.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::Amount256;
    /// assert_eq!(Amount256::from_f64(-3.7).unwrap().floor(), Amount256::from(-4));
    /// ```
    #[inline]
    pub const fn floor(self) -> Self {
        self.round_to(Rounding::Down)
    }

    /// Returns the smallest integer greater than or equal to a number.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::Amount256;
    /// assert_eq!(Amount256::from_f64(3.01).unwrap().ceil(), Amount256::from(4));
    /// assert_eq!(Amount256::from_f64(-3.7).unwrap().ceil(), Amount256::from(-3));
    /// ```
    #[inline]
    pub const fn ceil(self) -> Self {
        self.round_to(Rounding::Up)
    }

    /// Returns the nearest integer to a number. Rounds half-way cases away
    /// from `0.0`.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::Amount256;
    /// assert_eq!(Amount256::from_f64(-3.5).unwrap().round(), Amount256::from(-4));
    /// ```
    #[inline]
    pub const fn round(self) -> Self {
        self.round_to(Rounding::HalfUp)
    }

    /// Explicitly rounds the value to an integer using the specified rounding mode.
    ///
    /// # Panics
    /// Panics if rounding up at the very edge of the range overflows.
    pub const fn round_to(self, mode: Rounding) -> Self {
        match self.checked_round_to(mode) {
            Some(v) => v,
            None => panic!("attempt to round with overflow"),
        }
    }

    /// Checked form of [`round_to`](Self::round_to): `None` if rounding away
    /// from zero at the very edge of the range overflows.
    pub const fn checked_round_to(self, mode: Rounding) -> Option<Self> {
        let (neg, mag) = self.0.to_sign_mag();
        let mut q = mag;
        let rem = div_words_by_pow10::<DIGITS>(&mut q);
        if rem == 0 {
            return Some(self);
        }
        if round_up_by_cmp(
            cmp_twice_rem_u64(rem, Self::SCALE_U64),
            false,
            q[0] & 1 != 0,
            neg,
            mode,
        ) {
            mul_add_word(&mut q, 1, 1);
        }
        let overflow = mul_add_word(&mut q, Self::SCALE_U64, 0);
        match (overflow, I256::from_sign_mag(neg, q)) {
            (false, Some(v)) => Some(Decimal256::<DIGITS>(v)),
            _ => None,
        }
    }

    /// Multiply by another decimal, explicitly applying the given rounding mode.
    ///
    /// The right-hand side may have a different scale: the exact product is
    /// rounded once to `self`'s scale, so an amount times a high-precision
    /// rate needs no intermediate conversion.
    ///
    /// Usable in const contexts, so multiplication chains can be evaluated at
    /// compile time.
    ///
    /// # Panics
    /// Panics if the result overflows (like core integer arithmetic in debug
    /// builds); [`checked_mul_rounded`](Self::checked_mul_rounded) is the
    /// non-panicking form.
    pub const fn mul_rounded<const RHS_DIGITS: u8>(
        self,
        rhs: Decimal256<RHS_DIGITS>,
        mode: Rounding,
    ) -> Self {
        match self.checked_mul_rounded(rhs, mode) {
            Some(v) => v,
            None => panic!("attempt to multiply with overflow"),
        }
    }

    /// Checked form of [`mul_rounded`](Self::mul_rounded): `None` if the
    /// result overflows.
    #[inline]
    pub const fn checked_mul_rounded<const RHS_DIGITS: u8>(
        self,
        rhs: Decimal256<RHS_DIGITS>,
        mode: Rounding,
    ) -> Option<Self> {
        let (an, am) = self.0.to_sign_mag();
        let (bn, bm) = rhs.0.to_sign_mag();
        match dec_mul::<RHS_DIGITS, 4, 8>(an, &am, bn, &bm, mode) {
            Some((neg, mag)) => match I256::from_sign_mag(neg, mag) {
                Some(v) => Some(Decimal256::<DIGITS>(v)),
                None => unreachable!(),
            },
            None => None,
        }
    }

    /// Divide by another decimal, explicitly applying the given rounding mode.
    ///
    /// # Panics
    /// Panics if `rhs` is zero (like core's `/`) or the result overflows;
    /// [`checked_div_rounded`](Self::checked_div_rounded) is the
    /// non-panicking form.
    pub fn div_rounded(self, rhs: Self, mode: Rounding) -> Self {
        self.div_rounded_to::<DIGITS>(rhs, mode)
    }

    /// Checked form of [`div_rounded`](Self::div_rounded): `None` if `rhs`
    /// is zero or the result overflows.
    #[inline]
    pub fn checked_div_rounded(self, rhs: Self, mode: Rounding) -> Option<Self> {
        self.checked_div_rounded_to::<DIGITS>(rhs, mode)
    }

    /// Divide by another decimal of the same scale, producing the quotient at
    /// an explicitly chosen scale with the given rounding mode. The exact
    /// quotient is rounded once at `TO_DIGITS` digits, so a proportion of two
    /// amounts can be taken directly as a higher-precision rate.
    ///
    /// # Panics
    /// Panics if `rhs` is zero (like core's `/`) or the result overflows;
    /// [`checked_div_rounded_to`](Self::checked_div_rounded_to) is the
    /// non-panicking form.
    pub fn div_rounded_to<const TO_DIGITS: u8>(
        self,
        rhs: Self,
        mode: Rounding,
    ) -> Decimal256<TO_DIGITS> {
        if rhs.0.is_zero() {
            panic!("attempt to divide by zero");
        }
        match self.checked_div_rounded_to::<TO_DIGITS>(rhs, mode) {
            Some(v) => v,
            None => panic!("attempt to divide with overflow"),
        }
    }

    /// Checked form of [`div_rounded_to`](Self::div_rounded_to): `None` if
    /// `rhs` is zero or the result overflows.
    #[inline]
    pub fn checked_div_rounded_to<const TO_DIGITS: u8>(
        self,
        rhs: Self,
        mode: Rounding,
    ) -> Option<Decimal256<TO_DIGITS>> {
        let (an, am) = self.0.to_sign_mag();
        let (bn, bm) = rhs.0.to_sign_mag();
        match dec_div::<TO_DIGITS, 4, 5>(an, &am, bn, &bm, mode) {
            Some((neg, mag)) => Some(Decimal256::<TO_DIGITS>(I256::from_sign_mag(neg, mag)?)),
            None => None,
        }
    }

    /// Divide by an integer, explicitly applying the given rounding mode: the
    /// exact quotient is rounded once at the type's own scale. The divisor is
    /// a single word, so this is plain word division over the limbs.
    ///
    /// # Panics
    /// Panics if `n` is zero (like core's `/`);
    /// [`checked_div_int_rounded`](Self::checked_div_int_rounded) is the
    /// non-panicking form. The result itself cannot overflow: its magnitude
    /// never exceeds `self`'s (rounding up only happens for `|n| >= 2`).
    pub fn div_int_rounded(self, n: i64, mode: Rounding) -> Self {
        match self.checked_div_int_rounded(n, mode) {
            Some(v) => v,
            None => panic!("attempt to divide by zero"),
        }
    }

    /// Checked form of [`div_int_rounded`](Self::div_int_rounded): `None`
    /// only if `n` is zero (the result cannot overflow).
    #[inline]
    pub fn checked_div_int_rounded(self, n: i64, mode: Rounding) -> Option<Self> {
        if n == 0 {
            return None;
        }
        let (an, mag) = self.0.to_sign_mag();
        let neg = an != (n < 0);
        let q = div_mag_by_word(neg, &mag, n.unsigned_abs(), mode);
        // The magnitude only shrinks, so the sign-magnitude rebuild cannot
        // fail.
        match I256::from_sign_mag(neg, q) {
            Some(v) => Some(Decimal256::<DIGITS>(v)),
            None => unreachable!(),
        }
    }

    /// Checked form of [`round_dp`](Self::round_dp): `None` if rounding
    /// away from zero at the very edge of the range overflows.
    pub fn checked_round_dp(self, dp: u8, mode: Rounding) -> Option<Self> {
        if dp >= DIGITS {
            return Some(self);
        }
        let step = upow10((DIGITS - dp) as u32);
        let (neg, mag) = self.0.to_sign_mag();
        let q = round_mag_to_step(neg, &mag, step, mode);
        // The sign-magnitude range check catches the top-of-range edge.
        I256::from_sign_mag(neg, q).map(Decimal256::<DIGITS>)
    }

    /// Splits `self` into `n` parts that sum back to `self` **exactly**:
    /// `high_count` parts one unit in the last place larger than the
    /// remaining `low_count` parts (largest-remainder allocation). `None`
    /// if `n` is zero.
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::Amount256;
    /// let split = Amount256::from_str_const("100.00").checked_split_evenly(3).unwrap();
    /// // 1 part of 33.3334 + 2 parts of 33.3333 == 100.0000 exactly.
    /// assert_eq!(split.high, Amount256::from_str_const("33.3334"));
    /// assert_eq!(split.high_count, 1);
    /// assert_eq!(split.low, Amount256::from_str_const("33.3333"));
    /// assert_eq!(split.low_count, 2);
    /// ```
    pub fn checked_split_evenly(self, n: u32) -> Option<EvenSplit<Self>> {
        if n == 0 {
            return None;
        }
        let (neg, full) = self.0.to_sign_mag();
        let (lo, hi, r) = split_mag_even(&full, n);
        // Part magnitudes never exceed the total's, so the rebuilds cannot
        // fail.
        let low = match I256::from_sign_mag(neg, lo) {
            Some(v) => Decimal256::<DIGITS>(v),
            None => unreachable!(),
        };
        let high = if r == 0 {
            low
        } else {
            match I256::from_sign_mag(neg, hi) {
                Some(v) => Decimal256::<DIGITS>(v),
                None => unreachable!(),
            }
        };
        Some(EvenSplit {
            high,
            high_count: r,
            low,
            low_count: n - r,
        })
    }

    /// Square root with the given rounding mode: `None` for a negative
    /// value. (Overflow is impossible: the root of even `MAX`'s scaled
    /// mantissa stays below `2^160`.)
    ///
    /// The exact root of `self` is rounded once at the type's own scale:
    /// the result is the correctly rounded decimal square root, computed as
    /// the integer square root of `mantissa * 10^DIGITS`. For the half
    /// modes a tie cannot occur (`(s + 1/2)^2` is never an integer), so
    /// `HalfUp`, `HalfDown` and `HalfEven` always agree here.
    ///
    /// Not usable in const contexts (unlike the i64 backing's): the wide
    /// core's Newton steps divide by a runtime divisor, which is where the
    /// `asm` feature applies.
    pub fn checked_sqrt_rounded(self, mode: Rounding) -> Option<Self> {
        let (neg, mag) = self.0.to_sign_mag();
        if neg {
            return None;
        }
        // Single-limb fast tier for typical money magnitudes: the scaled
        // radicand fits u128, so the shared u128 core applies directly.
        if sig_limbs(&mag) == 1 {
            let n = mag[0] as u128 * const { upow10(DIGITS as u32) } as u128;
            let (s, rem_zero, rem_gt_root) = isqrt_u128_with_rem(n);
            let up = sqrt_round_up(mode, rem_zero, rem_gt_root);
            let root = (s as u128 + up as u128) as i128;
            return Some(Decimal256::<DIGITS>(I256::from_i128(root)));
        }
        let mut n = [0u64; 6];
        mul_words(&mut n[..5], &mag, &[const { upow10(DIGITS as u32) }]);
        let (root, rem_zero, rem_gt_root) = isqrt_words::<6, 3, 6>(&n);
        let up = sqrt_round_up(mode, rem_zero, rem_gt_root);
        let mut mag_r = [root[0], root[1], root[2], 0];
        if up {
            mul_add_word(&mut mag_r, 1, 1);
        }
        match I256::from_sign_mag(false, mag_r) {
            Some(v) => Some(Decimal256::<DIGITS>(v)),
            // The root is below 2^160, far inside the range.
            None => unreachable!(),
        }
    }

    /// `self * b / c` on the exact 512-bit product with a single rounding at
    /// the end, or `None` if `c` is zero or the result overflows.
    ///
    /// The muldiv/pro-rata primitive: allocating an amount by the proportion
    /// `b / c` this way avoids the double rounding of first taking the ratio
    /// and then multiplying by it. `b` and `c` share a scale — any scale,
    /// since it cancels in `b / c` — and the result keeps `self`'s scale.
    pub fn checked_mul_div_rounded<const S: u8>(
        self,
        b: Decimal256<S>,
        c: Decimal256<S>,
        mode: Rounding,
    ) -> Option<Self> {
        let (an, am) = self.0.to_sign_mag();
        let (bn, bm) = b.0.to_sign_mag();
        let (cn, cm) = c.0.to_sign_mag();
        match dec_mul_div::<4, 8>(an, &am, bn, &bm, cn, &cm, mode) {
            // The core's top-bit check guarantees the rebuild fits.
            Some((neg, mag)) => match I256::from_sign_mag(neg, mag) {
                Some(v) => Some(Decimal256::<DIGITS>(v)),
                None => unreachable!(),
            },
            None => None,
        }
    }

    /// `self * b / c` on the exact 512-bit product with a single rounding at
    /// the end. See
    /// [`checked_mul_div_rounded`](Self::checked_mul_div_rounded).
    ///
    /// # Examples
    /// ```
    /// use fin_decimal::{Amount256, Rounding};
    /// // Allocate a total pro rata by 1/3 without an intermediate rate.
    /// let total = Amount256::from_str_const("100.00");
    /// let share = total.mul_div_rounded(Amount256::from(1), Amount256::from(3), Rounding::HalfUp);
    /// assert_eq!(share, Amount256::from_str_const("33.3333"));
    /// ```
    ///
    /// # Panics
    /// Panics if `c` is zero (like core's `/`) or the result overflows;
    /// [`checked_mul_div_rounded`](Self::checked_mul_div_rounded) is the
    /// non-panicking form.
    pub fn mul_div_rounded<const S: u8>(
        self,
        b: Decimal256<S>,
        c: Decimal256<S>,
        mode: Rounding,
    ) -> Self {
        if c.0.is_zero() {
            panic!("attempt to divide by zero");
        }
        // The 2W-limb product is exact, so overflow is always quotient-driven.
        match self.checked_mul_div_rounded(b, c, mode) {
            Some(v) => v,
            None => panic!("attempt to divide with overflow"),
        }
    }

    /// Returns `true` if `self` is positive and `false` if the number is zero or negative.
    #[inline]
    pub const fn is_positive(self) -> bool {
        !self.0.is_negative() && !self.0.is_zero()
    }

    /// Returns `true` if `self` is negative and `false` if the number is zero or positive.
    #[inline]
    pub const fn is_negative(self) -> bool {
        self.0.is_negative()
    }

    /// Returns a number that represents the sign of `self`.
    pub const fn signum(self) -> Self {
        if self.0.is_negative() {
            Self::MINUS_ONE
        } else if self.0.is_zero() {
            Self::ZERO
        } else {
            Self::ONE
        }
    }

    /// Raw transmutation to the backing scaled integer.
    #[inline]
    pub const fn to_bits(self) -> I256 {
        self.0
    }

    /// Raw transmutation from a backing scaled integer.
    #[inline]
    pub const fn from_bits(v: I256) -> Self {
        Decimal256::<DIGITS>(v)
    }

    /// Return the memory representation of this value as a byte array in
    /// little-endian byte order.
    #[inline]
    pub const fn to_le_bytes(self) -> [u8; 32] {
        self.0.to_le_bytes()
    }

    /// Create a value from its representation as a byte array in little endian.
    #[inline]
    pub const fn from_le_bytes(bytes: [u8; 32]) -> Self {
        Decimal256::<DIGITS>(I256::from_le_bytes(bytes))
    }

    /// Raises a number to an integer power. Usable in const contexts.
    ///
    /// # Panics
    /// Panics if an intermediate product overflows;
    /// [`checked_powi`](Self::checked_powi) is the non-panicking form.
    #[inline]
    pub const fn powi(self, exp: u32) -> Self {
        match self.checked_powi(exp) {
            Some(v) => v,
            None => panic!("attempt to multiply with overflow"),
        }
    }

    /// Checked form of [`powi`](Self::powi): `None` if an intermediate
    /// product overflows. Each step rounds `HalfUp` at the type's scale,
    /// like `powi`.
    pub const fn checked_powi(self, mut exp: u32) -> Option<Self> {
        let mut base = self;
        let mut acc = Self::ONE;
        while exp > 1 {
            if (exp & 1) == 1 {
                acc = match base.checked_mul_rounded(acc, Rounding::HalfUp) {
                    Some(v) => v,
                    None => return None,
                };
            }
            exp /= 2;
            base = match base.checked_mul_rounded(base, Rounding::HalfUp) {
                Some(v) => v,
                None => return None,
            };
        }
        // The final bit of the exponent is handled separately: squaring the
        // base afterwards is unnecessary and could overflow needlessly.
        if exp == 1 {
            acc = match base.checked_mul_rounded(acc, Rounding::HalfUp) {
                Some(v) => v,
                None => return None,
            };
        }
        Some(acc)
    }

    /// Restrict a value to a certain interval.
    #[inline]
    pub fn clamp(self, min: Self, max: Self) -> Self {
        if self.0 < min.0 {
            min
        } else if self.0 > max.0 {
            max
        } else {
            self
        }
    }

    /// Returns the minimum of the two numbers.
    #[inline]
    pub fn min(self, other: Self) -> Self {
        if self <= other { self } else { other }
    }

    /// Returns the maximum of the two numbers.
    #[inline]
    pub fn max(self, other: Self) -> Self {
        if self >= other { self } else { other }
    }
}

impl<const DIGITS: u8> From<i32> for Decimal256<DIGITS> {
    #[inline]
    fn from(item: i32) -> Self {
        Self::from_i128(item as i128)
    }
}

impl<const DIGITS: u8> From<i64> for Decimal256<DIGITS> {
    #[inline]
    fn from(item: i64) -> Self {
        Self::from_i128(item as i128)
    }
}

impl<const DIGITS: u8> From<i128> for Decimal256<DIGITS> {
    #[inline]
    fn from(item: i128) -> Self {
        Self::from_i128(item)
    }
}

impl<const DIGITS: u8> From<f64> for Decimal256<DIGITS> {
    /// Converts an f64, saturating to `MIN`/`MAX` when out of range.
    #[inline]
    fn from(item: f64) -> Self {
        match Self::from_f64(item) {
            Ok(v) => v,
            Err(_) if item < 0.0 => Self::MIN,
            Err(_) => Self::MAX,
        }
    }
}

impl<const DIGITS: u8> From<f32> for Decimal256<DIGITS> {
    #[inline]
    fn from(item: f32) -> Self {
        Self::from(item as f64)
    }
}

impl<const DIGITS: u8> PartialOrd<i64> for Decimal256<DIGITS> {
    #[inline]
    fn partial_cmp(&self, other: &i64) -> Option<Ordering> {
        PartialOrd::partial_cmp(&self.0, &Self::from_i64(*other).0)
    }
}

impl<const DIGITS: u8> PartialEq<i64> for Decimal256<DIGITS> {
    #[inline]
    fn eq(&self, other: &i64) -> bool {
        self.0 == Self::from_i64(*other).0
    }
}

impl<const DIGITS: u8> Neg for Decimal256<DIGITS> {
    type Output = Self;
    #[inline]
    fn neg(self) -> Self::Output {
        Decimal256::<DIGITS>(self.0.wrapping_neg())
    }
}

impl<const DIGITS: u8> Add for Decimal256<DIGITS> {
    type Output = Self;
    /// # Panics
    /// Panics if the result overflows.
    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        match self.0.checked_add(rhs.0) {
            Some(v) => Decimal256::<DIGITS>(v),
            None => panic!("attempt to add with overflow"),
        }
    }
}

impl<const DIGITS: u8> Add<i64> for Decimal256<DIGITS> {
    type Output = Self;
    #[inline]
    fn add(self, other: i64) -> Self {
        self + Self::from_i64(other)
    }
}

impl<const DIGITS: u8> Add<i32> for Decimal256<DIGITS> {
    type Output = Self;
    #[inline]
    fn add(self, rhs: i32) -> Self {
        self + Self::from_i128(rhs as i128)
    }
}

impl<const DIGITS: u8> Sub for Decimal256<DIGITS> {
    type Output = Self;
    /// # Panics
    /// Panics if the result overflows.
    #[inline]
    fn sub(self, rhs: Self) -> Self {
        match self.0.checked_sub(rhs.0) {
            Some(v) => Decimal256::<DIGITS>(v),
            None => panic!("attempt to subtract with overflow"),
        }
    }
}

impl<const DIGITS: u8> Sub<i64> for Decimal256<DIGITS> {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: i64) -> Self {
        self - Self::from_i64(rhs)
    }
}

impl<const DIGITS: u8> Sub<i32> for Decimal256<DIGITS> {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: i32) -> Self {
        self - Self::from_i128(rhs as i128)
    }
}

impl<const DIGITS: u8> Mul for Decimal256<DIGITS> {
    type Output = Self;
    /// Multiplies with decimal `HalfUp` rounding (half away from zero).
    ///
    /// # Panics
    /// Panics if the result overflows.
    #[inline]
    fn mul(self, rhs: Self) -> Self::Output {
        self.mul_rounded(rhs, Rounding::HalfUp)
    }
}

impl<const DIGITS: u8> Mul<i64> for Decimal256<DIGITS> {
    type Output = Self;
    /// # Panics
    /// Panics if the result overflows.
    #[inline]
    fn mul(self, rhs: i64) -> Self {
        let (neg, mut mag) = self.0.to_sign_mag();
        let overflow = mul_add_word(&mut mag, rhs.unsigned_abs(), 0);
        match (overflow, I256::from_sign_mag(neg != (rhs < 0), mag)) {
            (false, Some(v)) => Decimal256::<DIGITS>(v),
            _ => panic!("attempt to multiply with overflow"),
        }
    }
}

impl<const DIGITS: u8> Mul<i32> for Decimal256<DIGITS> {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: i32) -> Self {
        self * (rhs as i64)
    }
}

impl<const DIGITS: u8> Div for Decimal256<DIGITS> {
    type Output = Self;
    /// Divides with decimal `HalfUp` rounding (half away from zero).
    ///
    /// # Panics
    /// Panics if `rhs` is zero or the result overflows.
    #[inline]
    fn div(self, rhs: Self) -> Self {
        self.div_rounded(rhs, Rounding::HalfUp)
    }
}

impl<const DIGITS: u8> Rem for Decimal256<DIGITS> {
    type Output = Self;
    /// # Panics
    /// Panics if `rhs` is zero.
    #[inline]
    fn rem(self, rhs: Self) -> Self {
        match self.checked_rem(rhs) {
            Some(v) => v,
            None => panic!("attempt to calculate the remainder with a divisor of zero"),
        }
    }
}

crate::common::impl_decimal_wide_ops!(Decimal256, "Amount256");
crate::common::impl_decimal_common!(Decimal256, "Decimal256");

#[cfg(test)]
mod tests {
    extern crate std;
    use super::*;
    use core::str::FromStr;
    use std::format;
    use std::string::ToString;

    fn raw(v: i128) -> Amount256 {
        Amount256::from_bits(I256::from_i128(v))
    }

    #[test]
    fn test_i256_basics() {
        let one = I256::from_i128(1);
        let minus_one = I256::from_i128(-1);
        assert!(minus_one.is_negative());
        assert!(!one.is_negative());
        assert_eq!(one.wrapping_neg(), minus_one);
        assert_eq!(minus_one.wrapping_neg(), one);
        assert_eq!(I256::ZERO.wrapping_neg(), I256::ZERO);
        assert_eq!(I256::MAX.wrapping_neg(), I256::MIN);

        // Carry across the 128-bit boundary.
        let max_lo = I256 {
            lo: u128::MAX,
            hi: 0,
        };
        let sum = max_lo.checked_add(one).unwrap();
        assert_eq!(sum, I256 { lo: 0, hi: 1 });
        assert_eq!(sum.checked_sub(one).unwrap(), max_lo);

        // Overflow detection at the very top.
        assert_eq!(I256::MAX.checked_add(one), None);
        assert_eq!(I256::MIN.checked_sub(I256::from_i128(2)), None);
        assert!(I256::MAX.checked_add(minus_one).is_some());

        // Ordering.
        assert!(minus_one < I256::ZERO);
        assert!(I256::MIN < minus_one);
        assert!(one < I256::MAX);
        assert!(
            I256 { lo: 0, hi: 1 }
                > I256 {
                    lo: u128::MAX,
                    hi: 0
                }
        );

        // Sign/magnitude round trip.
        for v in [0i128, 1, -1, i128::MAX, -i128::MAX, 12345, -98765] {
            let x = I256::from_i128(v);
            let (neg, mag) = x.to_sign_mag();
            assert_eq!(I256::from_sign_mag(neg, mag), Some(x));
        }
        let (neg, mag) = I256::MAX.to_sign_mag();
        assert!(!neg);
        assert_eq!(I256::from_sign_mag(neg, mag), Some(I256::MAX));
        assert_eq!(I256::from_sign_mag(false, [0, 0, 0, 1 << 63]), None);

        // Byte round trip.
        let x = I256::from_i128(-123456789);
        assert_eq!(I256::from_le_bytes(x.to_le_bytes()), x);

        assert_eq!(format!("{:?}", I256::from_i128(-42)), "-42");
    }

    #[test]
    fn test_basic_ops() {
        let a = Amount256::from(2);
        let b = Amount256::from_f64(0.5).unwrap();
        assert_eq!(a, raw(20000));
        assert_eq!(b, raw(5000));
        assert_eq!(a + b, raw(25000));
        assert_eq!(a - b, raw(15000));
        assert_eq!(a * b, raw(10000));
        assert_eq!(a / b, raw(40000));
        assert_eq!(-a, raw(-20000));
        assert_eq!(a % b, raw(0));
        assert_eq!(raw(25000) % raw(20000), raw(5000));
        assert_eq!(raw(-25000) % raw(20000), raw(-5000));
    }

    #[test]
    fn test_mul_div_match_decimal64_vectors() {
        assert_eq!(raw(10001) * raw(10001), raw(10002));
        assert_eq!(raw(11004) * raw(10015), raw(11021));
        assert_eq!(raw(11004) * raw(-10015), raw(-11021));
        assert_eq!(raw(10000) / raw(110000), raw(909));
        assert_eq!(raw(10000) / raw(130000), raw(769));
        assert_eq!(raw(10000) / raw(-130000), raw(-769));
        assert_eq!(raw(-10000) / raw(130000), raw(-769));
        assert_eq!(raw(-10000) / raw(-130000), raw(769));
        assert_eq!(raw(10000) / raw(180000), raw(556));
        assert_eq!(raw(-10000) / raw(-180000), raw(556));
    }

    #[test]
    fn test_beyond_128_bit_range() {
        // 10^36 as an Amount256: overflows Amount64 and pushes Amount128.
        let big = Amount256::from(10i128.pow(36));
        assert_eq!((big * big).to_string(), "1".to_string() + &"0".repeat(72));
        // Knuth-path division: divisor uses all four limbs.
        let q = (big * big) / big;
        assert_eq!(q, big);
        let r = (big * big + Amount256::from(7)) % (big * big);
        assert_eq!(r, Amount256::from(7));
        // 1 / 3 at scale 4 still rounds correctly.
        assert_eq!(Amount256::from(1) / Amount256::from(3), raw(3333));
        // MAX round-trips through Display/FromStr.
        let s = Amount256::MAX.to_string();
        assert_eq!(Amount256::from_str(&s).unwrap(), Amount256::MAX);
        let s = Amount256::MIN.to_string();
        assert_eq!(Amount256::from_str(&s).unwrap(), Amount256::MIN);

        // Wide multiplication result verified against an independently
        // computed value: (2^126 / 10^4) * (2^126 / 10^4) needs > 128 bits.
        let a = raw(i128::MAX / 2 + 1); // 2^126, value 2^126 / 10^4
        let prod = a * a;
        // value = 2^252 / 10^8, mantissa rounded HalfUp at 4 digits.
        assert_eq!(prod / a, a);
        assert_eq!(
            prod.to_string(),
            "72370055773322622139731865630429942408293740416025352524660990004945.706"
        );
    }

    #[test]
    fn test_checked_math() {
        assert_eq!(Amount256::MAX.checked_add(raw(1)), None);
        // Like the i64-backed type, checked math permits the asymmetric
        // two's-complement minimum (MIN - 1); one step further overflows.
        assert!(Amount256::MIN.checked_sub(raw(1)).is_some());
        assert_eq!(Amount256::MIN.checked_sub(raw(2)), None);
        assert_eq!(Amount256::MAX.checked_mul(Amount256::from(2)), None);
        assert_eq!(Amount256::from(2).checked_div(Amount256::ZERO), None);
        assert_eq!(
            Amount256::from(6).checked_div(Amount256::from(2)),
            Some(Amount256::from(3))
        );
        assert_eq!(
            Amount256::MAX.checked_div(raw(5000)), // MAX / 0.5 overflows
            None
        );
    }

    #[test]
    fn test_rounding() {
        let a = Amount256::from_f64(1.5).unwrap();
        assert_eq!(a.round_to(Rounding::HalfUp), Amount256::from(2));
        assert_eq!(a.round_to(Rounding::HalfDown), Amount256::from(1));
        assert_eq!(a.round_to(Rounding::HalfEven), Amount256::from(2));
        assert_eq!(a.round_to(Rounding::Down), Amount256::from(1));
        assert_eq!(a.round_to(Rounding::Up), Amount256::from(2));
        let b = Amount256::from_f64(-1.5).unwrap();
        assert_eq!(b.round_to(Rounding::HalfUp), Amount256::from(-2));
        assert_eq!(b.round_to(Rounding::Down), Amount256::from(-2));
        assert_eq!(b.round_to(Rounding::Up), Amount256::from(-1));

        assert_eq!(
            Amount256::from_f64(-3.7).unwrap().trunc(),
            Amount256::from(-3)
        );
        assert_eq!(
            Amount256::from_f64(-3.7).unwrap().floor(),
            Amount256::from(-4)
        );
        assert_eq!(Amount256::from_f64(3.2).unwrap().ceil(), Amount256::from(4));
        assert_eq!(
            Amount256::from_f64(-3.5).unwrap().round(),
            Amount256::from(-4)
        );
        assert_eq!(Amount256::from_f64(3.25).unwrap().fract(), raw(2500));

        // mul_rounded ties.
        let h = raw(5000); // 0.5
        let x = raw(10001);
        assert_eq!(h.mul_rounded(x, Rounding::HalfUp), raw(5001));
        assert_eq!(h.mul_rounded(x, Rounding::HalfDown), raw(5000));
        assert_eq!(h.mul_rounded(x, Rounding::HalfEven), raw(5000));
        assert_eq!((-h).mul_rounded(x, Rounding::Down), raw(-5001));
        assert_eq!((-h).mul_rounded(x, Rounding::Up), raw(-5000));

        let one = Amount256::from(1);
        let three = Amount256::from(3);
        assert_eq!(one.div_rounded(three, Rounding::Down), raw(3333));
        assert_eq!(one.div_rounded(three, Rounding::Up), raw(3334));
        assert_eq!((-one).div_rounded(three, Rounding::Down), raw(-3334));
        assert_eq!((-one).div_rounded(three, Rounding::Up), raw(-3333));
    }

    #[test]
    fn test_from_str_and_display() {
        assert_eq!(Amount256::from_str("1.0001").unwrap(), raw(10001));
        assert_eq!(Amount256::from_str("-1.0001").unwrap(), raw(-10001));
        assert_eq!(Amount256::from_str("1.00005").unwrap(), raw(10001));
        assert_eq!(Amount256::from_str(""), Err(AmountErrorKind::Empty));
        assert_eq!(Amount256::from_str("x"), Err(AmountErrorKind::InvalidDigit));
        // A 70-digit value round-trips exactly.
        let s = "-1234567890123456789012345678901234567890123456789012345678901234567890.5";
        let v = Amount256::from_str(s).unwrap();
        assert_eq!(v.to_string(), s);
        // Too large.
        let huge = "9".repeat(80);
        assert_eq!(Amount256::from_str(&huge), Err(AmountErrorKind::Overflow));
        // Parses into four limbs (6e76 < 2^256) but exceeds the symmetric
        // 255-bit range bound (2^255 ~ 5.79e76): rejected after the parse.
        let s = "6".to_string() + &"0".repeat(72);
        assert_eq!(Amount256::from_str(&s), Err(AmountErrorKind::Overflow));

        assert_eq!(&format!("{}", raw(10000)), "1");
        assert_eq!(&format!("{:+}", raw(10000)), "+1");
        assert_eq!(&format!("{:4.2}", raw(10000)), "1.00");
        assert_eq!(&format!("{}", raw(1)), "0.0001");
        assert_eq!(&format!("{}", raw(-10001)), "-1.0001");
        assert_eq!(&format!("{}", Amount256::ZERO), "0");
        assert_eq!(&format!("{:.2}", raw(10050)), "1.01");
    }

    #[test]
    fn test_conversions() {
        assert_eq!(Amount256::from(2.5f64), raw(25000));
        assert_eq!(Amount256::from(-2.5f32), raw(-25000));
        assert_eq!(Amount256::from(3i32), raw(30000));
        assert_eq!(
            Amount256::from_f64(f64::MAX),
            Err(AmountErrorKind::Overflow)
        );
        assert_eq!(Amount256::from(f64::MAX), Amount256::MAX);
        assert_eq!(Amount256::from(f64::MIN), Amount256::MIN);

        // Wide but f64-exact value: 2^140.
        let x = 1.393_796_574_908_164e42_f64;
        let v = Amount256::from_f64(x).unwrap();
        assert!((v.to_f64() - x).abs() / x < 1e-15);

        // to_i128 truncation and saturation.
        assert_eq!(Amount256::from_f64(-3.7).unwrap().to_i128(), -3);
        let big = Amount256::from(10i128.pow(36));
        assert_eq!((big * big).to_i128(), i128::MAX);
        assert_eq!((-(big * big)).to_i128(), i128::MIN);

        // i128 conversions are exact over the whole i128 range.
        let v = Amount256::from(i128::MAX);
        assert_eq!(v.to_i128(), i128::MAX);
        assert_eq!(v.to_string(), i128::MAX.to_string());

        // Bytes round trip.
        let v = Amount256::from(-42);
        assert_eq!(Amount256::from_le_bytes(v.to_le_bytes()), v);
    }

    #[test]
    fn test_misc() {
        assert_eq!(Amount256::from(10).signum(), Amount256::ONE);
        assert_eq!(Amount256::from(-10).signum(), Amount256::MINUS_ONE);
        assert_eq!(Amount256::from(0).signum(), Amount256::ZERO);
        assert!(Amount256::from(-10).is_negative());
        assert!(Amount256::from(10).is_positive());
        assert!(!Amount256::ZERO.is_positive());
        assert_eq!(Amount256::from(-3).abs(), Amount256::from(3));
        assert_eq!(Amount256::from(2).recip(), raw(5000));
        assert_eq!(Amount256::from(2).powi(100).to_string(), {
            // 2^100
            "1267650600228229401496703205376"
        });
        assert_eq!(
            Amount256::from(5).clamp(Amount256::ZERO, Amount256::ONE),
            Amount256::ONE
        );
        assert!(Amount256::from(1) == 1i64);
        assert!(Amount256::from(2) > 1i64);
        let v: Amount256 = [1, 2, 3].iter().map(|&x| Amount256::from(x)).sum();
        assert_eq!(v, Amount256::from(6));
        let p: Amount256 = [2, 3, 4].iter().map(|&x| Amount256::from(x)).product();
        assert_eq!(p, Amount256::from(24));
        assert_eq!(Amount256::from(7) * 3i64, Amount256::from(21));
        assert_eq!(Amount256::from(7) * -3i32, Amount256::from(-21));
        assert_eq!(Amount256::from(7) + 3i64, Amount256::from(10));
        assert_eq!(Amount256::from(7) - 3i64, Amount256::from(4));
        assert_eq!(
            Rate256::from_f64(1.12345678).unwrap().to_string(),
            "1.12345678"
        );
    }

    #[test]
    fn test_constructors_and_float_intake() {
        assert_eq!(Amount256::new(), Amount256::ZERO);
        assert_eq!(Amount256::from_f32(0.5f32), Ok(raw(5000)));
        assert_eq!(
            Amount256::from_f32(f32::INFINITY),
            Err(AmountErrorKind::Overflow)
        );
        assert_eq!(Amount256::from_str_const("1.5"), raw(15000));

        // Wide negative f64: |val * 10^4| > 2^127 and negative, so the
        // truncation toward zero overshoots and the floor adjustment
        // (hi -= 1, lo += 2^128) runs. The split is exact for this value,
        // so the result is the exact negation of the positive intake.
        let x = 1.5e42_f64;
        let pos = Amount256::from_f64(x).unwrap();
        let neg = Amount256::from_f64(-x).unwrap();
        assert_eq!(neg, -pos);
        assert!((neg.to_f64() + x).abs() / x < 1e-15);
    }

    #[test]
    fn test_checked_variants() {
        let six = Amount256::from(6);
        let two = Amount256::from(2);
        assert_eq!(six.checked_add(two), Some(Amount256::from(8)));
        assert_eq!(six.checked_sub(two), Some(Amount256::from(4)));
        assert_eq!(six.checked_mul(two), Some(Amount256::from(12)));
        assert_eq!(
            six.checked_mul_rounded(two, Rounding::HalfUp),
            Some(Amount256::from(12))
        );
        assert_eq!(
            Amount256::MAX.checked_mul_rounded(two, Rounding::HalfUp),
            None
        );
        assert_eq!(
            six.checked_div_rounded(two, Rounding::HalfUp),
            Some(Amount256::from(3))
        );
        assert_eq!(
            six.checked_div_rounded(Amount256::ZERO, Rounding::HalfUp),
            None
        );
        // MAX / 0.5 overflows.
        assert_eq!(
            Amount256::MAX.checked_div_rounded(raw(5000), Rounding::HalfUp),
            None
        );
        assert_eq!(six.checked_div_int_rounded(0, Rounding::HalfUp), None);
        assert_eq!(
            six.checked_div_int_rounded(4, Rounding::HalfUp),
            Some(raw(15000))
        );
    }

    #[test]
    fn test_rem_dividend_narrower_than_divisor() {
        // Divisor magnitude spans all four limbs while the dividend fits one:
        // |a| < |b|, so the remainder is the dividend itself.
        let big = Amount256::from(10i128.pow(36));
        let wide = big * big;
        assert_eq!(Amount256::from(7) % wide, Amount256::from(7));
        assert_eq!(Amount256::from(-7) % wide, Amount256::from(-7));
        // Two-limb divisor, one-limb dividend: same branch, shorter widths.
        let mid = Amount256::from(10i128.pow(18));
        assert_eq!(Amount256::from(7) % mid, Amount256::from(7));
    }

    #[test]
    fn test_mul_div_rounded() {
        use crate::Rounding::*;
        let one = Amount256::from(1);
        let two = Amount256::from(2);

        // The product needs limbs beyond i128's muldiv: 10^60 * 10^10 / 10^25
        // has a 10^78 product mantissa and a two-limb divisor (Knuth path).
        let a = Amount256::from(10i128.pow(30)) * Amount256::from(10i128.pow(30));
        let b = Amount256::from(10i128.pow(10));
        let c = Amount256::from(10i128.pow(25));
        assert_eq!(
            a.mul_div_rounded(b, c, HalfUp),
            Amount256::from(10i128.pow(30)) * Amount256::from(10i128.pow(15))
        );

        // Narrow-tier fall-through: two-limb operands whose doubled mantissa
        // needs a third limb overflow the 2-limb core but fit 4 limbs.
        let wide = Amount256::from_str_const("34028236692093846346337460743176821.1455");
        assert_eq!(wide.mul_div_rounded(two, one, HalfUp), wide + wide);

        // Product narrower than the divisor: quotient 0, remainder rounds.
        assert_eq!(one.mul_div_rounded(one, c, Down), Amount256::ZERO);
        assert_eq!(
            one.mul_div_rounded(one, c, Up),
            Amount256::from_str_const("0.0001")
        );

        // Exact tie: 0.0007 * 1 / 2 = 0.00035; quotient mantissa 3 is odd.
        let t = Amount256::from_str_const("0.0007");
        let p3 = Amount256::from_str_const("0.0003");
        let p4 = Amount256::from_str_const("0.0004");
        assert_eq!(t.mul_div_rounded(one, two, HalfUp), p4);
        assert_eq!(t.mul_div_rounded(one, two, HalfEven), p4);
        assert_eq!(t.mul_div_rounded(one, two, HalfDown), p3);
        assert_eq!(t.mul_div_rounded(one, two, Down), p3);
        assert_eq!(t.mul_div_rounded(one, two, Up), p4);
        // Down is directional (floor): a negative -0.00035 floors to -0.0004.
        assert_eq!((-t).mul_div_rounded(one, two, Down), -p4);
        assert_eq!(t.mul_div_rounded(-one, two, Down), -p4);
        assert_eq!((-t).mul_div_rounded(-one, two, Down), p3);
        assert_eq!((-t).mul_div_rounded(one, two, Up), -p3);

        // Checked form: zero divisor and overflow both yield None.
        assert_eq!(
            t.checked_mul_div_rounded(one, Amount256::ZERO, HalfUp),
            None
        );
        assert_eq!(
            Amount256::MAX.checked_mul_div_rounded(two, one, HalfUp),
            None
        );
    }

    #[test]
    fn test_round_dp() {
        use crate::Rounding::*;
        let v = Amount256::from_str_const("12.3456");
        assert_eq!(v.round_dp(2, HalfUp), Amount256::from_str_const("12.35"));
        assert_eq!(v.round_dp(2, Down), Amount256::from_str_const("12.34"));
        assert_eq!(v.round_dp(3, HalfUp), Amount256::from_str_const("12.346"));
        assert_eq!(v.round_dp(4, HalfUp), v);
        assert_eq!(v.round_dp(200, HalfUp), v);
        let w = Amount256::from_str_const("-7.5000");
        for mode in [HalfUp, HalfDown, HalfEven, Down, Up] {
            assert_eq!(v.round_dp(0, mode), v.round_to(mode), "{mode:?}");
            assert_eq!(w.round_dp(0, mode), w.round_to(mode), "{mode:?}");
        }
        assert_eq!(
            Amount256::from_str_const("0.0250").round_dp(2, HalfEven),
            Amount256::from_str_const("0.02")
        );
        assert_eq!(
            Amount256::from_str_const("0.0350").round_dp(2, HalfEven),
            Amount256::from_str_const("0.04")
        );
        let neg = Amount256::from_str_const("-12.3456");
        assert_eq!(neg.round_dp(2, Down), Amount256::from_str_const("-12.35"));
        assert_eq!(neg.round_dp(2, Up), Amount256::from_str_const("-12.34"));
        assert_eq!(Amount256::MAX.checked_round_dp(2, Up), None);
        assert_eq!(Amount256::MIN.checked_round_dp(2, Down), None);
    }

    #[test]
    #[should_panic(expected = "attempt to round with overflow")]
    fn test_round_dp_edge_overflow_panics() {
        let _ = Amount256::MAX.round_dp(2, Rounding::Up);
    }

    #[test]
    fn test_split_evenly() {
        let s = Amount256::from_str_const("100.00").split_evenly(3);
        assert_eq!(s.high, Amount256::from_str_const("33.3334"));
        assert_eq!(s.high_count, 1);
        assert_eq!(s.low, Amount256::from_str_const("33.3333"));
        assert_eq!(s.low_count, 2);
        // Exact split: high == low, high_count == 0.
        let s = Amount256::from_str_const("100.00").split_evenly(4);
        assert_eq!((s.high, s.high_count), (s.low, 0));
        assert_eq!((s.low, s.low_count), (Amount256::from_str_const("25"), 4));
        // Conservation on a value beyond the narrower backings, checked by
        // summing the parts back with exact type arithmetic.
        let big = Amount256::from_str_const("100000000000000000000.07");
        let s = big.split_evenly(9);
        assert_eq!(s.high_count + s.low_count, 9);
        let back = s.high * (s.high_count as i64) + s.low * (s.low_count as i64);
        assert_eq!(back, big, "conservation");
        assert_eq!(s.high - s.low, Amount256::from_bits(I256::from_i128(1)));
        // Negative totals: parts negative, high has the larger magnitude.
        let s = Amount256::from_str_const("-1.0001").split_evenly(2);
        let back = s.high * (s.high_count as i64) + s.low * (s.low_count as i64);
        assert_eq!(back, Amount256::from_str_const("-1.0001"));
        assert!(s.high < s.low);
        assert_eq!(Amount256::from(1).checked_split_evenly(0), None);
    }

    #[test]
    #[should_panic(expected = "attempt to divide by zero")]
    fn test_split_evenly_zero_panics() {
        let _ = Amount256::from(1).split_evenly(0);
    }

    #[test]
    fn test_sqrt() {
        use crate::Rounding::*;
        // Exact squares round-trip; zero is exact.
        let big = Amount256::from(10i128.pow(30));
        assert_eq!((big * big).sqrt(), big);
        assert_eq!(
            Amount256::from_str_const("2.25").sqrt(),
            Amount256::from_str_const("1.5")
        );
        assert_eq!(Amount256::ZERO.sqrt(), Amount256::ZERO);
        // Rounding modes (tie-free: all half modes agree).
        let two = Amount256::from(2);
        assert_eq!(two.sqrt_rounded(Down), Amount256::from_str_const("1.4142"));
        assert_eq!(
            two.sqrt_rounded(HalfEven),
            Amount256::from_str_const("1.4142")
        );
        assert_eq!(two.sqrt_rounded(Up), Amount256::from_str_const("1.4143"));
        // MAX takes the widest (5-limb) Newton path; pinned against an
        // independently computed root.
        assert_eq!(
            Amount256::MAX.sqrt(),
            Amount256::from_str_const("2406159691680045115450337724776250569.2711")
        );
        assert_eq!(
            Amount256::MAX.sqrt_rounded(Up),
            Amount256::from_str_const("2406159691680045115450337724776250569.2712")
        );
        // Negative input.
        assert_eq!(Amount256::from(-1).checked_sqrt(), None);
        assert_eq!(Amount256::from(-1).checked_sqrt_rounded(HalfEven), None);
    }

    #[test]
    #[should_panic(expected = "argument of integer square root cannot be negative")]
    fn test_sqrt_negative_panics() {
        let _ = Amount256::from(-1).sqrt();
    }

    #[test]
    fn test_checked_rem_powi_recip_round_to() {
        use crate::Rounding::*;
        let a = Amount256::from_str_const("7.5");
        let b = Amount256::from(2);
        assert_eq!(a.checked_rem(b), Some(Amount256::from_str_const("1.5")));
        assert_eq!(a.checked_rem(Amount256::ZERO), None);

        assert_eq!(b.checked_powi(10), Some(Amount256::from(1024)));
        assert_eq!(Amount256::MAX.checked_powi(2), None);
        // x^2 fits but x^3 does not: exp = 3 overflows at the final odd-bit
        // multiply, exp = 7 at the in-loop odd-bit multiply.
        let big = Amount256::from(10i128.pow(30));
        assert_eq!(big.checked_powi(3), None);
        assert_eq!(big.checked_powi(7), None);

        assert_eq!(b.checked_recip(), Some(Amount256::from_str_const("0.5")));
        assert_eq!(Amount256::ZERO.checked_recip(), None);
        assert_eq!(
            Amount256::from_str_const("0.0001").checked_recip(),
            Some(Amount256::from(10000))
        );

        assert_eq!(a.checked_round_to(Down), Some(Amount256::from(7)));
        assert_eq!(Amount256::MAX.checked_round_to(Up), None);
    }

    #[test]
    #[should_panic(expected = "attempt to multiply with overflow")]
    fn test_powi_overflow_panics() {
        let _ = Amount256::MAX.powi(2);
    }

    #[test]
    #[should_panic(expected = "attempt to divide by zero")]
    fn test_recip_zero_panics() {
        let _ = Amount256::ZERO.recip();
    }

    #[test]
    #[should_panic(expected = "attempt to divide by zero")]
    fn test_mul_div_rounded_by_zero() {
        let _ = Amount256::from(1).mul_div_rounded(
            Amount256::from(1),
            Amount256::ZERO,
            Rounding::HalfUp,
        );
    }

    #[test]
    #[should_panic(expected = "attempt to divide with overflow")]
    fn test_mul_div_rounded_overflow() {
        let _ = Amount256::MAX.mul_div_rounded(
            Amount256::from(2),
            Amount256::from(1),
            Rounding::HalfUp,
        );
    }

    #[test]
    fn test_misc_branches() {
        // abs of a non-negative value returns self.
        assert_eq!(Amount256::from(3).abs(), Amount256::from(3));
        assert_eq!(Amount256::ZERO.abs(), Amount256::ZERO);
        // to_bits / from_bits round trip.
        let v = Amount256::from(-42);
        assert_eq!(Amount256::from_bits(v.to_bits()), v);
        assert_eq!(Amount256::ONE.to_bits(), I256::from_i128(10000));
        // clamp: below and inside (the above case lives in test_misc).
        let (lo, hi) = (Amount256::ZERO, Amount256::ONE);
        assert_eq!(Amount256::from(-5).clamp(lo, hi), lo);
        assert_eq!(raw(5000).clamp(lo, hi), raw(5000));
        // min / max, both orders.
        let a = Amount256::from(1);
        let b = Amount256::from(2);
        assert_eq!(a.min(b), a);
        assert_eq!(b.min(a), a);
        assert_eq!(a.max(b), b);
        assert_eq!(b.max(a), b);
        // Mixed integer conversions and operators.
        assert_eq!(Amount256::from(3i64), raw(30000));
        assert_eq!(Amount256::from(7) + 3i32, Amount256::from(10));
        assert_eq!(Amount256::from(7) - 3i32, Amount256::from(4));
    }

    #[test]
    fn test_common_macro_surface() {
        // Assign operators.
        let mut v = Amount256::from(10);
        v += Amount256::from(2);
        assert_eq!(v, Amount256::from(12));
        v -= Amount256::from(4);
        assert_eq!(v, Amount256::from(8));
        v *= Amount256::from(3);
        assert_eq!(v, Amount256::from(24));
        v /= Amount256::from(6);
        assert_eq!(v, Amount256::from(4));
        v %= Amount256::from(3);
        assert_eq!(v, Amount256::from(1));

        // From<&str> (panicking string conversion).
        assert_eq!(Amount256::from("1.0001"), raw(10001));
        assert_eq!(Amount256::from("-2"), Amount256::from(-2));

        // Sum / Product over iterators of references.
        let xs = [Amount256::from(1), Amount256::from(2), Amount256::from(3)];
        let s: Amount256 = xs.iter().sum();
        assert_eq!(s, Amount256::from(6));
        let p: Amount256 = xs.iter().product();
        assert_eq!(p, Amount256::from(6));

        // Display with explicit precision: rounding (half away from zero),
        // zero-padding past the scale, and sign pass-through.
        assert_eq!(format!("{:.1}", raw(10500)), "1.1");
        assert_eq!(format!("{:.1}", raw(10450)), "1.0");
        assert_eq!(format!("{:.6}", raw(-10001)), "-1.000100");
        // Precision beyond the 128-byte format buffer falls back to the
        // error marker instead of overrunning.
        assert_eq!(format!("{:.200}", Amount256::ONE), "Amount::ERROR");
    }

    #[test]
    #[should_panic(expected = "attempt to add with overflow")]
    fn test_add_overflow_panics() {
        let _ = Amount256::MAX + raw(1);
    }

    #[test]
    #[should_panic(expected = "attempt to subtract with overflow")]
    fn test_sub_overflow_panics() {
        let _ = Amount256::MIN - raw(2);
    }

    #[test]
    #[should_panic(expected = "attempt to multiply with overflow")]
    fn test_mul_overflow_panics() {
        let _ = Amount256::MAX * Amount256::from(2);
    }

    #[test]
    #[should_panic(expected = "attempt to multiply with overflow")]
    fn test_mul_i64_overflow_panics() {
        let _ = Amount256::MAX * 2i64;
    }

    #[test]
    #[should_panic(expected = "attempt to divide by zero")]
    fn test_div_by_zero_panics() {
        let _ = Amount256::ONE / Amount256::ZERO;
    }

    #[test]
    #[should_panic(expected = "attempt to divide with overflow")]
    fn test_div_overflow_panics() {
        // MAX / 0.5 overflows.
        let _ = Amount256::MAX.div_rounded(raw(5000), Rounding::HalfUp);
    }

    #[test]
    #[should_panic(expected = "attempt to divide by zero")]
    fn test_div_int_by_zero_panics() {
        let _ = Amount256::ONE.div_int_rounded(0, Rounding::HalfUp);
    }

    #[test]
    #[should_panic(expected = "attempt to calculate the remainder with a divisor of zero")]
    fn test_rem_by_zero_panics() {
        let _ = Amount256::ONE % Amount256::ZERO;
    }

    #[test]
    #[should_panic(expected = "attempt to round with overflow")]
    fn test_round_to_overflow_panics() {
        // MAX's mantissa is 2^255 - 1 = ...9967 mod 10^4: rounding up the
        // non-zero fraction overflows the range.
        let _ = Amount256::MAX.round_to(Rounding::Up);
    }

    #[test]
    #[should_panic(expected = "invalid decimal literal")]
    fn test_from_str_const_invalid_panics() {
        let _ = Amount256::from_str_const("not a number");
    }

    #[test]
    fn test_const_eval() {
        const A: Amount256 = Amount256::from_str_const(
            "123456789012345678901234567890123456789012345678901234.5678",
        );
        const B: Amount256 = A.mul_rounded(Amount256::from_str_const("1.0001"), Rounding::HalfUp);
        const C: Amount256 = A.round_to(Rounding::HalfEven);
        const D: Amount256 = A.trunc();
        const E: Amount256 = Amount256::from_str_const("2").powi(100);
        const F: Option<Amount256> = A.checked_mul(A); // overflows -> None
        const G: Option<Amount256> = Amount256::ONE.checked_add(Amount256::ONE);
        const H: Amount256 = Amount256::from_i64(-3).abs();
        const BITS: I256 = Amount256::ONE.to_bits();
        const T: Amount256 = Amount256::from_bits(BITS);

        let a = Amount256::from_str("123456789012345678901234567890123456789012345678901234.5678")
            .unwrap();
        assert_eq!(A, a);
        assert_eq!(
            B,
            a.mul_rounded(Amount256::from_str("1.0001").unwrap(), Rounding::HalfUp)
        );
        assert_eq!(C, a.round_to(Rounding::HalfEven));
        assert_eq!(D, a.trunc());
        assert_eq!(E.to_string(), "1267650600228229401496703205376");
        assert_eq!(F, None);
        assert_eq!(G, Some(Amount256::from(2)));
        assert_eq!(H, Amount256::from(3));
        assert_eq!(T, Amount256::ONE);
    }

    /// Differential test: for values within the i128 range, Decimal256 must
    /// agree with Decimal128 on every operation and rounding mode. Operands
    /// go well past 64 bits so the Knuth division path is exercised.
    #[test]
    fn test_differential_vs_decimal128() {
        use crate::Decimal128;
        use crate::Rounding::*;

        let mut state = 0xDA3E39CB94B95BDBu64;
        let mut next = move || {
            state ^= state >> 12;
            state ^= state << 25;
            state ^= state >> 27;
            state.wrapping_mul(0x2545F4914F6CDD1D)
        };

        for i in 0..20000 {
            // Alternate magnitudes: up to ~2^60 (products stay well inside
            // i128) and small ones, so both division paths are hit.
            let shift = if i % 3 == 0 { 40 } else { 4 };
            let a = ((((next() as u128) << 64) | next() as u128) >> (68 + shift)) as i128
                * if next() & 1 == 0 { 1 } else { -1 };
            let b = ((((next() as u128) << 64) | next() as u128) >> (68 + shift)) as i128
                * if next() & 1 == 0 { 1 } else { -1 };
            let da = Decimal128::<4>(a);
            let db = Decimal128::<4>(b);
            let wa = Decimal256::<4>(I256::from_i128(a));
            let wb = Decimal256::<4>(I256::from_i128(b));
            fn to128<const D: u8>(v: Decimal256<D>) -> i128 {
                let (neg, mag) = v.0.to_sign_mag();
                assert_eq!(mag[2] | mag[3], 0);
                let m = ((mag[0] as u128) | ((mag[1] as u128) << 64)) as i128;
                if neg { -m } else { m }
            }

            assert_eq!((da + db).0, to128(wa + wb));
            assert_eq!((da - db).0, to128(wa - wb));
            assert_eq!((da * db).0, to128(wa * wb), "mul {a} * {b}");
            assert_eq!(format!("{da}"), format!("{wa}"));
            assert_eq!(format!("{da:.2}"), format!("{wa:.2}"));

            // The integer-rounding helpers: ceil/floor/round delegate to
            // round_to per backing; trunc/fract stay hand-rolled.
            assert_eq!(da.ceil().0, to128(wa.ceil()), "ceil {a}");
            assert_eq!(da.floor().0, to128(wa.floor()), "floor {a}");
            assert_eq!(da.round().0, to128(wa.round()), "round {a}");
            assert_eq!(da.trunc().0, to128(wa.trunc()), "trunc {a}");
            assert_eq!(da.fract().0, to128(wa.fract()), "fract {a}");
            let n = 1 + ((a as u32) & 63);
            let (sd, sw) = (da.split_evenly(n), wa.split_evenly(n));
            assert_eq!(sd.high.0, to128(sw.high), "split high {a} / {n}");
            assert_eq!(sd.low.0, to128(sw.low), "split low {a} / {n}");
            assert_eq!(
                (sd.high_count, sd.low_count),
                (sw.high_count, sw.low_count),
                "split counts {a} / {n}"
            );

            // Cross-scale operands (an 8-digit rate) for mul_rounded.
            let rb = Decimal128::<8>(b);
            let wrb = Decimal256::<8>(I256::from_i128(b));
            for mode in [HalfUp, HalfDown, HalfEven, Down, Up] {
                assert_eq!(
                    da.mul_rounded(db, mode).0,
                    to128(wa.mul_rounded(wb, mode)),
                    "mul_rounded {a} * {b}"
                );
                assert_eq!(
                    da.mul_rounded(rb, mode).0,
                    to128(wa.mul_rounded(wrb, mode)),
                    "mul_rounded cross-scale {a} * {b}"
                );
                assert_eq!(
                    da.round_to(mode).0,
                    to128(wa.round_to(mode)),
                    "round_to {a}"
                );
                if b != 0 {
                    assert_eq!(
                        da.div_rounded(db, mode).0,
                        to128(wa.div_rounded(wb, mode)),
                        "div_rounded {a} / {b}"
                    );
                    assert_eq!(
                        da.div_rounded_to::<8>(db, mode).0,
                        to128(wa.div_rounded_to::<8>(wb, mode)),
                        "div_rounded_to::<8> {a} / {b}"
                    );
                    if let Ok(n) = i64::try_from(b) {
                        assert_eq!(
                            da.div_int_rounded(n, mode).0,
                            to128(wa.div_int_rounded(n, mode)),
                            "div_int_rounded {a} / {n}"
                        );
                    }
                    assert_eq!(
                        da.checked_mul_div_rounded(da, db, mode).map(|v| v.0),
                        wa.checked_mul_div_rounded(wa, wb, mode).map(to128),
                        "mul_div ({a} * {a}) / {b}"
                    );
                    assert_eq!(
                        da.abs().sqrt_rounded(mode).0,
                        to128(wa.abs().sqrt_rounded(mode)),
                        "sqrt |{a}|"
                    );
                    for dp in [0u8, 1, 2, 3] {
                        assert_eq!(
                            da.round_dp(dp, mode).0,
                            to128(wa.round_dp(dp, mode)),
                            "round_dp({dp}) {a}"
                        );
                    }
                }
            }
            if b != 0 {
                assert_eq!((da / db).0, to128(wa / wb), "div {a} / {b}");
                assert_eq!((da % db).0, to128(wa % wb), "rem {a} % {b}");
            }
        }
    }
}