bigint.rs 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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. /// Returns the sign and the byte representation of the `BigInt` in little-endian byte order.
  855. ///
  856. /// # Examples
  857. ///
  858. /// ```
  859. /// use num_bigint::{ToBigInt, Sign};
  860. ///
  861. /// let i = -1125.to_bigint().unwrap();
  862. /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4]));
  863. /// ```
  864. #[inline]
  865. pub fn to_bytes_le(&self) -> (Sign, Vec<u8>) {
  866. (self.sign, self.data.to_bytes_le())
  867. }
  868. /// Returns the sign and the byte representation of the `BigInt` in big-endian byte order.
  869. ///
  870. /// # Examples
  871. ///
  872. /// ```
  873. /// use num_bigint::{ToBigInt, Sign};
  874. ///
  875. /// let i = -1125.to_bigint().unwrap();
  876. /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101]));
  877. /// ```
  878. #[inline]
  879. pub fn to_bytes_be(&self) -> (Sign, Vec<u8>) {
  880. (self.sign, self.data.to_bytes_be())
  881. }
  882. /// Returns the integer formatted as a string in the given radix.
  883. /// `radix` must be in the range `2...36`.
  884. ///
  885. /// # Examples
  886. ///
  887. /// ```
  888. /// use num_bigint::BigInt;
  889. ///
  890. /// let i = BigInt::parse_bytes(b"ff", 16).unwrap();
  891. /// assert_eq!(i.to_str_radix(16), "ff");
  892. /// ```
  893. #[inline]
  894. pub fn to_str_radix(&self, radix: u32) -> String {
  895. let mut v = to_str_radix_reversed(&self.data, radix);
  896. if self.is_negative() {
  897. v.push(b'-');
  898. }
  899. v.reverse();
  900. unsafe { String::from_utf8_unchecked(v) }
  901. }
  902. /// Returns the integer in the requested base in big-endian digit order.
  903. /// The output is not given in a human readable alphabet but as a zero
  904. /// based u8 number.
  905. /// `radix` must be in the range `2...256`.
  906. ///
  907. /// # Examples
  908. ///
  909. /// ```
  910. /// use num_bigint::{BigInt, Sign};
  911. ///
  912. /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_be(159),
  913. /// (Sign::Minus, vec![2, 94, 27]));
  914. /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27
  915. /// ```
  916. #[inline]
  917. pub fn to_radix_be(&self, radix: u32) -> (Sign, Vec<u8>) {
  918. (self.sign, self.data.to_radix_be(radix))
  919. }
  920. /// Returns the integer in the requested base in little-endian digit order.
  921. /// The output is not given in a human readable alphabet but as a zero
  922. /// based u8 number.
  923. /// `radix` must be in the range `2...256`.
  924. ///
  925. /// # Examples
  926. ///
  927. /// ```
  928. /// use num_bigint::{BigInt, Sign};
  929. ///
  930. /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_le(159),
  931. /// (Sign::Minus, vec![27, 94, 2]));
  932. /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2)
  933. /// ```
  934. #[inline]
  935. pub fn to_radix_le(&self, radix: u32) -> (Sign, Vec<u8>) {
  936. (self.sign, self.data.to_radix_le(radix))
  937. }
  938. /// Returns the sign of the `BigInt` as a `Sign`.
  939. ///
  940. /// # Examples
  941. ///
  942. /// ```
  943. /// use num_bigint::{ToBigInt, Sign};
  944. ///
  945. /// assert_eq!(ToBigInt::to_bigint(&1234).unwrap().sign(), Sign::Plus);
  946. /// assert_eq!(ToBigInt::to_bigint(&-4321).unwrap().sign(), Sign::Minus);
  947. /// assert_eq!(ToBigInt::to_bigint(&0).unwrap().sign(), Sign::NoSign);
  948. /// ```
  949. #[inline]
  950. pub fn sign(&self) -> Sign {
  951. self.sign
  952. }
  953. /// Creates and initializes a `BigInt`.
  954. ///
  955. /// # Examples
  956. ///
  957. /// ```
  958. /// use num_bigint::{BigInt, ToBigInt};
  959. ///
  960. /// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234));
  961. /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD));
  962. /// assert_eq!(BigInt::parse_bytes(b"G", 16), None);
  963. /// ```
  964. #[inline]
  965. pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigInt> {
  966. str::from_utf8(buf).ok().and_then(|s| BigInt::from_str_radix(s, radix).ok())
  967. }
  968. /// Determines the fewest bits necessary to express the `BigInt`,
  969. /// not including the sign.
  970. #[inline]
  971. pub fn bits(&self) -> usize {
  972. self.data.bits()
  973. }
  974. /// Converts this `BigInt` into a `BigUint`, if it's not negative.
  975. #[inline]
  976. pub fn to_biguint(&self) -> Option<BigUint> {
  977. match self.sign {
  978. Plus => Some(self.data.clone()),
  979. NoSign => Some(Zero::zero()),
  980. Minus => None,
  981. }
  982. }
  983. #[inline]
  984. pub fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
  985. return Some(self.add(v));
  986. }
  987. #[inline]
  988. pub fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
  989. return Some(self.sub(v));
  990. }
  991. #[inline]
  992. pub fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
  993. return Some(self.mul(v));
  994. }
  995. #[inline]
  996. pub fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
  997. if v.is_zero() {
  998. return None;
  999. }
  1000. return Some(self.div(v));
  1001. }
  1002. }