decimal-scaled 0.1.0

Generic scaled fixed-point decimal types for deterministic arithmetic. Multiply / divide use a 256-bit widening intermediate with the Moller-Granlund 2011 magic-number divide algorithm (adapted from ConstScaleFpdec, MIT-licensed; see LICENSE-THIRD-PARTY).
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
//! Arithmetic operator overloads for [`I128`].
//!
//! All operators work directly on the raw `i128` storage value.
//! Addition, subtraction, and negation require no rescaling because the
//! scale factor commutes with those operations. Multiplication and division
//! each require one rescaling step to keep the result in `value * 10^SCALE`
//! form; remainder requires none because both operands share the same scale.
//!
//! # Overflow policy
//!
//! Default operator semantics match Rust's `i128` arithmetic: **panics on
//! overflow in debug builds; wraps two's-complement in release builds.**
//! This is the standard Rust integer arithmetic contract. Explicit-overflow
//! variants (`checked_*`, `wrapping_*`, `saturating_*`, `overflowing_*`)
//! are not provided in this module.
//!
//! # Mul / Div algorithm
//!
//! `Mul` / `MulAssign` use a 256-bit widening intermediate followed by a
//! Moller-Granlund 2011 magic-number divide (see the `mg_divide` module).
//! This replaces a naive `(self.0 * rhs.0) / multiplier()` approach that
//! would silently overflow `i128` at operand magnitudes beyond
//! `sqrt(i128::MAX)`. With the widening approach the operand range covers
//! the full `i128` storage range; the only overflow possible is on the
//! final `i128` quotient.
//!
//! `Div` / `DivAssign` widen the numerator `a * 10^SCALE` to 256 bits via
//! the same schoolbook multiply, then divide by `b` using a hand-rolled
//! binary long-divide. MG-style magic does not apply because the divisor is
//! variable rather than a known power of ten.
//!
//! Both paths preserve panic-debug / wrap-release semantics for the final
//! `i128` result. The intermediate 256-bit calculation never observably
//! overflows.

use core::ops::{
    Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign,
};

use crate::core_type::I128;

impl<const SCALE: u32> Add for I128<SCALE> {
    type Output = Self;

    /// Add two values of the same scale.
    ///
    /// Because both operands are in `value * 10^S` form, the raw storage
    /// values can be added directly with no rescaling.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let a = I128s12::from_bits(1_500_000_000_000); // 1.5
    /// let b = I128s12::from_bits(2_500_000_000_000); // 2.5
    /// assert_eq!((a + b).to_bits(), 4_000_000_000_000);
    /// ```
    #[inline]
    fn add(self, rhs: Self) -> Self {
        Self(self.0 + rhs.0)
    }
}

impl<const SCALE: u32> AddAssign for I128<SCALE> {
    /// Add `rhs` to `self` in place.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    #[inline]
    fn add_assign(&mut self, rhs: Self) {
        self.0 += rhs.0;
    }
}

impl<const SCALE: u32> Sub for I128<SCALE> {
    type Output = Self;

    /// Subtract `rhs` from `self`.
    ///
    /// No rescaling needed; raw storage values are subtracted directly.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let a = I128s12::from_bits(3_000_000_000_000); // 3.0
    /// let b = I128s12::from_bits(1_500_000_000_000); // 1.5
    /// assert_eq!((a - b).to_bits(), 1_500_000_000_000);
    /// ```
    #[inline]
    fn sub(self, rhs: Self) -> Self {
        Self(self.0 - rhs.0)
    }
}

impl<const SCALE: u32> SubAssign for I128<SCALE> {
    /// Subtract `rhs` from `self` in place.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    #[inline]
    fn sub_assign(&mut self, rhs: Self) {
        self.0 -= rhs.0;
    }
}

impl<const SCALE: u32> Neg for I128<SCALE> {
    type Output = Self;

    /// Negate the value.
    ///
    /// Negates the raw `i128` storage directly; no rescaling needed.
    ///
    /// # Panics
    ///
    /// Panics in debug builds when `self == I128::MIN` because `i128::MIN`
    /// has no positive counterpart in two's-complement. In release builds
    /// the result wraps to `i128::MIN`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let x = I128s12::from_bits(1_500_000_000_000); // 1.5
    /// assert_eq!((-x).to_bits(), -1_500_000_000_000);
    /// ```
    #[inline]
    fn neg(self) -> Self {
        Self(-self.0)
    }
}

impl<const SCALE: u32> Mul for I128<SCALE> {
    type Output = Self;

    /// Multiply two values, rescaling the result back to `value * 10^S` form.
    ///
    /// The raw product `a.0 * b.0` has units `10^(2S)`, so it must be
    /// divided by `10^S` to restore the canonical scale. This is done via
    /// a 256-bit widening intermediate and a Moller-Granlund magic-number
    /// divide (see the `mg_divide` module), which avoids the intermediate
    /// overflow that would occur with a naive `i128` multiply at large
    /// operand magnitudes.
    ///
    /// # Panics
    ///
    /// Panics in debug builds when the final rescaled quotient overflows
    /// `i128::MAX`. In release builds the result wraps two's-complement.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let a = I128s12::from_bits(1_500_000_000_000); // 1.5
    /// let b = I128s12::from_bits(2_000_000_000_000); // 2.0
    /// assert_eq!((a * b).to_bits(), 3_000_000_000_000); // 3.0
    /// ```
    #[inline]
    fn mul(self, rhs: Self) -> Self {
        match crate::mg_divide::mul_div_pow10::<SCALE>(self.0, rhs.0) {
            Some(q) => Self(q),
            None => Self(panic_or_wrap_mul::<SCALE>(self.0, rhs.0)),
        }
    }
}

impl<const SCALE: u32> MulAssign for I128<SCALE> {
    /// Multiply `self` by `rhs` in place.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    #[inline]
    fn mul_assign(&mut self, rhs: Self) {
        *self = *self * rhs;
    }
}

impl<const SCALE: u32> Div for I128<SCALE> {
    type Output = Self;

    /// Divide `self` by `rhs`, rescaling the numerator to keep the result
    /// in `value * 10^S` form.
    ///
    /// The numerator `self.0` is widened to 256 bits and multiplied by
    /// `10^SCALE` before dividing by `rhs.0`. This avoids the intermediate
    /// overflow that would occur with a naive `(self.0 * 10^S) / rhs.0`
    /// approach at large dividend magnitudes.
    ///
    /// # Panics
    ///
    /// Panics on division by zero (matching `i128 /`). Also panics in debug
    /// builds when the final quotient overflows `i128`; wraps in release
    /// builds.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let a = I128s12::from_bits(3_000_000_000_000); // 3.0
    /// let b = I128s12::from_bits(2_000_000_000_000); // 2.0
    /// assert_eq!((a / b).to_bits(), 1_500_000_000_000); // 1.5
    /// ```
    #[inline]
    fn div(self, rhs: Self) -> Self {
        if rhs.0 == 0 {
            // Match the panic message from `i128 /`.
            panic!("attempt to divide by zero");
        }
        match crate::mg_divide::div_pow10_div::<SCALE>(self.0, rhs.0) {
            Some(q) => Self(q),
            None => Self(panic_or_wrap_div::<SCALE>(self.0, rhs.0)),
        }
    }
}

impl<const SCALE: u32> DivAssign for I128<SCALE> {
    /// Divide `self` by `rhs` in place.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    #[inline]
    fn div_assign(&mut self, rhs: Self) {
        *self = *self / rhs;
    }
}

// Overflow fallback helpers for Mul and Div.
//
// The widening multiply/divide paths return `None` when the final `i128`
// quotient overflows. These helpers reproduce Rust's standard integer
// overflow contract: panic in debug builds, wrap two's-complement in
// release builds. The wrapping form re-derives the result from the
// original operands using `wrapping_*` intrinsics so it matches the naive
// form's behavior at operand magnitudes where the naive form was correct.

/// Emit a debug panic or return the wrapping result for a Mul overflow.
///
/// # Precision
///
/// Strict: all arithmetic is integer-only; result is bit-exact.
#[inline(always)]
#[allow(clippy::arithmetic_side_effects)]
fn panic_or_wrap_mul<const SCALE: u32>(a: i128, b: i128) -> i128 {
    #[cfg(debug_assertions)]
    {
        let _ = (a, b);
        panic!("attempt to multiply with overflow");
    }
    #[cfg(not(debug_assertions))]
    {
        a.wrapping_mul(b).wrapping_div(I128::<SCALE>::multiplier())
    }
}

