llvm-native-core 0.1.15

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
//! Bit manipulation and math utility functions.
//!
//! Clean-room implementation based on Hacker's Delight and standard algorithms.
//! Many functions delegate to `std::primitive` methods where available, providing
//! a consistent naming convention matching LLVM's `MathExtras.h`.
//!
//! @llvm_behavior: LLVM's MathExtras.h provides portable bit-twiddling
//!   operations used throughout the compiler. This module provides
//!   equivalent functionality with clean-room implementations.

// ============================================================================
// Bit Counting
// ============================================================================

/// Count the number of leading zero bits in a u32.
/// Returns 32 if `x` is 0.
#[inline]
pub fn count_leading_zeros_u32(x: u32) -> u32 {
    x.leading_zeros()
}

/// Count the number of leading zero bits in a u64.
/// Returns 64 if `x` is 0.
#[inline]
pub fn count_leading_zeros_u64(x: u64) -> u32 {
    x.leading_zeros()
}

/// Count the number of trailing zero bits in a u32.
/// Returns 32 if `x` is 0.
#[inline]
pub fn count_trailing_zeros_u32(x: u32) -> u32 {
    x.trailing_zeros()
}

/// Count the number of trailing zero bits in a u64.
/// Returns 64 if `x` is 0.
#[inline]
pub fn count_trailing_zeros_u64(x: u64) -> u32 {
    x.trailing_zeros()
}

/// Count the number of set bits (population count) in a u32.
#[inline]
pub fn count_population_u32(x: u32) -> u32 {
    x.count_ones()
}

/// Count the number of set bits (population count) in a u64.
#[inline]
pub fn count_population_u64(x: u64) -> u32 {
    x.count_ones()
}

// ============================================================================
// Power of 2
// ============================================================================

/// Returns true if `x` is a power of 2. Returns false for 0.
#[inline]
pub fn is_power_of_2_u32(x: u32) -> bool {
    x != 0 && (x & (x.wrapping_sub(1))) == 0
}

/// Returns true if `x` is a power of 2. Returns false for 0.
#[inline]
pub fn is_power_of_2_u64(x: u64) -> bool {
    x != 0 && (x & (x.wrapping_sub(1))) == 0
}

/// Returns the smallest power of 2 greater than or equal to `x`.
/// If the next power of 2 would overflow, returns 0 (saturating behavior).
#[inline]
pub fn next_power_of_2_u32(x: u32) -> u32 {
    if x == 0 {
        return 1;
    }
    // Use checked next_power_of_two; return 0 on overflow (matching LLVM behavior).
    x.checked_next_power_of_two().unwrap_or(0)
}

/// Returns the smallest power of 2 greater than or equal to `x`.
/// If the next power of 2 would overflow, returns 0 (saturating behavior).
#[inline]
pub fn next_power_of_2_u64(x: u64) -> u64 {
    if x == 0 {
        return 1;
    }
    x.checked_next_power_of_two().unwrap_or(0)
}

/// Returns the floor of log base 2 of `x` (the position of the highest set bit).
/// `x` must be > 0.
#[inline]
pub fn floor_log2_u32(x: u32) -> u32 {
    debug_assert!(x > 0, "floor_log2_u32: argument must be > 0");
    // Safe: checked_sub handles x==0 at debug level; ilog2 on 0 is undefined in LLVM.
    u32::BITS - 1 - x.leading_zeros()
}

/// Returns the floor of log base 2 of `x` (the position of the highest set bit).
/// `x` must be > 0.
#[inline]
pub fn floor_log2_u64(x: u64) -> u32 {
    debug_assert!(x > 0, "floor_log2_u64: argument must be > 0");
    u64::BITS - 1 - x.leading_zeros()
}

/// Returns the ceiling of log base 2 of `x`.
/// `x` must be > 0. Equivalent to floor_log2(x - 1) + 1 for x > 1.
#[inline]
pub fn ceil_log2_u32(x: u32) -> u32 {
    debug_assert!(x > 0, "ceil_log2_u32: argument must be > 0");
    if x == 1 {
        return 0;
    }
    // For x > 1, ceil(log2(x)) = floor(log2(x - 1)) + 1
    floor_log2_u32(x - 1) + 1
}

/// Returns the ceiling of log base 2 of `x`.
/// `x` must be > 0.
#[inline]
pub fn ceil_log2_u64(x: u64) -> u32 {
    debug_assert!(x > 0, "ceil_log2_u64: argument must be > 0");
    if x == 1 {
        return 0;
    }
    floor_log2_u64(x - 1) + 1
}

// ============================================================================
// Alignment
// ============================================================================

/// Align `value` up to the nearest multiple of `align`.
/// `align` must be a power of 2.
///
/// Uses `Into<u64>` for conversion; the result is converted back via
/// `TryFrom<u64>`. For `u32`, `u16`, `u8` inputs this conversion is
/// infallible because alignment cannot exceed the original type's range
/// when `align <= value` (the common case). Panics on overflow.
#[inline]
pub fn align_to<T>(value: T, align: T) -> T
where
    T: Copy + Into<u64> + std::convert::TryFrom<u64>,
{
    let v: u64 = value.into();
    let a: u64 = align.into();
    debug_assert!(
        a > 0 && (a & (a - 1)) == 0,
        "align_to: align must be a power of 2"
    );
    let result = (v + a - 1) & !(a - 1);
    T::try_from(result)
        .unwrap_or_else(|_| panic!("align_to: result {} does not fit in target type", result))
}

/// Align `value` down to the nearest multiple of `align`.
/// `align` must be a power of 2.
#[inline]
pub fn align_down<T>(value: T, align: T) -> T
where
    T: Copy + Into<u64> + std::convert::TryFrom<u64>,
{
    let v: u64 = value.into();
    let a: u64 = align.into();
    debug_assert!(
        a > 0 && (a & (a - 1)) == 0,
        "align_down: align must be a power of 2"
    );
    let result = v & !(a - 1);
    T::try_from(result)
        .unwrap_or_else(|_| panic!("align_down: result {} does not fit in target type", result))
}

/// Returns true if `value` is aligned to `align` boundary.
/// `align` must be a power of 2.
#[inline]
pub fn is_aligned<T>(value: T, align: T) -> bool
where
    T: Copy + Into<u64>,
{
    let v: u64 = value.into();
    let a: u64 = align.into();
    debug_assert!(
        a > 0 && (a & (a - 1)) == 0,
        "is_aligned: align must be a power of 2"
    );
    (v & (a - 1)) == 0
}

// ============================================================================
// Bit Manipulation — Find First/Last Set
// ============================================================================

/// Find the index of the least significant set bit (0-based).
/// Returns -1 if no bits are set (i.e., `x` is 0).
#[inline]
pub fn find_first_set_u32(x: u32) -> i32 {
    if x == 0 {
        -1
    } else {
        x.trailing_zeros() as i32
    }
}

/// Find the index of the least significant set bit (0-based).
/// Returns -1 if no bits are set (i.e., `x` is 0).
#[inline]
pub fn find_first_set_u64(x: u64) -> i32 {
    if x == 0 {
        -1
    } else {
        x.trailing_zeros() as i32
    }
}

/// Find the index of the most significant set bit (0-based).
/// Returns -1 if no bits are set (i.e., `x` is 0).
#[inline]
pub fn find_last_set_u32(x: u32) -> i32 {
    if x == 0 {
        -1
    } else {
        (u32::BITS - 1 - x.leading_zeros()) as i32
    }
}

