bigint.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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. pub fn bits(&self) -> usize {
  936. self.data.bits()
  937. }
  938. /// Converts this `BigInt` into a `BigUint`, if it's not negative.
  939. #[inline]
  940. pub fn to_biguint(&self) -> Option<BigUint> {
  941. match self.sign {
  942. Plus => Some(self.data.clone()),
  943. NoSign => Some(Zero::zero()),
  944. Minus => None,
  945. }
  946. }
  947. #[inline]
  948. pub fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
  949. return Some(self.add(v));
  950. }
  951. #[inline]
  952. pub fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
  953. return Some(self.sub(v));
  954. }
  955. #[inline]
  956. pub fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
  957. return Some(self.mul(v));
  958. }
  959. #[inline]
  960. pub fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
  961. if v.is_zero() {
  962. return None;
  963. }
  964. return Some(self.div(v));
  965. }
  966. }