/// Emit a debug panic or return the wrapping result for a Div overflow.
///
/// # Precision
///
/// Strict: all arithmetic is integer-only; result is bit-exact.
#[inline(always)]
#[allow(clippy::arithmetic_side_effects)]
fn panic_or_wrap_div<const SCALE: u32>(a: i128, b: i128) -> i128 {
    #[cfg(debug_assertions)]
    {
        let _ = (a, b);
        panic!("attempt to divide with overflow");
    }
    #[cfg(not(debug_assertions))]
    {
        a.wrapping_mul(I128::<SCALE>::multiplier()).wrapping_div(b)
    }
}

impl<const SCALE: u32> Rem for I128<SCALE> {
    type Output = Self;

    /// Compute the remainder of dividing `self` by `rhs`, truncated toward
    /// zero.
    ///
    /// Because both operands share the same `SCALE`, the raw remainder
    /// `self.0 % rhs.0` already lives in `value * 10^S` form without any
    /// rescaling. Behavior matches `i128 %`: the result has the same sign
    /// as the dividend.
    ///
    /// # Panics
    ///
    /// Panics on `rhs == ZERO` (division by zero), matching `i128 %`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let a = I128s12::from_bits(5_500_000_000_000); // 5.5
    /// let b = I128s12::from_bits(2_000_000_000_000); // 2.0
    /// assert_eq!((a % b).to_bits(), 1_500_000_000_000); // 1.5
    /// ```
    #[inline]
    fn rem(self, rhs: Self) -> Self {
        Self(self.0 % rhs.0)
    }
}

impl<const SCALE: u32> RemAssign for I128<SCALE> {
    /// Compute the remainder of `self / rhs` and store it in `self`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    #[inline]
    fn rem_assign(&mut self, rhs: Self) {
        self.0 %= rhs.0;
    }
}

// Math methods.
//
// All methods delegate to `i128` stdlib intrinsics where possible.
// Default overflow policy matches Rust integer semantics: panic in debug
// builds, wrap in release builds.
//
// Sign notes:
// - `floor` uses `i128::div_euclid` (rounds the quotient toward negative
//   infinity for a positive divisor; `multiplier()` is always positive).
// - `ceil` is implemented as `-floor(-self)`.
// - `trunc` uses plain truncating `/`, which rounds toward zero — different
//   from `floor` for negative inputs.
// - `round` is half-away-from-zero: add half a unit with the sign of
//   `self`, then truncate.
// - `div_euclid` and `rem_euclid` share the same scale, so no rescaling
//   of the remainder is needed.
// - `div_floor` and `div_ceil` are implemented inline because
//   `i128::div_floor` / `i128::div_ceil` are still gated behind unstable
//   features for signed types as of Rust 1.95.
// - `abs_diff` is implemented as `max - min` so the subtraction is always
//   non-negative.

impl<const SCALE: u32> I128<SCALE> {
    /// Return the absolute value of `self`.
    ///
    /// # Panics
    ///
    /// Panics in debug builds when `self == I128::MIN` because `i128::MIN`
    /// has no positive counterpart in two's-complement. Wraps to `i128::MIN`
    /// in release builds.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let x = I128s12::from_bits(-1_500_000_000_000);
    /// assert_eq!(x.abs().to_bits(), 1_500_000_000_000);
    /// ```
    #[inline]
    pub const fn abs(self) -> Self {
        Self(self.0.abs())
    }

    /// Return the sign of `self` as a scaled `I128`.
    ///
    /// Returns `-ONE` for negative values, `ZERO` for zero, and `+ONE`
    /// for positive values, mirroring `f64::signum` / `i128::signum` lifted
    /// into the `I128` type. Unlike `i128::signum` which returns a bare
    /// `-1`, `0`, or `1`, this method encodes the result as `N * 10^S`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// assert_eq!(I128s12::from_bits(500_000_000_000).signum(), I128s12::ONE);
    /// assert_eq!(I128s12::ZERO.signum(), I128s12::ZERO);
    /// assert_eq!(I128s12::from_bits(-500_000_000_000).signum(), -I128s12::ONE);
    /// ```
    #[inline]
    pub fn signum(self) -> Self {
        match self.0.signum() {
            1 => Self::ONE,
            -1 => Self(-Self::multiplier()),
            _ => Self::ZERO,
        }
    }

    /// Return the largest integer multiple of `ONE` that is less than or
    /// equal to `self` (round toward negative infinity).
    ///
    /// For negative inputs this differs from truncation:
    /// `I128(-0.5).floor()` returns `I128(-1.0)`, not `I128(0.0)`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let x = I128s12::from_bits(2_500_000_000_000); // 2.5
    /// assert_eq!(x.floor().to_bits(), 2_000_000_000_000);
    ///
    /// let y = I128s12::from_bits(-2_500_000_000_000); // -2.5
    /// assert_eq!(y.floor().to_bits(), -3_000_000_000_000);
    /// ```
    #[inline]
    pub fn floor(self) -> Self {
        let m = Self::multiplier();
        Self(self.0.div_euclid(m) * m)
    }

    /// Return the smallest integer multiple of `ONE` that is greater than
    /// or equal to `self` (round toward positive infinity).
    ///
    /// For negative inputs: `I128(-0.5).ceil()` returns `I128(0.0)`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let x = I128s12::from_bits(2_500_000_000_000); // 2.5
    /// assert_eq!(x.ceil().to_bits(), 3_000_000_000_000);
    ///
    /// let y = I128s12::from_bits(-2_500_000_000_000); // -2.5
    /// assert_eq!(y.ceil().to_bits(), -2_000_000_000_000);
    /// ```
    #[inline]
    pub fn ceil(self) -> Self {
        let m = Self::multiplier();
        // Expand ceil as -floor(-self) to avoid the unstable `int_roundings` feature.
        Self(-((-self.0).div_euclid(m)) * m)
    }

    /// Round to the nearest integer using half-away-from-zero.
    ///
    /// Ties (values whose fractional part is exactly 0.5) round away from
    /// zero: `2.5` rounds to `3.0` and `-2.5` rounds to `-3.0`. This
    /// matches `f64::round`. Half-even ("banker's") rounding is not
    /// provided; use `floor` and `fract` to compose it if needed.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// assert_eq!(I128s12::from_bits(2_500_000_000_000).round().to_bits(), 3_000_000_000_000);
    /// assert_eq!(I128s12::from_bits(2_400_000_000_000).round().to_bits(), 2_000_000_000_000);
    /// assert_eq!(I128s12::from_bits(-2_500_000_000_000).round().to_bits(), -3_000_000_000_000);
    /// ```
    #[inline]
    pub fn round(self) -> Self {
        let m = Self::multiplier();
        let half = m / 2;
        let bias = if self.0 >= 0 { half } else { -half };
        // Truncating divide shifts the half-unit bias away from zero.
        Self((self.0 + bias) / m * m)
    }

    /// Drop the fractional part, rounding toward zero.
    ///
    /// For negative inputs this differs from `floor`:
    /// `I128(-2.5).trunc()` returns `I128(-2.0)`, whereas
    /// `I128(-2.5).floor()` returns `I128(-3.0)`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// assert_eq!(I128s12::from_bits(2_500_000_000_000).trunc().to_bits(), 2_000_000_000_000);
    /// assert_eq!(I128s12::from_bits(-2_500_000_000_000).trunc().to_bits(), -2_000_000_000_000);
    /// ```
    #[inline]
    pub fn trunc(self) -> Self {
        let m = Self::multiplier();
        Self(self.0 / m * m)
    }

    /// Return only the fractional part: `self - self.trunc()`.
    ///
    /// The result has the same sign as `self` because `trunc` rounds toward
    /// zero. `I128(2.5).fract()` is `I128(0.5)`; `I128(-2.5).fract()` is
    /// `I128(-0.5)`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// assert_eq!(I128s12::from_bits(2_500_000_000_000).fract().to_bits(), 500_000_000_000);
    /// assert_eq!(I128s12::from_bits(-2_500_000_000_000).fract().to_bits(), -500_000_000_000);
    /// assert_eq!(I128s12::from_bits(2_000_000_000_000).fract().to_bits(), 0);
    /// ```
    #[inline]
    pub fn fract(self) -> Self {
        let m = Self::multiplier();
        Self(self.0 - (self.0 / m * m))
    }

