bigint.rs 31 KB

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