/// Find the index of the most significant set bit (0-based).
/// Returns -1 if no bits are set (i.e., `x` is 0).
#[inline]
pub fn find_last_set_u64(x: u64) -> i32 {
    if x == 0 {
        -1
    } else {
        (u64::BITS - 1 - x.leading_zeros()) as i32
    }
}

// ============================================================================
// Bit Manipulation — Reverse
// ============================================================================

/// Reverse the order of bits in a u32.
/// Bit 0 becomes bit 31, bit 1 becomes bit 30, etc.
#[inline]
pub fn reverse_bits_u32(x: u32) -> u32 {
    x.reverse_bits()
}

/// Reverse the order of bits in a u64.
/// Bit 0 becomes bit 63, bit 1 becomes bit 62, etc.
#[inline]
pub fn reverse_bits_u64(x: u64) -> u64 {
    x.reverse_bits()
}

// ============================================================================
// Bit Floor / Bit Ceil
// ============================================================================

/// Returns the largest power of 2 less than or equal to `x`.
/// Returns 0 if `x` is 0.
///
/// Clean-room implementation: clear all bits below the highest set bit.
#[inline]
pub fn bit_floor_u32(x: u32) -> u32 {
    if x == 0 {
        return 0;
    }
    // Keep only the highest set bit
    1u32 << floor_log2_u32(x)
}

/// Returns the largest power of 2 less than or equal to `x`.
/// Returns 0 if `x` is 0.
#[inline]
pub fn bit_floor_u64(x: u64) -> u64 {
    if x == 0 {
        return 0;
    }
    1u64 << floor_log2_u64(x)
}

/// Returns the smallest power of 2 greater than or equal to `x`.
/// Returns 1 if `x` is 0. Returns 0 on overflow (e.g., x > 2^31 for u32).
#[inline]
pub fn bit_ceil_u32(x: u32) -> u32 {
    if x <= 1 {
        return 1;
    }
    next_power_of_2_u32(x)
}

/// Returns the smallest power of 2 greater than or equal to `x`.
/// Returns 1 if `x` is 0. Returns 0 on overflow (e.g., x > 2^63 for u64).
#[inline]
pub fn bit_ceil_u64(x: u64) -> u64 {
    if x <= 1 {
        return 1;
    }
    next_power_of_2_u64(x)
}

// ============================================================================
// Mask Operations
// ============================================================================

/// Check if `value` is a contiguous mask of the form `0b00...011...10...00`.
/// Returns `(is_mask, mask_idx, mask_len)` where:
/// - `is_mask`: true if the value is a shifted mask
/// - `mask_idx`: the index of the least significant set bit (trailing zeros)
/// - `mask_len`: the number of set bits in the mask
///
/// Clean-room algorithm: strip trailing zeros, then check that the remaining
/// bits plus one form a power of two (i.e., the remaining bits are all ones).
#[inline]
pub fn is_shifted_mask_32(value: u32) -> (bool, u32, u32) {
    if value == 0 {
        return (false, 0, 0);
    }
    let trailing = value.trailing_zeros();
    let shifted = value >> trailing;
    // shifted should be of the form 0b00...011...1 (all ones in the low bits).
    // shifted + 1 would then be a power of 2.
    if shifted & shifted.wrapping_add(1) == 0 {
        let mask_len = shifted.count_ones();
        (true, trailing, mask_len)
    } else {
        (false, 0, 0)
    }
}

/// Check if `value` is a contiguous mask of the form `0b00...011...10...00`.
/// Returns `(is_mask, mask_idx, mask_len)`.
#[inline]
pub fn is_shifted_mask_64(value: u64) -> (bool, u32, u32) {
    if value == 0 {
        return (false, 0, 0);
    }
    let trailing = value.trailing_zeros();
    let shifted = value >> trailing;
    if shifted & shifted.wrapping_add(1) == 0 {
        let mask_len = shifted.count_ones();
        (true, trailing, mask_len)
    } else {
        (false, 0, 0)
    }
}

/// Return a mask with `n` trailing ones set.
/// For n >= 32, returns `u32::MAX`.
#[inline]
pub fn mask_trailing_ones_u32(n: u32) -> u32 {
    if n >= u32::BITS {
        u32::MAX
    } else {
        (1u32 << n).wrapping_sub(1)
    }
}

/// Return a mask with `n` trailing ones set.
/// For n >= 64, returns `u64::MAX`.
#[inline]
pub fn mask_trailing_ones_u64(n: u32) -> u64 {
    if n >= u64::BITS {
        u64::MAX
    } else {
        (1u64 << n).wrapping_sub(1)
    }
}

/// Return a mask with `n` trailing zeros set (i.e., `!mask_trailing_ones_u32(n)`).
/// For n >= 32, returns 0.
#[inline]
pub fn mask_trailing_zeros_u32(n: u32) -> u32 {
    !mask_trailing_ones_u32(n)
}

/// Return a mask with `n` trailing zeros set (i.e., `!mask_trailing_ones_u64(n)`).
/// For n >= 64, returns 0.
#[inline]
pub fn mask_trailing_zeros_u64(n: u32) -> u64 {
    !mask_trailing_ones_u64(n)
}

// ============================================================================
// Integer Min / Max
// ============================================================================

/// Returns the minimum of `a` and `b` (unsigned comparison via Ord).
#[inline]
pub fn umin<T: Ord>(a: T, b: T) -> T {
    std::cmp::min(a, b)
}

/// Returns the maximum of `a` and `b` (unsigned comparison via Ord).
#[inline]
pub fn umax<T: Ord>(a: T, b: T) -> T {
    std::cmp::max(a, b)
}

// ============================================================================
// Saturation Arithmetic
// ============================================================================

/// Saturating unsigned addition: returns `u32::MAX` on overflow.
#[inline]
pub fn saturating_add_u32(a: u32, b: u32) -> u32 {
    a.saturating_add(b)
}

/// Saturating unsigned subtraction: returns 0 on underflow.
#[inline]
pub fn saturating_sub_u32(a: u32, b: u32) -> u32 {
    a.saturating_sub(b)
}

/// Saturating unsigned addition: returns `u64::MAX` on overflow.
#[inline]
pub fn saturating_add_u64(a: u64, b: u64) -> u64 {
    a.saturating_add(b)
}

/// Saturating unsigned subtraction: returns 0 on underflow.
#[inline]
pub fn saturating_sub_u64(a: u64, b: u64) -> u64 {
    a.saturating_sub(b)
}

// ============================================================================
// Division Helpers
// ============================================================================

/// Divide `numerator` by `denominator` and round to nearest (ties round up).
/// Panics if `denominator` is 0.
#[inline]
pub fn divide_nearest_u32(numerator: u32, denominator: u32) -> u32 {
    assert!(denominator != 0, "divide_nearest_u32: division by zero");
    (numerator + denominator / 2) / denominator
}

/// Divide `numerator` by `denominator` and round to nearest (ties round up).
/// Panics if `denominator` is 0.
#[inline]
pub fn divide_nearest_u64(numerator: u64, denominator: u64) -> u64 {
    assert!(denominator != 0, "divide_nearest_u64: division by zero");
    (numerator + denominator / 2) / denominator
}