    /// Return the lesser of `self` and `other`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let a = I128s12::from_bits(1_000_000_000_000);
    /// let b = I128s12::from_bits(2_000_000_000_000);
    /// assert_eq!(a.min(b), a);
    /// ```
    #[inline]
    pub fn min(self, other: Self) -> Self {
        Self(self.0.min(other.0))
    }

    /// Return the greater of `self` and `other`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let a = I128s12::from_bits(1_000_000_000_000);
    /// let b = I128s12::from_bits(2_000_000_000_000);
    /// assert_eq!(a.max(b), b);
    /// ```
    #[inline]
    pub fn max(self, other: Self) -> Self {
        Self(self.0.max(other.0))
    }

    /// Restrict `self` to the closed interval `[lo, hi]`.
    ///
    /// Returns `lo` if `self < lo`, `hi` if `self > hi`, and `self`
    /// otherwise.
    ///
    /// # Panics
    ///
    /// Panics if `lo > hi`, matching `Ord::clamp`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let lo = I128s12::from_bits(1_000_000_000_000); // 1.0
    /// let hi = I128s12::from_bits(3_000_000_000_000); // 3.0
    /// let x  = I128s12::from_bits(5_000_000_000_000); // 5.0
    /// assert_eq!(x.clamp(lo, hi), hi);
    /// ```
    #[inline]
    pub fn clamp(self, lo: Self, hi: Self) -> Self {
        Self(self.0.clamp(lo.0, hi.0))
    }

    /// Return the multiplicative inverse: `ONE / self`.
    ///
    /// # Panics
    ///
    /// Panics when `self == ZERO` (division by zero).
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let two  = I128s12::from_bits(2_000_000_000_000);
    /// let half = I128s12::from_bits(500_000_000_000);
    /// assert_eq!(two.recip(), half);
    /// ```
    #[inline]
    pub fn recip(self) -> Self {
        Self::ONE / self
    }

    /// Return a value with the magnitude of `self` and the sign of `sign`.
    ///
    /// When `sign == ZERO` the result is positive because `i128` has no
    /// negative-zero representation.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let pos = I128s12::from_bits(1_500_000_000_000);
    /// let neg = I128s12::from_bits(-2_000_000_000_000);
    /// assert_eq!(pos.copysign(neg).to_bits(), -1_500_000_000_000);
    /// ```
    #[inline]
    pub fn copysign(self, sign: Self) -> Self {
        let mag = self.0.abs();
        if sign.0 < 0 { Self(-mag) } else { Self(mag) }
    }

    /// Euclidean division: returns the quotient as a `I128` integer multiple
    /// of `ONE`, chosen so that the remainder is non-negative.
    ///
    /// Delegates to `i128::div_euclid` on the raw storage values; the
    /// quotient is rescaled by `multiplier()` to produce a value in
    /// `N * 10^S` form.
    ///
    /// # Panics
    ///
    /// Panics on `rhs == ZERO` and on overflow in debug builds (e.g.
    /// `I128::MIN.div_euclid(-ONE)` overflows the quotient, mirroring
    /// `i128::div_euclid`).
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let a = I128s12::from_bits(-5_000_000_000_000); // -5.0
    /// let b = I128s12::from_bits( 2_000_000_000_000); //  2.0
    /// // Euclidean: quotient = -3, remainder = 1 (always non-negative)
    /// assert_eq!(a.div_euclid(b).to_bits(), -3_000_000_000_000);
    /// ```
    #[inline]
    pub fn div_euclid(self, rhs: Self) -> Self {
        Self(self.0.div_euclid(rhs.0) * Self::multiplier())
    }

    /// Euclidean remainder: `self - rhs * self.div_euclid(rhs)`.
    ///
    /// The result is always non-negative when `rhs != ZERO`. Because both
    /// operands share the same scale, `self.0.rem_euclid(rhs.0)` already
    /// lives in `value * 10^S` form without rescaling.
    ///
    /// # Panics
    ///
    /// Panics on `rhs == ZERO`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let a = I128s12::from_bits(-5_000_000_000_000); // -5.0
    /// let b = I128s12::from_bits( 2_000_000_000_000); //  2.0
    /// assert_eq!(a.rem_euclid(b).to_bits(), 1_000_000_000_000); // 1.0, non-negative
    /// ```
    #[inline]
    pub fn rem_euclid(self, rhs: Self) -> Self {
        Self(self.0.rem_euclid(rhs.0))
    }

    /// Floor-rounded division: returns `floor(self / rhs)` as a `I128`
    /// integer multiple of `ONE`.
    ///
    /// Differs from `div_euclid` for negative divisors: `div_floor` is
    /// keyed to the real-number quotient, while `div_euclid` is keyed to
    /// keeping the remainder non-negative regardless of divisor sign.
    ///
    /// Implemented inline because `i128::div_floor` for signed types is
    /// still behind an unstable feature as of Rust 1.95.
    ///
    /// # Panics
    ///
    /// Panics on `rhs == ZERO`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let a = I128s12::from_bits(-5_000_000_000_000); // -5.0
    /// let b = I128s12::from_bits( 2_000_000_000_000); //  2.0
    /// // floor(-2.5) = -3
    /// assert_eq!(a.div_floor(b).to_bits(), -3_000_000_000_000);
    /// ```
    #[inline]
    pub fn div_floor(self, rhs: Self) -> Self {
        let q = self.0 / rhs.0;
        let r = self.0 % rhs.0;
        // Adjust when the truncated quotient rounded the wrong way.
        // XOR of sign bits detects a sign mismatch between remainder and divisor.
        let raw = if r != 0 && (r ^ rhs.0) < 0 { q - 1 } else { q };
        Self(raw * Self::multiplier())
    }

    /// Ceil-rounded division: returns `ceil(self / rhs)` as a `I128`
    /// integer multiple of `ONE`.
    ///
    /// Implemented inline because `i128::div_ceil` for signed types is
    /// still behind an unstable feature as of Rust 1.95.
    ///
    /// # Panics
    ///
    /// Panics on `rhs == ZERO`.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let a = I128s12::from_bits(5_000_000_000_000); // 5.0
    /// let b = I128s12::from_bits(2_000_000_000_000); // 2.0
    /// // ceil(2.5) = 3
    /// assert_eq!(a.div_ceil(b).to_bits(), 3_000_000_000_000);
    /// ```
    #[inline]
    pub fn div_ceil(self, rhs: Self) -> Self {
        let q = self.0 / rhs.0;
        let r = self.0 % rhs.0;
        let raw = if r != 0 && (r ^ rhs.0) >= 0 { q + 1 } else { q };
        Self(raw * Self::multiplier())
    }

    /// Return the absolute difference `|self - rhs|` as a `I128`.
    ///
    /// Computed as `max(self, rhs) - min(self, rhs)` so the subtraction
    /// is always non-negative. Returns a signed `I128` rather than a `u128`
    /// because `I128` uses signed storage. Standard panic-debug /
    /// wrap-release applies if the difference exceeds `i128::MAX` (only
    /// possible at the `MAX - MIN` boundary).
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let a = I128s12::from_bits( 5_000_000_000_000); //  5.0
    /// let b = I128s12::from_bits(-2_000_000_000_000); // -2.0
    /// assert_eq!(a.abs_diff(b).to_bits(), 7_000_000_000_000); // 7.0
    /// ```
    #[inline]
    pub fn abs_diff(self, rhs: Self) -> Self {
        Self(self.0.max(rhs.0) - self.0.min(rhs.0))
    }

    /// Return the midpoint of `self` and `rhs` without intermediate
    /// overflow.
    ///
    /// Delegates to `i128::midpoint` (stable since Rust 1.85). Rounds
    /// toward negative infinity when the exact midpoint is not
    /// representable, matching `i128::midpoint` semantics.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// let a = I128s12::from_bits(1_000_000_000_000); // 1.0
    /// let b = I128s12::from_bits(3_000_000_000_000); // 3.0
    /// assert_eq!(a.midpoint(b).to_bits(), 2_000_000_000_000); // 2.0
    /// ```
    #[inline]
    pub fn midpoint(self, rhs: Self) -> Self {
        Self(self.0.midpoint(rhs.0))
    }

