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
//! `big_int` - Arbitrary precision, arbitrary base integer arithmetic library.
//!
//! ```
//! use big_int::prelude::*;
//!
//! let mut a: Loose<10> = "9000000000000000000000000000000000000000".parse().unwrap();
//! a /= 13.into();
//! assert_eq!(a, "692307692307692307692307692307692307692".parse().unwrap());
//!
//! let mut b: Loose<16> = a.convert();
//! assert_eq!(b, "208D59C8D8669EDC306F76344EC4EC4EC".parse().unwrap());
//! b >>= 16.into();
//!
//! let c: Loose<2> = b.convert();
//! assert_eq!(c, "100000100011010101100111001000110110000110011010011110110111000011".parse().unwrap());
//!
//! let mut d: Tight<256> = c.convert();
//! d += vec![15, 90, 0].into();
//! assert_eq!(d, vec![2, 8, 213, 156, 141, 134, 121, 71, 195].into());
//!
//! let e: Tight<10> = d.convert();
//! assert_eq!(format!("{e}"), "37530075201422313411".to_string());
//! ```
//!
//! This crate contains five primary big int implementations:
//! * `LooseBytes<BASE>` - A collection of loosely packed 8-bit byte values representing each digit.
//! Slightly memory inefficient, but with minimal performance overhead.
//! Capable of representing any base from 2-256.
//! * `LooseShorts<BASE>` - A collection of loosely packed 16-bit short values representing each digit.
//! Somewhat memory inefficient, but with minimal performance overhead.
//! Capable of representing any base from 2-65536.
//! * `LooseWords<BASE>` - A collection of loosely packed 32-bit word values representing each digit.
//! Fairly memory inefficient, but with minimal performance overhead.
//! Capable of representing any base from 2-2^32.
//! * `Loose<BASE>` - A collection of loosely packed 64-bit ints representing each digit.
//! Very memory inefficient, but with minimal performance overhead.
//! Capable of representing any base from 2-2^64.
//! * `Tight<BASE>` - A collection of tightly packed bits representing each digit.
//! Maximally memory efficient, and capable of representing any base from
//! 2-2^64. However, the additional indirection adds some performance overhead.
//!
//! Ints support most basic arithmetic operations, including addition, subtraction, multiplication,
//! division, exponentiation, logarithm, nth root, and left/right shifting. Notably, shifting acts
//! on the `BASE` of the associated number, increasing or decreasing the magnitude by powers of `BASE`
//! as opposed to powers of 2.
extern crate self as big_int;
use std::{
cmp::Ordering,
fmt::Display,
ops::{
Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Shl, ShlAssign, Shr, ShrAssign, Sub,
SubAssign,
},
str::FromStr,
};
use error::{BigIntError, ParseError};
use get_back::GetBack;
use self::Sign::*;
pub use big_int_proc::*;
pub mod prelude {
//! Default exports: includes `Loose`, `Tight`, `Sign`, & `Denormal`
pub use crate::denormal::*;
pub use crate::loose::*;
pub use crate::tight::*;
pub use crate::Sign::*;
pub use crate::*;
}
mod tests;
pub(crate) mod test_utils;
pub mod base64;
pub mod denormal;
pub mod error;
pub mod get_back;
pub mod loose;
pub mod tight;
/// Standard alphabet used when translating between text and big ints.
pub const STANDARD_ALPHABET: &str =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
/// Size of an individual big int digit.
pub type Digit = u64;
pub(crate) type DoubleDigit = u128;
/// Safely create a bitmask of `n` bits in size shifted
/// to the right side of the number without overflowing.
#[macro_export(local_inner_macros)]
macro_rules! mask {
($n:expr) => {
(((1 << (($n) - 1)) - 1) << 1) + 1
};
}
/// A big int.
///
/// Represents an arbitrary precision, arbitrary base natural number.
///
/// Supports basic arithmetic operations, as well as all utilities necessary for
/// coercing to and from various builtin types, such as primitive int types, `Vec`s, and `String`s.
///
/// ### For implementors:
/// If implementing this trait for your own type, don't be alarmed by the massive list of `Self`
/// constraints. Use the included derive macro `big_int::BigIntTraits` to automatically derive
/// all traits using default `*_inner` implementations pre-provided by `BigInt`.
///
/// At least one of `normalize` or `normalized` must be defined to prevent recursion.\
/// At least one of `shl_inner` or `shl_assign_inner` must be defined to prevent recursion.\
/// At least one of `shr_inner` or `shr_assign_inner` must be defined to prevent recursion.\
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a = TightBuilder::<10>::new();
/// a.push_back(1);
/// a.push_back(0);
/// a.push_back(4);
/// let a: DenormalTight<10> = a.into();
/// let a: Tight<10> = a.unwrap();
/// assert_eq!(a, 104.into());
/// ```
pub trait BigInt<const BASE: usize>
where
Self: GetBack<Item = Digit>
+ Clone
+ Default
+ std::fmt::Debug
+ Display
+ PartialEq
+ Eq
+ PartialOrd
+ Ord
+ Neg<Output = Self>
+ Add<Output = Self>
+ AddAssign
+ Sub<Output = Self>
+ SubAssign
+ Div<Output = Self>
+ DivAssign
+ Mul<Output = Self>
+ MulAssign
+ Shl<Output = Self>
+ ShlAssign
+ Shr<Output = Self>
+ ShrAssign
+ FromStr<Err = BigIntError>
+ FromIterator<Digit>
+ Iterator<Item = Digit>
+ DoubleEndedIterator<Item = Digit>
+ From<Vec<Digit>>
+ From<u8>
+ From<u16>
+ From<u32>
+ From<u64>
+ From<u128>
+ From<usize>
+ From<i8>
+ From<i16>
+ From<i32>
+ From<i64>
+ From<i128>
+ From<isize>
+ Into<u8>
+ Into<u16>
+ Into<u32>
+ Into<u64>
+ Into<u128>
+ Into<usize>
+ Into<i8>
+ Into<i16>
+ Into<i32>
+ Into<i64>
+ Into<i128>
+ Into<isize>,
{
type Builder: BigIntBuilder<{ BASE }> + Into<Self::Denormal> + Into<Self>;
type Denormal: BigInt<BASE> + From<Self> + UnsafeInto<Self> + Unwrap<Self>;
const BITS_PER_DIGIT: usize = bits_per_digit(BASE);
/// Default implementation of `big_int::GetBack`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn get_back_inner(&self, index: usize) -> Option<Digit> {
self.len()
.checked_sub(index)
.and_then(|index| self.get_digit(index))
}
/// Default implementation of `Default`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn default_inner() -> Self {
Self::zero()
}
/// Default implementation of `Display`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn fmt_inner(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
self.display(STANDARD_ALPHABET)
.map_err(|_| std::fmt::Error)?
)
}
/// Default implementation of `PartialOrd`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn partial_cmp_inner<RHS: BigInt<{ BASE }>>(&self, other: &RHS) -> Option<Ordering> {
Some(self.cmp_inner(other))
}
/// Default implementation of `Ord`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn cmp_inner<RHS: BigInt<{ BASE }>>(&self, other: &RHS) -> Ordering {
if self.is_zero() && other.is_zero() {
Ordering::Equal
} else {
match (self.sign(), other.sign()) {
(Positive, Negative) => Ordering::Greater,
(Negative, Positive) => Ordering::Less,
(Positive, Positive) => self.cmp_magnitude(other),
(Negative, Negative) => other.cmp_magnitude(self),
}
}
}
/// Default implementation of `PartialEq`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn eq_inner<RHS: BigInt<{ BASE }>>(&self, other: &RHS) -> bool {
matches!(self.cmp_inner(other), Ordering::Equal)
}
/// Default implementation of `Neg`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn neg_inner(self) -> Self::Denormal {
let sign = self.sign();
self.with_sign(-sign).into()
}
/// Default implementation of `Add`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn add_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(self, rhs: RHS) -> OUT::Denormal {
if self.sign() != rhs.sign() {
self.sub_inner::<_, OUT>(rhs.neg())
} else {
let sign = self.sign();
let mut carry = 0;
let mut result = OUT::Builder::new();
for i in 1.. {
match (self.get_back(i), rhs.get_back(i), carry) {
(None, None, 0) => break,
(left_digit, right_digit, carry_in) => {
let left_digit = left_digit.unwrap_or_default() as DoubleDigit;
let right_digit = right_digit.unwrap_or_default() as DoubleDigit;
let mut sum = left_digit + right_digit + carry_in;
if sum >= BASE as DoubleDigit {
sum -= BASE as DoubleDigit;
carry = 1;
} else {
carry = 0;
}
result.push_front(sum as Digit);
}
}
}
result.with_sign(sign).into()
}
}
/// Default implementation of `AddAssign`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
///
/// If this method is used directly, it may cause the number to become denormalized.
unsafe fn add_assign_inner<RHS: BigInt<{ BASE }>>(&mut self, rhs: RHS) {
if self.sign() != rhs.sign() {
self.sub_assign_inner(rhs.neg_inner());
} else {
let self_len = self.len();
let mut carry = 0;
for i in 1.. {
match (self.get_back(i), rhs.get_back(i), carry) {
(None, None, 0) => break,
(left_digit, right_digit, carry_in) => {
let left_digit = left_digit.unwrap_or_default() as DoubleDigit;
let right_digit = right_digit.unwrap_or_default() as DoubleDigit;
let mut sum = left_digit + right_digit + carry_in;
if sum >= BASE as DoubleDigit {
sum -= BASE as DoubleDigit;
carry = 1;
} else {
carry = 0;
}
if i <= self_len {
self.set_digit(self_len - i, sum as Digit);
} else {
self.push_front(sum as Digit);
}
}
}
}
}
}
/// Default implementation of `Sub`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn sub_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
mut self,
rhs: RHS,
) -> OUT::Denormal {
if self.sign() != rhs.sign() {
self.add_inner::<_, OUT>(rhs.neg_inner())
} else if rhs.cmp_magnitude(&self).is_gt() {
unsafe { rhs.sub_inner::<_, OUT>(self).unsafe_into() }.neg_inner()
} else {
let sign = self.sign();
let mut result = OUT::Builder::new();
let self_len = self.len();
for i in 1.. {
match (self.get_back(i), rhs.get_back(i)) {
(None, None) => break,
(left_digit, right_digit) => {
let mut left_digit = left_digit.unwrap_or_default() as DoubleDigit;
let right_digit = right_digit.unwrap_or_default() as DoubleDigit;
if left_digit < right_digit {
for j in i + 1.. {
match self.get_back(j) {
None => unreachable!("big int subtraction with overflow"),
Some(0) => {
self.set_digit(self_len - j, (BASE - 1) as Digit);
}
Some(digit) => {
self.set_digit(self_len - j, digit - 1);
break;
}
}
}
left_digit += BASE as DoubleDigit;
}
result.push_front((left_digit - right_digit) as Digit);
}
}
}
result.with_sign(sign).into()
}
}
/// Default implementation of `SubAssign`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
///
/// If this method is used directly, it may cause the number to become denormalized.
unsafe fn sub_assign_inner<RHS: BigInt<{ BASE }>>(&mut self, rhs: RHS) {
if self.sign() != rhs.sign() {
self.add_assign_inner(rhs.neg_inner());
} else if rhs.cmp_magnitude(self).is_gt() {
*self = rhs
.sub_inner::<_, Self>(self.clone())
.unsafe_into()
.neg_inner()
.unsafe_into();
} else {
let self_len = self.len();
for i in 1.. {
match (self.get_back(i), rhs.get_back(i)) {
(None, None) => break,
(left_digit, right_digit) => {
let mut left_digit = left_digit.unwrap_or_default() as DoubleDigit;
let right_digit = right_digit.unwrap_or_default() as DoubleDigit;
if left_digit < right_digit {
for j in i + 1.. {
match self.get_back(j) {
None => unreachable!("big int subtraction with overflow"),
Some(0) => {
self.set_digit(self_len - j, (BASE - 1) as Digit);
}
Some(digit) => {
self.set_digit(self_len - j, digit - 1);
break;
}
}
}
left_digit += BASE as DoubleDigit;
}
let difference = (left_digit - right_digit) as Digit;
if i <= self_len {
self.set_digit(self_len - i, difference);
} else {
self.push_front(difference);
}
}
}
}
}
}
/// Default implementation of `Mul`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn mul_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
mut self,
mut rhs: RHS,
) -> OUT::Denormal {
let sign = self.sign() * rhs.sign();
self.set_sign(Positive);
rhs.set_sign(Positive);
let mut shift = 0;
if !self.is_zero() {
while let Some(0) = self.get_back(1) {
unsafe {
self.shr_assign_inner(1);
}
shift += 1;
}
}
if !rhs.is_zero() {
while let Some(0) = rhs.get_back(1) {
unsafe {
rhs.shr_assign_inner(1);
}
shift += 1;
}
}
let mut result = OUT::zero();
let mut addends = rhs.clone().addends().memo();
for digit in self.rev() {
for index in 0..Self::BITS_PER_DIGIT {
if digit & (1 << index) != 0 {
unsafe {
result.add_assign_inner(addends.get(index).unwrap().clone());
}
}
unsafe {
addends.get_mut(index).unwrap().shl_assign_inner(1);
}
}
}
OUT::from(result.with_sign(sign)).shl_inner(shift)
}
/// Default implementation of `MulAssign`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
///
/// If this method is used directly, it may cause the number to become denormalized.
unsafe fn mul_assign_inner<RHS: BigInt<{ BASE }>>(&mut self, rhs: RHS) {
*self = self.clone().mul_inner::<_, Self>(rhs).unsafe_into();
}
/// Default implementation of `Div`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn div_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(self, rhs: RHS) -> OUT::Denormal {
self.div_rem_inner::<_, OUT>(rhs).unwrap().0
}
/// Default implementation of `DivAssign`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
///
/// If this method is used directly, it may cause the number to become denormalized.
unsafe fn div_assign_inner<RHS: BigInt<{ BASE }>>(&mut self, rhs: RHS) {
*self = self
.clone()
.div_rem_inner::<_, Self>(rhs)
.unwrap()
.0
.unsafe_into();
}
/// Default implementation of `FromStr`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
///
/// ### Errors:
/// * `ParseFailed` if parsing of the string fails.
fn from_str_inner(s: &str) -> Result<Self::Denormal, BigIntError> {
Self::parse(s, STANDARD_ALPHABET).map_err(BigIntError::ParseFailed)
}
/// Default implementation of `FromIterator`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn from_iter_inner<T: IntoIterator<Item = Digit>>(iter: T) -> Self::Denormal {
let mut builder = Self::Builder::new();
for digit in iter {
builder.push_back(digit);
}
builder.into()
}
/// Default implementation of `Iterator`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
///
/// If this method is used directly, it may cause the number to become denormalized.
unsafe fn next_inner(&mut self) -> Option<Digit> {
self.pop_front()
}
/// Default implementation of `DoubleEndedIterator`.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
///
/// If this method is used directly, it may cause the number to become denormalized.
unsafe fn next_back_inner(&mut self) -> Option<Digit> {
self.pop_back()
}
/// Default implementation of `From<_>` for all unsigned primitive int types.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn from_u128_inner(mut value: u128) -> Self::Denormal {
let base = BASE as u128;
let mut result = Self::Builder::new();
while value >= base {
let (new_value, rem) = (value / base, value % base);
value = new_value;
result.push_front(rem as Digit);
}
result.push_front(value as Digit);
result.into()
}
/// Default implementation of `From<_>` for all signed primitive int types.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn from_i128_inner(value: i128) -> Self::Denormal {
if value < 0 {
-Self::from_u128_inner((-value) as u128)
} else {
Self::from_u128_inner(value as u128)
}
}
/// Default implementation of `Into<_>` for all unsigned primitive int types.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn into_u128_inner(self) -> u128 {
if self.sign() == Negative {
panic!("uint conversion with underflow");
}
let mut total: u128 = 0;
let mut place: u128 = 0;
for digit in self.rev() {
place = if place == 0 { 1 } else { place * BASE as u128 };
total += (digit as u128) * place;
}
total
}
/// Default implementation of `Into<_>` for all signed primitive int types.
///
/// Trait implementation may be provided automatically by `big_int_proc::BigIntTraits`.
fn into_i128_inner(self) -> i128 {
let mut total: i128 = 0;
let mut place: i128 = 0;
let sign = self.sign();
for digit in self.rev() {
place = if place == 0 { 1 } else { place * BASE as i128 };
total += (digit as i128) * place;
}
if sign == Negative {
total = -total;
}
total
}
/// The length of the big int in digits.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Tight<10> = 211864.into();
/// assert_eq!(a.len(), 6);
/// ```
fn len(&self) -> usize;
/// Get the digit of the big int at position `digit`,
/// or None if the number does not have that many digits.
///
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Tight<10> = 12345.into();
/// assert_eq!(a.get_digit(2), Some(3));
/// assert_eq!(a.get_digit(6), None);
/// ```
fn get_digit(&self, digit: usize) -> Option<Digit>;
/// Set the digit of the big int to `value` at position `digit`.
///
/// If the set digit causes the leftmost digit of the number to be zero,
/// the number will become denormal, and should be normalized before being used.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a: Tight<10> = 10000.into();
/// a.set_digit(1, 7);
/// a.set_digit(4, 9);
/// assert_eq!(a, 17009.into());
/// ```
fn set_digit(&mut self, digit: usize, value: Digit);
/// The value zero represented as a big int.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Tight<10> = 13.into();
/// let b = 13.into();
/// assert_eq!(a - b, BigInt::zero());
/// ```
fn zero() -> Self;
/// Check if the big int is zero.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Tight<10> = 13.into();
/// let b = 13.into();
/// assert!((a - b).is_zero());
/// ```
fn is_zero(&self) -> bool {
self.iter().all(|digit| digit == 0)
}
/// The sign of the big int.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a: Tight<10> = 5.into();
/// assert_eq!(a.sign(), Positive);
/// a -= 14.into();
/// assert_eq!(a.sign(), Negative);
/// ```
fn sign(&self) -> Sign;
/// The big int with the given sign.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Tight<10> = 95.into();
/// assert_eq!(a.with_sign(Negative), (-95).into());
/// ```
fn with_sign(self, sign: Sign) -> Self;
/// Set the sign of the big int to `sign`.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a: Tight<10> = (-109).into();
/// a.set_sign(Positive);
/// assert_eq!(a, 109.into());
/// ```
fn set_sign(&mut self, sign: Sign);
/// Append a digit to the right side of the int. Equivalent to `(int << 1) + digit`
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a: Tight<10> = 6.into();
/// a.push_back(1);
/// assert_eq!(a, 61.into());
/// ```
fn push_back(&mut self, digit: Digit);
/// Append a digit to the left side of the int.
///
/// If a zero is pushed onto the end
/// of the int, it will become denormalized.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a: Tight<10> = 6.into();
/// unsafe {
/// a.push_front(1);
/// }
/// assert_eq!(a.normalized(), 16.into());
/// ```
unsafe fn push_front(&mut self, digit: Digit);
/// Pop the rightmost digit from the end of the int, and return it.
///
/// If the last digit is popped, the number will become denormalized.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a: Tight<10> = 651.into();
/// let digit = unsafe { a.pop_back() };
/// assert_eq!(a, 65.into());
/// assert_eq!(digit, Some(1));
/// ```
unsafe fn pop_back(&mut self) -> Option<Digit>;
/// Pop the leftmost digit from the end of the int, and return it.
///
/// If the last digit is popped, the number will become denormalized.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a: Tight<10> = 651.into();
/// let digit = unsafe { a.pop_front() };
/// assert_eq!(a, 51.into());
/// assert_eq!(digit, Some(6));
/// ```
unsafe fn pop_front(&mut self) -> Option<Digit>;
/// Divide the int by BASE^amount.
///
/// Note: works in powers of BASE, not in powers of 2.
///
/// Defined in terms of `shr_assign`; at least one of `shr`
/// or `shr_assign` must be defined by implementers.
///
/// Also acts as the default implementation of the `Shr` trait,
/// as provided automatically by `big_int_proc::BigIntTraits`.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Tight<10> = 600.into();
/// assert_eq!(a.shr_inner(2), 6.into());
/// ```
fn shr_inner(mut self, amount: usize) -> Self::Denormal {
unsafe {
self.shr_assign_inner(amount);
}
self.into()
}
/// Divide the int by BASE^amount in place.
///
/// Note: works in powers of BASE, not in powers of 2.
///
/// Defined in terms of `shr`; at least one of `shr`
/// or `shr_assign` must be defined by implementers.
///
/// Also acts as the default implementation of the `ShrAssign` trait,
/// as provided automatically by `big_int_proc::BigIntTraits`.
///
/// If the last number is shifted off, may cause the number to become denormalized.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a: Tight<10> = 600.into();
/// unsafe {
/// a.shr_assign_inner(2);
/// }
/// assert_eq!(a, 6.into());
/// ```
unsafe fn shr_assign_inner(&mut self, amount: usize) {
*self = self.clone().shr_inner(amount).unsafe_into();
}
/// Multiply the int by BASE^amount.
///
/// Note: works in powers of BASE, not in powers of 2.
///
/// Defined in terms of `shl_assign`; at least one of `shl`
/// or `shl_assign` must be defined by implementers.
///
/// Also acts as the default implementation of the `Shl` trait,
/// as provided automatically by `big_int_proc::BigIntTraits`.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Tight<10> = 3.into();
/// assert_eq!(a.shl_inner(2), 300.into());
/// ```
fn shl_inner(mut self, amount: usize) -> Self::Denormal {
unsafe {
self.shl_assign_inner(amount);
}
self.into()
}
/// Multiply the int by BASE^amount in place.
///
/// Note: works in powers of BASE, not in powers of 2.
///
/// Defined in terms of `shl`; at least one of `shl`
/// or `shl_assign` must be defined by implementers.
///
/// Also acts as the default implementation of the `ShlAssign` trait,
/// as provided automatically by `big_int_proc::BigIntTraits`.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a: Tight<10> = 3.into();
/// unsafe {
/// a.shl_assign_inner(2);
/// }
/// assert_eq!(a, 300.into());
/// ```
unsafe fn shl_assign_inner(&mut self, amount: usize) {
*self = self.clone().shl_inner(amount).unsafe_into();
}
/// Divide one int by another, returning the quotient & remainder as a pair.
/// Returns the result as a denormalized pair.
///
/// ### Errors:
/// * `DivisionByZero` if `rhs` is zero.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Loose<10> = 999_999_999.into();
/// let b: Loose<10> = 56_789.into();
/// assert_eq!(a.div_rem_inner::<_, Loose<10>>(b), Ok((17_609.into(), 2_498.into())));
/// ```
fn div_rem_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
mut self,
mut rhs: RHS,
) -> Result<(OUT::Denormal, OUT::Denormal), BigIntError> {
if rhs.is_zero() {
return Err(BigIntError::DivisionByZero);
}
if rhs.len() > self.len() {
return Ok((OUT::Denormal::zero(), self.convert_inner::<BASE, OUT>()));
}
let mut shift = 0;
while let (Some(0), Some(0)) = (self.get_back(1), rhs.get_back(1)) {
unsafe {
self.shr_assign_inner(1);
rhs.shr_assign_inner(1);
}
shift += 1;
}
let sign = self.sign() * rhs.sign();
self.set_sign(Positive);
rhs.set_sign(Positive);
let quot_digits = self.len() - rhs.len() + 1;
let mut quot = OUT::Builder::new();
let mut prod = Self::zero();
let mut addends = rhs.clone().shl_inner(quot_digits - 1).addends().memo();
for _ in 0..quot_digits {
let mut digit_value = 0;
for index in (0..Self::BITS_PER_DIGIT).rev() {
let power = 1 << index;
let new_prod = unsafe {
prod.clone()
.add_inner::<_, Self>(addends.get(index).unwrap().clone())
.unsafe_into()
};
if new_prod <= self {
digit_value += power;
prod = new_prod;
}
unsafe {
addends.get_mut(index).unwrap().shr_assign_inner(1);
}
}
quot.push_back(digit_value);
}
let mut rem: OUT::Denormal = self.sub_inner::<_, OUT>(prod);
if !rem.is_zero() {
rem.set_sign(sign);
}
unsafe {
rem.shl_assign_inner(shift);
}
Ok((quot.with_sign(sign).into(), rem))
}
/// Divide one int by another, returning the quotient & remainder as a pair.
///
/// ### Errors:
/// * `DivisionByZero` if `rhs` is zero.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Loose<10> = 999_999_999.into();
/// let b: Loose<10> = 56_789.into();
/// assert_eq!(a.div_rem::<_, Loose<10>>(b), Ok((17_609.into(), 2_498.into())));
/// ```
fn div_rem<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
self,
rhs: RHS,
) -> Result<(OUT, OUT), BigIntError> {
self.div_rem_inner::<RHS, OUT>(rhs)
.map(|(q, r): (OUT::Denormal, OUT::Denormal)| (q.unwrap(), r.unwrap()))
}
/// Exponentiate the big int by `rhs`.
/// Returns the result as a denormalized number.
///
/// ### Errors:
/// * `NegativeExponentiation` if `rhs` is negative.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Loose<10> = 10.into();
/// let b: Loose<10> = a.exp::<Loose<10>, Loose<10>>(3.into()).unwrap();
/// assert_eq!(b, 1000.into());
/// ```
fn exp_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
self,
mut rhs: RHS,
) -> Result<OUT::Denormal, BigIntError> {
if rhs < RHS::zero() {
return Err(BigIntError::NegativeExponentiation);
}
let mut mullands = self.mullands().memo();
let mut addends = RHS::from(1).addends().memo();
let mut power = 0;
let mut result: OUT = 1.into();
while rhs.cmp_inner(addends.get(power).unwrap()).is_ge() {
rhs -= addends.get(power).unwrap().clone();
unsafe {
result.mul_assign_inner(mullands.get(power).unwrap().clone());
}
power += 1;
}
for mulland_index in (0..power).rev() {
let comparison = rhs.cmp_inner(addends.get(mulland_index).unwrap());
if comparison.is_ge() {
rhs -= addends.get(mulland_index).unwrap().clone();
unsafe {
result.mul_assign_inner(mullands.get(mulland_index).unwrap().clone());
}
if comparison.is_eq() {
break;
}
}
}
Ok(result.into())
}
/// Exponentiate the big int by `rhs`.
///
/// ### Errors:
/// * `NegativeExponentiation` if `rhs` is negative.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Loose<10> = 10.into();
/// let b: Loose<10> = a.exp::<Loose<10>, Loose<10>>(3.into()).unwrap();
/// assert_eq!(b, 1000.into());
/// ```
fn exp<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
self,
rhs: RHS,
) -> Result<OUT, BigIntError> {
self.exp_inner::<RHS, OUT>(rhs).map(|x| x.unwrap())
}
/// Compute the logarithm of the big int with the base `rhs`.
/// Returns the result as a denormalized number.
///
/// ### Errors:
/// * `NonPositiveLogarithm` if the number is less than 1.
/// * `LogOfSmallBase` if `rhs` is less than 2.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Loose<10> = 1000.into();
/// let b: Loose<10> = a.log::<Loose<10>, Loose<10>>(10.into()).unwrap();
/// assert_eq!(b, 3.into());
/// ```
fn log_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
self,
rhs: RHS,
) -> Result<OUT::Denormal, BigIntError> {
if self <= Self::zero() {
return Err(BigIntError::NonPositiveLogarithm);
}
if rhs <= 1.into() {
return Err(BigIntError::LogOfSmallBase);
}
let mut mullands = rhs.mullands().memo();
let mut addends = OUT::from(1).addends().memo();
let mut power = 0;
let mut base: Self = 1.into();
let mut exp = OUT::zero();
let result = 'outer: {
loop {
let next_base: Self = unsafe {
base.clone()
.mul_inner::<RHS, Self>(mullands.get(power).unwrap().clone())
.unsafe_into()
};
let comparison = next_base.cmp_inner(&self);
if comparison.is_le() {
exp += addends.get(power).unwrap().clone();
base = next_base;
power += 1;
}
if comparison.is_ge() {
break;
}
}
for mulland_index in (0..power).rev() {
let next_base: Self = unsafe {
base.clone()
.mul_inner::<RHS, Self>(mullands.get(mulland_index).unwrap().clone())
.unsafe_into()
};
let comparison = next_base.cmp_inner(&self);
if comparison.is_le() {
exp += addends.get(mulland_index).unwrap().clone();
if comparison.is_eq() {
break 'outer exp;
}
base = next_base;
}
}
exp
};
Ok(result.into())
}
/// Compute the logarithm of the big int with the base `rhs`.
///
/// ### Errors:
/// * `NonPositiveLogarithm` if the number is less than 1.
/// * `LogOfSmallBase` if `rhs` is less than 2.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Loose<10> = 1000.into();
/// let b: Loose<10> = a.log::<Loose<10>, Loose<10>>(10.into()).unwrap();
/// assert_eq!(b, 3.into());
/// ```
fn log<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
self,
rhs: RHS,
) -> Result<OUT, BigIntError> {
self.log_inner::<RHS, OUT>(rhs).map(|x| x.unwrap())
}
/// Compute the square root of the big int.
/// Returns the result as a denormalized number.
///
/// ### Errors:
/// * `NegativeRoot` if the number is negative.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Loose<10> = 100.into();
/// assert_eq!(a.sqrt::<Loose<10>>().unwrap(), 10.into());
/// ```
fn sqrt_inner<OUT: BigInt<{ BASE }>>(self) -> Result<OUT::Denormal, BigIntError> {
if self < Self::zero() {
return Err(BigIntError::NegativeRoot);
}
if self.is_zero() {
return Ok(OUT::Denormal::zero());
}
let mut sq_addends = OUT::from(1).n_addends(4.into()).memo();
let mut base_addends = OUT::from(1).addends().memo();
let mut index = 0;
loop {
let comparison = sq_addends.get(index + 1).unwrap().cmp_inner(&self);
if comparison.is_le() {
index += 1;
if comparison.is_eq() {
return Ok(base_addends.get(index).unwrap().clone().into());
}
} else {
break;
}
}
let mut square = sq_addends.get(index).unwrap().clone();
let mut base = base_addends.get(index).unwrap().clone();
for i in (0..index).rev() {
let base_addition = base_addends.get(i).unwrap().clone();
let sq_addition = sq_addends.get(i).unwrap().clone();
let mut middle_part = base.clone() * base_addition.clone();
middle_part += middle_part.clone();
let new_square = square.clone() + middle_part + sq_addition;
let comparison = new_square.cmp_inner(&self);
if comparison.is_le() {
base += base_addition;
if comparison.is_eq() {
break;
}
square = new_square;
}
}
Ok(base.into())
}
/// Compute the square root of the big int.
///
/// ### Errors:
/// * `NegativeRoot` if the number is negative.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Loose<10> = 100.into();
/// assert_eq!(a.sqrt::<Loose<10>>().unwrap(), 10.into());
/// ```
fn sqrt<OUT: BigInt<{ BASE }>>(self) -> Result<OUT, BigIntError> {
self.sqrt_inner::<OUT>().map(|x| x.unwrap())
}
/// Compute the nth root of the big int, with root `rhs`.
/// Returns the result as a denormalized number.
///
/// ### Errors:
/// * `NegativeRoot` if the number is negative.
/// * `SmallRoot` if `rhs` is less than 2.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Loose<10> = 27.into();
/// assert_eq!(a.root::<Loose<10>, Loose<10>>(3.into()).unwrap(), 3.into());
/// ```
fn root_inner<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
self,
rhs: RHS,
) -> Result<OUT::Denormal, BigIntError> {
if self < Self::zero() {
return Err(BigIntError::NegativeRoot);
}
if self.is_zero() {
return Ok(OUT::Denormal::zero());
}
if rhs <= 1.into() {
return Err(BigIntError::SmallRoot);
}
let result_digits = (self.len() / Into::<usize>::into(rhs.clone())).max(1);
let mut result = OUT::from(1).shl_inner(result_digits);
result.set_digit(0, 0);
'outer: for i in 0..result.len() {
let mut digit_value = 0;
for index in (0..Self::BITS_PER_DIGIT).rev() {
let power = 1 << index;
result.set_digit(i, digit_value + power);
let new_exp: Self = result.clone().exp(rhs.clone()).unwrap();
let comparison = new_exp.cmp_inner(&self);
if comparison.is_le() {
digit_value += power;
if comparison.is_eq() {
break 'outer;
}
}
}
result.set_digit(i, digit_value);
}
Ok(result.into())
}
/// Compute the nth root of the big int, with root `rhs`.
///
/// ### Errors:
/// * `NegativeRoot` if the number is negative.
/// * `SmallRoot` if `rhs` is less than 2.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Loose<10> = 27.into();
/// assert_eq!(a.root::<Loose<10>, Loose<10>>(3.into()).unwrap(), 3.into());
/// ```
fn root<RHS: BigInt<{ BASE }>, OUT: BigInt<{ BASE }>>(
self,
rhs: RHS,
) -> Result<OUT, BigIntError> {
self.root_inner::<RHS, OUT>(rhs).map(|x| x.unwrap())
}
/// Check if the number is even.
///
/// O(1) for numbers with even bases, and O(log(n)) for numbers
/// with odd bases.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut n: Tight<10> = 16.into();
/// assert!(n.is_even());
/// n += 1.into();
/// assert!(!n.is_even());
/// ```
fn is_even(&self) -> bool {
if BASE % 2 == 0 {
self.get_digit(self.len() - 1)
.map(|d| d % 2 == 0)
.unwrap_or(true)
} else {
self.iter().filter(|d| d % 2 == 1).count() % 2 == 0
}
}
/// Iterate over the digits of the int.
///
/// implements `DoubleEndedIterator`, so digits can be iterated over forward or in reverse.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Tight<10> = 12345.into();
/// assert_eq!(a.iter().collect::<Vec<_>>(), vec![1, 2, 3, 4, 5]);
/// assert_eq!(a.iter().rev().collect::<Vec<_>>(), vec![5, 4, 3, 2, 1]);
/// ```
fn iter<'a>(&'a self) -> BigIntIter<'a, BASE, Self> {
BigIntIter {
index: 0,
back_index: self.len(),
int: self,
}
}
/// Return a normalized version of the int. A normalized int:
/// * has no trailing zeros
/// * has at least one digit
/// * is not negative zero
///
/// Additionally, `Tight` ints will be aligned to the beginning of their data segment
/// when normalized.
///
/// Defined in terms of `normalize`; at least one of `normalize` or `normalized`
/// must be defined by the implementer.
///
/// ```
/// use big_int::prelude::*;
///
/// let n = unsafe { Loose::<10>::from_raw_parts(vec![0, 0, 8, 3]) };
/// assert_eq!(n.normalized(), 83.into());
/// ```
fn normalized(mut self) -> Self {
self.normalize();
self
}
/// Normalize a big int in place. A normalized int:
/// * has no trailing zeros
/// * has at least one digit
/// * is not negative zero
///
/// Additionally, `Tight` ints will be aligned to the beginning of their data segment
/// when normalized.
///
/// Defined in terms of `normalized`; at least one of `normalize` or `normalized`
/// must be defined by the implementer.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut n = unsafe { Loose::<10>::from_raw_parts(vec![0, 0, 8, 3]) };
/// n.normalize();
/// assert_eq!(n, 83.into());
/// ```
fn normalize(&mut self) {
*self = self.clone().normalized();
}
/// Convert a big int to a printable string using the provided alphabet `alphabet`.
/// `Display` uses this method with the default alphabet `STANDARD_ALPHABET`.
///
/// ### Errors:
/// * `BaseTooHigh` if a digit in the number is too large to be displayed with
/// the chosen character alphabet.
///
/// ```
/// use big_int::prelude::*;
///
/// assert_eq!(
/// Loose::<10>::from(6012).display(STANDARD_ALPHABET).unwrap(),
/// "6012".to_string()
/// );
/// ```
fn display(&self, alphabet: &str) -> Result<String, BigIntError> {
let digits = self
.iter()
.map(|digit| {
alphabet
.chars()
.nth(digit as usize)
.ok_or(BigIntError::BaseTooHigh(BASE, alphabet.len()))
})
.collect::<Result<String, _>>()?;
if self.sign() == Negative {
Ok(format!("-{digits}"))
} else {
Ok(digits)
}
}
/// Parse a big int from a `value: &str`, referencing the provided `alphabet`
/// to determine what characters represent which digits. `FromStr` uses this method
/// with the default alphabet `STANDARD_ALPHABET`.
///
/// ### Errors:
/// * `NotEnoughCharacters` if there are no digit characters in the string.
/// * `UnrecognizedCharacter` if there is a character present which is neither a `-` sign
/// nor a character present in the passed alphabet.
/// * `DigitTooLarge` if a character decodes to a digit value which is larger than the base
/// of the number being parsed can represent.
///
/// ```
/// use big_int::prelude::*;
///
/// assert_eq!(Loose::parse("125", STANDARD_ALPHABET), Ok(DenormalLoose::<10>::from(125)));
/// ```
fn parse(value: &str, alphabet: &str) -> Result<Self::Denormal, ParseError> {
let mut builder = Self::Builder::new();
let (sign, chars) = match value.chars().next() {
Some('-') => (Negative, value.chars().skip(1)),
Some(_) => (Positive, value.chars().skip(0)),
None => return Err(ParseError::NotEnoughCharacters),
};
for char in chars {
match alphabet.chars().position(|c| c == char) {
Some(pos) => {
if pos >= BASE {
return Err(ParseError::DigitTooLarge(char, pos, BASE));
} else {
builder.push_back(pos as Digit);
}
}
None => return Err(ParseError::UnrecognizedCharacter(char)),
}
}
if builder.is_empty() {
Err(ParseError::NotEnoughCharacters)
} else {
Ok(builder.with_sign(sign).into())
}
}
/// Convert an int from its own base to another target base,
/// to another `BigInt` type, or both at once. Returns the result as
/// a denormalized number.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: DenormalTight<16> = Loose::<10>::from(99825).convert_inner::<16, Tight<16>>();
/// assert_eq!(a, DenormalTight::<16>::from(99825));
/// ```
fn convert_inner<const TO: usize, OUT: BigInt<{ TO }>>(mut self) -> OUT::Denormal {
let to = TO as Digit;
let base = BASE as Digit;
let sign = self.sign();
let mut result = OUT::Builder::new();
// bases are the same; just move the digits from one representation
// into the other
if BASE == TO {
for digit in self {
result.push_back(digit);
}
// current base is a power of the target base; perform a fast conversion
// by converting each individual digit from the current number into
// several contiguous digits of the target number
} else if let Some(power) = is_power(BASE, TO) {
for mut from_digit in self.rev() {
for _ in 0..power {
result.push_front(from_digit % to);
if from_digit >= to {
from_digit /= to;
} else {
from_digit = 0;
}
}
}
// target base is a power of the current base; perform a fast conversion
// by creating a single digit of the target number from several contiguous digits
// of the current number
} else if let Some(power) = is_power(TO, BASE) {
let mut iter = self.rev();
loop {
let mut to_digit = 0;
let mut done = false;
let mut place = 1;
for _ in 0..power {
if let Some(from_digit) = iter.next() {
to_digit += from_digit * place;
place *= base;
} else {
done = true;
break;
}
}
result.push_front(to_digit);
if done {
break;
}
}
// no special conditions apply; just perform the conversion normally via
// repeated divisons
} else {
self.set_sign(Positive);
let to_base: Self = to.into();
while self >= to_base {
let (quot, rem) = self.div_rem_inner::<_, Self>(to_base.clone()).unwrap();
self = unsafe { quot.unsafe_into() }.normalized();
result.push_front(Into::<Digit>::into(rem));
}
result.push_front(Into::<Digit>::into(self));
}
result.with_sign(sign).into()
}
/// Convert an int from its own base to another target base,
/// to another `BigInt` type, or both at once.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Tight<16> = Loose::<10>::from(99825).convert();
/// assert_eq!(a, Tight::<16>::from(99825));
/// ```
fn convert<const TO: usize, OUT: BigInt<{ TO }>>(self) -> OUT {
self.convert_inner::<TO, OUT>().unwrap()
}
/// Compare the absolute magnitude of two big ints, ignoring their sign.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Tight<10> = (-105).into();
/// let b: Tight<10> = 15.into();
/// assert!(a.cmp_magnitude(&b).is_gt());
/// ```
fn cmp_magnitude<RHS: BigInt<{ BASE }>>(&self, rhs: &RHS) -> Ordering {
for i in (1..=self.len().max(rhs.len())).rev() {
match (self.get_back(i), rhs.get_back(i)) {
(Some(1..), None) => return Ordering::Greater,
(None, Some(1..)) => return Ordering::Less,
(self_digit, rhs_digit) => match self_digit
.unwrap_or_default()
.cmp(&rhs_digit.unwrap_or_default())
{
Ordering::Equal => {}
ordering => return ordering,
},
}
}
Ordering::Equal
}
/// Return the absolute value of the int.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Loose<10> = (-13).into();
/// assert_eq!(a.abs(), 13.into());
/// ```
fn abs(self) -> Self {
self.with_sign(Positive)
}
}
/// Prepare a set of addends.
///
/// In an addend set, each element is 2x the element before it.
///
/// Used internally for efficient multiplication, division,
/// exponentiation, and logarithm algorithms.
struct AddendSet<const BASE: usize, B: BigInt<{ BASE }>> {
addend: B,
}
/// Construct an addend set from a big int.
trait Addends<const BASE: usize, B: BigInt<{ BASE }>> {
/// Construct an addend set from a big int.
fn addends(self) -> AddendSet<BASE, B>;
}
impl<const BASE: usize, B: BigInt<{ BASE }>> Addends<BASE, B> for B {
fn addends(self) -> AddendSet<BASE, B> {
AddendSet { addend: self }
}
}
impl<const BASE: usize, B: BigInt<{ BASE }>> Iterator for AddendSet<BASE, B> {
type Item = B;
fn next(&mut self) -> Option<Self::Item> {
let next_addend = self.addend.clone();
self.addend += self.addend.clone();
Some(next_addend)
}
}
/// Prepare a set of mullands.
///
/// In a mulland set, each element is the square of the element before it.
///
/// Used internally for efficient exponentiation & logarithm algorithms.
struct MullandSet<const BASE: usize, B: BigInt<{ BASE }>> {
mulland: B,
}
/// Construct a mulland set from a big int.
trait Mullands<const BASE: usize, B: BigInt<{ BASE }>> {
/// Construct a mulland set from a big int.
fn mullands(self) -> MullandSet<BASE, B>;
}
impl<const BASE: usize, B: BigInt<{ BASE }>> Mullands<BASE, B> for B {
fn mullands(self) -> MullandSet<BASE, B> {
MullandSet { mulland: self }
}
}
impl<const BASE: usize, B: BigInt<{ BASE }>> Iterator for MullandSet<BASE, B> {
type Item = B;
fn next(&mut self) -> Option<Self::Item> {
let next_mulland = self.mulland.clone();
self.mulland *= self.mulland.clone();
Some(next_mulland)
}
}
/// Prepare a set of n-addends.
///
/// In an n-addend set, each element is `factor` * the element before it.
///
/// Used internally for the efficient square root algorithm.
struct NAddendSet<const BASE: usize, B: BigInt<{ BASE }>> {
addend: B,
factor: B,
}
/// Construct an n-adddend set from a big int.
trait NAddends<const BASE: usize, B: BigInt<{ BASE }>> {
/// Construct an n-adddend set from a big int.
fn n_addends(self, factor: B) -> NAddendSet<BASE, B>;
}
impl<const BASE: usize, B: BigInt<{ BASE }>> NAddends<BASE, B> for B {
fn n_addends(self, factor: B) -> NAddendSet<BASE, B> {
NAddendSet {
addend: self,
factor,
}
}
}
impl<const BASE: usize, B: BigInt<{ BASE }>> Iterator for NAddendSet<BASE, B> {
type Item = B;
fn next(&mut self) -> Option<Self::Item> {
let next_mulland = self.addend.clone();
self.addend *= self.factor.clone();
Some(next_mulland)
}
}
/// A memoized iterator. Remembers elements that were yielded by the
/// underlying iterator, and allows fetching of them after the fact.
struct IterMemo<I: Iterator> {
memo: Vec<I::Item>,
iter: I,
exhausted: bool,
}
impl<I: Iterator> IterMemo<I> {
/// Fetch a memoized item from the iterator, pulling new items from it
/// as needed.
fn get(&mut self, index: usize) -> Option<&I::Item> {
while self.memo.len() <= index && !self.exhausted {
self.store_next();
}
self.memo.get(index)
}
/// Fetch a mutable reference to a memoized item from the iterator,
/// pulling new items from it as needed.
fn get_mut(&mut self, index: usize) -> Option<&mut I::Item> {
while self.memo.len() <= index && !self.exhausted {
self.store_next();
}
self.memo.get_mut(index)
}
/// Store the next element from the iterator in the memo, growing
/// it by one.
fn store_next(&mut self) {
if let Some(item) = self.iter.next() {
self.memo.push(item);
} else {
self.exhausted = true;
}
}
}
impl<I: Iterator> From<I> for IterMemo<I> {
fn from(value: I) -> Self {
IterMemo {
memo: Vec::new(),
iter: value,
exhausted: false,
}
}
}
/// Transitive trait to allow one to call `.memo()` on iterators
/// to make a memoizer from them
trait ToMemo: Iterator + Sized {
/// Translate an iterator into a memoized iterator.
fn memo(self) -> IterMemo<Self> {
self.into()
}
}
impl<I: Iterator> ToMemo for I {}
/// A builder for a big int. Use this to construct a big int one digit at a time,
/// then call .into() to construct the final int.
///
/// You're most likely better off using one of the `From` implementations
/// as opposed to directly building your int via a builder.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a = TightBuilder::<10>::new();
/// a.push_back(5);
/// a.push_back(3);
/// a.push_back(0);
/// a.push_back(4);
/// let a: Tight<10> = a.into();
/// assert_eq!(a, 5304.into());
/// ```
pub trait BigIntBuilder<const BASE: usize>
where
Self: std::fmt::Debug,
{
/// Create a new builder.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a = TightBuilder::<10>::new();
/// unsafe {
/// a.push_back(5);
/// }
/// let a: Tight<10> = a.into();
/// assert_eq!(a, 5.into());
/// ```
fn new() -> Self;
/// Push a new digit to the end of the int.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a = TightBuilder::<10>::new();
/// a.push_back(5);
/// a.push_back(6);
/// let a: Tight<10> = a.into();
/// assert_eq!(a, 56.into());
/// ```
fn push_front(&mut self, digit: Digit);
/// Push a new digit to the beginning of the int.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a = TightBuilder::<10>::new();
/// a.push_front(5);
/// a.push_front(6);
/// let a: Tight<10> = a.into();
/// assert_eq!(a, 65.into());
/// ```
fn push_back(&mut self, digit: Digit);
/// Check if the builder is empty.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a = TightBuilder::<10>::new();
/// assert!(a.is_empty());
/// a.push_front(5);
/// assert!(!a.is_empty());
/// ```
fn is_empty(&self) -> bool;
/// The builder with the given sign.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a = TightBuilder::<10>::new();
/// a.push_back(9);
/// let a: Tight<10> = a.with_sign(Negative).into();
/// assert_eq!(a, (-9).into());
/// ```
fn with_sign(self, sign: Sign) -> Self;
}
/// A conversion that may only be performed unsafely.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Tight<10> = unsafe { Tight::<10>::from_u128_inner(532).unsafe_into() };
/// assert_eq!(a, 532.into());
/// ```
pub trait UnsafeInto<T> {
unsafe fn unsafe_into(self) -> T;
}
impl<T> UnsafeInto<T> for T {
unsafe fn unsafe_into(self) -> T {
self
}
}
/// A value that may be unwrapped.
///
/// ```
/// use big_int::prelude::*;
///
/// let a: Tight<10> = 120.into();
/// let b: Tight<10> = 5.into();
/// let b: DenormalTight<10> = a.div_inner::<_, Tight<10>>(b);
/// let c: Tight<10> = b.unwrap();
/// assert_eq!(c, 24.into());
/// ```
pub trait Unwrap<T> {
fn unwrap(self) -> T;
}
/// Represents the sign of a big int; either Positive or Negative.
///
/// ```
/// use big_int::prelude::*;
///
/// let mut a: Tight<10> = 18.into();
/// let s = a.sign();
/// assert_eq!(s, Positive);
/// a *= (-1).into();
/// let s = a.sign();
/// assert_eq!(s, Negative);
/// ```
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Sign {
Positive,
Negative,
}
impl Neg for Sign {
type Output = Sign;
fn neg(self) -> Self::Output {
match self {
Positive => Negative,
Negative => Positive,
}
}
}
impl Mul for Sign {
type Output = Sign;
fn mul(self, rhs: Self) -> Self::Output {
if self == rhs {
Positive
} else {
Negative
}
}
}
/// An iterator over the digits of a big int.
///
/// ```
/// use big_int::prelude::*;
/// use std::iter::Rev;
///
/// let a: Loose<10> = 12345.into();
/// let it = a.iter();
/// let rev_it = a.iter().rev();
/// assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3, 4, 5]);
/// assert_eq!(rev_it.collect::<Vec<_>>(), vec![5, 4, 3, 2, 1]);
/// ```
pub struct BigIntIter<'a, const BASE: usize, B: BigInt<{ BASE }>> {
index: usize,
back_index: usize,
int: &'a B,
}
impl<'a, const BASE: usize, B: BigInt<{ BASE }>> Iterator for BigIntIter<'_, BASE, B> {
type Item = Digit;
fn next(&mut self) -> Option<Self::Item> {
(self.index < self.back_index)
.then_some(&mut self.index)
.and_then(|index| {
*index += 1;
self.int.get_digit(*index - 1)
})
}
}
impl<'a, const BASE: usize, B: BigInt<{ BASE }>> DoubleEndedIterator for BigIntIter<'_, BASE, B> {
fn next_back(&mut self) -> Option<Self::Item> {
(self.back_index > self.index)
.then_some(&mut self.back_index)
.and_then(|index| {
*index -= 1;
self.int.get_digit(*index)
})
}
}
/// Check if a number is a power of another number.
///
/// If `x` is a power of `y`, return `Some(n)` such that
/// `x == y^n`. If not, return `None`.
///
/// ```
/// use big_int::prelude::*;
///
/// assert_eq!(is_power(2, 3), None);
/// assert_eq!(is_power(16, 4), Some(2));
/// assert_eq!(is_power(27, 3), Some(3));
/// assert_eq!(is_power(256, 2), Some(8));
/// ```
pub(crate) fn is_power(mut x: usize, y: usize) -> Option<usize> {
if x == 1 {
Some(0)
} else {
let mut power = 1;
loop {
if x % y != 0 {
return None;
}
match x.cmp(&y) {
Ordering::Equal => return Some(power),
Ordering::Less => return None,
Ordering::Greater => {
power += 1;
x /= y;
}
}
}
}
}
/// Calculate the minimum number of bits required to store a digit in a given base.
pub(crate) const fn bits_per_digit(base: usize) -> usize {
let mut bits = 1;
let mut max_base_of_bits = 2;
while max_base_of_bits < base {
bits += 1;
max_base_of_bits <<= 1;
}
bits
}