/// Divide `numerator` by `denominator` and round up.
/// Panics if `denominator` is 0.
#[inline]
pub fn divide_ceil_u32(numerator: u32, denominator: u32) -> u32 {
    assert!(denominator != 0, "divide_ceil_u32: division by zero");
    (numerator + denominator - 1) / denominator
}

/// Divide `numerator` by `denominator` and round up.
/// Panics if `denominator` is 0.
#[inline]
pub fn divide_ceil_u64(numerator: u64, denominator: u64) -> u64 {
    assert!(denominator != 0, "divide_ceil_u64: division by zero");
    (numerator + denominator - 1) / denominator
}

// ============================================================================
// Rotate
// ============================================================================

/// Rotate `x` left by `r` bits.
#[inline]
pub fn rotl_u32(x: u32, r: u32) -> u32 {
    x.rotate_left(r)
}

/// Rotate `x` right by `r` bits.
#[inline]
pub fn rotr_u32(x: u32, r: u32) -> u32 {
    x.rotate_right(r)
}

/// Rotate `x` left by `r` bits.
#[inline]
pub fn rotl_u64(x: u64, r: u32) -> u64 {
    x.rotate_left(r)
}

/// Rotate `x` right by `r` bits.
#[inline]
pub fn rotr_u64(x: u64, r: u32) -> u64 {
    x.rotate_right(r)
}

// ============================================================================
// Byte Swap
// ============================================================================

/// Reverse the byte order of a u16.
#[inline]
pub fn byte_swap_16(x: u16) -> u16 {
    x.swap_bytes()
}

/// Reverse the byte order of a u32.
#[inline]
pub fn byte_swap_32(x: u32) -> u32 {
    x.swap_bytes()
}

/// Reverse the byte order of a u64.
#[inline]
pub fn byte_swap_64(x: u64) -> u64 {
    x.swap_bytes()
}

// ============================================================================
// Hi/Lo Parts of Multiplication
// ============================================================================

/// Return the high 32 bits of the 64-bit product `a * b`.
#[inline]
pub fn mul_hi_u32(a: u32, b: u32) -> u32 {
    ((a as u64).wrapping_mul(b as u64) >> 32) as u32
}

/// Return the low 32 bits of the product `a * b` (same as `a.wrapping_mul(b)`).
#[inline]
pub fn mul_lo_u32(a: u32, b: u32) -> u32 {
    a.wrapping_mul(b)
}

/// Return the high 64 bits of the 128-bit product `a * b`.
#[inline]
pub fn mul_hi_u64(a: u64, b: u64) -> u64 {
    ((a as u128).wrapping_mul(b as u128) >> 64) as u64
}

/// Return the low 64 bits of the product `a * b` (same as `a.wrapping_mul(b)`).
#[inline]
pub fn mul_lo_u64(a: u64, b: u64) -> u64 {
    a.wrapping_mul(b)
}

// ============================================================================
// Arithmetic with Overflow Detection
// ============================================================================

/// Add `a` and `b`, returning the result and an overflow flag.
/// The result wraps on overflow.
#[inline]
pub fn add_overflow_u32(a: u32, b: u32) -> (u32, bool) {
    a.overflowing_add(b)
}

/// Add `a` and `b`, returning the result and an overflow flag.
/// The result wraps on overflow.
#[inline]
pub fn add_overflow_u64(a: u64, b: u64) -> (u64, bool) {
    a.overflowing_add(b)
}

/// Subtract `b` from `a`, returning the result and an overflow flag.
/// The result wraps on underflow.
#[inline]
pub fn sub_overflow_u32(a: u32, b: u32) -> (u32, bool) {
    a.overflowing_sub(b)
}

/// Subtract `b` from `a`, returning the result and an overflow flag.
/// The result wraps on underflow.
#[inline]
pub fn sub_overflow_u64(a: u64, b: u64) -> (u64, bool) {
    a.overflowing_sub(b)
}

/// Multiply `a` and `b`, returning the result and an overflow flag.
/// The result wraps on overflow.
#[inline]
pub fn mul_overflow_u32(a: u32, b: u32) -> (u32, bool) {
    a.overflowing_mul(b)
}

/// Multiply `a` and `b`, returning the result and an overflow flag.
/// The result wraps on overflow.
#[inline]
pub fn mul_overflow_u64(a: u64, b: u64) -> (u64, bool) {
    a.overflowing_mul(b)
}

/// Determine if a 32-bit value has exactly one bit set.
#[inline]
pub fn is_power_of_2_32(v: u32) -> bool {
    v != 0 && (v & (v - 1)) == 0
}

/// Determine if a 64-bit value has exactly one bit set.
#[inline]
pub fn is_power_of_2_64(v: u64) -> bool {
    v != 0 && (v & (v - 1)) == 0
}

/// Find the next power of 2 for a 32-bit value.
/// Returns v if v is already a power of 2; panics on overflow.
#[inline]
pub fn next_power_of_2_32(v: u32) -> u32 {
    if v == 0 {
        return 1;
    }
    let mut p = 1u32;
    while p < v {
        p = p.wrapping_mul(2);
    }
    p
}

/// Find the next power of 2 for a 64-bit value.
#[inline]
pub fn next_power_of_2_64(v: u64) -> u64 {
    if v == 0 {
        return 1;
    }
    let mut p = 1u64;
    while p < v {
        p = p.wrapping_mul(2);
    }
    p
}

/// Align a value up to the nearest multiple of alignment.
/// Alignment must be a power of 2.
#[inline]
pub fn align_to_u32(v: u32, alignment: u32) -> u32 {
    debug_assert!(is_power_of_2_32(alignment));
    (v + alignment - 1) & !(alignment - 1)
}

/// Align a value up to the nearest multiple of alignment (64-bit).
#[inline]
pub fn align_to_u64(v: u64, alignment: u64) -> u64 {
    debug_assert!(is_power_of_2_64(alignment));
    (v + alignment - 1) & !(alignment - 1)
}

/// Align a value down to the nearest multiple of alignment.
#[inline]
pub fn align_down_u32(v: u32, alignment: u32) -> u32 {
    debug_assert!(is_power_of_2_32(alignment));
    v & !(alignment - 1)
}

/// Align a value down to the nearest multiple of alignment (64-bit).
#[inline]
pub fn align_down_u64(v: u64, alignment: u64) -> u64 {
    debug_assert!(is_power_of_2_64(alignment));
    v & !(alignment - 1)
}

/// Count leading zeros (32-bit). Wraps the built-in.
#[inline]
pub fn clz_u32(v: u32) -> u32 {
    if v == 0 {
        32
    } else {
        v.leading_zeros()
    }
}

/// Count leading zeros (64-bit).
#[inline]
pub fn clz_u64(v: u64) -> u32 {
    if v == 0 {
        64
    } else {
        v.leading_zeros()
    }
}

/// Count trailing zeros (32-bit).
#[inline]
pub fn ctz_u32(v: u32) -> u32 {
    if v == 0 {
        32
    } else {
        v.trailing_zeros()
    }
}

/// Count trailing zeros (64-bit).
#[inline]
pub fn ctz_u64(v: u64) -> u32 {
    if v == 0 {
        64
    } else {
        v.trailing_zeros()
    }
}

/// Count population (number of 1 bits) for 32-bit.
#[inline]
pub fn popcount_u32(v: u32) -> u32 {
    v.count_ones()
}

