1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339
#![deny(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, unstable_features, unused_import_braces, unused_qualifications)] //! Bitwise manipulation algorithms for `Word`s and sequences of `Words`. //! //! The algorithms have long and boring readable names that explicitly state //! what the algorithm does, but their documentation also contain other popular //! names of each algorithm as well as the hardware intrinsics they map to (if //! any) to make them easier to find. //! //! The following architectures are supported using feature flags: //! //! - SSE 4.2: sse42, //! - BMI 1.0: bmi1, //! - BMI 2.0: bmi2, //! - ABM: abm, //! - TBM: tbm. //! //! The crate [llvmint](https://github.com/huonw/llvmint) is used to implement //! the intrinsics whenever possible. Inline assembly prevents compiler //! optimizations and is deliberately not used. Ideally, these intrinsics should //! be somehow exposed by rustc (or a similar crate to this should be part of //! the standard library). #![cfg_attr(feature = "dev", allow(unstable_features))] #![cfg_attr(feature = "dev", feature(plugin))] #![cfg_attr(feature = "dev", plugin(clippy))] #[cfg(feature = "llvmint")] extern crate llvmint; use std::ops::{Add, Sub, Mul, Div}; use std::ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr}; use std::mem; /// Bitwise manipulation algorithms for `Word`s. /// /// Note: this trat is not supposed to be implemented by library users. The /// distinction between functionality required and inherited has been /// arbitrarily placed at the boundary between "what is easier to implement /// within the trait" and "what is easier to implement with a macro" for the /// primitive integer types. pub trait Word : Sized + Copy + Not<Output=Self> + BitOr<Output=Self> + BitXor<Output=Self> + Add<Output=Self> + Sub<Output=Self> + Mul<Output=Self> + Div<Output=Self> + Shr<u32, Output=Self> + Shl<u32, Output=Self> + BitAnd<Output=Self> + Eq + PartialOrd { /// Signed Word Type of the same size as Self. type Signed : Word; /// Unsigned Word Type of the same size as Self. type Unsigned : Word; /// Size of the word in bytes. fn size() -> usize; /// Size of the word in bits. fn bit_size() -> usize { 8 * Self::size() } /// Transmutes the integer into an unsigned integer of the /// same size (bitwise loss-less). /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!((8i32).to_unsigned().to_signed(), 8i32); /// assert_eq!((-1i32).to_unsigned().to_signed(), -1i32); /// ``` fn to_unsigned(self) -> Self::Unsigned; /// Transmutes an integer into a signed integer of the /// same size (bitwise loss-less). /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!((8i32).to_unsigned().to_signed(), 8i32); /// assert_eq!((-1i32).to_unsigned().to_signed(), -1i32); /// ``` fn to_signed(self) -> Self::Signed; /// Returns a word with no bits set (an integer of value zero). fn zero() -> Self; /// Returns a word with the least significant bit set (an integer of value one). fn one() -> Self; /// Returns a word with the second least significant bit set (an integer of value two). fn two() -> Self; /// Returns the number of zeros in the binary representation of `self`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0100_1100u8; /// /// assert_eq!(n.count_zeros(), 5); /// ``` fn count_zeros(self) -> usize; /// Returns the number of ones in the binary representation of `self`. /// /// # Keywords: /// /// Population count, popcount, hamming weight, sideways sum. /// /// # Intrinsics: /// - ABM: popcnt. /// - SSE4.2: popcnt. /// - NEON: vcnt. /// - PowerPC: popcntb. /// - gcc/llvm builtin: `__builtin_popcount(x)`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0100_1100u8; /// /// assert_eq!(n.count_ones(), 3); /// ``` fn count_ones(self) -> usize; /// Returns the number of leading zeros in the binary representation /// of `self`. /// /// # Keywords: /// /// Count leading zeros. /// /// # Intrinsics: /// - ABM: lzcnt. /// - BMI 1.0: lzcnt. /// - ARMv5: clz. /// - PowerPC: cntlzd. /// - gcc/llvm builtin: `x == 0 ? mem::size_of(x) * 8 : __builtin_clz(x)`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0010_1000u16; /// /// assert_eq!(n.leading_zeros(), 10); /// ``` fn leading_zeros(self) -> usize; /// Returns the number of trailing zeros in the binary representation /// of `self`. /// /// # Keywords: /// /// Count trailing zeros. /// /// # Intrinsics: /// - BMI 1.0: tzcnt. /// - gcc/llvm builtin: `x == 0 ? mem::size_of(x) * 8 : __builtin_ctz(x)`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0010_1000u16; /// /// assert_eq!(n.trailing_zeros(), 3); /// ``` fn trailing_zeros(self) -> usize; /// Returns the number of leading ones in the binary representation /// of `self`. /// /// # Keywords: /// /// Count leading ones. /// /// # Intrinsics: /// - ARMv8: cls. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1111_1111_1100_1000u16; /// /// assert_eq!(n.leading_ones(), 10); /// ``` fn leading_ones(self) -> usize { Self::leading_zeros(!self) } /// Returns the number of trailing ones in the binary representation /// of `self`. /// /// # Keywords: /// /// Count trailing ones. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0010_0111u16; /// /// assert_eq!(n.trailing_ones(), 3); /// ``` fn trailing_ones(self) -> usize { Self::trailing_zeros(!self) } /// Shift the bits to the left by a specified amount, `n`. /// /// # Panics /// /// If `n > bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let a = 0b0000_1010u8; /// let b = 0b0000_1001u8; /// /// assert_eq!(a.shift_logical_left(4), 0b1010_0000u8); /// assert_eq!(b.shift_logical_left(4), 0b1001_0000u8); /// b.shift_logical_right((<u8 as Word>::bit_size() - 1) as u32); /// /// ``` fn shift_logical_left(self, n: u32) -> Self; /// Shift the bits to the right by a specified amount, `n`, with the /// high-order bits of the result cleared. /// /// # Panics /// /// If `n > bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let a = 0b0111_0000u8; /// let b = 0b1001_0000u8; /// /// assert_eq!(a.shift_logical_right(4), 0b0000_0111u8); /// assert_eq!(b.shift_logical_right(4), 0b0000_1001u8); /// b.shift_logical_right((<u8 as Word>::bit_size() - 1) as u32); /// /// ``` fn shift_logical_right(self, n: u32) -> Self; /// Shift the bits to the left by a specified amount, `n` (same as /// [`shift_logical_left`](tymethod.shift_logical_left), provided for /// symmetry). /// /// # Panics /// /// If `n > bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let a = 0b0000_1010u8; /// let b = 0b0000_1001u8; /// /// assert_eq!(a.shift_arithmetic_left(4), 0b1010_0000u8); /// assert_eq!(b.shift_arithmetic_left(4), 0b1001_0000u8); /// b.shift_arithmetic_left((<u8 as Word>::bit_size() - 1) as u32); /// /// ``` fn shift_arithmetic_left(self, n: u32) -> Self; /// Shift the bits to the right by a specified amount, `n`, setting the /// high-order bits of the result to the value of the most significant bit /// of `self`. /// /// # Panics /// /// If `n > bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let a = 0b0111_0000u8; /// let b = 0b1001_0000u8; /// /// assert_eq!(a.shift_arithmetic_right(4), 0b0000_0111u8); /// assert_eq!(b.shift_arithmetic_right(4), 0b1111_1001u8); /// b.shift_arithmetic_right((<u8 as Word>::bit_size() - 1) as u32); /// /// ``` fn shift_arithmetic_right(self, n: u32) -> Self; /// Shifts the bits to the left by a specified amount, `n`, wrapping /// the truncated bits to the end of the resulting integer. /// /// # Panics /// /// If `n > bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0x0123456789ABCDEFu64; /// let m = 0x3456789ABCDEF012u64; /// /// assert_eq!(n.rotate_left(12), m); /// n.rotate_left(<u64 as Word>::bit_size() as u32); /// ``` fn rotate_left(self, n: u32) -> Self; /// Shifts the bits to the right by a specified amount, `n`, wrapping /// the truncated bits to the beginning of the resulting integer. /// /// # Panics /// /// If `n > bit_size()`. /// /// # Intrinsics: /// - BMI 2.0: rorx. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0x0123456789ABCDEFu64; /// let m = 0xDEF0123456789ABCu64; /// /// assert_eq!(n.rotate_right(12), m); /// n.rotate_right(<u64 as Word>::bit_size() as u32); /// ``` fn rotate_right(self, n: u32) -> Self; /// Logical and not of `self` with `y`. /// /// # Intrinsics: /// - BMI 2.0: andn. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0100_1101u8; /// let m = 0b1110_1010u8; /// /// assert_eq!(n.and_not(m), 0b1010_0010u8); /// ``` fn and_not(self, y: Self) -> Self { !self & y } /// Reverses the byte order of the integer. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0x0123456789ABCDEFu64; /// let m = 0xEFCDAB8967452301u64; /// /// assert_eq!(n.swap_bytes(), m); /// ``` fn swap_bytes(self) -> Self; /// Convert an integer from big endian to the target's endianness. /// /// On big endian this is a no-op. On little endian the bytes are swapped. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0x0123456789ABCDEFu64; /// /// if cfg!(target_endian = "big") { /// assert_eq!(u64::from_be(n), n) /// } else { /// assert_eq!(u64::from_be(n), n.swap_bytes()) /// } /// ``` fn from_be(x: Self) -> Self; /// Convert an integer from little endian to the target's endianness. /// /// On little endian this is a no-op. On big endian the bytes are swapped. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0x0123456789ABCDEFu64; /// /// if cfg!(target_endian = "little") { /// assert_eq!(u64::from_le(n), n) /// } else { /// assert_eq!(u64::from_le(n), n.swap_bytes()) /// } /// ``` fn from_le(x: Self) -> Self; /// Convert `self` to big endian from the target's endianness. /// /// On big endian this is a no-op. On little endian the bytes are swapped. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0x0123456789ABCDEFu64; /// /// if cfg!(target_endian = "big") { /// assert_eq!(n.to_be(), n) /// } else { /// assert_eq!(n.to_be(), n.swap_bytes()) /// } /// ``` fn to_be(self) -> Self; /// Convert `self` to little endian from the target's endianness. /// /// On little endian this is a no-op. On big endian the bytes are swapped. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0x0123456789ABCDEFu64; /// /// if cfg!(target_endian = "little") { /// assert_eq!(n.to_le(), n) /// } else { /// assert_eq!(n.to_le(), n.swap_bytes()) /// } /// ``` fn to_le(self) -> Self; /// Raises self to the power of `exp`, using exponentiation by squaring. /// /// # Panics /// /// If the result does not fit in `Self`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!(2i32.pow(4), 16); /// ``` fn pow(self, mut exp: u32) -> Self; /// Returns the number of 1 bits in `self` mod 2, that is, returns 1 if the /// number of 1 bits in `self` is odd, and zero otherwise /// /// # Intrinsics: /// -gcc/llvm: `__builtin_parity(x)`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n0 = 0b0000; // 0 -> even => parity = 0 /// let n1 = 0b0001; // 1 -> odd => partiy = 1 /// let n2 = 0b0010; // 1 -> odd => parity = 1 /// let n3 = 0b0011; // 2 -> even => parity = 0 /// /// assert_eq!(n0.parity(), 0); /// assert_eq!(n1.parity(), 1); /// assert_eq!(n2.parity(), 1); /// assert_eq!(n3.parity(), 0); /// ``` fn parity(self) -> usize { // TODO: use intrinsics depending on size: // - __builtin_parity, __builtin_parityl, __builtin_parityll self.count_ones() & 1 } /// Returns the next "absolute" even even number x such that `|self| < |x| and /// sign(self) == sign(x)`. /// /// That is, for positive numbers the next even is greater than `self` and for /// negative numbers it is smaller than `self` (see examples). /// /// # Panics /// /// If `self` overflows. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!(-3.next_abs_greater_even(), -4); /// assert_eq!(-2.next_abs_greater_even(), -4); /// assert_eq!(-1.next_abs_greater_even(), -2); /// assert_eq!(0.next_abs_greater_even(), 2); /// assert_eq!(1.next_abs_greater_even(), 2); /// assert_eq!(2.next_abs_greater_even(), 4); /// assert_eq!(3.next_abs_greater_even(), 4); /// ``` fn next_abs_greater_even(self) -> Self { (self | Self::one()) + Self::one() } /// Returns the previous "absolute" even number x such that `|x| < |self| and /// sign(x) == sign(self)`. /// /// That is, for positive numbers the previous even is smaller than `self` and /// for negative numbers it is greater than `self` (see examples). /// /// # Panics /// /// If `self` overflows. Note that zero is handled as -0 and that the previous /// even of zero for Unsigned numbers overflows (because its negative). /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!(-3.prev_abs_smaller_even(), -2); /// assert_eq!(-2.prev_abs_smaller_even(), 0); /// assert_eq!(-1.prev_abs_smaller_even(), 0); /// // assert_eq!(0u32.prev_abs_smaller_even(), 2); // overflows /// assert_eq!(0.prev_abs_smaller_even(), -2); /// assert_eq!(1.prev_abs_smaller_even(), 0); /// assert_eq!(2.prev_abs_smaller_even(), 0); /// assert_eq!(3.prev_abs_smaller_even(), 2); /// assert_eq!(4.prev_abs_smaller_even(), 2); /// ``` fn prev_abs_smaller_even(self) -> Self { (self - Self::one()) & !Self::one() } /// Returns the next "absolute" even number x such that `|self| <= |x| and /// sign(self) == sign(x)`. /// /// That is, for positive numbers the next even is greater or equal than `self` /// and for negative numbers it is smaller or equal than `self` (see examples). /// /// # Panics /// /// If `self` overflows. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!(-3.next_abs_greater_equal_even(), -4); /// assert_eq!(-2.next_abs_greater_equal_even(), -2); /// assert_eq!(-1.next_abs_greater_equal_even(), -2); /// assert_eq!(0.next_abs_greater_equal_even(), 0); /// assert_eq!(1.next_abs_greater_equal_even(), 2); /// assert_eq!(2.next_abs_greater_equal_even(), 2); /// assert_eq!(3.next_abs_greater_equal_even(), 4); /// ``` fn next_abs_greater_equal_even(self) -> Self { (self + Self::one()) & !Self::one() } /// Returns the previous "absolute" even number x such that `|x| <= |self| and /// sign(x) == sign(self)`. /// /// That is, for positive numbers the previous even is smaller or equalt than /// `self` and for negative numbers it is greater or equalt than `self` (see /// examples). /// /// # Panics /// /// If `self` overflows. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!(-3.prev_abs_smaller_equal_even(), -2); /// assert_eq!(-2.prev_abs_smaller_equal_even(), -2); /// assert_eq!(-1.prev_abs_smaller_equal_even(), 0); /// assert_eq!(0u32.prev_abs_smaller_equal_even(), 0); /// assert_eq!(0.prev_abs_smaller_equal_even(), 0); /// assert_eq!(1.prev_abs_smaller_equal_even(), 0); /// assert_eq!(2.prev_abs_smaller_equal_even(), 2); /// assert_eq!(3.prev_abs_smaller_equal_even(), 2); /// assert_eq!(4.prev_abs_smaller_equal_even(), 4); /// ``` fn prev_abs_smaller_equal_even(self) -> Self { self & !Self::one() } /// Returns the next "absolute" odd number x such that `|self| < |x| and /// sign(self) == sign(x)`. /// /// That is, for positive numbers the next odd is greater than `self` and for /// negative numbers it is smaller than `self` (see examples). /// /// # Panics /// /// If `self` overflows. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!(-3.next_abs_greater_odd(), -5); /// assert_eq!(-2.next_abs_greater_odd(), -3); /// assert_eq!(-1.next_abs_greater_odd(), -3); /// assert_eq!(0.next_abs_greater_odd(), 1); /// assert_eq!(1.next_abs_greater_odd(), 3); /// assert_eq!(2.next_abs_greater_odd(), 3); /// assert_eq!(3.next_abs_greater_odd(), 5); /// ``` fn next_abs_greater_odd(self) -> Self { (self + Self::one()) | Self::one() } /// Returns the previous "absolute" odd number x such that `|x| < |self| and /// sign(x) == sign(self)`. /// /// That is, for positive numbers the previous odd is smaller than `self` and /// for negative numbers it is greater than `self` (see examples). /// /// # Panics /// /// If `self` overflows. Note that zero is handled as -0 and that the previous /// odd of zero and one for Unsigned numbers overflows (because its negative). /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!(-4.prev_abs_smaller_odd(), -3); /// assert_eq!(-3.prev_abs_smaller_odd(), -1); /// assert_eq!(-2.prev_abs_smaller_odd(), -1); /// assert_eq!(-1.prev_abs_smaller_odd(), 1); /// // assert_eq!(0u32.prev_abs_smaller_odd(), 2); // overflows /// //assert_eq!(1u32.prev_abs_smaller_odd(), 2); // overflows /// assert_eq!(0.prev_abs_smaller_odd(), -1); /// assert_eq!(1.prev_abs_smaller_odd(), -1); /// assert_eq!(2.prev_abs_smaller_odd(), 1); /// assert_eq!(3.prev_abs_smaller_odd(), 1); /// assert_eq!(4.prev_abs_smaller_odd(), 3); /// ``` fn prev_abs_smaller_odd(self) -> Self { (self & !Self::one()) - Self::one() } /// Returns the next "absolute" odd odd number x such that `|self| <= |x| and /// sign(self) == sign(x)`. /// /// That is, for positive numbers the next odd is greater or equal than `self` /// and for negative numbers it is smaller or equal than `self` (see examples). /// /// # Panics /// /// If `self` overflows. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!(-3.next_abs_greater_equal_odd(), -3); /// assert_eq!(-2.next_abs_greater_equal_odd(), -3); /// assert_eq!(-1.next_abs_greater_equal_odd(), -1); /// assert_eq!(0.next_abs_greater_equal_odd(), 1); /// assert_eq!(1.next_abs_greater_equal_odd(), 1); /// assert_eq!(2.next_abs_greater_equal_odd(), 3); /// assert_eq!(3.next_abs_greater_equal_odd(), 3); /// ``` fn next_abs_greater_equal_odd(self) -> Self { self | Self::one() } /// Returns the previous "absolute" odd number x such that `|x| <= |self| and /// sign(x) == sign(self)`. /// /// That is, for positive numbers the previous odd is smaller or equalt than /// `self` and for negative numbers it is greater or equalt than `self` (see /// examples). /// /// # Panics /// /// If `self` overflows. Note that the previous of zero is negative and will /// overflow for Unsigned Integers. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!(-3.prev_abs_smaller_equal_odd(), -3); /// assert_eq!(-2.prev_abs_smaller_equal_odd(), -1); /// assert_eq!(-1.prev_abs_smaller_equal_odd(), -1); /// // assert_eq!(0u32.prev_abs_smaller_equal_odd(), -1); // overflows /// assert_eq!(0.prev_abs_smaller_equal_odd(), -1); /// assert_eq!(1.prev_abs_smaller_equal_odd(), 1); /// assert_eq!(2.prev_abs_smaller_equal_odd(), 1); /// assert_eq!(3.prev_abs_smaller_equal_odd(), 3); /// assert_eq!(4.prev_abs_smaller_equal_odd(), 3); /// ``` fn prev_abs_smaller_equal_odd(self) -> Self { (self - Self::one()) | Self::one() } /// Clear all bits of `self`. /// /// Equivalent to [`zero()`](#tymethod.zero). /// /// # Example /// /// ``` /// use bitwise::Word; /// /// assert_eq!(0b1010_1010u8.clear(), 0u8); /// ``` fn clear(self) -> Self { Self::zero() } /// Clear least significant 1 bit of `self`; returns 0 if `self` is 0. /// /// # Intrinsics: /// - BMI 1.0: blsr. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0110; /// let s = 0b0100; /// /// assert_eq!(n.clear_least_significant_one(), s); /// ``` fn clear_least_significant_one(self) -> Self { self & (self - Self::one()) } /// Set least significant 0 bit of `self`. /// /// # Intrinsics: /// - TBM: blcs. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0101; /// let s = 0b0111; /// /// assert_eq!(n.set_least_significant_zero(), s); /// ``` fn set_least_significant_zero(self) -> Self { self | (self + Self::one()) } /// Isolate least significant 1 bit of `self` and returns it; returns 0 /// if `self` is 0. /// /// # Intrinsics: /// - BMI 1.0: blsi. /// - TBM: blsic, not. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0110; /// let s = 0b0010; /// /// assert_eq!(n.isolate_least_significant_one(), s); /// ``` fn isolate_least_significant_one(self) -> Self { // note: self & -self is intended, which is rewritten as: self & (Self::zero() - self) } /// Set the least significant zero bit of `self` to 1 and all of the /// rest to 0. /// /// # Intrinsics: /// - TBM: blcic (or: blci, not). /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0101; /// let s = 0b0010; /// /// assert_eq!(n.isolate_least_significant_zero(), s); /// ``` fn isolate_least_significant_zero(self) -> Self { (!self) & (self + Self::one()) } /// Clear the trailing 1's in `self`. /// /// # Intrinsics: /// - TBM: blcfill. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0110_1111; /// let s = 0b0110_0000; /// /// assert_eq!(n.clear_trailing_ones(), s); /// ``` fn clear_trailing_ones(self) -> Self { self & (self + Self::one()) } /// Set all of the trailing 0's in `self`. /// /// # Intrinsics: /// - TBM: blsfill. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0110_0000u8; /// let s = 0b0111_1111u8; /// /// assert_eq!(n.set_trailing_zeros(), s); /// ``` fn set_trailing_zeros(self) -> Self { self | (self - Self::one()) } /// Returns a mask with all of the trailing 0's of `self` set. /// /// # Intrinsics: /// - TBM: tzmsk. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0110_0000u8; /// let s = 0b0001_1111u8; /// /// assert_eq!(n.mask_trailing_zeros(), s); /// ``` fn mask_trailing_zeros(self) -> Self { (!self) & (self - Self::one()) } /// Returns a mask with all of the trailing 1's of `self` set. /// /// # Intrinsics: /// - TBM: tlmskc, not. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0101_1111u8; /// let s = 0b0001_1111u8; /// /// assert_eq!(n.mask_trailing_ones(), s); /// ``` fn mask_trailing_ones(self) -> Self { !((!self) | (self + Self::one())) } /// Returns a mask with all of the trailing 0's of `self` set and the least /// significant 1 bit set. /// /// # Intrinsics: /// - TBM: blsmsk. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0101_0000u8; /// let s = 0b0001_1111u8; /// /// assert_eq!(n.mask_trailing_zeros_and_least_significant_one(), s); /// ``` fn mask_trailing_zeros_and_least_significant_one(self) -> Self { (self - Self::one()) ^ self } /// Returns a mask with all of the trailing 1's of `self` set and the least /// significant 0 bit set. /// /// # Intrinsics: /// - TBM: blcmsk. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0101_1111u8; /// let s = 0b0011_1111u8; /// /// assert_eq!(n.mask_trailing_ones_and_least_significant_zero(), s); /// ``` fn mask_trailing_ones_and_least_significant_zero(self) -> Self { self ^ (self + Self::one()) } /// Returns the position of the first bit that is set (starting from the /// low-order bits). /// /// Returns `bit_size()` if no bit is found. /// /// # Keywords: /// /// Find first bit set, find first one, bit scan forward. /// /// # Examples: /// /// ``` /// use bitwise::Word; /// /// assert_eq!(0b0101_1111u8.first_bit_set(), 0); /// assert_eq!(0b0101_1100u8.first_bit_set(), 2); /// assert_eq!(0b1000_0000u8.first_bit_set(), 7); /// assert_eq!(0b0000_0000u8.first_bit_set(), 8); /// /// ``` fn first_bit_set(self) -> usize { self.trailing_zeros() } /// Returns the position of the first bit that is set (starting from the /// low-order bits). /// /// Returns `bit_size()` if no bit is found. /// /// # Keywords: /// /// Find first zero. /// /// # Examples: /// /// ``` /// use bitwise::Word; /// /// assert_eq!(0b1111_1111u8.first_bit_clear(), 8); /// assert_eq!(0b0111_1111u8.first_bit_clear(), 7); /// assert_eq!(0b1010_0011u8.first_bit_clear(), 2); /// assert_eq!(0b1000_1010u8.first_bit_clear(), 0); /// /// ``` fn first_bit_clear(self) -> usize { self.trailing_ones() } /// Reverses the bits of `self` by `subword_bits` and `group_subwords`: /// /// - `subword_bits`: the bits will be reversed in grous: /// 1 (single bits), 2 (pair-wise), 4 (nibbles), /// - `group_subwords`: the subword size is 8 bits: `mem::size_of::<u8>()`, /// the bits will be reversed within each subword. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0101_1101_1010_0101_u16; /// /// // Single bits: /// let s0 = 0b1010_0101_1011_1010u16; /// assert_eq!(n.reverse_bit_groups(1, 1), s0); /// /// // Bit pairs: /// let s1 = 0b0101_1010_0111_0101u16; /// assert_eq!(n.reverse_bit_groups(2, 1), s1); /// /// // Bit nibbles: /// let s2 = 0b0101_1010_1101_0101u16; /// assert_eq!(n.reverse_bit_groups(4, 1), s2); /// /// // Single bits: group_subwords = 2 /// let s3 = 0b1011_1010_1010_0101u16; /// assert_eq!(n.reverse_bit_groups(1, 2), s3); /// /// // Bit pairs: group_subwords = 2 /// let s4 = 0b0111_0101_0101_1010u16; /// assert_eq!(n.reverse_bit_groups(2, 2), s4); /// /// // Bit nibbles: group_subwords = 2 /// let s5 = 0b1101_0101_0101_1010u16; /// assert_eq!(n.reverse_bit_groups(4, 2), s5); /// ``` fn reverse_bit_groups(self, subword_bits: u32, group_subwords: u32) -> Self; /// Reverses the bits of `self`. /// /// # Intrinsics: /// - ARM: rbit (u32 ARMv7, u64 ARMv8). /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1011_0010u8; /// let s = 0b0100_1101u8; /// assert_eq!(n.reverse_bits(), s); /// /// let n1 = 0b1011_0010_1010_1001u16; /// let s1 = 0b1001_0101_0100_1101u16; /// assert_eq!(n1.reverse_bits(), s1); /// ``` fn reverse_bits(self) -> Self { self.reverse_bit_groups(1, 1) } /// Reverses the pairs of bits of `self`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1011_0010u8; /// let s = 0b1000_1110u8; /// assert_eq!(n.reverse_bit_pairs(), s); /// /// let n1 = 0b1011_0010_1010_1001u16; /// let s1 = 0b0110_1010_1000_1110u16; /// assert_eq!(n1.reverse_bit_pairs(), s1); /// ``` fn reverse_bit_pairs(self) -> Self { self.reverse_bit_groups(2, 1) } /// Reverses the nibbles of `self`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1011_0010u8; /// let s = 0b0010_1011u8; /// assert_eq!(n.reverse_bit_nibbles(), s); /// /// let n1 = 0b1011_0010_1010_1001u16; /// let s1 = 0b1001_1010_0010_1011u16; /// assert_eq!(n1.reverse_bit_nibbles(), s1); /// ``` fn reverse_bit_nibbles(self) -> Self { self.reverse_bit_groups(4, 1) } /// Reverses the bytes of `self`. /// /// - `bytes_per_block`: number of bytes per block to reverse. /// - `blocks_per_group`: number of blocks per group of blocks. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0101_1101_1010_0101_u16; /// /// // Single bytes: /// let s0 = 0b1010_0101_0101_1101u16; /// assert_eq!(n.reverse_byte_groups(1, 1), s0); /// /// // Single bytes: group_subwords = 2 /// let s3 = 0b0101_1101_1010_0101u16; /// assert_eq!(n.reverse_byte_groups(1, 2), s3); /// ``` fn reverse_byte_groups(self, bytes_per_block: u32, blocks_per_group: u32) -> Self { self.reverse_bit_groups(8 * bytes_per_block, blocks_per_group) } /// Reverses the bytes of `self` (equivalent to swap bytes). /// /// # Intrinsics: /// - x86_64: bswap. /// - ARM: rev (v5), revsh (v5), rev16 (v6,v8), rev32(v8). /// - gcc/llvm: `__builtin_bswap16/32/64`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1011_0010u8; /// let s = 0b1011_0010u8; /// assert_eq!(n.reverse_bytes(), s); /// assert_eq!(n.swap_bytes(), s); /// /// let n1 = 0b1011_0010_1010_1001u16; /// let s1 = 0b1010_1001_1011_0010u16; /// assert_eq!(n1.reverse_bytes(), s1); /// assert_eq!(n1.swap_bytes(), s1); /// ``` fn reverse_bytes(self) -> Self { self.swap_bytes() } /// Sets the `bit` of `self`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1011_0010u8; /// let s0 = 0b1111_0010u8; /// let s1 = 0b1011_0011u8; /// let s2 = 0b1011_1010u8; /// assert_eq!(n.set_bit(6), s0); /// assert_eq!(n.set_bit(0), s1); /// assert_eq!(n.set_bit(3), s2); /// ``` fn set_bit(self, bit: u32) -> Self { debug_assert!((bit as usize) < Self::bit_size()); self | (Self::one() << bit) } /// Sets the `bit` of `self` to `value`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1001_0011u8; /// assert_eq!(n.set_bit_to(6, true), 0b1101_0011u8); /// assert_eq!(n.set_bit_to(0, false), 0b1001_0010u8); /// assert_eq!(n.set_bit_to(3, true), 0b1001_1011u8); /// ``` fn set_bit_to(self, bit: u32, value: bool) -> Self; /// Clears the `bit` of `self`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1011_0010u8; /// let s0 = 0b0011_0010u8; /// let s1 = 0b1011_0000u8; /// let s2 = 0b1001_0010u8; /// assert_eq!(n.clear_bit(7), s0); /// assert_eq!(n.clear_bit(1), s1); /// assert_eq!(n.clear_bit(5), s2); /// ``` fn clear_bit(self, bit: u32) -> Self { debug_assert!((bit as usize) < Self::bit_size()); self & !(Self::one() << bit) } /// Flip the `bit` of `self`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1011_0010u8; /// let s0 = 0b0011_0010u8; /// let s1 = 0b1111_0010u8; /// let s2 = 0b1001_0010u8; /// assert_eq!(n.flip_bit(7), s0); /// assert_eq!(n.flip_bit(6), s1); /// assert_eq!(n.flip_bit(5), s2); /// ``` fn flip_bit(self, bit: u32) -> Self { debug_assert!((bit as usize) < Self::bit_size()); self ^ (Self::one() << bit) } /// Test the `bit` of `self`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1011_0010u8; /// assert_eq!(n.test_bit(7), true); /// assert_eq!(n.test_bit(6), false); /// assert_eq!(n.test_bit(5), true); /// ``` fn test_bit(self, bit: u32) -> bool { debug_assert!((bit as usize) < Self::bit_size()); self & (Self::one() << bit) != Self::zero() } /// Clears all bits of `self` at position >= `bit`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Intrinsics: /// - BMI 2.0: bzhi. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1111_0010u8; /// let s = 0b0001_0010u8; /// assert_eq!(n.clear_bits_geq(5), s); /// ``` fn clear_bits_geq(self, bit: u32) -> Self; /// Clears all bits of `self` at position <= `bit`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1111_0010u8; /// let s = 0b1100_0000u8; /// assert_eq!(n.clear_bits_leq(5), s); /// ``` fn clear_bits_leq(self, bit: u32) -> Self { debug_assert!((bit as usize) < Self::bit_size()); self & !((Self::one() << (bit + 1)) - Self::one()) } /// Sets all bits of `self` at position >= `bit`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1000_0010u8; /// let s = 0b1110_0010u8; /// assert_eq!(n.set_bits_geq(5), s); /// ``` fn set_bits_geq(self, bit: u32) -> Self { debug_assert!((bit as usize) < Self::bit_size()); self | !((Self::one() << bit) - Self::one()) } /// Sets all bits of `self` at position <= `bit`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1000_0010u8; /// let s = 0b1011_1111u8; /// assert_eq!(n.set_bits_leq(5), s); /// ``` fn set_bits_leq(self, bit: u32) -> Self { debug_assert!((bit as usize) < Self::bit_size()); self | ((Self::one() << (bit + 1)) - Self::one()) } /// Flip all bits of `self` at position >= `bit`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1001_0010u8; /// let s = 0b0111_0010u8; /// assert_eq!(n.flip_bits_geq(5), s); /// ``` fn flip_bits_geq(self, bit: u32) -> Self { debug_assert!((bit as usize) < Self::bit_size()); self ^ !((Self::one() << bit) - Self::one()) } /// Flip all bits of `self` at position <= `bit`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1011_0010u8; /// let s = 0b1000_1101u8; /// assert_eq!(n.flip_bits_leq(5), s); /// ``` fn flip_bits_leq(self, bit: u32) -> Self { debug_assert!((bit as usize) < Self::bit_size()); self ^ ((Self::one() << (bit + 1)) - Self::one() ) } /// Is `self` a power of 2. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert!(2.is_pow2()); /// assert!(!3.is_pow2()); /// assert!(4.is_pow2()); /// assert!(!5.is_pow2()); /// assert!(!6.is_pow2()); /// assert!(!7.is_pow2()); /// assert!(8.is_pow2()); /// ``` fn is_pow2(self) -> bool { self > Self::zero() && ((self & (self - Self::one())) == Self::zero()) } /// Round `self` to the next power of 2. /// /// # Panics /// /// If the next power of 2 cannot be represented by Self. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!(2.ceil_pow2(), 2); /// assert_eq!(3.ceil_pow2(), 4); /// assert_eq!(4.ceil_pow2(), 4); /// assert_eq!(5.ceil_pow2(), 8); /// assert_eq!(6.ceil_pow2(), 8); /// assert_eq!(7.ceil_pow2(), 8); /// assert_eq!(8.ceil_pow2(), 8); /// assert_eq!(2u32.pow(30).ceil_pow2(), 2u32.pow(30)); /// assert_eq!((2u32.pow(30) + 1).ceil_pow2(), 2u32.pow(31)); /// assert_eq!(2u32.pow(31).ceil_pow2(), 2u32.pow(31)); /// // panics: /// // assert_eq!((2u32.pow(31) + 1).ceil_pow2(), 2u32.pow(32)); /// ``` fn ceil_pow2(self)-> Self { let mut x = self - Self::one(); let s = Self::size(); x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); if s > 1 { x = x | (x >> 8); if s > 2 { x = x | (x >> 16); if s > 4 { x = x | (x >> 32); } } } x + Self::one() } /// Round `self` to the previous power of 2. /// /// # Panics /// /// If `self <= 0`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!(2.floor_pow2(), 2); /// assert_eq!(3.floor_pow2(), 2); /// assert_eq!(4.floor_pow2(), 4); /// assert_eq!(5.floor_pow2(), 4); /// assert_eq!(6.floor_pow2(), 4); /// assert_eq!(7.floor_pow2(), 4); /// assert_eq!(8.floor_pow2(), 8); /// ``` fn floor_pow2(self) -> Self { debug_assert!(self > Self::zero()); let mut x = self; let s = Self::size(); x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); if s > 1 { x = x | (x >> 8); if s > 2 { x = x | (x >> 16); if s > 4 { x = x | (x >> 32); } } } x - (x >> 1) } /// Average without overflow (rounds to the smallest value). /// /// # Example /// ``` /// use bitwise::Word; /// /// // The following would overflow: /// let a = u64::max_value() / 2; /// let b = a + 1; /// let result = u64::max_value() / 2; /// assert_eq!(<u64 as Word>::average_floor(a, b), result); /// assert_eq!(<u64 as Word>::average_floor(b, a), result); /// /// ``` fn average_floor(x: Self, y: Self) -> Self { (x & y) + ((x ^ y) >> 1) } /// Average without overflow (rounds to the largest value). /// /// # Example /// ``` /// use bitwise::Word; /// /// // The following would overflow: /// let a = u64::max_value() / 2 + 1; /// let b = a - 1; /// let result = u64::max_value() / 2 + 1; /// assert_eq!(<u64 as Word>::average_ceil(a, b), result); /// assert_eq!(<u64 as Word>::average_ceil(b, a), result); /// /// ``` fn average_ceil(x: Self, y: Self) -> Self { (x | y) - ((x ^ y) >> 1) } /// Is `self` aligned to `alignment` bytes. /// /// Returns true if `self == 0` or `self` is a multiple of `alignment`. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert!(2.is_aligned(1)); /// assert!(2.is_aligned(2)); /// assert!(!2.is_aligned(4)); /// assert!(!2.is_aligned(8)); /// /// assert!(3.is_aligned(1)); /// assert!(!3.is_aligned(2)); /// assert!(!3.is_aligned(4)); /// assert!(!3.is_aligned(8)); /// /// assert!(4.is_aligned(1)); /// assert!(4.is_aligned(2)); /// assert!(4.is_aligned(4)); /// assert!(!4.is_aligned(8)); /// ``` fn is_aligned(self, alignment: u32) -> bool; /// Align `self` up to `alignment`. /// /// Returns `n`, where `n` is the least number >= `self` /// and `is_aligned(n, alignment)`. /// /// # Panics /// /// `alignment` must be a power of two. which is asserted in debug /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!(2.align_up(1), 2); /// assert_eq!(2.align_up(2), 2); /// assert_eq!(2.align_up(4), 4); /// assert_eq!(2.align_up(8), 8); /// /// assert_eq!(3.align_up(1), 3); /// assert_eq!(3.align_up(2), 4); /// assert_eq!(3.align_up(4), 4); /// assert_eq!(3.align_up(8), 8); /// /// assert_eq!(4.align_up(1), 4); /// assert_eq!(4.align_up(2), 4); /// assert_eq!(4.align_up(4), 4); /// assert_eq!(4.align_up(8), 8); /// ``` fn align_up(self, alignment: u32) -> Self; /// Align `self` down to `alignment`. /// /// Returns `n`, where `n` is the greatest number <= `self` /// and `is_aligned(n, alignment)`. /// /// # Panics /// /// `alignment` must be a power of two. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// assert_eq!(2.align_down(1), 2); /// assert_eq!(2.align_down(2), 2); /// assert_eq!(2.align_down(4), 0); /// assert_eq!(2.align_down(8), 0); /// /// assert_eq!(3.align_down(1), 3); /// assert_eq!(3.align_down(2), 2); /// assert_eq!(3.align_down(4), 0); /// assert_eq!(3.align_down(8), 0); /// /// assert_eq!(4.align_down(1), 4); /// assert_eq!(4.align_down(2), 4); /// assert_eq!(4.align_down(4), 4); /// assert_eq!(4.align_down(8), 0); /// ``` fn align_down(self, alignment: u32) -> Self; /// Outer Perfect Shuffle of `self`. /// /// See also: /// [Hacker's Delight: shuffling bits](http://icodeguru.com/Embedded/Hacker's-Delight/047.htm). /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0110_0101_1101_1011_1111_1001_0110_0011u32; /// // abcd efgh ijkl mnop ABCD EFGH IJKL MNOP, /// let s = 0b0111_1101_0110_0011_1011_0110_1000_1111u32; /// // aAbB cCdD eEfF gGhH iIjJ kKlL mMnN oOpP, /// /// assert_eq!(n.outer_perfect_shuffle(), s); /// ``` fn outer_perfect_shuffle(self) -> Self; /// Outer Perfect Unshuffle of `self`. /// /// See also: /// [Hacker's Delight: shuffling bits](http://icodeguru.com/Embedded/Hacker's-Delight/047.htm). /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0111_1101_0110_0011_1011_0110_1000_1111u32; /// // aAbB cCdD eEfF gGhH iIjJ kKlL mMnN oOpP, /// let s = 0b0110_0101_1101_1011_1111_1001_0110_0011u32; /// // abcd efgh ijkl mnop ABCD EFGH IJKL MNOP, /// /// assert_eq!(n.outer_perfect_unshuffle(), s); /// ``` fn outer_perfect_unshuffle(self) -> Self; /// Inner Perfect Shuffle of `self`. /// /// See also: /// [Hacker's Delight: shuffling bits](http://icodeguru.com/Embedded/Hacker's-Delight/047.htm). /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b0110_0101_1101_1011_1111_1001_0110_0011u32; /// // abcd efgh ijkl mnop ABCD EFGH IJKL MNOP, /// let s = 0b1011_1110_1001_0011_0111_1001_0100_1111u32; /// // AaBb CcDd EeFf GgHh IiJj KkLl MmNn OoPp /// /// assert_eq!(n.inner_perfect_shuffle(), s); /// ``` fn inner_perfect_shuffle(self) -> Self { let hwb = Self::size() * 8 / 2; self.reverse_bit_groups(hwb as u32, 1).outer_perfect_shuffle() } /// Inner Perfect Unshuffle of `self`. /// /// See also: /// [Hacker's Delight: shuffling bits](http://icodeguru.com/Embedded/Hacker's-Delight/047.htm). /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1011_1110_1001_0011_0111_1001_0100_1111u32; /// // AaBb CcDd EeFf GgHh IiJj KkLl MmNn OoPp /// let s = 0b0110_0101_1101_1011_1111_1001_0110_0011u32; /// // abcd efgh ijkl mnop ABCD EFGH IJKL MNOP, /// /// assert_eq!(n.inner_perfect_unshuffle(), s); /// ``` fn inner_perfect_unshuffle(self) -> Self { let hwb = Self::size() * 8 / 2; self.outer_perfect_unshuffle().reverse_bit_groups(hwb as u32, 1) } /// Scatter the low-ordr bits of self into the positions of the result selected /// by the `mask`. /// /// The contiguous low-order bits of `self` are to be copied to the bits of the /// destination selected by the `mask`. in the destination. The bits nothing was /// copied to are cleared. /// /// # Keywords: /// /// Parallel bits deposit, scatter. /// /// Scatter. /// /// # Intrinsics: /// - BMI 2.0: pdep. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1011_1110_1001_0011u16; /// /// let m0 = 0b0110_0011_1000_0101u16; /// let s0 = 0b0000_0010_0000_0101u16; /// /// let m1 = 0b1110_1011_1110_1111u16; /// let s1 = 0b1110_1001_0010_0011u16; /// /// assert_eq!(n.scatter_bits(m0), s0); /// assert_eq!(n.scatter_bits(m1), s1); /// /// // The following examples are from Wikipedia: /// let w = 0b1101_0101u8; /// // abcd efgh /// /// assert_eq!(w.scatter_bits(0b1111_0000u8), 0b0101_0000u8); /// // efgh ____ efgh ____ /// assert_eq!(w.scatter_bits(0b1111_1100u8), 0b0101_0100u8); /// // cdef gh__ cdef gh__ /// assert_eq!(w.scatter_bits(0b0101_0101u8), 0b0001_0001u8); /// // _e_f _g_h _e_f _g_h /// assert_eq!(w.scatter_bits(0b1101_1101u8), 0b0100_1001u8); /// // cd_e fg_h cd_e fg_h /// assert_eq!(w.scatter_bits(0b0001_1111u8), 0b0001_0101u8); /// // ___d efgh ___d efgh /// ``` fn scatter_bits(self, mask_: Self) -> Self; /// Gather the bits of `self` selected by the `mask` into the low-order bits of /// the result. /// /// The bits from `self` selected by the `mask` are copied into the contiguous /// low order bits of the destination. High-order bits of the destination are /// cleared. /// /// # Keywords: /// /// Gather bits, parallel bits extract. /// /// # Intrinsics: /// - BMI 2.0: pext. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1011_1110_1001_0011u16; /// /// let m0 = 0b0110_0011_1000_0101u16; /// let s0 = 0b0000_0000_0011_0101u16; /// /// let m1 = 0b1110_1011_1110_1111u16; /// let s1 = 0b0001_0111_0100_0011u16; /// /// assert_eq!(n.gather_bits(m0), s0); /// assert_eq!(n.gather_bits(m1), s1); /// /// // The following examples are from Wikipedia: /// let w = 0b1101_0101u8; /// // abcd efgh /// /// assert_eq!(w.gather_bits(0b1111_0000u8), 0b0000_1101u8); /// // abcd ____ ____ abcd /// assert_eq!(w.gather_bits(0b1111_1100u8), 0b0011_0101u8); /// // abcd ef__ __ab cdef /// assert_eq!(w.gather_bits(0b0101_0101u8), 0b0000_1111u8); /// // _b_d _f_h ____ bdfh /// assert_eq!(w.gather_bits(0b1101_1101u8), 0b0011_1011u8); /// // ab_d ef_h __ab defh /// assert_eq!(w.gather_bits(0b0001_1111u8), 0b0001_0101u8); /// // ___d efgh ___d efgh /// ``` fn gather_bits(self, mask_: Self) -> Self; /// Gathers the contiguous low-order bits of `self` in range `[first, /// first+length]` into the low-order bits of the result. /// /// The range increases from low-order to high-order bits, is zero-indexed, /// and closed. /// /// # Keywords: /// /// Extract bit range. /// /// # Panics /// /// If `first + length >= bit_size()`. /// /// # Intrinsics: /// - BMI 2.0: bextr. /// /// # Examples /// /// ``` /// use bitwise::Word; /// /// let n = 0b1011_1110_1001_0011u16; /// // abcd efgh ijkl mnop /// /// assert_eq!(n.gather_bit_range(2, 6), 0b0000_0000_0010_0100u16); /// // [2, 8] => [n, i] ____ ____ __ij klmn /// /// ``` fn gather_bit_range(self, first: u32, length: u32) -> Self; /// Encode coordinates `x` into an interleaved Morton index for a Z-Curve. /// /// Layout: `xy|xy|xy|xy|...` . /// /// # Example /// ``` /// use bitwise::Word; /// /// let idx : u64 = 30; /// assert_eq!(idx, 0b01_11_10); /// /// let x = idx.morton_decode_2d(); /// /// assert!(Word::morton_encode_2d(x) == idx); /// /// assert_eq!(x[0], 0b_110); /// assert_eq!(x[1], 0b_011); /// /// ``` fn morton_encode_2d(x: [Self; 2]) -> Self; /// Encode coordinates `x` into an interleaved Morton index for a Z-Curve. /// /// Layout: `xyz|xyz|xyz|xyz|...` . /// /// # Example /// ``` /// use bitwise::Word; /// /// let idx : u64 = 30; /// assert_eq!(idx, 0b011_110); /// /// let x = idx.morton_decode_3d(); /// /// assert!(Word::morton_encode_3d(x) == idx); /// /// assert_eq!(x[0], 0b10); /// assert_eq!(x[1], 0b11); /// assert_eq!(x[2], 0b01); /// /// ``` fn morton_encode_3d(x: [Self; 3]) -> Self; /// Decode interleaved Morton index for a Z-Curve into coordinates. /// /// See [`morton_encode_2d`](#tymethod.morton_encode_2d). fn morton_decode_2d(self) -> [Self; 2]; /// Decode interleaved Morton index for a Z-Curve into coordinates. /// /// See [`morton_encode_3d`](#tymethod.morton_encode_3d). fn morton_decode_3d(self) -> [Self; 3]; } macro_rules! bitwise_word_impl { ($T:ty, $AS:ty, $AU:ty) => ( impl Word for $T { type Signed = $AS; type Unsigned = $AU; fn size() -> usize { mem::size_of::<$T>() } fn to_unsigned(self) -> $AU { self as $AU } fn to_signed(self) -> $AS { self as $AS } fn zero() -> $T { 0 as $T } fn leading_zeros(self) -> usize { <$T>::leading_zeros(self) as usize } // TODO: calling the intrinsic is broken since rustc does not seem // to propagate the constant to LLVM directly. #[cfg(all(not(feature = "bmi1x"), not(feature = "bmi2x")))] fn trailing_zeros(self) -> usize { <$T>::trailing_zeros(self) as usize } #[cfg(any(feature = "bmi1x", feature = "bmi2x"))] fn trailing_zeros(self) -> usize { // llvmint::cttz_iX(iX, is_zero_undef_flag), where the flag // indicates whether zero should produce a consistent result // (false => bit_size) or not (true). match <Self as Word>::bit_size() { 8 => unsafe { llvmint::cttz_i8(self as i8, false) as usize }, 16 => unsafe { llvmint::cttz_i16(self as i16, false) as usize }, 32 => unsafe { llvmint::cttz_i32(self as i32, false) as usize }, 64 => unsafe { llvmint::cttz_i64(self as i64, false) as usize }, _ => unreachable!() } } fn count_ones(self) -> usize { <$T>::count_ones(self) as usize } fn count_zeros(self) -> usize { <$T>::count_zeros(self) as usize } fn one() -> $T { 1 as $T } fn two() -> $T { 2 as $T } fn shift_logical_left(self, n: u32) -> Self { debug_assert!(n as usize <= <Self as Word>::bit_size()); (self.to_unsigned() << n) as Self } fn shift_logical_right(self, n: u32) -> Self { debug_assert!(n as usize <= <Self as Word>::bit_size()); (self.to_unsigned() >> n) as Self } fn shift_arithmetic_left(self, n: u32) -> Self { debug_assert!(n as usize <= <Self as Word>::bit_size()); self.shift_logical_left(n) } fn shift_arithmetic_right(self, n: u32) -> Self { debug_assert!(n as usize <= <Self as Word>::bit_size()); (self.to_signed() >> n) as Self } fn rotate_left(self, n: u32) -> Self { debug_assert!(n as usize <= <Self as Word>::bit_size()); <$T>::rotate_left(self, n) } fn rotate_right(self, n: u32) -> Self { debug_assert!(n as usize <= <Self as Word>::bit_size()); <$T>::rotate_right(self, n) } fn swap_bytes(self) -> Self { <$T>::swap_bytes(self) } fn from_be(x: Self) -> Self { <$T>::from_be(x) } fn from_le(x: Self) -> Self { <$T>::from_le(x) } fn to_be(self) -> Self { <$T>::to_be(self) } fn to_le(self) -> Self { <$T>::to_le(self) } fn pow(self, exp: u32) -> Self { <$T>::pow(self, exp) } fn set_bit_to(self, bit: u32, value: bool) -> Self { debug_assert!((bit as usize) < Self::bit_size()); self & !(1 << bit) | ((value as Self) << bit) } fn reverse_bit_groups(self, subword_bits: u32, group_subwords: u32) -> Self { // Adapted from Matthew Fioravante's stdcxx-bitops, which // is released under the MIT's License here: // https://github.com/fmatthew5876/stdcxx-bitops let mut x: Self::Unsigned = self.to_unsigned(); let width: u32 = <Self as Word>::size() as u32; let group_sz: u32 = width * 8 / group_subwords; let k: u32 = group_sz - subword_bits; { let mut up0 = |i: u32, l: u64, r: u64| { if k & i > 0 { x = ((x & (l as Self::Unsigned)) << (i as Self::Unsigned)) | ((x & (r as Self::Unsigned)) >> (i as Self::Unsigned)); } }; up0(1, 0x5555555555555555u64, 0xAAAAAAAAAAAAAAAAu64); up0(2, 0x3333333333333333u64, 0xCCCCCCCCCCCCCCCCu64); up0(4, 0x0F0F0F0F0F0F0F0Fu64, 0xF0F0F0F0F0F0F0F0u64); } { let mut up1 = |i: u32, s: u32, l: u64, r: u64| { if width > i && (k & s > 0) { x = ((x & (l as Self::Unsigned)) << (s as Self::Unsigned)) | ((x & (r as Self::Unsigned)) >> (s as Self::Unsigned)); } }; up1(1, 8, 0x00FF00FF00FF00FFu64, 0xFF00FF00FF00FF00u64); up1(2, 16, 0x0000FFFF0000FFFFu64, 0xFFFF0000FFFF0000u64); up1(4, 32, 0x00000000FFFFFFFFu64, 0xFFFFFFFF00000000u64); } x as Self } fn align_up(self, alignment: u32) -> Self { debug_assert!(alignment.is_pow2()); let x = self.to_unsigned(); let a = alignment as Self::Unsigned; ((x + (a - 1)) & !(a - 1)) as Self } fn align_down(self, alignment: u32) -> Self { debug_assert!(alignment.is_pow2()); self & (!(alignment - 1) as Self) } #[allow(exceeding_bitshifts)] fn outer_perfect_shuffle(self) -> Self { let mut x = self; let mut t; let s = <Self as Word>::size(); if s > 4 { t = (x ^ (x >> 16)) & 0x00000000FFFF0000u64 as Self; x = x ^ t ^ (t << 16); } if s > 2 { t = (x ^ (x >> 8)) & 0x0000FF000000FF00u64 as Self; x = x ^ t ^ (t << 8); } if s > 1 { t = (x ^ (x >> 4)) & 0x00F000F000F000F0u64 as Self; x = x ^ t ^ (t << 4); } t = (x ^ (x >> 2)) & 0x0C0C0C0C0C0C0C0Cu64 as Self; x = x ^ t ^ (t << 2); t = (x ^ (x >> 1)) & 0x2222222222222222u64 as Self; x = x ^ t ^ (t << 1); x } #[allow(exceeding_bitshifts)] fn outer_perfect_unshuffle(self) -> Self { let mut x = self; let s = <Self as Word>::size(); let mut t = (x ^ (x >> 1)) & (0x2222222222222222u64 as Self); x = x ^ t ^ (t << 1); t = (x ^ (x >> 2)) & (0x0C0C0C0C0C0C0C0Cu64 as Self); x = x ^ t ^ (t << 2); if s > 1 { t = (x ^ (x >> 4)) & (0x00F000F000F000F0u64 as Self); x = x ^ t ^ (t << 4); } if s > 2 { t = (x ^ (x >> 8)) & (0x0000FF000000FF00u64 as Self); x = x ^ t ^ (t << 8); } if s > 4 { t = (x ^ (x >> 16)) & (0x00000000FFFF0000u64 as Self); x = x ^ t ^ (t << 16); } x } fn is_aligned(self, alignment: u32) -> bool { debug_assert!(alignment as i32 - 1 >= 0); (self & ((alignment - 1) as Self)) == Self::zero() } #[cfg(not(feature = "bmi2"))] fn clear_bits_geq(self, bit: u32) -> Self { debug_assert!((bit as usize) < Self::bit_size()); self & ((Self::one() << bit) - Self::one()) } #[cfg(feature = "bmi2")] fn clear_bits_geq(self, bit: u32) -> Self { debug_assert!((bit as usize) < Self::bit_size()); match Self::bit_size() { 0...32 => unsafe { llvmint::x86::bmi_bzhi_32(self as i32, bit as i32) as Self }, 64 => unsafe { llvmint::x86::bmi_bzhi_64(self as i64, bit as i64) as Self }, _ => unreachable!() } } #[cfg(not(feature = "bmi2"))] fn scatter_bits(self, mask_: Self) -> Self { let mut res = Self::zero(); let mut mask = mask_; let mut bb = Self::one(); loop { if mask == Self::zero() { break; } if (self & bb) != Self::zero() { res |= mask & mask.wrapping_neg(); } mask &= mask - Self::one(); bb += bb; } res } #[cfg(not(feature = "bmi2"))] fn gather_bits(self, mask_: Self) -> Self { let mut res = Self::zero(); let mut mask = mask_; let mut bb = Self::one(); loop { if mask == Self::zero() { break; } if self & mask & (mask.wrapping_neg()) != Self::zero() { res |= bb; } mask &= mask - Self::one(); bb += bb; } res } #[cfg(feature = "bmi2")] fn scatter_bits(self, mask_: Self) -> Self { match <Self as Word>::bit_size() { // TODO: benchmark: for 8/16 bytes it is probably faster // to up cast and use the intrinsic but should test this. 0...32 => unsafe { llvmint::x86::bmi_pdep_32(self as i32, mask_ as i32) as Self }, 64 => unsafe { llvmint::x86::bmi_pdep_64(self as i64, mask_ as i64) as Self }, _ => unreachable!() } } #[cfg(feature = "bmi2")] fn gather_bits(self, mask_: Self) -> Self { match <Self as Word>::bit_size() { 0...32 => unsafe { llvmint::x86::bmi_pext_32(self as i32, mask_ as i32) as Self }, 64 => unsafe { llvmint::x86::bmi_pext_64(self as i64, mask_ as i64) as Self }, _ => unreachable!() } } #[cfg(not(feature = "bmi2"))] fn gather_bit_range(self, first: u32, length: u32) -> Self { debug_assert!(((first + length) as usize) < Self::bit_size()); (self >> first) & ((Self::one() << length as Self)- Self::one()) } #[cfg(feature = "bmi2")] fn gather_bit_range(self, first: u32, length: u32) -> Self { debug_assert!(((first + length) as usize) < Self::bit_size()); // Bits [7:0] specify the index, bits [15:8] specify the number // of bits to be extracted. let rng = (first & 0xff) | ((length & 0xff) << 8); match <Self as Word>::bit_size() { 0...32 => unsafe { llvmint::x86::bmi_bextr_32(self as i32, rng as i32) as Self }, 64 => unsafe { llvmint::x86::bmi_bextr_64(self as i64, rng as i64) as Self }, _ => unreachable!() } } fn morton_encode_2d(x: [Self; 2]) -> Self { Self::scatter_bits(x[1], 0xAAAAAAAAAAAAAAAAu64 as Self) | Self::scatter_bits(x[0], 0x5555555555555555u64 as Self) } fn morton_encode_3d(x: [Self; 3]) -> Self { Self::scatter_bits(x[2], 0x4924924924924924u64 as Self) | Self::scatter_bits(x[1], 0x2492492492492492u64 as Self) | Self::scatter_bits(x[0], 0x9249249249249249u64 as Self) } fn morton_decode_2d(self) -> [Self; 2] { [ self.gather_bits(0x5555555555555555u64 as Self), self.gather_bits(0xAAAAAAAAAAAAAAAAu64 as Self) ] } fn morton_decode_3d(self) -> [Self; 3] { [ self.gather_bits(0x9249249249249249u64 as Self), self.gather_bits(0x2492492492492492u64 as Self), self.gather_bits(0x4924924924924924u64 as Self) ] } } ) } bitwise_word_impl!(u8, i8, u8); bitwise_word_impl!(u16, i16, u16); bitwise_word_impl!(u32, i32, u32); bitwise_word_impl!(u64, i64, u64); bitwise_word_impl!(usize, isize, usize); bitwise_word_impl!(i8, i8, u8); bitwise_word_impl!(i16, i16, u16); bitwise_word_impl!(i32, i32, u32); bitwise_word_impl!(i64, i64, u64); bitwise_word_impl!(isize, isize, usize); /// Bitwise manimpulation algorithms for sequences of `Words`. /// /// Note: this trait is not supposed to be implemented by library users. The /// distinction between functionality required and inherited has been /// arbitrarily placed at the boundary between "what is easier to implement /// within the trait" and "what is easier to implement with a macro" for the /// primitive integer types. pub trait Words { /// Returns the number of ones in the binary representation of `self`. /// /// # Examples /// /// ``` /// use bitwise::Words; /// /// let n = 0b0100_1100u8; /// /// assert_eq!(n.count_ones(), 3); /// /// let ns0 = [0u8, 1u8, 0b0100_1100u8]; /// let ns1 = [1u64, 0u64, 0b0100_1100u64]; /// /// assert_eq!(ns0.count_ones(), 4); /// assert_eq!(ns1.count_ones(), 4); /// ``` fn count_ones(&self) -> usize; /// Returns the number of zeros in the binary representation of `self`. /// /// # Examples /// /// ``` /// use bitwise::Words; /// /// let n = 0b0100_1100u8; /// /// assert_eq!(n.count_zeros(), 5); /// /// let ns = [0u8, 1u8, 0b0100_1100u8]; /// /// assert_eq!(ns.count_zeros(), 8 + 7 + 5); /// ``` fn count_zeros(&self) -> usize; /// Returns the number of leading zeros in the binary representation of /// `self`. /// /// # Examples /// /// ``` /// use bitwise::Words; /// /// let n = 0b0010_1000u16; /// /// assert_eq!(n.leading_zeros(), 10); /// /// let ns = [0u8, 0b0010_1000u8, 1u8]; /// /// assert_eq!(ns.leading_zeros(), 10); /// ``` fn leading_zeros(&self) -> usize; /// Size of the word sequence. fn size(&self) -> usize; } impl<T: Word> Words for T { fn size(&self) -> usize { <Self as Word>::size() as usize } fn count_ones(&self) -> usize { <Self as Word>::count_ones(*self) as usize } fn count_zeros(&self) -> usize { <Self as Word>::count_zeros(*self) as usize } fn leading_zeros(&self) -> usize { <Self as Word>::leading_zeros(*self) as usize } } impl<T: Words> Words for [T] { fn size(&self) -> usize { self.iter().fold(0usize, |sum, i| sum + i.size()) } fn count_ones(&self) -> usize { self.iter().fold(0usize, |sum, i| sum + i.count_ones()) } fn count_zeros(&self) -> usize { self.iter().fold(0usize, |sum, i| sum + i.count_zeros()) } fn leading_zeros(&self) -> usize { // TODO: transmute into the largest possible word size and count leading // zeros on that, e.g., given [u32; 5] // => [u64; 2].leading_zeros() ?+ [u32; 1].leading_zeros() let mut sum: usize = 0; for i in self { let tmp: usize = i.leading_zeros(); sum += tmp; if tmp != i.size() * 8 { break; } } sum } }