    // Float-shape compatibility predicates.
    //
    // I128 is a deterministic fixed-point type with no NaN, no infinity,
    // and no subnormals. These predicates allow I128 to satisfy generic
    // bounds that expect an f64-shaped interface.

    /// Always returns `false`; `I128` has no NaN representation.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// assert!(!I128s12::ZERO.is_nan());
    /// assert!(!I128s12::MAX.is_nan());
    /// ```
    #[inline]
    pub const fn is_nan(self) -> bool {
        false
    }

    /// Always returns `false`; `I128` has no infinity representation.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// assert!(!I128s12::MAX.is_infinite());
    /// ```
    #[inline]
    pub const fn is_infinite(self) -> bool {
        false
    }

    /// Always returns `true`; every `I128` value is finite.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// assert!(I128s12::MAX.is_finite());
    /// assert!(I128s12::MIN.is_finite());
    /// ```
    #[inline]
    pub const fn is_finite(self) -> bool {
        true
    }

    /// Returns `true` for any non-zero value.
    ///
    /// `I128` has no subnormal representation, so zero is the only value
    /// that is not normal.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// assert!(!I128s12::ZERO.is_normal());
    /// assert!(I128s12::ONE.is_normal());
    /// ```
    #[inline]
    pub const fn is_normal(self) -> bool {
        self.0 != 0
    }

    /// Returns `true` if the value is zero.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// assert!(I128s12::ZERO.is_zero());
    /// assert!(!I128s12::ONE.is_zero());
    /// ```
    #[inline]
    pub const fn is_zero(self) -> bool {
        self.0 == 0
    }

    /// Returns `true` if the value is strictly greater than zero.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// assert!(I128s12::ONE.is_positive());
    /// assert!(!I128s12::ZERO.is_positive());
    /// assert!(!(-I128s12::ONE).is_positive());
    /// ```
    #[inline]
    pub const fn is_positive(self) -> bool {
        self.0 > 0
    }

    /// Returns `true` if the value is strictly less than zero.
    ///
    /// # Precision
    ///
    /// Strict: all arithmetic is integer-only; result is bit-exact.
    ///
    /// # Examples
    ///
    /// ```
    /// use decimal_scaled::I128s12;
    ///
    /// assert!((-I128s12::ONE).is_negative());
    /// assert!(!I128s12::ZERO.is_negative());
    /// assert!(!I128s12::ONE.is_negative());
    /// ```
    #[inline]
    pub const fn is_negative(self) -> bool {
        self.0 < 0
    }
}

#[cfg(test)]
mod tests {
    use crate::core_type::I128s12;

    /// ZERO + ZERO == ZERO.
    #[test]
    fn add_zero_to_zero_is_zero() {
        assert_eq!(I128s12::ZERO + I128s12::ZERO, I128s12::ZERO);
    }

    /// ZERO - ZERO == ZERO.
    #[test]
    fn sub_zero_from_zero_is_zero() {
        assert_eq!(I128s12::ZERO - I128s12::ZERO, I128s12::ZERO);
    }

    /// -ZERO == ZERO.
    #[test]
    fn neg_zero_is_zero() {
        assert_eq!(-I128s12::ZERO, I128s12::ZERO);
    }

    /// AddAssign mutates in place.
    #[test]
    fn add_assign_zero() {
        let mut v = I128s12::ZERO;
        v += I128s12::ZERO;
        assert_eq!(v, I128s12::ZERO);
    }

    /// SubAssign mutates in place.
    #[test]
    fn sub_assign_zero() {
        let mut v = I128s12::ZERO;
        v -= I128s12::ZERO;
        assert_eq!(v, I128s12::ZERO);
    }

    /// Canonical claim: `(a + b) - b == a` for representative values.
    /// At SCALE = 12, `a = 1.5 mm` is bits `1_500_000_000_000`, `b =
    /// 0.25 mm` is bits `250_000_000_000`.
    #[test]
    fn add_sub_round_trip_canonical_claim() {
        let a = I128s12::from_bits(1_500_000_000_000);
        let b = I128s12::from_bits(250_000_000_000);
        assert_eq!((a + b) - b, a);
    }

    /// Round-trip with a negative `a` to exercise sign handling.
    #[test]
    fn add_sub_round_trip_negative() {
        let a = I128s12::from_bits(-7_321_654_987_000);
        let b = I128s12::from_bits(42_000_000_000_000);
        assert_eq!((a + b) - b, a);
    }

    /// `ONE + ONE` is the scaled bit-pattern `2 * 10^12`.
    #[test]
    fn one_plus_one_is_two_in_scaled_bits() {
        let two = I128s12::ONE + I128s12::ONE;
        // 2 * 10^12 = 2_000_000_000_000
        assert_eq!(two.to_bits(), 2_000_000_000_000);
    }

    /// `-ONE + ONE == ZERO` -- additive inverse property.
    #[test]
    fn neg_one_plus_one_is_zero() {
        assert_eq!(-I128s12::ONE + I128s12::ONE, I128s12::ZERO);
    }