/// Count population for 64-bit.
#[inline]
pub fn popcount_u64(v: u64) -> u32 {
    v.count_ones()
}

/// Get the maximum signed value for N bits.
#[inline]
pub fn max_int_n(bits: u32) -> i64 {
    if bits == 0 {
        return 0;
    }
    if bits >= 64 {
        return i64::MAX;
    }
    (1i64 << (bits - 1)) - 1
}

/// Get the minimum signed value for N bits.
#[inline]
pub fn min_int_n(bits: u32) -> i64 {
    if bits == 0 {
        return 0;
    }
    if bits >= 64 {
        return i64::MIN;
    }
    -(1i64 << (bits - 1))
}

/// Check if a signed integer fits in N bits.
#[inline]
pub fn is_int_n(v: i64, bits: u32) -> bool {
    if bits >= 64 {
        return true;
    }
    let min = min_int_n(bits);
    let max = max_int_n(bits);
    v >= min && v <= max
}

/// Check if an unsigned integer fits in N bits.
#[inline]
pub fn is_uint_n(v: u64, bits: u32) -> bool {
    if bits >= 64 {
        return true;
    }
    v < (1u64 << bits)
}

/// Create a mask with `count` leading ones.
#[inline]
pub fn mask_leading_ones_u32(count: u32) -> u32 {
    if count == 0 {
        return 0;
    }
    mask_trailing_ones_u32(count).rotate_left(32 - count)
}

/// Create a mask with `count` leading ones (64-bit).
#[inline]
pub fn mask_leading_ones_u64(count: u32) -> u64 {
    if count == 0 {
        return 0;
    }
    mask_trailing_ones_u64(count).rotate_left(64 - count)
}

/// Rotate left (32-bit).
#[inline]
pub fn rotl_32(v: u32, count: u32) -> u32 {
    v.rotate_left(count % 32)
}

/// Rotate right (32-bit).
#[inline]
pub fn rotr_32(v: u32, count: u32) -> u32 {
    v.rotate_right(count % 32)
}

/// Rotate left (64-bit).
#[inline]
pub fn rotl_64(v: u64, count: u32) -> u64 {
    v.rotate_left(count as u32 % 64)
}

/// Rotate right (64-bit).
#[inline]
pub fn rotr_64(v: u64, count: u32) -> u64 {
    v.rotate_right(count as u32 % 64)
}

/// Sign-extend a value from `from_bits` to `to_bits`.
#[inline]
pub fn sign_extend(val: u64, from_bits: u32) -> i64 {
    let shift = 64 - from_bits;
    ((val << shift) as i64) >> shift
}

/// Zero-extend a value from `from_bits` to 64 bits.
#[inline]
pub fn zero_extend(val: u64, from_bits: u32) -> u64 {
    if from_bits >= 64 {
        return val;
    }
    val & ((1u64 << from_bits) - 1)
}

/// Get the low half of a wider value (e.g., low 32 bits of 64-bit).
#[inline]
pub fn lo_half(val: u64) -> u32 {
    val as u32
}

/// Get the high half of a wider value.
#[inline]
pub fn hi_half(val: u64) -> u32 {
    (val >> 32) as u32
}

/// Combine two 32-bit values into a 64-bit value.
#[inline]
pub fn make_u64(hi: u32, lo: u32) -> u64 {
    ((hi as u64) << 32) | (lo as u64)
}

/// Extract a range of bits from a value.
#[inline]
pub fn extract_bits_u32(val: u32, msb: u32, lsb: u32) -> u32 {
    debug_assert!(msb >= lsb);
    let width = msb - lsb + 1;
    if width >= 32 {
        return val >> lsb;
    }
    (val >> lsb) & ((1u32 << width) - 1)
}

/// Extract a range of bits from a 64-bit value.
#[inline]
pub fn extract_bits_u64(val: u64, msb: u32, lsb: u32) -> u64 {
    debug_assert!(msb >= lsb);
    let width = msb - lsb + 1;
    if width >= 64 {
        return val >> lsb;
    }
    (val >> lsb) & ((1u64 << width) - 1)
}

/// Check if a 32-bit value is a power-of-2 minus 1 (all ones mask).
#[inline]
pub fn is_mask_32(val: u32) -> bool {
    val != 0 && (val & (val + 1)) == 0
}

/// Check if a 64-bit value is a power-of-2 minus 1.
#[inline]
pub fn is_mask_64(val: u64) -> bool {
    val != 0 && (val & (val + 1)) == 0
}

/// Get the bit at position `pos` (0-indexed).
#[inline]
pub fn get_bit_u32(val: u32, pos: u32) -> bool {
    debug_assert!(pos < 32);
    (val >> pos) & 1 != 0
}

/// Get the bit at position `pos` (0-indexed) for 64-bit.
#[inline]
pub fn get_bit_u64(val: u64, pos: u32) -> bool {
    debug_assert!(pos < 64);
    (val >> pos) & 1 != 0
}

/// Set a bit at position `pos`.
#[inline]
pub fn set_bit_u32(val: u32, pos: u32) -> u32 {
    val | (1u32 << pos)
}

/// Set a bit at position `pos` for 64-bit.
#[inline]
pub fn set_bit_u64(val: u64, pos: u32) -> u64 {
    val | (1u64 << pos)
}

/// Clear a bit at position `pos`.
#[inline]
pub fn clear_bit_u32(val: u32, pos: u32) -> u32 {
    val & !(1u32 << pos)
}

/// Clear a bit at position `pos` for 64-bit.
#[inline]
pub fn clear_bit_u64(val: u64, pos: u32) -> u64 {
    val & !(1u64 << pos)
}

/// Flip a bit at position `pos`.
#[inline]
pub fn flip_bit_u32(val: u32, pos: u32) -> u32 {
    val ^ (1u32 << pos)
}

/// Flip a bit at position `pos` for 64-bit.
#[inline]
pub fn flip_bit_u64(val: u64, pos: u32) -> u64 {
    val ^ (1u64 << pos)
}

/// Absolute difference between two unsigned values.
#[inline]
pub fn abs_diff_u32(a: u32, b: u32) -> u32 {
    if a > b {
        a - b
    } else {
        b - a
    }
}

/// Absolute difference between two unsigned 64-bit values.
#[inline]
pub fn abs_diff_u64(a: u64, b: u64) -> u64 {
    if a > b {
        a - b
    } else {
        b - a
    }
}

/// Get the min of two values.
#[inline]
pub fn min_u32(a: u32, b: u32) -> u32 {
    if a < b {
        a
    } else {
        b
    }
}

/// Get the max of two values.
#[inline]
pub fn max_u32(a: u32, b: u32) -> u32 {
    if a > b {
        a
    } else {
        b
    }
}

/// Get the min of two 64-bit values.
#[inline]
pub fn min_u64(a: u64, b: u64) -> u64 {
    if a < b {
        a
    } else {
        b
    }
}

/// Get the max of two 64-bit values.
#[inline]
pub fn max_u64(a: u64, b: u64) -> u64 {
    if a > b {
        a
    } else {
        b
    }
}

/// Compute (a * b) >> shift with full-precision intermediate.
#[inline]
pub fn mul_u32_hi(a: u32, b: u32, shift: u32) -> u32 {
    let product = (a as u64) * (b as u64);
    (product >> shift) as u32
}

