bigint.rs 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. use std::default::Default;
  2. use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub};
  3. use std::str::{self, FromStr};
  4. use std::fmt;
  5. use std::cmp::Ordering::{self, Less, Greater, Equal};
  6. use std::{f32, f64};
  7. use std::{u8, i64, u64};
  8. use std::ascii::AsciiExt;
  9. #[cfg(feature = "serde")]
  10. use serde;
  11. // Some of the tests of non-RNG-based functionality are randomized using the
  12. // RNG-based functionality, so the RNG-based functionality needs to be enabled
  13. // for tests.
  14. #[cfg(any(feature = "rand", test))]
  15. use rand::Rng;
  16. use integer::Integer;
  17. use traits::{ToPrimitive, FromPrimitive, Num, CheckedAdd, CheckedSub, CheckedMul,
  18. CheckedDiv, Signed, Zero, One};
  19. use self::Sign::{Minus, NoSign, Plus};
  20. use super::ParseBigIntError;
  21. use super::big_digit;
  22. use super::big_digit::BigDigit;
  23. use biguint;
  24. use biguint::to_str_radix_reversed;
  25. use biguint::BigUint;
  26. #[cfg(test)]
  27. #[path = "tests/bigint.rs"]
  28. mod bigint_tests;
  29. /// A Sign is a `BigInt`'s composing element.
  30. #[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone, Debug, Hash)]
  31. #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
  32. pub enum Sign {
  33. Minus,
  34. NoSign,
  35. Plus,
  36. }
  37. impl Neg for Sign {
  38. type Output = Sign;
  39. /// Negate Sign value.
  40. #[inline]
  41. fn neg(self) -> Sign {
  42. match self {
  43. Minus => Plus,
  44. NoSign => NoSign,
  45. Plus => Minus,
  46. }
  47. }
  48. }
  49. impl Mul<Sign> for Sign {
  50. type Output = Sign;
  51. #[inline]
  52. fn mul(self, other: Sign) -> Sign {
  53. match (self, other) {
  54. (NoSign, _) | (_, NoSign) => NoSign,
  55. (Plus, Plus) | (Minus, Minus) => Plus,
  56. (Plus, Minus) | (Minus, Plus) => Minus,
  57. }
  58. }
  59. }
  60. #[cfg(feature = "serde")]
  61. impl serde::Serialize for Sign {
  62. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
  63. where S: serde::Serializer
  64. {
  65. match *self {
  66. Sign::Minus => (-1i8).serialize(serializer),
  67. Sign::NoSign => 0i8.serialize(serializer),
  68. Sign::Plus => 1i8.serialize(serializer),
  69. }
  70. }
  71. }
  72. #[cfg(feature = "serde")]
  73. impl serde::Deserialize for Sign {
  74. fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
  75. where D: serde::Deserializer
  76. {
  77. use serde::de::Error;
  78. let sign: i8 = try!(serde::Deserialize::deserialize(deserializer));
  79. match sign {
  80. -1 => Ok(Sign::Minus),
  81. 0 => Ok(Sign::NoSign),
  82. 1 => Ok(Sign::Plus),
  83. _ => Err(D::Error::invalid_value("sign must be -1, 0, or 1")),
  84. }
  85. }
  86. }
  87. /// A big signed integer type.
  88. #[derive(Clone, Debug, Hash)]
  89. #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
  90. pub struct BigInt {
  91. sign: Sign,
  92. data: BigUint,
  93. }
  94. impl PartialEq for BigInt {
  95. #[inline]
  96. fn eq(&self, other: &BigInt) -> bool {
  97. self.cmp(other) == Equal
  98. }
  99. }
  100. impl Eq for BigInt {}
  101. impl PartialOrd for BigInt {
  102. #[inline]
  103. fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> {
  104. Some(self.cmp(other))
  105. }
  106. }
  107. impl Ord for BigInt {
  108. #[inline]
  109. fn cmp(&self, other: &BigInt) -> Ordering {
  110. let scmp = self.sign.cmp(&other.sign);
  111. if scmp != Equal {
  112. return scmp;
  113. }
  114. match self.sign {
  115. NoSign => Equal,
  116. Plus => self.data.cmp(&other.data),
  117. Minus => other.data.cmp(&self.data),
  118. }
  119. }
  120. }
  121. impl Default for BigInt {
  122. #[inline]
  123. fn default() -> BigInt {
  124. Zero::zero()
  125. }
  126. }
  127. impl fmt::Display for BigInt {
  128. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  129. f.pad_integral(!self.is_negative(), "", &self.data.to_str_radix(10))
  130. }
  131. }
  132. impl fmt::Binary for BigInt {
  133. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  134. f.pad_integral(!self.is_negative(), "0b", &self.data.to_str_radix(2))
  135. }
  136. }
  137. impl fmt::Octal for BigInt {
  138. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  139. f.pad_integral(!self.is_negative(), "0o", &self.data.to_str_radix(8))
  140. }
  141. }
  142. impl fmt::LowerHex for BigInt {
  143. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  144. f.pad_integral(!self.is_negative(), "0x", &self.data.to_str_radix(16))
  145. }
  146. }
  147. impl fmt::UpperHex for BigInt {
  148. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  149. f.pad_integral(!self.is_negative(),
  150. "0x",
  151. &self.data.to_str_radix(16).to_ascii_uppercase())
  152. }
  153. }
  154. impl FromStr for BigInt {
  155. type Err = ParseBigIntError;
  156. #[inline]
  157. fn from_str(s: &str) -> Result<BigInt, ParseBigIntError> {
  158. BigInt::from_str_radix(s, 10)
  159. }
  160. }
  161. impl Num for BigInt {
  162. type FromStrRadixErr = ParseBigIntError;
  163. /// Creates and initializes a BigInt.
  164. #[inline]
  165. fn from_str_radix(mut s: &str, radix: u32) -> Result<BigInt, ParseBigIntError> {
  166. let sign = if s.starts_with('-') {
  167. let tail = &s[1..];
  168. if !tail.starts_with('+') {
  169. s = tail
  170. }
  171. Minus
  172. } else {
  173. Plus
  174. };
  175. let bu = try!(BigUint::from_str_radix(s, radix));
  176. Ok(BigInt::from_biguint(sign, bu))
  177. }
  178. }
  179. impl Shl<usize> for BigInt {
  180. type Output = BigInt;
  181. #[inline]
  182. fn shl(self, rhs: usize) -> BigInt {
  183. (&self) << rhs
  184. }
  185. }
  186. impl<'a> Shl<usize> for &'a BigInt {
  187. type Output = BigInt;
  188. #[inline]
  189. fn shl(self, rhs: usize) -> BigInt {
  190. BigInt::from_biguint(self.sign, &self.data << rhs)
  191. }
  192. }
  193. impl Shr<usize> for BigInt {
  194. type Output = BigInt;
  195. #[inline]
  196. fn shr(self, rhs: usize) -> BigInt {
  197. BigInt::from_biguint(self.sign, self.data >> rhs)
  198. }
  199. }
  200. impl<'a> Shr<usize> for &'a BigInt {
  201. type Output = BigInt;
  202. #[inline]
  203. fn shr(self, rhs: usize) -> BigInt {
  204. BigInt::from_biguint(self.sign, &self.data >> rhs)
  205. }
  206. }
  207. impl Zero for BigInt {
  208. #[inline]
  209. fn zero() -> BigInt {
  210. BigInt::from_biguint(NoSign, Zero::zero())
  211. }
  212. #[inline]
  213. fn is_zero(&self) -> bool {
  214. self.sign == NoSign
  215. }
  216. }
  217. impl One for BigInt {
  218. #[inline]
  219. fn one() -> BigInt {
  220. BigInt::from_biguint(Plus, One::one())
  221. }
  222. }
  223. impl Signed for BigInt {
  224. #[inline]
  225. fn abs(&self) -> BigInt {
  226. match self.sign {
  227. Plus | NoSign => self.clone(),
  228. Minus => BigInt::from_biguint(Plus, self.data.clone()),
  229. }
  230. }
  231. #[inline]
  232. fn abs_sub(&self, other: &BigInt) -> BigInt {
  233. if *self <= *other {
  234. Zero::zero()
  235. } else {
  236. self - other
  237. }
  238. }
  239. #[inline]
  240. fn signum(&self) -> BigInt {
  241. match self.sign {
  242. Plus => BigInt::from_biguint(Plus, One::one()),
  243. Minus => BigInt::from_biguint(Minus, One::one()),
  244. NoSign => Zero::zero(),
  245. }
  246. }
  247. #[inline]
  248. fn is_positive(&self) -> bool {
  249. self.sign == Plus
  250. }
  251. #[inline]
  252. fn is_negative(&self) -> bool {
  253. self.sign == Minus
  254. }
  255. }
  256. // We want to forward to BigUint::add, but it's not clear how that will go until
  257. // we compare both sign and magnitude. So we duplicate this body for every
  258. // val/ref combination, deferring that decision to BigUint's own forwarding.
  259. macro_rules! bigint_add {
  260. ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
  261. match ($a.sign, $b.sign) {
  262. (_, NoSign) => $a_owned,
  263. (NoSign, _) => $b_owned,
  264. // same sign => keep the sign with the sum of magnitudes
  265. (Plus, Plus) | (Minus, Minus) =>
  266. BigInt::from_biguint($a.sign, $a_data + $b_data),
  267. // opposite signs => keep the sign of the larger with the difference of magnitudes
  268. (Plus, Minus) | (Minus, Plus) =>
  269. match $a.data.cmp(&$b.data) {
  270. Less => BigInt::from_biguint($b.sign, $b_data - $a_data),
  271. Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
  272. Equal => Zero::zero(),
  273. },
  274. }
  275. };
  276. }
  277. impl<'a, 'b> Add<&'b BigInt> for &'a BigInt {
  278. type Output = BigInt;
  279. #[inline]
  280. fn add(self, other: &BigInt) -> BigInt {
  281. bigint_add!(self,
  282. self.clone(),
  283. &self.data,
  284. other,
  285. other.clone(),
  286. &other.data)
  287. }
  288. }
  289. impl<'a> Add<BigInt> for &'a BigInt {
  290. type Output = BigInt;
  291. #[inline]
  292. fn add(self, other: BigInt) -> BigInt {
  293. bigint_add!(self, self.clone(), &self.data, other, other, other.data)
  294. }
  295. }
  296. impl<'a> Add<&'a BigInt> for BigInt {
  297. type Output = BigInt;
  298. #[inline]
  299. fn add(self, other: &BigInt) -> BigInt {
  300. bigint_add!(self, self, self.data, other, other.clone(), &other.data)
  301. }
  302. }
  303. impl Add<BigInt> for BigInt {
  304. type Output = BigInt;
  305. #[inline]
  306. fn add(self, other: BigInt) -> BigInt {
  307. bigint_add!(self, self, self.data, other, other, other.data)
  308. }
  309. }
  310. // We want to forward to BigUint::sub, but it's not clear how that will go until
  311. // we compare both sign and magnitude. So we duplicate this body for every
  312. // val/ref combination, deferring that decision to BigUint's own forwarding.
  313. macro_rules! bigint_sub {
  314. ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
  315. match ($a.sign, $b.sign) {
  316. (_, NoSign) => $a_owned,
  317. (NoSign, _) => -$b_owned,
  318. // opposite signs => keep the sign of the left with the sum of magnitudes
  319. (Plus, Minus) | (Minus, Plus) =>
  320. BigInt::from_biguint($a.sign, $a_data + $b_data),
  321. // same sign => keep or toggle the sign of the left with the difference of magnitudes
  322. (Plus, Plus) | (Minus, Minus) =>
  323. match $a.data.cmp(&$b.data) {
  324. Less => BigInt::from_biguint(-$a.sign, $b_data - $a_data),
  325. Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
  326. Equal => Zero::zero(),
  327. },
  328. }
  329. };
  330. }
  331. impl<'a, 'b> Sub<&'b BigInt> for &'a BigInt {
  332. type Output = BigInt;
  333. #[inline]
  334. fn sub(self, other: &BigInt) -> BigInt {
  335. bigint_sub!(self,
  336. self.clone(),
  337. &self.data,
  338. other,
  339. other.clone(),
  340. &other.data)
  341. }
  342. }
  343. impl<'a> Sub<BigInt> for &'a BigInt {
  344. type Output = BigInt;
  345. #[inline]
  346. fn sub(self, other: BigInt) -> BigInt {
  347. bigint_sub!(self, self.clone(), &self.data, other, other, other.data)
  348. }
  349. }
  350. impl<'a> Sub<&'a BigInt> for BigInt {
  351. type Output = BigInt;
  352. #[inline]
  353. fn sub(self, other: &BigInt) -> BigInt {
  354. bigint_sub!(self, self, self.data, other, other.clone(), &other.data)
  355. }
  356. }
  357. impl Sub<BigInt> for BigInt {
  358. type Output = BigInt;
  359. #[inline]
  360. fn sub(self, other: BigInt) -> BigInt {
  361. bigint_sub!(self, self, self.data, other, other, other.data)
  362. }
  363. }
  364. forward_all_binop_to_ref_ref!(impl Mul for BigInt, mul);
  365. impl<'a, 'b> Mul<&'b BigInt> for &'a BigInt {
  366. type Output = BigInt;
  367. #[inline]
  368. fn mul(self, other: &BigInt) -> BigInt {
  369. BigInt::from_biguint(self.sign * other.sign, &self.data * &other.data)
  370. }
  371. }
  372. forward_all_binop_to_ref_ref!(impl Div for BigInt, div);
  373. impl<'a, 'b> Div<&'b BigInt> for &'a BigInt {
  374. type Output = BigInt;
  375. #[inline]
  376. fn div(self, other: &BigInt) -> BigInt {
  377. let (q, _) = self.div_rem(other);
  378. q
  379. }
  380. }
  381. forward_all_binop_to_ref_ref!(impl Rem for BigInt, rem);
  382. impl<'a, 'b> Rem<&'b BigInt> for &'a BigInt {
  383. type Output = BigInt;
  384. #[inline]
  385. fn rem(self, other: &BigInt) -> BigInt {
  386. let (_, r) = self.div_rem(other);
  387. r
  388. }
  389. }
  390. impl Neg for BigInt {
  391. type Output = BigInt;
  392. #[inline]
  393. fn neg(mut self) -> BigInt {
  394. self.sign = -self.sign;
  395. self
  396. }
  397. }
  398. impl<'a> Neg for &'a BigInt {
  399. type Output = BigInt;
  400. #[inline]
  401. fn neg(self) -> BigInt {
  402. -self.clone()
  403. }
  404. }
  405. impl CheckedAdd for BigInt {
  406. #[inline]
  407. fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
  408. return Some(self.add(v));
  409. }
  410. }
  411. impl CheckedSub for BigInt {
  412. #[inline]
  413. fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
  414. return Some(self.sub(v));
  415. }
  416. }
  417. impl CheckedMul for BigInt {
  418. #[inline]
  419. fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
  420. return Some(self.mul(v));
  421. }
  422. }
  423. impl CheckedDiv for BigInt {
  424. #[inline]
  425. fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
  426. if v.is_zero() {
  427. return None;
  428. }
  429. return Some(self.div(v));
  430. }
  431. }
  432. impl Integer for BigInt {
  433. #[inline]
  434. fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) {
  435. // r.sign == self.sign
  436. let (d_ui, r_ui) = self.data.div_mod_floor(&other.data);
  437. let d = BigInt::from_biguint(self.sign, d_ui);
  438. let r = BigInt::from_biguint(self.sign, r_ui);
  439. if other.is_negative() {
  440. (-d, r)
  441. } else {
  442. (d, r)
  443. }
  444. }
  445. #[inline]
  446. fn div_floor(&self, other: &BigInt) -> BigInt {
  447. let (d, _) = self.div_mod_floor(other);
  448. d
  449. }
  450. #[inline]
  451. fn mod_floor(&self, other: &BigInt) -> BigInt {
  452. let (_, m) = self.div_mod_floor(other);
  453. m
  454. }
  455. fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) {
  456. // m.sign == other.sign
  457. let (d_ui, m_ui) = self.data.div_rem(&other.data);
  458. let d = BigInt::from_biguint(Plus, d_ui);
  459. let m = BigInt::from_biguint(Plus, m_ui);
  460. let one: BigInt = One::one();
  461. match (self.sign, other.sign) {
  462. (_, NoSign) => panic!(),
  463. (Plus, Plus) | (NoSign, Plus) => (d, m),
  464. (Plus, Minus) | (NoSign, Minus) => {
  465. if m.is_zero() {
  466. (-d, Zero::zero())
  467. } else {
  468. (-d - one, m + other)
  469. }
  470. }
  471. (Minus, Plus) => {
  472. if m.is_zero() {
  473. (-d, Zero::zero())
  474. } else {
  475. (-d - one, other - m)
  476. }
  477. }
  478. (Minus, Minus) => (d, -m),
  479. }
  480. }
  481. /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
  482. ///
  483. /// The result is always positive.
  484. #[inline]
  485. fn gcd(&self, other: &BigInt) -> BigInt {
  486. BigInt::from_biguint(Plus, self.data.gcd(&other.data))
  487. }
  488. /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
  489. #[inline]
  490. fn lcm(&self, other: &BigInt) -> BigInt {
  491. BigInt::from_biguint(Plus, self.data.lcm(&other.data))
  492. }
  493. /// Deprecated, use `is_multiple_of` instead.
  494. #[inline]
  495. fn divides(&self, other: &BigInt) -> bool {
  496. return self.is_multiple_of(other);
  497. }
  498. /// Returns `true` if the number is a multiple of `other`.
  499. #[inline]
  500. fn is_multiple_of(&self, other: &BigInt) -> bool {
  501. self.data.is_multiple_of(&other.data)
  502. }
  503. /// Returns `true` if the number is divisible by `2`.
  504. #[inline]
  505. fn is_even(&self) -> bool {
  506. self.data.is_even()
  507. }
  508. /// Returns `true` if the number is not divisible by `2`.
  509. #[inline]
  510. fn is_odd(&self) -> bool {
  511. self.data.is_odd()
  512. }
  513. }
  514. impl ToPrimitive for BigInt {
  515. #[inline]
  516. fn to_i64(&self) -> Option<i64> {
  517. match self.sign {
  518. Plus => self.data.to_i64(),
  519. NoSign => Some(0),
  520. Minus => {
  521. self.data.to_u64().and_then(|n| {
  522. let m: u64 = 1 << 63;
  523. if n < m {
  524. Some(-(n as i64))
  525. } else if n == m {
  526. Some(i64::MIN)
  527. } else {
  528. None
  529. }
  530. })
  531. }
  532. }
  533. }
  534. #[inline]
  535. fn to_u64(&self) -> Option<u64> {
  536. match self.sign {
  537. Plus => self.data.to_u64(),
  538. NoSign => Some(0),
  539. Minus => None,
  540. }
  541. }
  542. #[inline]
  543. fn to_f32(&self) -> Option<f32> {
  544. self.data.to_f32().map(|n| {
  545. if self.sign == Minus {
  546. -n
  547. } else {
  548. n
  549. }
  550. })
  551. }
  552. #[inline]
  553. fn to_f64(&self) -> Option<f64> {
  554. self.data.to_f64().map(|n| {
  555. if self.sign == Minus {
  556. -n
  557. } else {
  558. n
  559. }
  560. })
  561. }
  562. }
  563. impl FromPrimitive for BigInt {
  564. #[inline]
  565. fn from_i64(n: i64) -> Option<BigInt> {
  566. Some(BigInt::from(n))
  567. }
  568. #[inline]
  569. fn from_u64(n: u64) -> Option<BigInt> {
  570. Some(BigInt::from(n))
  571. }
  572. #[inline]
  573. fn from_f64(n: f64) -> Option<BigInt> {
  574. if n >= 0.0 {
  575. BigUint::from_f64(n).map(|x| BigInt::from_biguint(Plus, x))
  576. } else {
  577. BigUint::from_f64(-n).map(|x| BigInt::from_biguint(Minus, x))
  578. }
  579. }
  580. }
  581. impl From<i64> for BigInt {
  582. #[inline]
  583. fn from(n: i64) -> Self {
  584. if n >= 0 {
  585. BigInt::from(n as u64)
  586. } else {
  587. let u = u64::MAX - (n as u64) + 1;
  588. BigInt {
  589. sign: Minus,
  590. data: BigUint::from(u),
  591. }
  592. }
  593. }
  594. }
  595. macro_rules! impl_bigint_from_int {
  596. ($T:ty) => {
  597. impl From<$T> for BigInt {
  598. #[inline]
  599. fn from(n: $T) -> Self {
  600. BigInt::from(n as i64)
  601. }
  602. }
  603. }
  604. }
  605. impl_bigint_from_int!(i8);
  606. impl_bigint_from_int!(i16);
  607. impl_bigint_from_int!(i32);
  608. impl_bigint_from_int!(isize);
  609. impl From<u64> for BigInt {
  610. #[inline]
  611. fn from(n: u64) -> Self {
  612. if n > 0 {
  613. BigInt {
  614. sign: Plus,
  615. data: BigUint::from(n),
  616. }
  617. } else {
  618. BigInt::zero()
  619. }
  620. }
  621. }
  622. macro_rules! impl_bigint_from_uint {
  623. ($T:ty) => {
  624. impl From<$T> for BigInt {
  625. #[inline]
  626. fn from(n: $T) -> Self {
  627. BigInt::from(n as u64)
  628. }
  629. }
  630. }
  631. }
  632. impl_bigint_from_uint!(u8);
  633. impl_bigint_from_uint!(u16);
  634. impl_bigint_from_uint!(u32);
  635. impl_bigint_from_uint!(usize);
  636. impl From<BigUint> for BigInt {
  637. #[inline]
  638. fn from(n: BigUint) -> Self {
  639. if n.is_zero() {
  640. BigInt::zero()
  641. } else {
  642. BigInt {
  643. sign: Plus,
  644. data: n,
  645. }
  646. }
  647. }
  648. }
  649. #[cfg(feature = "serde")]
  650. impl serde::Serialize for BigInt {
  651. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
  652. where S: serde::Serializer
  653. {
  654. (self.sign, &self.data).serialize(serializer)
  655. }
  656. }
  657. #[cfg(feature = "serde")]
  658. impl serde::Deserialize for BigInt {
  659. fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
  660. where D: serde::Deserializer
  661. {
  662. let (sign, data) = try!(serde::Deserialize::deserialize(deserializer));
  663. Ok(BigInt {
  664. sign: sign,
  665. data: data,
  666. })
  667. }
  668. }
  669. /// A generic trait for converting a value to a `BigInt`.
  670. pub trait ToBigInt {
  671. /// Converts the value of `self` to a `BigInt`.
  672. fn to_bigint(&self) -> Option<BigInt>;
  673. }
  674. impl ToBigInt for BigInt {
  675. #[inline]
  676. fn to_bigint(&self) -> Option<BigInt> {
  677. Some(self.clone())
  678. }
  679. }
  680. impl ToBigInt for BigUint {
  681. #[inline]
  682. fn to_bigint(&self) -> Option<BigInt> {
  683. if self.is_zero() {
  684. Some(Zero::zero())
  685. } else {
  686. Some(BigInt {
  687. sign: Plus,
  688. data: self.clone(),
  689. })
  690. }
  691. }
  692. }
  693. impl biguint::ToBigUint for BigInt {
  694. #[inline]
  695. fn to_biguint(&self) -> Option<BigUint> {
  696. match self.sign() {
  697. Plus => Some(self.data.clone()),
  698. NoSign => Some(Zero::zero()),
  699. Minus => None,
  700. }
  701. }
  702. }
  703. macro_rules! impl_to_bigint {
  704. ($T:ty, $from_ty:path) => {
  705. impl ToBigInt for $T {
  706. #[inline]
  707. fn to_bigint(&self) -> Option<BigInt> {
  708. $from_ty(*self)
  709. }
  710. }
  711. }
  712. }
  713. impl_to_bigint!(isize, FromPrimitive::from_isize);
  714. impl_to_bigint!(i8, FromPrimitive::from_i8);
  715. impl_to_bigint!(i16, FromPrimitive::from_i16);
  716. impl_to_bigint!(i32, FromPrimitive::from_i32);
  717. impl_to_bigint!(i64, FromPrimitive::from_i64);
  718. impl_to_bigint!(usize, FromPrimitive::from_usize);
  719. impl_to_bigint!(u8, FromPrimitive::from_u8);
  720. impl_to_bigint!(u16, FromPrimitive::from_u16);
  721. impl_to_bigint!(u32, FromPrimitive::from_u32);
  722. impl_to_bigint!(u64, FromPrimitive::from_u64);
  723. impl_to_bigint!(f32, FromPrimitive::from_f32);
  724. impl_to_bigint!(f64, FromPrimitive::from_f64);
  725. pub trait RandBigInt {
  726. /// Generate a random `BigUint` of the given bit size.
  727. fn gen_biguint(&mut self, bit_size: usize) -> BigUint;
  728. /// Generate a random BigInt of the given bit size.
  729. fn gen_bigint(&mut self, bit_size: usize) -> BigInt;
  730. /// Generate a random `BigUint` less than the given bound. Fails
  731. /// when the bound is zero.
  732. fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint;
  733. /// Generate a random `BigUint` within the given range. The lower
  734. /// bound is inclusive; the upper bound is exclusive. Fails when
  735. /// the upper bound is not greater than the lower bound.
  736. fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;
  737. /// Generate a random `BigInt` within the given range. The lower
  738. /// bound is inclusive; the upper bound is exclusive. Fails when
  739. /// the upper bound is not greater than the lower bound.
  740. fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt;
  741. }
  742. #[cfg(any(feature = "rand", test))]
  743. impl<R: Rng> RandBigInt for R {
  744. fn gen_biguint(&mut self, bit_size: usize) -> BigUint {
  745. let (digits, rem) = bit_size.div_rem(&big_digit::BITS);
  746. let mut data = Vec::with_capacity(digits + 1);
  747. for _ in 0..digits {
  748. data.push(self.gen());
  749. }
  750. if rem > 0 {
  751. let final_digit: BigDigit = self.gen();
  752. data.push(final_digit >> (big_digit::BITS - rem));
  753. }
  754. BigUint::new(data)
  755. }
  756. fn gen_bigint(&mut self, bit_size: usize) -> BigInt {
  757. // Generate a random BigUint...
  758. let biguint = self.gen_biguint(bit_size);
  759. // ...and then randomly assign it a Sign...
  760. let sign = if biguint.is_zero() {
  761. // ...except that if the BigUint is zero, we need to try
  762. // again with probability 0.5. This is because otherwise,
  763. // the probability of generating a zero BigInt would be
  764. // double that of any other number.
  765. if self.gen() {
  766. return self.gen_bigint(bit_size);
  767. } else {
  768. NoSign
  769. }
  770. } else if self.gen() {
  771. Plus
  772. } else {
  773. Minus
  774. };
  775. BigInt::from_biguint(sign, biguint)
  776. }
  777. fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint {
  778. assert!(!bound.is_zero());
  779. let bits = bound.bits();
  780. loop {
  781. let n = self.gen_biguint(bits);
  782. if n < *bound {
  783. return n;
  784. }
  785. }
  786. }
  787. fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint {
  788. assert!(*lbound < *ubound);
  789. return lbound + self.gen_biguint_below(&(ubound - lbound));
  790. }
  791. fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt {
  792. assert!(*lbound < *ubound);
  793. let delta = (ubound - lbound).to_biguint().unwrap();
  794. return lbound + self.gen_biguint_below(&delta).to_bigint().unwrap();
  795. }
  796. }
  797. impl BigInt {
  798. /// Creates and initializes a BigInt.
  799. ///
  800. /// The digits are in little-endian base 2^32.
  801. #[inline]
  802. pub fn new(sign: Sign, digits: Vec<BigDigit>) -> BigInt {
  803. BigInt::from_biguint(sign, BigUint::new(digits))
  804. }
  805. /// Creates and initializes a `BigInt`.
  806. ///
  807. /// The digits are in little-endian base 2^32.
  808. #[inline]
  809. pub fn from_biguint(sign: Sign, data: BigUint) -> BigInt {
  810. if sign == NoSign || data.is_zero() {
  811. return BigInt {
  812. sign: NoSign,
  813. data: Zero::zero(),
  814. };
  815. }
  816. BigInt {
  817. sign: sign,
  818. data: data,
  819. }
  820. }
  821. /// Creates and initializes a `BigInt`.
  822. #[inline]
  823. pub fn from_slice(sign: Sign, slice: &[BigDigit]) -> BigInt {
  824. BigInt::from_biguint(sign, BigUint::from_slice(slice))
  825. }
  826. /// Creates and initializes a `BigInt`.
  827. ///
  828. /// The bytes are in big-endian byte order.
  829. ///
  830. /// # Examples
  831. ///
  832. /// ```
  833. /// use num_bigint::{BigInt, Sign};
  834. ///
  835. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"A"),
  836. /// BigInt::parse_bytes(b"65", 10).unwrap());
  837. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AA"),
  838. /// BigInt::parse_bytes(b"16705", 10).unwrap());
  839. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AB"),
  840. /// BigInt::parse_bytes(b"16706", 10).unwrap());
  841. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"Hello world!"),
  842. /// BigInt::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
  843. /// ```
  844. #[inline]
  845. pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt {
  846. BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes))
  847. }
  848. /// Creates and initializes a `BigInt`.
  849. ///
  850. /// The bytes are in little-endian byte order.
  851. #[inline]
  852. pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt {
  853. BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes))
  854. }
  855. /// Returns the sign and the byte representation of the `BigInt` in little-endian byte order.
  856. ///
  857. /// # Examples
  858. ///
  859. /// ```
  860. /// use num_bigint::{ToBigInt, Sign};
  861. ///
  862. /// let i = -1125.to_bigint().unwrap();
  863. /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4]));
  864. /// ```
  865. #[inline]
  866. pub fn to_bytes_le(&self) -> (Sign, Vec<u8>) {
  867. (self.sign, self.data.to_bytes_le())
  868. }
  869. /// Returns the sign and the byte representation of the `BigInt` in big-endian byte order.
  870. ///
  871. /// # Examples
  872. ///
  873. /// ```
  874. /// use num_bigint::{ToBigInt, Sign};
  875. ///
  876. /// let i = -1125.to_bigint().unwrap();
  877. /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101]));
  878. /// ```
  879. #[inline]
  880. pub fn to_bytes_be(&self) -> (Sign, Vec<u8>) {
  881. (self.sign, self.data.to_bytes_be())
  882. }
  883. /// Returns the integer formatted as a string in the given radix.
  884. /// `radix` must be in the range `[2, 36]`.
  885. ///
  886. /// # Examples
  887. ///
  888. /// ```
  889. /// use num_bigint::BigInt;
  890. ///
  891. /// let i = BigInt::parse_bytes(b"ff", 16).unwrap();
  892. /// assert_eq!(i.to_str_radix(16), "ff");
  893. /// ```
  894. #[inline]
  895. pub fn to_str_radix(&self, radix: u32) -> String {
  896. let mut v = to_str_radix_reversed(&self.data, radix);
  897. if self.is_negative() {
  898. v.push(b'-');
  899. }
  900. v.reverse();
  901. unsafe { String::from_utf8_unchecked(v) }
  902. }
  903. /// Returns the sign of the `BigInt` as a `Sign`.
  904. ///
  905. /// # Examples
  906. ///
  907. /// ```
  908. /// use num_bigint::{ToBigInt, Sign};
  909. ///
  910. /// assert_eq!(ToBigInt::to_bigint(&1234).unwrap().sign(), Sign::Plus);
  911. /// assert_eq!(ToBigInt::to_bigint(&-4321).unwrap().sign(), Sign::Minus);
  912. /// assert_eq!(ToBigInt::to_bigint(&0).unwrap().sign(), Sign::NoSign);
  913. /// ```
  914. #[inline]
  915. pub fn sign(&self) -> Sign {
  916. self.sign
  917. }
  918. /// Creates and initializes a `BigInt`.
  919. ///
  920. /// # Examples
  921. ///
  922. /// ```
  923. /// use num_bigint::{BigInt, ToBigInt};
  924. ///
  925. /// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234));
  926. /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD));
  927. /// assert_eq!(BigInt::parse_bytes(b"G", 16), None);
  928. /// ```
  929. #[inline]
  930. pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigInt> {
  931. str::from_utf8(buf).ok().and_then(|s| BigInt::from_str_radix(s, radix).ok())
  932. }
  933. /// Determines the fewest bits necessary to express the `BigInt`,
  934. /// not including the sign.
  935. #[inline]
  936. pub fn bits(&self) -> usize {
  937. self.data.bits()
  938. }
  939. /// Converts this `BigInt` into a `BigUint`, if it's not negative.
  940. #[inline]
  941. pub fn to_biguint(&self) -> Option<BigUint> {
  942. match self.sign {
  943. Plus => Some(self.data.clone()),
  944. NoSign => Some(Zero::zero()),
  945. Minus => None,
  946. }
  947. }
  948. #[inline]
  949. pub fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
  950. return Some(self.add(v));
  951. }
  952. #[inline]
  953. pub fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
  954. return Some(self.sub(v));
  955. }
  956. #[inline]
  957. pub fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
  958. return Some(self.mul(v));
  959. }
  960. #[inline]
  961. pub fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
  962. if v.is_zero() {
  963. return None;
  964. }
  965. return Some(self.div(v));
  966. }
  967. }