    /// Default policy: overflow panics in debug builds. Locks the
    /// debug-vs-release split documented in module docs. The matching
    /// release-build wrap behaviour is delegated to the toolchain's
    /// `i128 +` semantics; testing it here would require a release-
    /// only test gate that's overkill for a base-ops slice.
    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "overflow")]
    fn add_overflow_panics_in_debug() {
        let _ = I128s12::MAX + I128s12::ONE;
    }

    /// Default policy: underflow panics in debug builds.
    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "overflow")]
    fn sub_underflow_panics_in_debug() {
        let _ = I128s12::MIN - I128s12::ONE;
    }

    /// Default policy: `-MIN` panics in debug builds (i128::MIN has
    /// no positive counterpart in two's-complement).
    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "overflow")]
    fn neg_min_panics_in_debug() {
        let _ = -I128s12::MIN;
    }

    /// AddAssign with non-zero values.
    #[test]
    fn add_assign_accumulates() {
        let mut v = I128s12::from_bits(100);
        v += I128s12::from_bits(250);
        assert_eq!(v.to_bits(), 350);
        v += I128s12::from_bits(-50);
        assert_eq!(v.to_bits(), 300);
    }

    /// SubAssign with non-zero values.
    #[test]
    fn sub_assign_accumulates() {
        let mut v = I128s12::from_bits(1000);
        v -= I128s12::from_bits(250);
        assert_eq!(v.to_bits(), 750);
    }

    // ── Mul / Div / Rem ──

    /// `ONE * ONE == ONE` -- multiplicative identity.
    #[test]
    fn mul_one_one_is_one() {
        assert_eq!(I128s12::ONE * I128s12::ONE, I128s12::ONE);
    }

    /// `ONE / ONE == ONE`.
    #[test]
    fn div_one_one_is_one() {
        assert_eq!(I128s12::ONE / I128s12::ONE, I128s12::ONE);
    }

    /// `ZERO % ONE == ZERO`.
    #[test]
    fn rem_zero_one_is_zero() {
        assert_eq!(I128s12::ZERO % I128s12::ONE, I128s12::ZERO);
    }

    /// `ZERO * x == ZERO` for representative non-trivial `x`.
    #[test]
    fn mul_zero_is_zero() {
        let x = I128s12::from_bits(1_500_000_000_000); // 1.5
        assert_eq!(I128s12::ZERO * x, I128s12::ZERO);
        assert_eq!(x * I128s12::ZERO, I128s12::ZERO);
    }

    /// `ONE * x == x` for representative `x` (left and right identity).
    #[test]
    fn mul_one_is_identity() {
        let x = I128s12::from_bits(1_500_000_000_000); // 1.5
        assert_eq!(I128s12::ONE * x, x);
        assert_eq!(x * I128s12::ONE, x);

        let y = I128s12::from_bits(-7_321_654_987_000); // -7.321...
        assert_eq!(I128s12::ONE * y, y);
        assert_eq!(y * I128s12::ONE, y);
    }

    /// `x / ONE == x`.
    #[test]
    fn div_one_is_identity() {
        let x = I128s12::from_bits(1_500_000_000_000);
        assert_eq!(x / I128s12::ONE, x);

        let y = I128s12::from_bits(-7_321_654_987_000);
        assert_eq!(y / I128s12::ONE, y);
    }

    /// `x / x == ONE` for non-zero x.
    #[test]
    fn div_self_is_one() {
        let x = I128s12::from_bits(1_500_000_000_000); // 1.5
        assert_eq!(x / x, I128s12::ONE);

        let y = I128s12::from_bits(-7_321_654_987_000);
        assert_eq!(y / y, I128s12::ONE);

        // ONE / ONE already covered; a smaller value to exercise the
        // promotion path.
        let small = I128s12::from_bits(1); // 1 LSB
        assert_eq!(small / small, I128s12::ONE);
    }

    /// `(x * 7) % x == 0` -- multiple-of property.
    #[test]
    fn rem_multiple_is_zero() {
        let x = I128s12::from_bits(3_500_000_000_000); // 3.5
        let seven = I128s12::ONE + I128s12::ONE + I128s12::ONE + I128s12::ONE
            + I128s12::ONE + I128s12::ONE + I128s12::ONE; // 7
        assert_eq!((x * seven) % x, I128s12::ZERO);
    }

    /// `x % x == ZERO` for non-zero x.
    #[test]
    fn rem_self_is_zero() {
        let x = I128s12::from_bits(1_500_000_000_000);
        assert_eq!(x % x, I128s12::ZERO);

        let y = I128s12::from_bits(-7_321_654_987_000);
        assert_eq!(y % y, I128s12::ZERO);
    }

    /// **Headline claim**: `1.1 + 2.2 == 3.3` exactly. This is the
    /// distinguishing property versus binary floats (`f64`'s
    /// `1.1 + 2.2 == 3.3000000000000003`). Uses known scaled
    /// bit-patterns rather than the (not-yet-shipped) `FromStr`.
    #[test]
    fn one_point_one_plus_two_point_two_equals_three_point_three() {
        let one_point_one = I128s12::from_bits(1_100_000_000_000); // 1.1
        let two_point_two = I128s12::from_bits(2_200_000_000_000); // 2.2
        let three_point_three = I128s12::from_bits(3_300_000_000_000); // 3.3
        assert_eq!(one_point_one + two_point_two, three_point_three);
    }

    /// `(a * b) / b == a` round-trip for representative non-trivial values.
    /// At SCALE = 12, picking moderate operands keeps `a.0 * b.0` well
    /// inside the i128 boundary.
    #[test]
    fn mul_round_trip_canonical_claim() {
        // a = 1.5, b = 2.5 -> a * b = 3.75; (3.75 / 2.5) == 1.5
        let a = I128s12::from_bits(1_500_000_000_000);
        let b = I128s12::from_bits(2_500_000_000_000);
        let product = a * b;
        assert_eq!(product, I128s12::from_bits(3_750_000_000_000));
        assert_eq!(product / b, a);

        // Negative-operand round-trip.
        let c = I128s12::from_bits(-7_321_654_987_000);
        let d = I128s12::from_bits(13_000_000_000); // 0.013
        let cd = c * d;
        assert_eq!(cd / d, c);
    }

    /// In-place MulAssign matches `Mul`.
    #[test]
    fn mul_assign_matches_mul() {
        let a = I128s12::from_bits(1_500_000_000_000);
        let b = I128s12::from_bits(2_500_000_000_000);
        let mut x = a;
        x *= b;
        assert_eq!(x, a * b);
    }

    /// In-place DivAssign matches `Div`.
    #[test]
    fn div_assign_matches_div() {
        let a = I128s12::from_bits(3_750_000_000_000);
        let b = I128s12::from_bits(2_500_000_000_000);
        let mut x = a;
        x /= b;
        assert_eq!(x, a / b);
    }

    /// In-place RemAssign matches `Rem`.
    #[test]
    fn rem_assign_matches_rem() {
        let a = I128s12::from_bits(7_500_000_000_000);
        let b = I128s12::from_bits(2_000_000_000_000); // 2.0
        let mut x = a;
        x %= b;
        assert_eq!(x, a % b);
    }

    /// `Mul` is commutative under canonical equality.
    #[test]
    fn mul_is_commutative() {
        let a = I128s12::from_bits(1_500_000_000_000);
        let b = I128s12::from_bits(2_500_000_000_000);
        assert_eq!(a * b, b * a);
    }

    /// `Mul` rescales correctly: 0.5 * 0.5 == 0.25 (bit-exact).
    #[test]
    fn mul_subunit_rescales_exactly() {
        let half = I128s12::from_bits(500_000_000_000); // 0.5
        let quarter = I128s12::from_bits(250_000_000_000); // 0.25
        assert_eq!(half * half, quarter);
    }

    /// `Div` rescales correctly: 0.5 / 2 == 0.25.
    #[test]
    fn div_rescales_exactly() {
        let half = I128s12::from_bits(500_000_000_000); // 0.5
        let two = I128s12::from_bits(2_000_000_000_000); // 2.0
        let quarter = I128s12::from_bits(250_000_000_000); // 0.25
        assert_eq!(half / two, quarter);
    }

    /// `Rem` matches `i128 %` truncated-toward-zero semantics.
    /// 5.5 % 2.0 == 1.5 (since 5.5 = 2 * 2.0 + 1.5).
    #[test]
    fn rem_truncates_toward_zero() {
        let a = I128s12::from_bits(5_500_000_000_000);
        let b = I128s12::from_bits(2_000_000_000_000);
        let expected = I128s12::from_bits(1_500_000_000_000);
        assert_eq!(a % b, expected);

        // Negative dividend keeps the sign of the dividend (matches i128 %).
        let neg = I128s12::from_bits(-5_500_000_000_000);
        let neg_expected = I128s12::from_bits(-1_500_000_000_000);
        assert_eq!(neg % b, neg_expected);
    }

    /// Default policy: Mul overflow panics in debug. The product
    /// `MAX * 2` overflows the FINAL i128 quotient (256-bit
    /// intermediate doesn't matter -- the result still can't fit).
    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "overflow")]
    fn mul_overflow_panics_in_debug() {
        let two = I128s12::from_bits(2_000_000_000_000);
        let _ = I128s12::MAX * two;
    }

    /// Widening multiply correctness: at operand magnitudes above the
    /// naive form's `sqrt(i128::MAX)` ~= 1.3e19 boundary, the widening
    /// multiply produces the correct result.
    ///
    /// Operands chosen around +/- 5e22. Expected result hand-computed:
    /// `(5e22 * 3e22) / 10^12 = 1.5e33`, which fits comfortably inside
    /// the final i128 range (i128::MAX ~= 1.7e38).
    #[test]
    fn mul_wide_operands_match_widened_form() {
        let a = I128s12::from_bits(50_000_000_000_000_000_000_000);
        let b = I128s12::from_bits(30_000_000_000_000_000_000_000);
        let expected = I128s12::from_bits(1_500_000_000_000_000_000_000_000_000_000_000);
        assert_eq!(a * b, expected);
        // Symmetric.
        assert_eq!(b * a, expected);
    }

    /// Signed round-trip at wide operand magnitudes: `(a * b) / b == a`.
    #[test]
    fn mul_div_wide_round_trip() {
        let a = I128s12::from_bits(50_000_000_000_000_000_000_000);
        let b = I128s12::from_bits(30_000_000_000_000_000_000_000);
        let prod = a * b;
        // Round-trip: prod / b should recover a.
        assert_eq!(prod / b, a);
    }

    /// Sign handling at wide operand magnitudes: mixed and same signs.
    #[test]
    fn mul_wide_negative_signs() {
        let a = I128s12::from_bits(50_000_000_000_000_000_000_000);
        let b = I128s12::from_bits(30_000_000_000_000_000_000_000);
        let neg_a = -a;
        let neg_b = -b;
        let pos_prod = a * b;
        let neg_prod = -pos_prod;
        assert_eq!(neg_a * b, neg_prod);
        assert_eq!(a * neg_b, neg_prod);
        assert_eq!(neg_a * neg_b, pos_prod);
    }

    /// Widening divide correctness at large dividend magnitudes.
    #[test]
    fn div_wide_dividend_correct() {
        // a = 10^22 raw (~10^10 in scaled value at SCALE=12)
        let a = I128s12::from_bits(10_i128.pow(22));
        // b = 2 raw (sub-LSB; effectively divides by 2 * 10^-12)
        let b = I128s12::from_bits(2);
        // Expected: (a.0 * 10^12) / b.0 = (10^34) / 2 = 5e33.
        let expected = I128s12::from_bits(5 * 10_i128.pow(33));
        assert_eq!(a / b, expected);
    }

    /// Widening divide round-trip: forces the numerator widening path
    /// because `a * 10^12` exceeds `i128::MAX`.
    #[test]
    fn div_wide_round_trip_exact() {
        // a = 10^27 raw: a * 10^12 = 10^39 > i128::MAX (1.7e38).
        // Divide by b = 100 raw: q = 10^39 / 100 = 10^37, which fits i128.
        let a = I128s12::from_bits(10_i128.pow(27));
        let b = I128s12::from_bits(100);
        let q = a / b;
        // q = (10^27 * 10^12) / 100 = 10^37 raw.
        let expected = I128s12::from_bits(10_i128.pow(37));
        assert_eq!(q, expected);
    }

    /// Div at SCALE = 0: reduces to plain `i128 /`.
    #[test]
    fn div_scale_zero_matches_i128_div() {
        type D0 = crate::core_type::I128<0>;
        let a = D0::from_bits(15);
        let b = D0::from_bits(4);
        assert_eq!(a / b, D0::from_bits(3));
        assert_eq!((-a) / b, D0::from_bits(-3));
    }

    /// Mul at SCALE = 0: reduces to plain `i128 *`.
    #[test]
    fn mul_scale_zero_matches_i128_mul() {
        type D0 = crate::core_type::I128<0>;
        let a = D0::from_bits(7);
        let b = D0::from_bits(11);
        assert_eq!(a * b, D0::from_bits(77));
        assert_eq!((-a) * b, D0::from_bits(-77));
    }

    /// Default policy: division by zero panics.
    #[test]
    #[should_panic]
    fn div_by_zero_panics() {
        let _ = I128s12::ONE / I128s12::ZERO;
    }

    /// Default policy: remainder with zero divisor panics.
    #[test]
    #[should_panic]
    fn rem_by_zero_panics() {
        let _ = I128s12::ONE % I128s12::ZERO;
    }

    // ── Math methods ──

    // ── abs ──

    /// `abs(0) == 0`.
    #[test]
    fn abs_zero_is_zero() {
        assert_eq!(I128s12::ZERO.abs(), I128s12::ZERO);
    }

    /// `abs(positive) == positive`.
    #[test]
    fn abs_positive_is_self() {
        let x = I128s12::from_bits(1_500_000_000_000); // 1.5
        assert_eq!(x.abs(), x);
    }

    /// `abs(negative) == positive(magnitude)`.
    #[test]
    fn abs_negative_is_positive() {
        let neg = I128s12::from_bits(-1_500_000_000_000);
        let pos = I128s12::from_bits(1_500_000_000_000);
        assert_eq!(neg.abs(), pos);
    }

    /// `abs(MIN)` panics in debug builds (no positive counterpart in
    /// two's-complement). Locks the panic-debug policy.
    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "overflow")]
    fn abs_min_panics_in_debug() {
        let _ = I128s12::MIN.abs();
    }

    // ── signum ──

    /// `signum(0) == ZERO` (no sign for zero).
    #[test]
    fn signum_zero_is_zero() {
        assert_eq!(I128s12::ZERO.signum(), I128s12::ZERO);
    }

    /// `signum(positive) == ONE`.
    #[test]
    fn signum_positive_is_one() {
        let x = I128s12::from_bits(1_500_000_000_000);
        assert_eq!(x.signum(), I128s12::ONE);

        // Smallest positive (1 LSB).
        let tiny = I128s12::from_bits(1);
        assert_eq!(tiny.signum(), I128s12::ONE);
    }

    /// `signum(negative) == -ONE`.
    #[test]
    fn signum_negative_is_neg_one() {
        let x = I128s12::from_bits(-1_500_000_000_000);
        assert_eq!(x.signum(), -I128s12::ONE);

        let tiny_neg = I128s12::from_bits(-1);
        assert_eq!(tiny_neg.signum(), -I128s12::ONE);
    }

    // ── floor ──

    /// `floor(2.5) == 2.0` (positive fractional rounds down).
    #[test]
    fn floor_positive_fractional_rounds_down() {
        let x = I128s12::from_bits(2_500_000_000_000);
        let expected = I128s12::from_bits(2_000_000_000_000);
        assert_eq!(x.floor(), expected);
    }

    /// `floor(-2.5) == -3.0` (negative fractional rounds toward
    /// negative infinity, NOT toward zero -- this is the key sign
    /// distinction from `trunc`).
    #[test]
    fn floor_negative_fractional_rounds_down_toward_neg_inf() {
        let x = I128s12::from_bits(-2_500_000_000_000);
        let expected = I128s12::from_bits(-3_000_000_000_000);
        assert_eq!(x.floor(), expected);

        // Smaller fractional part: -0.5 -> -1.0
        let small_neg = I128s12::from_bits(-500_000_000_000);
        let small_expected = I128s12::from_bits(-1_000_000_000_000);
        assert_eq!(small_neg.floor(), small_expected);
    }

    /// `floor(integer) == integer` (already at an integer boundary).
    #[test]
    fn floor_integer_unchanged() {
        let two = I128s12::from_bits(2_000_000_000_000);
        assert_eq!(two.floor(), two);

        let neg_two = I128s12::from_bits(-2_000_000_000_000);
        assert_eq!(neg_two.floor(), neg_two);

        assert_eq!(I128s12::ZERO.floor(), I128s12::ZERO);
    }

    // ── ceil ──

    /// `ceil(2.5) == 3.0`.
    #[test]
    fn ceil_positive_fractional_rounds_up() {
        let x = I128s12::from_bits(2_500_000_000_000);
        let expected = I128s12::from_bits(3_000_000_000_000);
        assert_eq!(x.ceil(), expected);
    }

    /// `ceil(-2.5) == -2.0`. Sign distinction from `floor`: ceiling
    /// rounds toward positive infinity.
    #[test]
    fn ceil_negative_fractional_rounds_up_toward_pos_inf() {
        let x = I128s12::from_bits(-2_500_000_000_000);
        let expected = I128s12::from_bits(-2_000_000_000_000);
        assert_eq!(x.ceil(), expected);

        // -0.5 -> 0
        let small_neg = I128s12::from_bits(-500_000_000_000);
        assert_eq!(small_neg.ceil(), I128s12::ZERO);
    }

    /// `ceil(integer) == integer`.
    #[test]
    fn ceil_integer_unchanged() {
        let two = I128s12::from_bits(2_000_000_000_000);
        assert_eq!(two.ceil(), two);

        let neg_two = I128s12::from_bits(-2_000_000_000_000);
        assert_eq!(neg_two.ceil(), neg_two);

        assert_eq!(I128s12::ZERO.ceil(), I128s12::ZERO);
    }

    // ── round ──

    /// Half-away-from-zero locked policy. Property test asserting:
    /// - 2.5 -> 3.0  (positive half rounds up)
    /// - 2.4 -> 2.0
    /// - 2.6 -> 3.0
    /// - -2.5 -> -3.0  (negative half rounds away from zero, i.e. down)
    /// - -2.4 -> -2.0
    /// - -2.6 -> -3.0
    #[test]
    fn round_half_away_from_zero() {
        // Positive halves
        let two_point_five = I128s12::from_bits(2_500_000_000_000);
        assert_eq!(two_point_five.round(), I128s12::from_bits(3_000_000_000_000));

        let two_point_four = I128s12::from_bits(2_400_000_000_000);
        assert_eq!(two_point_four.round(), I128s12::from_bits(2_000_000_000_000));

        let two_point_six = I128s12::from_bits(2_600_000_000_000);
        assert_eq!(two_point_six.round(), I128s12::from_bits(3_000_000_000_000));

        // Negative halves -- away from zero == toward neg infinity
        let neg_two_point_five = I128s12::from_bits(-2_500_000_000_000);
        assert_eq!(neg_two_point_five.round(), I128s12::from_bits(-3_000_000_000_000));

        let neg_two_point_four = I128s12::from_bits(-2_400_000_000_000);
        assert_eq!(neg_two_point_four.round(), I128s12::from_bits(-2_000_000_000_000));

        let neg_two_point_six = I128s12::from_bits(-2_600_000_000_000);
        assert_eq!(neg_two_point_six.round(), I128s12::from_bits(-3_000_000_000_000));

        // Zero
        assert_eq!(I128s12::ZERO.round(), I128s12::ZERO);
    }

    // ── trunc / fract ──

    /// `trunc` drops the fractional part (rounds toward zero), unlike
    /// `floor` which rounds toward negative infinity.
    #[test]
    fn trunc_drops_fractional() {
        // Positive
        let x = I128s12::from_bits(2_500_000_000_000);
        assert_eq!(x.trunc(), I128s12::from_bits(2_000_000_000_000));

        // Negative -- key sign distinction: trunc(-2.5) == -2.0
        // (floor(-2.5) would be -3.0)
        let neg = I128s12::from_bits(-2_500_000_000_000);
        assert_eq!(neg.trunc(), I128s12::from_bits(-2_000_000_000_000));

        // Zero
        assert_eq!(I128s12::ZERO.trunc(), I128s12::ZERO);

        // Already-integer values
        let two = I128s12::from_bits(2_000_000_000_000);
        assert_eq!(two.trunc(), two);
    }

    /// `fract` keeps only the fractional part. Sign matches the sign
    /// of `self` (because `trunc` rounds toward zero).
    #[test]
    fn fract_keeps_only_fractional() {
        let x = I128s12::from_bits(2_500_000_000_000);
        assert_eq!(x.fract(), I128s12::from_bits(500_000_000_000));

        // Negative: fract preserves dividend sign
        let neg = I128s12::from_bits(-2_500_000_000_000);
        assert_eq!(neg.fract(), I128s12::from_bits(-500_000_000_000));

        // Integer values have zero fract
        let two = I128s12::from_bits(2_000_000_000_000);
        assert_eq!(two.fract(), I128s12::ZERO);

        assert_eq!(I128s12::ZERO.fract(), I128s12::ZERO);
    }

    /// Identity: `trunc(x) + fract(x) == x` for any `x`.
    #[test]
    fn trunc_plus_fract_equals_self() {
        let cases = [
            I128s12::from_bits(2_500_000_000_000),
            I128s12::from_bits(-2_500_000_000_000),
            I128s12::from_bits(7_321_654_987_000),
            I128s12::from_bits(-7_321_654_987_000),
            I128s12::ZERO,
            I128s12::ONE,
            -I128s12::ONE,
            I128s12::from_bits(1), // sub-LSB fractional
            I128s12::from_bits(-1),
        ];
        for x in cases {
            assert_eq!(x.trunc() + x.fract(), x, "failed for {:?}", x);
        }
    }

    // ── min / max / clamp ──

    /// Basic min/max/clamp on representative values.
    #[test]
    fn min_max_clamp_basic() {
        let a = I128s12::from_bits(1_000_000_000_000); // 1.0
        let b = I128s12::from_bits(2_000_000_000_000); // 2.0
        let c = I128s12::from_bits(3_000_000_000_000); // 3.0

        assert_eq!(a.min(b), a);
        assert_eq!(b.min(a), a);
        assert_eq!(a.max(b), b);
        assert_eq!(b.max(a), b);

        // clamp inside range -- pass through
        assert_eq!(b.clamp(a, c), b);
        // clamp below lo
        assert_eq!(I128s12::ZERO.clamp(a, c), a);
        // clamp above hi
        let four = I128s12::from_bits(4_000_000_000_000);
        assert_eq!(four.clamp(a, c), c);

        // Negative values
        let neg_a = -a;
        let neg_b = -b;
        assert_eq!(neg_a.min(neg_b), neg_b); // -2.0 < -1.0
        assert_eq!(neg_a.max(neg_b), neg_a);
    }

    // ── recip ──

    /// `recip(2.0) == 0.5`, `recip(0.5) == 2.0`.
    #[test]
    fn recip_inverts_known_values() {
        let two = I128s12::from_bits(2_000_000_000_000);
        let half = I128s12::from_bits(500_000_000_000);
        assert_eq!(two.recip(), half);
        assert_eq!(half.recip(), two);

        // recip of ONE is ONE
        assert_eq!(I128s12::ONE.recip(), I128s12::ONE);

        // recip of -ONE is -ONE
        assert_eq!((-I128s12::ONE).recip(), -I128s12::ONE);
    }

    /// `recip(ZERO)` panics (division by zero).
    #[test]
    #[should_panic]
    fn recip_zero_panics() {
        let _ = I128s12::ZERO.recip();
    }

    // ── copysign ──

    /// Magnitude of self, sign of `sign` arg.
    #[test]
    fn copysign_basic() {
        let pos = I128s12::from_bits(1_500_000_000_000);
        let neg = I128s12::from_bits(-1_500_000_000_000);

        // copysign(pos, pos) == pos
        assert_eq!(pos.copysign(pos), pos);
        // copysign(pos, neg) == neg
        assert_eq!(pos.copysign(neg), neg);
        // copysign(neg, pos) == pos
        assert_eq!(neg.copysign(pos), pos);
        // copysign(neg, neg) == neg
        assert_eq!(neg.copysign(neg), neg);
    }

    /// `copysign(x, ZERO)` -- zero is treated as positive (no negative
    /// zero in i128). This locks the v1 policy.
    #[test]
    fn copysign_zero() {
        let neg = I128s12::from_bits(-1_500_000_000_000);
        let pos = I128s12::from_bits(1_500_000_000_000);

        // sign == ZERO -> positive magnitude
        assert_eq!(neg.copysign(I128s12::ZERO), pos);
        assert_eq!(pos.copysign(I128s12::ZERO), pos);

        // self == ZERO -> result == ZERO regardless of sign
        assert_eq!(I128s12::ZERO.copysign(neg), I128s12::ZERO);
        assert_eq!(I128s12::ZERO.copysign(pos), I128s12::ZERO);
    }

    // ── div_euclid / rem_euclid ──

    /// Positive operands match plain integer division.
    /// 5.0 / 2.0 = 2.5; div_euclid -> floor = 2.0; rem_euclid -> 1.0.
    #[test]
    fn div_euclid_positive() {
        let a = I128s12::from_bits(5_000_000_000_000); // 5.0
        let b = I128s12::from_bits(2_000_000_000_000); // 2.0

        let q = a.div_euclid(b);
        assert_eq!(q, I128s12::from_bits(2_000_000_000_000)); // 2

        let r = a.rem_euclid(b);
        assert_eq!(r, I128s12::from_bits(1_000_000_000_000)); // 1

        // Identity: q*b + r == a
        assert_eq!(q * b + r, a);
    }

    /// Negative dividend: -5.0 div_euclid 2.0 -> -3.0 (Euclidean, with
    /// non-negative remainder).
    #[test]
    fn div_euclid_negative_dividend() {
        let a = I128s12::from_bits(-5_000_000_000_000); // -5.0
        let b = I128s12::from_bits(2_000_000_000_000); // 2.0

        let q = a.div_euclid(b);
        // -5 = -3*2 + 1, so quotient = -3, rem = 1
        assert_eq!(q, I128s12::from_bits(-3_000_000_000_000));

        let r = a.rem_euclid(b);
        assert_eq!(r, I128s12::from_bits(1_000_000_000_000));

        // Identity: q*b + r == a
        assert_eq!(q * b + r, a);
    }

    /// Negative divisor: 5.0 div_euclid -2.0 -> -2.0 (Euclidean keeps
    /// remainder non-negative).
    #[test]
    fn div_euclid_negative_divisor() {
        let a = I128s12::from_bits(5_000_000_000_000); // 5.0
        let b = I128s12::from_bits(-2_000_000_000_000); // -2.0

        let q = a.div_euclid(b);
        assert_eq!(q, I128s12::from_bits(-2_000_000_000_000)); // -2

        let r = a.rem_euclid(b);
        assert_eq!(r, I128s12::from_bits(1_000_000_000_000)); // 1 (non-negative!)

        // Identity: q*b + r == a
        assert_eq!(q * b + r, a);
    }

    /// Property: `(a.div_euclid(b)) * b + a.rem_euclid(b) == a` for
    /// representative sign combinations.
    #[test]
    fn rem_euclid_consistency_with_div_euclid() {
        let cases: &[(i128, i128)] = &[
            (5_000_000_000_000, 2_000_000_000_000),
            (-5_000_000_000_000, 2_000_000_000_000),
            (5_000_000_000_000, -2_000_000_000_000),
            (-5_000_000_000_000, -2_000_000_000_000),
            (7_321_654_987_000, 13_000_000_000),
            (-7_321_654_987_000, 13_000_000_000),
        ];
        for (a_bits, b_bits) in cases {
            let a = I128s12::from_bits(*a_bits);
            let b = I128s12::from_bits(*b_bits);
            let q = a.div_euclid(b);
            let r = a.rem_euclid(b);
            assert_eq!(q * b + r, a, "failed for a={}, b={}", a_bits, b_bits);
            // Remainder must be non-negative (Euclidean property)
            assert!(r.0 >= 0, "rem_euclid returned negative for a={}, b={}: {}",
                    a_bits, b_bits, r.0);
        }
    }

    // ── div_floor / div_ceil ──

    /// `div_floor` rounds toward negative infinity. Positive operands
    /// match plain truncating div.
    #[test]
    fn div_floor_basic() {
        // 5.0 / 2.0 -> floor(2.5) = 2.0
        let a = I128s12::from_bits(5_000_000_000_000);
        let b = I128s12::from_bits(2_000_000_000_000);
        assert_eq!(a.div_floor(b), I128s12::from_bits(2_000_000_000_000));

        // -5.0 / 2.0 -> floor(-2.5) = -3.0
        let neg_a = I128s12::from_bits(-5_000_000_000_000);
        assert_eq!(neg_a.div_floor(b), I128s12::from_bits(-3_000_000_000_000));

        // -5.0 / -2.0 -> floor(2.5) = 2.0 (sign distinction from div_euclid)
        let neg_b = I128s12::from_bits(-2_000_000_000_000);
        assert_eq!(neg_a.div_floor(neg_b), I128s12::from_bits(2_000_000_000_000));

        // 5.0 / -2.0 -> floor(-2.5) = -3.0
        // (div_euclid here would be -2 because rem must be >= 0.)
        assert_eq!(a.div_floor(neg_b), I128s12::from_bits(-3_000_000_000_000));
    }

    /// `div_ceil` rounds toward positive infinity.
    #[test]
    fn div_ceil_basic() {
        // 5.0 / 2.0 -> ceil(2.5) = 3.0
        let a = I128s12::from_bits(5_000_000_000_000);
        let b = I128s12::from_bits(2_000_000_000_000);
        assert_eq!(a.div_ceil(b), I128s12::from_bits(3_000_000_000_000));

        // -5.0 / 2.0 -> ceil(-2.5) = -2.0
        let neg_a = I128s12::from_bits(-5_000_000_000_000);
        assert_eq!(neg_a.div_ceil(b), I128s12::from_bits(-2_000_000_000_000));

        // 4.0 / 2.0 -> exact -> 2.0
        let four = I128s12::from_bits(4_000_000_000_000);
        assert_eq!(four.div_ceil(b), I128s12::from_bits(2_000_000_000_000));
    }

    // ── abs_diff ──

    /// `abs_diff` is commutative and non-negative.
    #[test]
    fn abs_diff_commutative() {
        let a = I128s12::from_bits(5_000_000_000_000); // 5.0
        let b = I128s12::from_bits(2_000_000_000_000); // 2.0
        let expected = I128s12::from_bits(3_000_000_000_000); // 3.0

        assert_eq!(a.abs_diff(b), expected);
        assert_eq!(b.abs_diff(a), expected);

        // Negative operands
        let neg_a = -a;
        let neg_b = -b;
        // |(-5) - (-2)| = |-3| = 3
        assert_eq!(neg_a.abs_diff(neg_b), expected);
        assert_eq!(neg_b.abs_diff(neg_a), expected);

        // Mixed sign: |5 - (-2)| = 7
        let seven = I128s12::from_bits(7_000_000_000_000);
        assert_eq!(a.abs_diff(neg_b), seven);
        assert_eq!(neg_b.abs_diff(a), seven);
    }

    /// `abs_diff(x, x) == 0` and `abs_diff(x, 0) == abs(x)`.
    #[test]
    fn abs_diff_zero() {
        let x = I128s12::from_bits(1_500_000_000_000);
        assert_eq!(x.abs_diff(x), I128s12::ZERO);
        assert_eq!(x.abs_diff(I128s12::ZERO), x.abs());

        let neg = -x;
        assert_eq!(neg.abs_diff(I128s12::ZERO), x);
    }

    // ── midpoint ──

    /// Midpoint of two representative values.
    #[test]
    fn midpoint_basic() {
        let a = I128s12::from_bits(1_000_000_000_000); // 1.0
        let b = I128s12::from_bits(3_000_000_000_000); // 3.0
        assert_eq!(a.midpoint(b), I128s12::from_bits(2_000_000_000_000)); // 2.0

        // Negative
        let neg_a = -a;
        let neg_b = -b;
        assert_eq!(neg_a.midpoint(neg_b), I128s12::from_bits(-2_000_000_000_000));

        // Mixed sign: midpoint(-1, 1) == 0
        assert_eq!(neg_a.midpoint(a), I128s12::ZERO);
    }

    /// Midpoint near MAX must not overflow (the whole point of using
    /// `i128::midpoint` over `(a + b) / 2`).
    #[test]
    fn midpoint_no_overflow_at_max() {
        // (MAX + MAX) / 2 == MAX, but a naive (a+b)/2 would overflow.
        // i128::midpoint handles this without intermediate overflow.
        assert_eq!(I128s12::MAX.midpoint(I128s12::MAX), I128s12::MAX);
        assert_eq!(I128s12::MIN.midpoint(I128s12::MIN), I128s12::MIN);
        // midpoint(MIN, MAX) -- delegates to i128::midpoint. The
        // Rust 1.95 stabilised implementation rounds the average
        // toward zero for signed integers (so MIN + MAX = -1 averages
        // to 0, not -1). Just assert it doesn't overflow / panic.
        let mid = I128s12::MIN.midpoint(I128s12::MAX);
        assert!(mid.0 == 0 || mid.0 == -1,
                "midpoint(MIN, MAX) should be 0 or -1, got {}", mid.0);
    }

    // ── Float-shape compat predicates ──

    #[test]
    fn is_nan_always_false() {
        assert!(!I128s12::ZERO.is_nan());
        assert!(!I128s12::ONE.is_nan());
        assert!(!I128s12::MAX.is_nan());
        assert!(!I128s12::MIN.is_nan());
    }

    #[test]
    fn is_infinite_always_false() {
        assert!(!I128s12::ZERO.is_infinite());
        assert!(!I128s12::MAX.is_infinite());
        assert!(!I128s12::MIN.is_infinite());
    }

    #[test]
    fn is_finite_always_true() {
        assert!(I128s12::ZERO.is_finite());
        assert!(I128s12::ONE.is_finite());
        assert!(I128s12::MAX.is_finite());
        assert!(I128s12::MIN.is_finite());
    }

    #[test]
    fn is_normal_zero_is_false() {
        assert!(!I128s12::ZERO.is_normal());
    }

    #[test]
    fn is_normal_nonzero_is_true() {
        assert!(I128s12::ONE.is_normal());
        assert!((-I128s12::ONE).is_normal());
        assert!(I128s12::from_bits(1).is_normal()); // smallest positive
        assert!(I128s12::from_bits(-1).is_normal()); // smallest negative
        assert!(I128s12::MAX.is_normal());
        assert!(I128s12::MIN.is_normal());
    }

    /// is_zero / is_positive / is_negative resolve in the foundation
    /// slice (cheap predicates).
    #[test]
    fn is_zero_predicates() {
        assert!(I128s12::ZERO.is_zero());
        assert!(!I128s12::ZERO.is_positive());
        assert!(!I128s12::ZERO.is_negative());

        assert!(!I128s12::from_bits(1).is_zero());
        assert!(I128s12::from_bits(1).is_positive());
        assert!(!I128s12::from_bits(1).is_negative());

        assert!(!I128s12::from_bits(-1).is_zero());
        assert!(!I128s12::from_bits(-1).is_positive());
        assert!(I128s12::from_bits(-1).is_negative());
    }
}