/// Compute (a * b) >> shift with full-precision intermediate (64-bit).
#[inline]
pub fn mul_u64_hi(a: u64, b: u64, shift: u32) -> u64 {
    let product = (a as u128) * (b as u128);
    (product >> shift) as u64
}

/// Compute avg = (a + b) / 2 without overflow.
#[inline]
pub fn avg_floor_u32(a: u32, b: u32) -> u32 {
    (a & b) + ((a ^ b) >> 1)
}

/// Compute avg = (a + b) / 2 without overflow (64-bit).
#[inline]
pub fn avg_floor_u64(a: u64, b: u64) -> u64 {
    (a & b) + ((a ^ b) >> 1)
}

/// Compute ceil(a / b) without floating point.
#[inline]
pub fn ceil_div_u32(a: u32, b: u32) -> u32 {
    (a + b - 1) / b
}

/// Compute ceil(a / b) without floating point (64-bit).
#[inline]
pub fn ceil_div_u64(a: u64, b: u64) -> u64 {
    (a + b - 1) / b
}

/// Compute a % b where b is a power of 2.
#[inline]
pub fn mod_pow2_u32(a: u32, b: u32) -> u32 {
    debug_assert!(is_power_of_2_32(b));
    a & (b - 1)
}

/// Compute a % b where b is a power of 2 (64-bit).
#[inline]
pub fn mod_pow2_u64(a: u64, b: u64) -> u64 {
    debug_assert!(is_power_of_2_64(b));
    a & (b - 1)
}

/// Byte swap a 16-bit value.
#[inline]
pub fn byteswap_16(v: u16) -> u16 {
    ((v & 0xFF) << 8) | ((v >> 8) & 0xFF)
}

/// Byte swap a 32-bit value.
#[inline]
pub fn byteswap_32(v: u32) -> u32 {
    ((v & 0xFF) << 24) | ((v & 0xFF00) << 8) | ((v >> 8) & 0xFF00) | ((v >> 24) & 0xFF)
}

/// Byte swap a 64-bit value.
#[inline]
pub fn byteswap_64(v: u64) -> u64 {
    ((v & 0xFF) << 56)
        | ((v & 0xFF00) << 40)
        | ((v & 0xFF_0000) << 24)
        | ((v & 0xFF_0000_00) << 8)
        | ((v >> 8) & 0xFF_0000_00)
        | ((v >> 24) & 0xFF_0000)
        | ((v >> 40) & 0xFF00)
        | ((v >> 56) & 0xFF)
}

/// Interleave the low 16 bits of two 32-bit values.
#[inline]
pub fn interleave_16(a: u32, b: u32) -> u32 {
    let mut result = 0u32;
    for i in 0..16 {
        result |= ((a >> i) & 1) << (2 * i);
        result |= ((b >> i) & 1) << (2 * i + 1);
    }
    result
}

/// Check if all bits in a range are zero.
#[inline]
pub fn bits_all_zero_u32(val: u32, msb: u32, lsb: u32) -> bool {
    extract_bits_u32(val, msb, lsb) == 0
}

/// Check if all bits in a range are zero (64-bit).
#[inline]
pub fn bits_all_zero_u64(val: u64, msb: u32, lsb: u32) -> bool {
    extract_bits_u64(val, msb, lsb) == 0
}

/// Gray code encode.
#[inline]
pub fn gray_encode_u32(val: u32) -> u32 {
    val ^ (val >> 1)
}

/// Gray code decode.
#[inline]
pub fn gray_decode_u32(mut val: u32) -> u32 {
    let mut mask = val >> 1;
    while mask != 0 {
        val ^= mask;
        mask >>= 1;
    }
    val
}

/// Compute the absolute value of a signed 32-bit integer.
#[inline]
pub fn abs_i32(v: i32) -> i32 {
    v.abs()
}

/// Compute the absolute value of a signed 64-bit integer.
#[inline]
pub fn abs_i64(v: i64) -> i64 {
    v.abs()
}

/// Clamp a value to the given range [min, max].
#[inline]
pub fn clamp_u32(val: u32, min: u32, max: u32) -> u32 {
    if val < min {
        min
    } else if val > max {
        max
    } else {
        val
    }
}

/// Clamp a value to the given range (64-bit).
#[inline]
pub fn clamp_u64(val: u64, min: u64, max: u64) -> u64 {
    if val < min {
        min
    } else if val > max {
        max
    } else {
        val
    }
}

/// Compute log2 of a power-of-2 value.
#[inline]
pub fn log2_u32(v: u32) -> u32 {
    debug_assert!(is_power_of_2_32(v));
    31 - v.leading_zeros()
}

#[inline]
pub fn log2_u64(v: u64) -> u32 {
    debug_assert!(is_power_of_2_64(v));
    63 - v.leading_zeros()
}

#[inline]
pub fn gcd_u32(mut a: u32, mut b: u32) -> u32 {
    while b != 0 {
        let t = b;
        b = a % b;
        a = t;
    }
    a
}

#[inline]
pub fn gcd_u64(mut a: u64, mut b: u64) -> u64 {
    while b != 0 {
        let t = b;
        b = a % b;
        a = t;
    }
    a
}

#[inline]
pub fn lcm_u32(a: u32, b: u32) -> u32 {
    if a == 0 || b == 0 {
        return 0;
    }
    a / gcd_u32(a, b) * b
}

#[inline]
pub fn lcm_u64(a: u64, b: u64) -> u64 {
    if a == 0 || b == 0 {
        return 0;
    }
    a / gcd_u64(a, b) * b
}

#[inline]
pub fn in_range_u32(v: u32, lo: u32, hi: u32) -> bool {
    v >= lo && v <= hi
}

#[inline]
pub fn in_range_u64(v: u64, lo: u64, hi: u64) -> bool {
    v >= lo && v <= hi
}

#[inline]
pub fn round_up_u32(v: u32, mult: u32) -> u32 {
    ((v + mult - 1) / mult) * mult
}

#[inline]
pub fn round_up_u64(v: u64, mult: u64) -> u64 {
    ((v + mult - 1) / mult) * mult
}

#[inline]
pub fn round_down_u32(v: u32, mult: u32) -> u32 {
    (v / mult) * mult
}

#[inline]
pub fn round_down_u64(v: u64, mult: u64) -> u64 {
    (v / mult) * mult
}

#[inline]
pub fn bswap_16(v: u16) -> u16 {
    v.swap_bytes()
}

#[inline]
pub fn bswap_32(v: u32) -> u32 {
    v.swap_bytes()
}

#[inline]
pub fn bswap_64(v: u64) -> u64 {
    v.swap_bytes()
}

#[inline]
pub fn count_trailing_ones_u32(v: u32) -> u32 {
    if v == u32::MAX {
        32
    } else {
        (!v).trailing_zeros()
    }
}

#[inline]
pub fn count_trailing_ones_u64(v: u64) -> u32 {
    if v == u64::MAX {
        64
    } else {
        (!v).trailing_zeros()
    }
}

#[inline]
pub fn count_leading_ones_u32(v: u32) -> u32 {
    if v == u32::MAX {
        32
    } else {
        (!v).leading_zeros()
    }
}

