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
//! Module containing integer aritimetic methods closely following the Rust
//! standard library API for `uN` types.
use super::U256;
use crate::{intrinsics, I256};
use core::{
mem::{self, MaybeUninit},
num::ParseIntError,
};
impl U256 {
/// The smallest value that can be represented by this integer type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::MIN, U256::new(0));
/// ```
pub const MIN: Self = Self([0; 2]);
/// The largest value that can be represented by this integer type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(
/// U256::MAX.to_string(),
/// "115792089237316195423570985008687907853269984665640564039457584007913129639935",
/// );
/// ```
pub const MAX: Self = Self([!0; 2]);
/// The size of this integer type in bits.
///
/// # Examples
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::BITS, 256);
/// ```
pub const BITS: u32 = 256;
/// Converts a string slice in a given base to an integer.
///
/// The string is expected to be an optional `+` sign followed by digits.
/// Leading and trailing whitespace represent an error. Digits are a subset
/// of these characters, depending on `radix`:
///
/// * `0-9`
/// * `a-z`
/// * `A-Z`
///
/// # Panics
///
/// This function panics if `radix` is not in the range from 2 to 36.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::from_str_radix("A", 16), Ok(U256::new(10)));
/// ```
#[inline]
pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
crate::parse::from_str_radix(src, radix, None)
}
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// let n = U256::new(0b01001100);
/// assert_eq!(n.count_ones(), 3);
/// ```
#[inline]
pub const fn count_ones(self) -> u32 {
let Self([a, b]) = self;
a.count_ones() + b.count_ones()
}
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::MIN.count_zeros(), 256);
/// assert_eq!(U256::MAX.count_zeros(), 0);
/// ```
#[inline]
pub const fn count_zeros(self) -> u32 {
let Self([a, b]) = self;
a.count_zeros() + b.count_zeros()
}
/// Returns the number of leading zeros in the binary representation of
/// `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// let n = U256::MAX >> 2u32;
/// assert_eq!(n.leading_zeros(), 2);
/// ```
#[inline(always)]
pub fn leading_zeros(self) -> u32 {
intrinsics::signed::uctlz(&self)
}
/// Returns the number of trailing zeros in the binary representation of
/// `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// let n = U256::new(0b0101000);
/// assert_eq!(n.trailing_zeros(), 3);
/// ```
#[inline(always)]
pub fn trailing_zeros(self) -> u32 {
intrinsics::signed::ucttz(&self)
}
/// Returns the number of leading ones in the binary representation of
/// `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// let n = !(U256::MAX >> 2u32);
/// assert_eq!(n.leading_ones(), 2);
/// ```
#[inline]
pub fn leading_ones(self) -> u32 {
(!self).leading_zeros()
}
/// Returns the number of trailing ones in the binary representation of
/// `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// let n = U256::new(0b1010111);
/// assert_eq!(n.trailing_ones(), 3);
/// ```
#[inline]
pub fn trailing_ones(self) -> u32 {
(!self).trailing_zeros()
}
/// Shifts the bits to the left by a specified amount, `n`, wrapping the
/// truncated bits to the end of the resulting integer.
///
/// Please note this isn't the same operation as the `<<` shifting
/// operator!
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// let n = U256::from_words(
/// 0x13f40000000000000000000000000000,
/// 0x00000000000000000000000000004f76,
/// );
/// let m = U256::new(0x4f7613f4);
/// assert_eq!(n.rotate_left(16), m);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn rotate_left(self, n: u32) -> Self {
let mut r = MaybeUninit::uninit();
intrinsics::signed::urol3(&mut r, &self, n);
unsafe { r.assume_init() }
}
/// Shifts the bits to the right by a specified amount, `n`, wrapping the
/// truncated bits to the beginning of the resulting integer.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// let n = U256::new(0x4f7613f4);
/// let m = U256::from_words(
/// 0x13f40000000000000000000000000000,
/// 0x00000000000000000000000000004f76,
/// );
///
/// assert_eq!(n.rotate_right(16), m);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn rotate_right(self, n: u32) -> Self {
let mut r = MaybeUninit::uninit();
intrinsics::signed::uror3(&mut r, &self, n);
unsafe { r.assume_init() }
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// let n = U256::from_words(
/// 0x00010203_04050607_08090a0b_0c0d0e0f,
/// 0x10111213_14151617_18191a1b_1c1d1e1f,
/// );
/// assert_eq!(
/// n.swap_bytes(),
/// U256::from_words(
/// 0x1f1e1d1c_1b1a1918_17161514_13121110,
/// 0x0f0e0d0c_0b0a0908_07060504_03020100,
/// ),
/// );
/// ```
#[inline]
pub const fn swap_bytes(self) -> Self {
let Self([a, b]) = self;
Self([b.swap_bytes(), a.swap_bytes()])
}
/// Reverses the bit pattern of the integer.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// let n = U256::from_words(
/// 0x00010203_04050607_08090a0b_0c0d0e0f,
/// 0x10111213_14151617_18191a1b_1c1d1e1f,
/// );
/// assert_eq!(
/// n.reverse_bits(),
/// U256::from_words(
/// 0xf878b838_d8589818_e868a828_c8488808,
/// 0xf070b030_d0509010_e060a020_c0408000,
/// ),
/// );
/// ```
#[inline]
pub const fn reverse_bits(self) -> Self {
let Self([a, b]) = self;
Self([b.reverse_bits(), a.reverse_bits()])
}
/// Converts 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
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// let n = U256::new(0x1A);
/// if cfg!(target_endian = "big") {
/// assert_eq!(U256::from_be(n), n);
/// } else {
/// assert_eq!(U256::from_be(n), n.swap_bytes());
/// }
/// ```
#[inline(always)]
#[allow(clippy::wrong_self_convention)]
pub const fn from_be(x: Self) -> Self {
#[cfg(target_endian = "big")]
{
x
}
#[cfg(not(target_endian = "big"))]
{
x.swap_bytes()
}
}
/// Converts 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
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// let n = U256::new(0x1A);
/// if cfg!(target_endian = "little") {
/// assert_eq!(U256::from_le(n), n)
/// } else {
/// assert_eq!(U256::from_le(n), n.swap_bytes())
/// }
/// ```
#[inline(always)]
#[allow(clippy::wrong_self_convention)]
pub const fn from_le(x: Self) -> Self {
#[cfg(target_endian = "little")]
{
x
}
#[cfg(not(target_endian = "little"))]
{
x.swap_bytes()
}
}
/// Converts `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
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// let n = U256::new(0x1A);
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[inline(always)]
pub const fn to_be(self) -> Self {
#[cfg(target_endian = "big")]
{
self
}
#[cfg(not(target_endian = "big"))]
{
self.swap_bytes()
}
}
/// Converts `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
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// let n = U256::new(0x1A);
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[inline(always)]
pub const fn to_le(self) -> Self {
#[cfg(target_endian = "little")]
{
self
}
#[cfg(not(target_endian = "little"))]
{
self.swap_bytes()
}
}
/// Checked integer addition. Computes `self + rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!((U256::MAX - 2).checked_add(U256::new(1)), Some(U256::MAX - 1));
/// assert_eq!((U256::MAX - 2).checked_add(U256::new(3)), None);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if b {
None
} else {
Some(a)
}
}
/// Checked addition with a signed integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::{I256, U256};
/// assert_eq!(U256::new(1).checked_add_signed(I256::new(2)), Some(U256::new(3)));
/// assert_eq!(U256::new(1).checked_add_signed(I256::new(-2)), None);
/// assert_eq!((U256::MAX - 2).checked_add_signed(I256::new(3)), None);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn checked_add_signed(self, rhs: I256) -> Option<Self> {
let (a, b) = self.overflowing_add_signed(rhs);
if b {
None
} else {
Some(a)
}
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(1).checked_sub(U256::new(1)), Some(U256::ZERO));
/// assert_eq!(U256::new(0).checked_sub(U256::new(1)), None);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if b {
None
} else {
Some(a)
}
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(5).checked_mul(U256::new(1)), Some(U256::new(5)));
/// assert_eq!(U256::MAX.checked_mul(U256::new(2)), None);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if b {
None
} else {
Some(a)
}
}
/// Checked integer division. Computes `self / rhs`, returning `None` if
/// `rhs == 0`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(128).checked_div(U256::new(2)), Some(U256::new(64)));
/// assert_eq!(U256::new(1).checked_div(U256::new(0)), None);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn checked_div(self, rhs: Self) -> Option<Self> {
if rhs == U256::ZERO {
None
} else {
Some(self / rhs)
}
}
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning
/// `None` if `rhs == 0`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(128).checked_div_euclid(U256::new(2)), Some(U256::new(64)));
/// assert_eq!(U256::new(1).checked_div_euclid(U256::new(0)), None);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if rhs == U256::ZERO {
None
} else {
Some(self.div_euclid(rhs))
}
}
/// Checked integer remainder. Computes `self % rhs`, returning `None` if
/// `rhs == 0`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(5).checked_rem(U256::new(2)), Some(U256::new(1)));
/// assert_eq!(U256::new(5).checked_rem(U256::new(0)), None);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn checked_rem(self, rhs: Self) -> Option<Self> {
if rhs == U256::ZERO {
None
} else {
Some(self % rhs)
}
}
/// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning
/// `None` if `rhs == 0`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(5).checked_rem_euclid(U256::new(2)), Some(U256::new(1)));
/// assert_eq!(U256::new(5).checked_rem_euclid(U256::new(0)), None);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if rhs == U256::ZERO {
None
} else {
Some(self.rem_euclid(rhs))
}
}
/// Checked negation. Computes `-self`, returning `None` unless `self == 0`.
///
/// Note that negating any positive integer will overflow.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::ZERO.checked_neg(), Some(U256::ZERO));
/// assert_eq!(U256::new(1).checked_neg(), None);
/// ```
#[inline]
pub fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if b {
None
} else {
Some(a)
}
}
/// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(0x1).checked_shl(4), Some(U256::new(0x10)));
/// assert_eq!(U256::new(0x10).checked_shl(257), None);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn checked_shl(self, rhs: u32) -> Option<Self> {
let (a, b) = self.overflowing_shl(rhs);
if b {
None
} else {
Some(a)
}
}
/// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs`
/// is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(0x10).checked_shr(4), Some(U256::new(0x1)));
/// assert_eq!(U256::new(0x10).checked_shr(257), None);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn checked_shr(self, rhs: u32) -> Option<Self> {
let (a, b) = self.overflowing_shr(rhs);
if b {
None
} else {
Some(a)
}
}
/// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(2).checked_pow(5), Some(U256::new(32)));
/// assert_eq!(U256::MAX.checked_pow(2), None);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc = U256::ONE;
while exp > 1 {
if (exp & 1) == 1 {
acc = acc.checked_mul(base)?;
}
exp /= 2;
base = base.checked_mul(base)?;
}
// Deal with the final bit of the exponent separately, since
// squaring the base afterwards is not necessary and may cause a
// needless overflow.
if exp == 1 {
acc = acc.checked_mul(base)?;
}
Some(acc)
}
/// Saturating integer addition. Computes `self + rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(100).saturating_add(U256::new(1)), U256::new(101));
/// assert_eq!(U256::MAX.saturating_add(U256::new(127)), U256::MAX);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn saturating_add(self, rhs: Self) -> Self {
self.checked_add(rhs).unwrap_or(U256::MAX)
}
/// Saturating addition with a signed integer. Computes `self + rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::{I256, U256};
/// assert_eq!(U256::new(1).saturating_add_signed(I256::new(2)), U256::new(3));
/// assert_eq!(U256::new(1).saturating_add_signed(I256::new(-2)), U256::new(0));
/// assert_eq!((U256::MAX - 2).saturating_add_signed(I256::new(4)), U256::MAX);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn saturating_add_signed(self, rhs: I256) -> Self {
let (res, overflow) = self.overflowing_add(rhs.as_u256());
if overflow == (rhs < 0) {
res
} else if overflow {
Self::MAX
} else {
Self::ZERO
}
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(100).saturating_sub(U256::new(27)), U256::new(73));
/// assert_eq!(U256::new(13).saturating_sub(U256::new(127)), U256::new(0));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn saturating_sub(self, rhs: Self) -> Self {
self.checked_sub(rhs).unwrap_or(U256::MIN)
}
/// Saturating integer multiplication. Computes `self * rhs`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(2).saturating_mul(U256::new(10)), U256::new(20));
/// assert_eq!((U256::MAX).saturating_mul(U256::new(10)), U256::MAX);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn saturating_mul(self, rhs: Self) -> Self {
match self.checked_mul(rhs) {
Some(x) => x,
None => Self::MAX,
}
}
/// Saturating integer division. Computes `self / rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(5).saturating_div(U256::new(2)), U256::new(2));
/// ```
///
/// ```should_panic
/// # use ethnum::U256;
/// let _ = U256::new(1).saturating_div(U256::ZERO);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn saturating_div(self, rhs: Self) -> Self {
// on unsigned types, there is no overflow in integer division
self.wrapping_div(rhs)
}
/// Saturating integer exponentiation. Computes `self.pow(exp)`, saturating
/// at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(4).saturating_pow(3), U256::new(64));
/// assert_eq!(U256::MAX.saturating_pow(2), U256::MAX);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None => Self::MAX,
}
}
/// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at
/// the boundary of the type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(200).wrapping_add(U256::new(55)), U256::new(255));
/// assert_eq!(U256::new(200).wrapping_add(U256::MAX), U256::new(199));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn wrapping_add(self, rhs: Self) -> Self {
let mut result = MaybeUninit::uninit();
intrinsics::signed::uadd3(&mut result, &self, &rhs);
unsafe { result.assume_init() }
}
/// Wrapping (modular) addition with a signed integer. Computes
/// `self + rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::{I256, U256};
/// assert_eq!(U256::new(1).wrapping_add_signed(I256::new(2)), U256::new(3));
/// assert_eq!(U256::new(1).wrapping_add_signed(I256::new(-2)), U256::MAX);
/// assert_eq!((U256::MAX - 2).wrapping_add_signed(I256::new(4)), U256::new(1));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn wrapping_add_signed(self, rhs: I256) -> Self {
self.wrapping_add(rhs.as_u256())
}
/// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around
/// at the boundary of the type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(100).wrapping_sub(U256::new(100)), U256::new(0));
/// assert_eq!(U256::new(100).wrapping_sub(U256::MAX), U256::new(101));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn wrapping_sub(self, rhs: Self) -> Self {
let mut result = MaybeUninit::uninit();
intrinsics::signed::usub3(&mut result, &self, &rhs);
unsafe { result.assume_init() }
}
/// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping
/// around at the boundary of the type.
///
/// # Examples
///
/// Basic usage:
///
/// Please note that this example is shared between integer types.
/// Which explains why `u8` is used here.
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(10).wrapping_mul(U256::new(12)), U256::new(120));
/// assert_eq!(U256::MAX.wrapping_mul(U256::new(2)), U256::MAX - 1);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn wrapping_mul(self, rhs: Self) -> Self {
let mut result = MaybeUninit::uninit();
intrinsics::signed::umul3(&mut result, &self, &rhs);
unsafe { result.assume_init() }
}
/// Wrapping (modular) division. Computes `self / rhs`. Wrapped division on
/// unsigned types is just normal division. There's no way wrapping could
/// ever happen. This function exists, so that all operations are accounted
/// for in the wrapping operations.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(100).wrapping_div(U256::new(10)), U256::new(10));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn wrapping_div(self, rhs: Self) -> Self {
self / rhs
}
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`. Wrapped
/// division on unsigned types is just normal division. There's no way
/// wrapping could ever happen. This function exists, so that all operations
/// are accounted for in the wrapping operations. Since, for the positive
/// integers, all common definitions of division are equal, this is exactly
/// equal to `self.wrapping_div(rhs)`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(100).wrapping_div_euclid(U256::new(10)), U256::new(10));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
self / rhs
}
/// Wrapping (modular) remainder. Computes `self % rhs`. Wrapped remainder
/// calculation on unsigned types is just the regular remainder calculation.
/// There's no way wrapping could ever happen. This function exists, so that
/// all operations are accounted for in the wrapping operations.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(100).wrapping_rem(U256::new(10)), U256::new(0));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn wrapping_rem(self, rhs: Self) -> Self {
self % rhs
}
/// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`. Wrapped
/// modulo calculation on unsigned types is just the regular remainder
/// calculation. There's no way wrapping could ever happen. This function
/// exists, so that all operations are accounted for in the wrapping
/// operations. Since, for the positive integers, all common definitions of
/// division are equal, this is exactly equal to `self.wrapping_rem(rhs)`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(100).wrapping_rem_euclid(U256::new(10)), U256::new(0));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
self % rhs
}
/// Wrapping (modular) negation. Computes `-self`, wrapping around at the
/// boundary of the type.
///
/// Since unsigned types do not have negative equivalents all applications
/// of this function will wrap (except for `-0`). For values smaller than
/// the corresponding signed type's maximum the result is the same as
/// casting the corresponding signed value. Any larger values are equivalent
/// to `MAX + 1 - (val - MAX - 1)` where `MAX` is the corresponding signed
/// type's maximum.
///
/// # Examples
///
/// Basic usage:
///
/// Please note that this example is shared between integer types.
/// Which explains why `i8` is used here.
///
/// ```
/// # use ethnum::{U256, AsU256};
/// assert_eq!(U256::new(100).wrapping_neg(), (-100i128).as_u256());
/// assert_eq!(
/// U256::from_words(i128::MIN as _, 0).wrapping_neg(),
/// U256::from_words(i128::MIN as _, 0),
/// );
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn wrapping_neg(self) -> Self {
self.overflowing_neg().0
}
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask`
/// removes any high-order bits of `rhs` that would cause the shift to
/// exceed the bitwidth of the type.
///
/// Note that this is *not* the same as a rotate-left; the RHS of a wrapping
/// shift-left is restricted to the range of the type, rather than the bits
/// shifted out of the LHS being returned to the other end. The primitive
/// integer types all implement a `rotate_left` function, which maybe what
/// you want instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(1).wrapping_shl(7), U256::new(128));
/// assert_eq!(U256::new(1).wrapping_shl(128), U256::from_words(1, 0));
/// assert_eq!(U256::new(1).wrapping_shl(256), U256::new(1));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn wrapping_shl(self, rhs: u32) -> Self {
let mut result = MaybeUninit::uninit();
intrinsics::signed::ushl3(&mut result, &self, rhs & 0xff);
unsafe { result.assume_init() }
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
/// removes any high-order bits of `rhs` that would cause the shift to
/// exceed the bitwidth of the type.
///
/// Note that this is *not* the same as a rotate-right; the RHS of a
/// wrapping shift-right is restricted to the range of the type, rather than
/// the bits shifted out of the LHS being returned to the other end. The
/// primitive integer types all implement a `rotate_right` function, which
/// may be what you want instead.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(128).wrapping_shr(7), U256::new(1));
/// assert_eq!(U256::from_words(128, 0).wrapping_shr(128), U256::new(128));
/// assert_eq!(U256::new(128).wrapping_shr(256), U256::new(128));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn wrapping_shr(self, rhs: u32) -> Self {
let mut result = MaybeUninit::uninit();
intrinsics::signed::ushr3(&mut result, &self, rhs & 0xff);
unsafe { result.assume_init() }
}
/// Wrapping (modular) exponentiation. Computes `self.pow(exp)`, wrapping
/// around at the boundary of the type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(3).wrapping_pow(5), U256::new(243));
/// assert_eq!(
/// U256::new(1337).wrapping_pow(42),
/// U256::from_words(
/// 45367329835866155830012179193722278514,
/// 159264946433345088039815329994094210673,
/// ),
/// );
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn wrapping_pow(self, mut exp: u32) -> Self {
let mut base = self;
let mut acc = U256::ONE;
while exp > 1 {
if (exp & 1) == 1 {
acc = acc.wrapping_mul(base);
}
exp /= 2;
base = base.wrapping_mul(base);
}
// Deal with the final bit of the exponent separately, since
// squaring the base afterwards is not necessary and may cause a
// needless overflow.
if exp == 1 {
acc = acc.wrapping_mul(base);
}
acc
}
/// Calculates `self` + `rhs`
///
/// Returns a tuple of the addition along with a boolean indicating whether
/// an arithmetic overflow would occur. If an overflow would have occurred
/// then the wrapped value is returned.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(5).overflowing_add(U256::new(2)), (U256::new(7), false));
/// assert_eq!(U256::MAX.overflowing_add(U256::new(1)), (U256::new(0), true));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
let mut result = MaybeUninit::uninit();
let overflow = intrinsics::signed::uaddc(&mut result, &self, &rhs);
(unsafe { result.assume_init() }, overflow)
}
/// Calculates `self` + `rhs` with a signed `rhs`
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::{I256, U256};
/// assert_eq!(U256::new(1).overflowing_add_signed(I256::new(2)), (U256::new(3), false));
/// assert_eq!(U256::new(1).overflowing_add_signed(I256::new(-2)), (U256::MAX, true));
/// assert_eq!((U256::MAX - 2).overflowing_add_signed(I256::new(4)), (U256::new(1), true));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn overflowing_add_signed(self, rhs: I256) -> (Self, bool) {
let (res, overflowed) = self.overflowing_add(rhs.as_u256());
(res, overflowed ^ (rhs < 0))
}
/// Calculates `self` - `rhs`
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would have
/// occurred then the wrapped value is returned.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(5).overflowing_sub(U256::new(2)), (U256::new(3), false));
/// assert_eq!(U256::new(0).overflowing_sub(U256::new(1)), (U256::MAX, true));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
let mut result = MaybeUninit::uninit();
let overflow = intrinsics::signed::usubc(&mut result, &self, &rhs);
(unsafe { result.assume_init() }, overflow)
}
/// Computes the absolute difference between `self` and `other`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(100).abs_diff(U256::new(80)), 20);
/// assert_eq!(U256::new(100).abs_diff(U256::new(110)), 10);
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn abs_diff(self, other: Self) -> Self {
if self < other {
other - self
} else {
self - other
}
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would have
/// occurred then the wrapped value is returned.
///
/// # Examples
///
/// Basic usage:
///
/// Please note that this example is shared between integer types.
/// Which explains why `u32` is used here.
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(5).overflowing_mul(U256::new(2)), (U256::new(10), false));
/// assert_eq!(
/// U256::MAX.overflowing_mul(U256::new(2)),
/// (U256::MAX - 1, true),
/// );
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
let mut result = MaybeUninit::uninit();
let overflow = intrinsics::signed::umulc(&mut result, &self, &rhs);
(unsafe { result.assume_init() }, overflow)
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether
/// an arithmetic overflow would occur. Note that for unsigned integers
/// overflow never occurs, so the second value is always `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is 0.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(5).overflowing_div(U256::new(2)), (U256::new(2), false));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether
/// an arithmetic overflow would occur. Note that for unsigned integers
/// overflow never occurs, so the second value is always `false`. Since,
/// for the positive integers, all common definitions of division are equal,
/// this is exactly equal to `self.overflowing_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is 0.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(5).overflowing_div_euclid(U256::new(2)), (U256::new(2), false));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is always
/// `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is 0.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(5).overflowing_rem(U256::new(2)), (U256::new(1), false));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean
/// division.
///
/// Returns a tuple of the modulo after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is always
/// `false`. Since, for the positive integers, all common definitions of
/// division are equal, this operation is exactly equal to
/// `self.overflowing_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is 0.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(5).overflowing_rem_euclid(U256::new(2)), (U256::new(1), false));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Negates self in an overflowing fashion.
///
/// Returns `!self + 1` using wrapping operations to return the value that
/// represents the negation of this unsigned value. Note that for positive
/// unsigned values overflow always occurs, but negating 0 does not
/// overflow.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// # use ethnum::{U256, AsU256};
/// assert_eq!(U256::new(0).overflowing_neg(), (U256::new(0), false));
/// assert_eq!(U256::new(2).overflowing_neg(), ((-2i32).as_u256(), true));
/// ```
#[inline]
pub fn overflowing_neg(self) -> (Self, bool) {
((!self).wrapping_add(U256::ONE), self != U256::ZERO)
}
/// Shifts self left by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is masked
/// (N-1) where N is the number of bits, and this value is then used to
/// perform the shift.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(0x1).overflowing_shl(4), (U256::new(0x10), false));
/// assert_eq!(U256::new(0x1).overflowing_shl(260), (U256::new(0x10), true));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shl(rhs), rhs > 255)
}
/// Shifts self right by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is masked
/// (N-1) where N is the number of bits, and this value is then used to
/// perform the shift.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(0x10).overflowing_shr(4), (U256::new(0x1), false));
/// assert_eq!(U256::new(0x10).overflowing_shr(260), (U256::new(0x1), true));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shr(rhs), rhs > 255)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// Returns a tuple of the exponentiation along with a bool indicating
/// whether an overflow happened.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(3).overflowing_pow(5), (U256::new(243), false));
/// assert_eq!(
/// U256::new(1337).overflowing_pow(42),
/// (
/// U256::from_words(
/// 45367329835866155830012179193722278514,
/// 159264946433345088039815329994094210673,
/// ),
/// true,
/// )
/// );
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
let mut base = self;
let mut acc = U256::ONE;
let mut overflown = false;
// Scratch space for storing results of overflowing_mul.
let mut r;
while exp > 1 {
if (exp & 1) == 1 {
r = acc.overflowing_mul(base);
acc = r.0;
overflown |= r.1;
}
exp /= 2;
r = base.overflowing_mul(base);
base = r.0;
overflown |= r.1;
}
// Deal with the final bit of the exponent separately, since
// squaring the base afterwards is not necessary and may cause a
// needless overflow.
if exp == 1 {
r = acc.overflowing_mul(base);
acc = r.0;
overflown |= r.1;
}
(acc, overflown)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(2).pow(5), U256::new(32));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline]
pub fn pow(self, mut exp: u32) -> Self {
let mut base = self;
let mut acc = U256::ONE;
while exp > 1 {
if (exp & 1) == 1 {
acc *= base;
}
exp /= 2;
base = base * base;
}
// Deal with the final bit of the exponent separately, since
// squaring the base afterwards is not necessary and may cause a
// needless overflow.
if exp == 1 {
acc *= base;
}
acc
}
/// Performs Euclidean division.
///
/// Since, for the positive integers, all common definitions of division are
/// equal, this is exactly equal to `self / rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is 0.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(7).div_euclid(U256::new(4)), U256::new(1));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn div_euclid(self, rhs: Self) -> Self {
self / rhs
}
/// Calculates the least remainder of `self (mod rhs)`.
///
/// Since, for the positive integers, all common definitions of division are
/// equal, this is exactly equal to `self % rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is 0.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(7).rem_euclid(U256::new(4)), U256::new(3));
/// ```
#[must_use = "this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub fn rem_euclid(self, rhs: Self) -> Self {
self % rhs
}
/// Returns `true` if and only if `self == 2^k` for some `k`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert!(U256::new(16).is_power_of_two());
/// assert!(!U256::new(10).is_power_of_two());
/// ```
#[inline]
pub fn is_power_of_two(self) -> bool {
self.count_ones() == 1
}
/// Returns one less than next power of two. (For 8u8 next power of two is
/// 8u8 and for 6u8 it is 8u8).
///
/// 8u8.one_less_than_next_power_of_two() == 7
/// 6u8.one_less_than_next_power_of_two() == 7
///
/// This method cannot overflow, as in the `next_power_of_two` overflow
/// cases it instead ends up returning the maximum value of the type, and
/// can return 0 for 0.
#[inline]
fn one_less_than_next_power_of_two(self) -> Self {
if self <= 1 {
return U256::ZERO;
}
let p = self - 1;
let z = p.leading_zeros();
U256::MAX >> z
}
/// Returns the smallest power of two greater than or equal to `self`.
///
/// When return value overflows (i.e., `self > (1 << (N-1))` for type `uN`),
/// it panics in debug mode and return value is wrapped to 0 in release mode
/// (the only situation in which method can return 0).
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(2).next_power_of_two(), U256::new(2));
/// assert_eq!(U256::new(3).next_power_of_two(), U256::new(4));
/// ```
#[inline]
pub fn next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two() + 1
}
/// Returns the smallest power of two greater than or equal to `n`. If the
/// next power of two is greater than the type's maximum value, `None` is
/// returned, otherwise the power of two is wrapped in `Some`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ethnum::U256;
/// assert_eq!(U256::new(2).checked_next_power_of_two(), Some(U256::new(2)));
/// assert_eq!(U256::new(3).checked_next_power_of_two(), Some(U256::new(4)));
/// assert_eq!(U256::MAX.checked_next_power_of_two(), None);
/// ```
#[inline]
pub fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two()
.checked_add(U256::ONE)
}
/// Return the memory representation of this integer as a byte array in big
/// endian (network) byte order.
///
/// # Examples
///
/// ```
/// # use ethnum::U256;
/// let bytes = U256::from_words(
/// 0x00010203_04050607_08090a0b_0c0d0e0f,
/// 0x10111213_14151617_18191a1b_1c1d1e1f,
/// );
/// assert_eq!(
/// bytes.to_be_bytes(),
/// [
/// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
/// 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
/// ],
/// );
/// ```
#[inline]
pub fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Return the memory representation of this integer as a byte array in
/// little endian byte order.
///
/// # Examples
///
/// ```
/// # use ethnum::U256;
/// let bytes = U256::from_words(
/// 0x00010203_04050607_08090a0b_0c0d0e0f,
/// 0x10111213_14151617_18191a1b_1c1d1e1f,
/// );
/// assert_eq!(
/// bytes.to_le_bytes(),
/// [
/// 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
/// 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
/// ],
/// );
/// ```
#[inline]
pub fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Return the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code should
/// use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
///
/// [`to_be_bytes`]: #method.to_be_bytes
/// [`to_le_bytes`]: #method.to_le_bytes
///
/// # Examples
///
/// ```
/// # use ethnum::U256;
/// let bytes = U256::from_words(
/// 0x00010203_04050607_08090a0b_0c0d0e0f,
/// 0x10111213_14151617_18191a1b_1c1d1e1f,
/// );
/// assert_eq!(
/// bytes.to_ne_bytes(),
/// if cfg!(target_endian = "big") {
/// [
/// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
/// 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
/// ]
/// } else {
/// [
/// 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
/// 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
/// ]
/// }
/// );
/// ```
#[inline]
pub fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Create an integer value from its representation as a byte array in big
/// endian.
///
/// # Examples
///
/// ```
/// # use ethnum::U256;
/// let value = U256::from_be_bytes([
/// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
/// 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
/// ]);
/// assert_eq!(
/// value,
/// U256::from_words(
/// 0x00010203_04050607_08090a0b_0c0d0e0f,
/// 0x10111213_14151617_18191a1b_1c1d1e1f,
/// ),
/// );
/// ```
///
/// When starting from a slice rather than an array, fallible conversion
/// APIs can be used:
///
/// ```
/// # use ethnum::U256;
/// use std::convert::TryInto;
///
/// fn read_be_u256(input: &mut &[u8]) -> U256 {
/// let (int_bytes, rest) = input.split_at(std::mem::size_of::<U256>());
/// *input = rest;
/// U256::from_be_bytes(int_bytes.try_into().unwrap())
/// }
/// ```
#[inline]
pub fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Create an integer value from its representation as a byte array in
/// little endian.
///
/// # Examples
///
/// ```
/// # use ethnum::U256;
/// let value = U256::from_le_bytes([
/// 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
/// 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
/// ]);
/// assert_eq!(
/// value,
/// U256::from_words(
/// 0x00010203_04050607_08090a0b_0c0d0e0f,
/// 0x10111213_14151617_18191a1b_1c1d1e1f,
/// ),
/// );
/// ```
///
/// When starting from a slice rather than an array, fallible conversion
/// APIs can be used:
///
/// ```
/// # use ethnum::U256;
/// use std::convert::TryInto;
///
/// fn read_be_u256(input: &mut &[u8]) -> U256 {
/// let (int_bytes, rest) = input.split_at(std::mem::size_of::<U256>());
/// *input = rest;
/// U256::from_le_bytes(int_bytes.try_into().unwrap())
/// }
/// ```
#[inline]
pub fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Create an integer value from its memory representation as a byte array
/// in native endianness.
///
/// As the target platform's native endianness is used, portable code likely
/// wants to use [`from_be_bytes`] or [`from_le_bytes`], as appropriate
/// instead.
///
/// [`from_be_bytes`]: #method.from_be_bytes
/// [`from_le_bytes`]: #method.from_le_bytes
///
/// # Examples
///
/// ```
/// # use ethnum::U256;
/// let value = U256::from_ne_bytes(if cfg!(target_endian = "big") {
/// [
/// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
/// 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
/// ]
/// } else {
/// [
/// 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
/// 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
/// ]
/// });
/// assert_eq!(
/// value,
/// U256::from_words(
/// 0x00010203_04050607_08090a0b_0c0d0e0f,
/// 0x10111213_14151617_18191a1b_1c1d1e1f,
/// ),
/// );
/// ```
///
/// When starting from a slice rather than an array, fallible conversion
/// APIs can be used:
///
/// ```
/// # use ethnum::U256;
/// use std::convert::TryInto;
///
/// fn read_be_u256(input: &mut &[u8]) -> U256 {
/// let (int_bytes, rest) = input.split_at(std::mem::size_of::<U256>());
/// *input = rest;
/// U256::from_ne_bytes(int_bytes.try_into().unwrap())
/// }
/// ```
#[inline]
pub fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
}