#[inline]
pub fn count_leading_ones_u64(v: u64) -> u32 {
    if v == u64::MAX {
        64
    } else {
        (!v).leading_zeros()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // --- Bit Counting ---

    #[test]
    fn test_count_leading_zeros() {
        assert_eq!(count_leading_zeros_u32(0), 32);
        assert_eq!(count_leading_zeros_u32(1), 31);
        assert_eq!(count_leading_zeros_u32(0x8000_0000), 0);
        assert_eq!(count_leading_zeros_u32(0x0000_FFFF), 16);

        assert_eq!(count_leading_zeros_u64(0), 64);
        assert_eq!(count_leading_zeros_u64(1), 63);
        assert_eq!(count_leading_zeros_u64(0x8000_0000_0000_0000), 0);
        assert_eq!(count_leading_zeros_u64(0x0000_0000_FFFF_FFFF), 32);
    }

    #[test]
    fn test_count_trailing_zeros() {
        assert_eq!(count_trailing_zeros_u32(0), 32);
        assert_eq!(count_trailing_zeros_u32(1), 0);
        assert_eq!(count_trailing_zeros_u32(2), 1);
        assert_eq!(count_trailing_zeros_u32(0x8000_0000), 31);
        assert_eq!(count_trailing_zeros_u32(12), 2); // 1100 binary

        assert_eq!(count_trailing_zeros_u64(0), 64);
        assert_eq!(count_trailing_zeros_u64(1), 0);
        assert_eq!(count_trailing_zeros_u64(0x8000_0000_0000_0000), 63);
        assert_eq!(count_trailing_zeros_u64(24), 3); // 11000 binary
    }

    #[test]
    fn test_count_population() {
        assert_eq!(count_population_u32(0), 0);
        assert_eq!(count_population_u32(1), 1);
        assert_eq!(count_population_u32(0xFFFF_FFFF), 32);
        assert_eq!(count_population_u32(0x5555_5555), 16);

        assert_eq!(count_population_u64(0), 0);
        assert_eq!(count_population_u64(1), 1);
        assert_eq!(count_population_u64(0xFFFF_FFFF_FFFF_FFFF), 64);
        assert_eq!(count_population_u64(0xAAAA_AAAA_AAAA_AAAA), 32);
    }

    // --- Power of 2 ---

    #[test]
    fn test_is_power_of_2() {
        assert!(!is_power_of_2_u32(0));
        assert!(is_power_of_2_u32(1));
        assert!(is_power_of_2_u32(2));
        assert!(is_power_of_2_u32(4));
        assert!(!is_power_of_2_u32(3));
        assert!(!is_power_of_2_u32(5));
        assert!(is_power_of_2_u32(0x8000_0000));

        assert!(!is_power_of_2_u64(0));
        assert!(is_power_of_2_u64(1));
        assert!(is_power_of_2_u64(0x8000_0000_0000_0000));
        assert!(!is_power_of_2_u64(0x8000_0000_0000_0001));
    }

    #[test]
    fn test_next_power_of_2() {
        assert_eq!(next_power_of_2_u32(0), 1);
        assert_eq!(next_power_of_2_u32(1), 1);
        assert_eq!(next_power_of_2_u32(2), 2);
        assert_eq!(next_power_of_2_u32(3), 4);
        assert_eq!(next_power_of_2_u32(5), 8);
        assert_eq!(next_power_of_2_u32(0x8000_0001), 0); // overflow

        assert_eq!(next_power_of_2_u64(0), 1);
        assert_eq!(next_power_of_2_u64(3), 4);
        assert_eq!(next_power_of_2_u64(1u64 << 62), 1u64 << 62);
        assert_eq!(next_power_of_2_u64((1u64 << 62) + 1), 1u64 << 63);
        assert_eq!(next_power_of_2_u64(0x8000_0000_0000_0001), 0); // overflow
    }

    #[test]
    fn test_floor_log2() {
        assert_eq!(floor_log2_u32(1), 0);
        assert_eq!(floor_log2_u32(2), 1);
        assert_eq!(floor_log2_u32(3), 1);
        assert_eq!(floor_log2_u32(4), 2);
        assert_eq!(floor_log2_u32(7), 2);
        assert_eq!(floor_log2_u32(8), 3);
        assert_eq!(floor_log2_u32(0x8000_0000), 31);

        assert_eq!(floor_log2_u64(1), 0);
        assert_eq!(floor_log2_u64(0x8000_0000_0000_0000), 63);
        assert_eq!(floor_log2_u64((1u64 << 63) | (1u64 << 62)), 63);
    }

    #[test]
    fn test_ceil_log2() {
        assert_eq!(ceil_log2_u32(1), 0);
        assert_eq!(ceil_log2_u32(2), 1);
        assert_eq!(ceil_log2_u32(3), 2);
        assert_eq!(ceil_log2_u32(4), 2);
        assert_eq!(ceil_log2_u32(5), 3);
        assert_eq!(ceil_log2_u32(8), 3);
        assert_eq!(ceil_log2_u32(9), 4);

        assert_eq!(ceil_log2_u64(1), 0);
        assert_eq!(ceil_log2_u64(3), 2);
        assert_eq!(ceil_log2_u64(1u64 << 63), 63);
        // (1<<63)|1 = 0x8000_0000_0000_0001 > 2^63, so ceil_log2 = 64
        assert_eq!(ceil_log2_u64((1u64 << 63) | 1), 64);
    }

    // --- Alignment ---

    #[test]
    fn test_align_to() {
        assert_eq!(align_to(0u64, 4u64), 0);
        assert_eq!(align_to(1u64, 4u64), 4);
        assert_eq!(align_to(3u64, 4u64), 4);
        assert_eq!(align_to(4u64, 4u64), 4);
        assert_eq!(align_to(5u64, 4u64), 8);
        assert_eq!(align_to(0u32, 8u32), 0);
        assert_eq!(align_to(7u32, 8u32), 8);
        assert_eq!(align_to(8u32, 8u32), 8);
        assert_eq!(align_to(9u32, 8u32), 16);
    }

    #[test]
    fn test_align_down() {
        assert_eq!(align_down(0u64, 4u64), 0);
        assert_eq!(align_down(1u64, 4u64), 0);
        assert_eq!(align_down(3u64, 4u64), 0);
        assert_eq!(align_down(4u64, 4u64), 4);
        assert_eq!(align_down(5u64, 4u64), 4);
        assert_eq!(align_down(7u64, 4u64), 4);
        assert_eq!(align_down(8u64, 4u64), 8);
    }

    #[test]
    fn test_is_aligned() {
        assert!(is_aligned(0u64, 4u64));
        assert!(!is_aligned(1u64, 4u64));
        assert!(!is_aligned(2u64, 4u64));
        assert!(!is_aligned(3u64, 4u64));
        assert!(is_aligned(4u64, 4u64));
        assert!(is_aligned(8u64, 4u64));
        assert!(is_aligned(16u64, 8u64));
        assert!(!is_aligned(17u64, 8u64));
    }

    // --- Find First/Last Set ---

    #[test]
    fn test_find_first_set() {
        assert_eq!(find_first_set_u32(0), -1);
        assert_eq!(find_first_set_u32(1), 0);
        assert_eq!(find_first_set_u32(2), 1);
        assert_eq!(find_first_set_u32(4), 2);
        assert_eq!(find_first_set_u32(8), 3);
        assert_eq!(find_first_set_u32(0x8000_0000), 31);
        assert_eq!(find_first_set_u32(0b10100), 2);

        assert_eq!(find_first_set_u64(0), -1);
        assert_eq!(find_first_set_u64(1), 0);
        assert_eq!(find_first_set_u64(0x8000_0000_0000_0000), 63);
        assert_eq!(find_first_set_u64(12), 2);
    }

    #[test]
    fn test_find_last_set() {
        assert_eq!(find_last_set_u32(0), -1);
        assert_eq!(find_last_set_u32(1), 0);
        assert_eq!(find_last_set_u32(2), 1);
        assert_eq!(find_last_set_u32(0x8000_0000), 31);
        assert_eq!(find_last_set_u32(0b10100), 4);
        assert_eq!(find_last_set_u32(0xFFFF_FFFF), 31);

        assert_eq!(find_last_set_u64(0), -1);
        assert_eq!(find_last_set_u64(1), 0);
        assert_eq!(find_last_set_u64(0x8000_0000_0000_0000), 63);
        assert_eq!(find_last_set_u64(0xFFFF_FFFF_FFFF_FFFF), 63);
    }

    // --- Reverse Bits ---

    #[test]
    fn test_reverse_bits() {
        assert_eq!(reverse_bits_u32(0), 0);
        assert_eq!(reverse_bits_u32(0x8000_0000), 1);
        assert_eq!(reverse_bits_u32(1), 0x8000_0000);
        assert_eq!(reverse_bits_u32(0xFFFF_FFFF), 0xFFFF_FFFF);
        // 0b1100 -> reversed = 0b0011 followed by 28 zeros
        assert_eq!(reverse_bits_u32(0xC000_0000), 3);

        assert_eq!(reverse_bits_u64(0), 0);
        assert_eq!(reverse_bits_u64(1), 0x8000_0000_0000_0000);
        assert_eq!(reverse_bits_u64(0x8000_0000_0000_0000), 1);
    }

    // --- Bit Floor / Bit Ceil ---

    #[test]
    fn test_bit_floor() {
        assert_eq!(bit_floor_u32(0), 0);
        assert_eq!(bit_floor_u32(1), 1);
        assert_eq!(bit_floor_u32(2), 2);
        assert_eq!(bit_floor_u32(3), 2);
        assert_eq!(bit_floor_u32(4), 4);
        assert_eq!(bit_floor_u32(5), 4);
        assert_eq!(bit_floor_u32(7), 4);
        assert_eq!(bit_floor_u32(8), 8);
        assert_eq!(bit_floor_u32(0x8000_0000), 0x8000_0000);

        assert_eq!(bit_floor_u64(0), 0);
        assert_eq!(bit_floor_u64(3), 2);
        assert_eq!(bit_floor_u64(0x8000_0000_0000_0000), 0x8000_0000_0000_0000);
    }

    #[test]
    fn test_bit_ceil() {
        assert_eq!(bit_ceil_u32(0), 1);
        assert_eq!(bit_ceil_u32(1), 1);
        assert_eq!(bit_ceil_u32(2), 2);
        assert_eq!(bit_ceil_u32(3), 4);
        assert_eq!(bit_ceil_u32(4), 4);
        assert_eq!(bit_ceil_u32(5), 8);
        assert_eq!(bit_ceil_u32(0x8000_0000), 0x8000_0000);
        assert_eq!(bit_ceil_u32(0x8000_0001), 0); // overflow

        assert_eq!(bit_ceil_u64(0), 1);
        assert_eq!(bit_ceil_u64(3), 4);
        assert_eq!(bit_ceil_u64(0x8000_0000_0000_0000), 0x8000_0000_0000_0000);
    }

    // --- Mask Operations ---

    #[test]
    fn test_is_shifted_mask() {
        // Valid masks
        assert_eq!(is_shifted_mask_32(0b1), (true, 0, 1));
        assert_eq!(is_shifted_mask_32(0b11), (true, 0, 2));
        assert_eq!(is_shifted_mask_32(0b110), (true, 1, 2));
        assert_eq!(is_shifted_mask_32(0b11100), (true, 2, 3));
        assert_eq!(is_shifted_mask_32(0xFFFF_FFFF), (true, 0, 32));

        // Invalid masks (non-contiguous)
        assert_eq!(is_shifted_mask_32(0b101), (false, 0, 0));
        assert_eq!(is_shifted_mask_32(0b10010), (false, 0, 0));
        assert_eq!(is_shifted_mask_32(0), (false, 0, 0));

        // Large valid mask for u64
        assert_eq!(is_shifted_mask_64(0x00FF_FF00), (true, 8, 16));
        assert_eq!(is_shifted_mask_64(0), (false, 0, 0));
        assert_eq!(is_shifted_mask_64(0xFFFF_FFFF_FFFF_FFFF), (true, 0, 64));
        // Invalid
        assert_eq!(is_shifted_mask_64(0xA000_0000_0000_0000), (false, 0, 0));
    }

    #[test]
    fn test_mask_trailing_ones() {
        assert_eq!(mask_trailing_ones_u32(0), 0);
        assert_eq!(mask_trailing_ones_u32(1), 1);
        assert_eq!(mask_trailing_ones_u32(2), 3);
        assert_eq!(mask_trailing_ones_u32(3), 7);
        assert_eq!(mask_trailing_ones_u32(31), 0x7FFF_FFFF);
        assert_eq!(mask_trailing_ones_u32(32), u32::MAX);
        assert_eq!(mask_trailing_ones_u32(100), u32::MAX);

        assert_eq!(mask_trailing_ones_u64(0), 0);
        assert_eq!(mask_trailing_ones_u64(1), 1);
        assert_eq!(mask_trailing_ones_u64(2), 3);
        assert_eq!(mask_trailing_ones_u64(63), 0x7FFF_FFFF_FFFF_FFFF);
        assert_eq!(mask_trailing_ones_u64(64), u64::MAX);
        assert_eq!(mask_trailing_ones_u64(100), u64::MAX);
    }

    #[test]
    fn test_mask_trailing_zeros() {
        assert_eq!(mask_trailing_zeros_u32(0), u32::MAX);
        assert_eq!(mask_trailing_zeros_u32(1), u32::MAX - 1);
        assert_eq!(mask_trailing_zeros_u32(2), u32::MAX - 3);
        assert_eq!(mask_trailing_zeros_u32(32), 0);

        assert_eq!(mask_trailing_zeros_u64(0), u64::MAX);
        assert_eq!(mask_trailing_zeros_u64(1), u64::MAX - 1);
        assert_eq!(mask_trailing_zeros_u64(64), 0);
    }

    // --- Integer Min/Max ---

    #[test]
    fn test_umin_umax() {
        assert_eq!(umin(3u32, 5u32), 3);
        assert_eq!(umin(10u32, 7u32), 7);
        assert_eq!(umin(0u64, 0u64), 0);

        assert_eq!(umax(3u32, 5u32), 5);
        assert_eq!(umax(10u32, 7u32), 10);
        assert_eq!(umax(0u64, 0u64), 0);
    }

    // --- Saturation ---

    #[test]
    fn test_saturating_add() {
        assert_eq!(saturating_add_u32(10, 20), 30);
        assert_eq!(saturating_add_u32(u32::MAX, 1), u32::MAX);
        assert_eq!(saturating_add_u32(u32::MAX, u32::MAX), u32::MAX);

        assert_eq!(saturating_add_u64(10, 20), 30);
        assert_eq!(saturating_add_u64(u64::MAX, 1), u64::MAX);
    }

    #[test]
    fn test_saturating_sub() {
        assert_eq!(saturating_sub_u32(20, 10), 10);
        assert_eq!(saturating_sub_u32(10, 20), 0);
        assert_eq!(saturating_sub_u32(0, 1), 0);

        assert_eq!(saturating_sub_u64(20, 10), 10);
        assert_eq!(saturating_sub_u64(0, 1), 0);
    }

    // --- Division Helpers ---

    #[test]
    fn test_divide_nearest() {
        assert_eq!(divide_nearest_u32(10, 3), 3); // 3.33 -> 3
        assert_eq!(divide_nearest_u32(11, 3), 4); // 3.67 -> 4
        assert_eq!(divide_nearest_u32(9, 3), 3);
        assert_eq!(divide_nearest_u32(5, 2), 3); // 2.5 -> 3 (ties round up)

        assert_eq!(divide_nearest_u64(10, 3), 3);
        assert_eq!(divide_nearest_u64(5, 2), 3);
    }

    #[test]
    fn test_divide_ceil() {
        assert_eq!(divide_ceil_u32(10, 3), 4);
        assert_eq!(divide_ceil_u32(9, 3), 3);
        assert_eq!(divide_ceil_u32(1, 3), 1);
        assert_eq!(divide_ceil_u32(0, 3), 0);

        assert_eq!(divide_ceil_u64(10, 3), 4);
        assert_eq!(divide_ceil_u64(9, 3), 3);
    }

    #[test]
    #[should_panic]
    fn test_divide_nearest_by_zero() {
        divide_nearest_u32(10, 0);
    }

    #[test]
    #[should_panic]
    fn test_divide_ceil_by_zero() {
        divide_ceil_u64(10, 0);
    }

    // --- Rotate ---

    #[test]
    fn test_rotl() {
        assert_eq!(rotl_u32(0x0000_0001, 0), 0x0000_0001);
        assert_eq!(rotl_u32(0x0000_0001, 1), 0x0000_0002);
        assert_eq!(rotl_u32(0x0000_0001, 31), 0x8000_0000);
        assert_eq!(rotl_u32(0x8000_0000, 1), 1);
        assert_eq!(rotl_u32(0x0000_0001, 32), 0x0000_0001); // mod 32
        assert_eq!(rotl_u32(0x0000_0001, 33), 0x0000_0002);

        assert_eq!(rotl_u64(1, 63), 0x8000_0000_0000_0000);
        assert_eq!(rotl_u64(0x8000_0000_0000_0000, 1), 1);
        assert_eq!(rotl_u64(1, 64), 1);
    }

    #[test]
    fn test_rotr() {
        assert_eq!(rotr_u32(0x0000_0001, 0), 0x0000_0001);
        assert_eq!(rotr_u32(0x0000_0001, 1), 0x8000_0000);
        assert_eq!(rotr_u32(0x8000_0000, 1), 0x4000_0000);
        assert_eq!(rotr_u32(0x8000_0000, 31), 1);

        assert_eq!(rotr_u64(0x8000_0000_0000_0000, 63), 1);
        assert_eq!(rotr_u64(1, 1), 0x8000_0000_0000_0000);
    }

    // --- Byte Swap ---

    #[test]
    fn test_byte_swap() {
        assert_eq!(byte_swap_16(0x1234u16), 0x3412u16);
        assert_eq!(byte_swap_16(0x0001u16), 0x0100u16);

        assert_eq!(byte_swap_32(0x1234_5678u32), 0x7856_3412u32);
        assert_eq!(byte_swap_32(0x0000_00FFu32), 0xFF00_0000u32);
        assert_eq!(byte_swap_32(0xFF00_0000u32), 0x0000_00FFu32);

        assert_eq!(
            byte_swap_64(0x0123_4567_89AB_CDEFu64),
            0xEFCD_AB89_6745_2301u64
        );
        // Round-trip
        assert_eq!(
            byte_swap_64(byte_swap_64(0xDEAD_BEEF_CAFE_BABEu64)),
            0xDEAD_BEEF_CAFE_BABEu64
        );
    }

    // --- Hi/Lo Multiplication ---

    #[test]
    fn test_mul_hi_lo() {
        // 0x100000001 * 0x2 = 0x200000002 -> hi: 0x2, lo: 0x2
        assert_eq!(mul_hi_u32(0x0001_0001, 2), 0);
        assert_eq!(mul_lo_u32(0x0001_0001, 2), 0x0002_0002);

        // 0xFFFF_FFFF * 0xFFFF_FFFF = 0xFFFF_FFFE_0000_0001
        assert_eq!(mul_hi_u32(u32::MAX, u32::MAX), u32::MAX - 1); // 0xFFFF_FFFE
        assert_eq!(mul_lo_u32(u32::MAX, u32::MAX), 1); // 0x0000_0001

        // 0x1_0000_0000 * 0x1_0000_0000 = 0x1_0000_0000_0000_0000 (hi=1, lo=0)
        assert_eq!(mul_hi_u64(0x1_0000_0000u64, 0x1_0000_0000u64), 1);
        assert_eq!(mul_lo_u64(0x1_0000_0000u64, 0x1_0000_0000u64), 0);

        // u64::MAX * u64::MAX: hi = u64::MAX - 1, lo = 1
        assert_eq!(mul_hi_u64(u64::MAX, u64::MAX), u64::MAX - 1);
        assert_eq!(mul_lo_u64(u64::MAX, u64::MAX), 1);
    }

    // --- Overflow Detection ---

    #[test]
    fn test_add_overflow() {
        assert_eq!(add_overflow_u32(10, 20), (30, false));
        assert_eq!(add_overflow_u32(u32::MAX, 1), (0, true));
        assert_eq!(add_overflow_u32(u32::MAX, 0), (u32::MAX, false));

        assert_eq!(add_overflow_u64(10, 20), (30, false));
        assert_eq!(add_overflow_u64(u64::MAX, 1), (0, true));
    }

    #[test]
    fn test_sub_overflow() {
        assert_eq!(sub_overflow_u32(20, 10), (10, false));
        assert_eq!(sub_overflow_u32(0, 1), (u32::MAX, true));
        assert_eq!(sub_overflow_u32(10, 20), (u32::MAX - 9, true));

        assert_eq!(sub_overflow_u64(20, 10), (10, false));
        assert_eq!(sub_overflow_u64(0, 1), (u64::MAX, true));
    }

    #[test]
    fn test_mul_overflow() {
        assert_eq!(mul_overflow_u32(10, 20), (200, false));
        assert_eq!(mul_overflow_u32(u32::MAX, 2), (u32::MAX - 1, true));
        assert_eq!(mul_overflow_u32(0, u32::MAX), (0, false));

        assert_eq!(mul_overflow_u64(10, 20), (200, false));
        assert_eq!(mul_overflow_u64(u64::MAX, 2), (u64::MAX - 1, true));
    }

    // --- Additional edge cases ---

    #[test]
    fn test_floor_log2_edge() {
        assert_eq!(floor_log2_u32(1), 0);
        assert_eq!(floor_log2_u32(u32::MAX), 31);
    }

    #[test]
    #[should_panic]
    fn test_floor_log2_zero_panics() {
        floor_log2_u32(0);
    }

    #[test]
    fn test_align_to_power_of_two_requirement() {
        // Alignment of 8
        assert_eq!(align_to(0u32, 8u32), 0);
        assert_eq!(align_to(21879u32, 8u32), 21880);
    }
}