bigint.rs 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  1. use std::default::Default;
  2. use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Not};
  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,
  17. CheckedMul, 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` from an array of bytes in
  855. /// two's complement binary representation.
  856. ///
  857. /// The digits are in big-endian base 2^8.
  858. #[inline]
  859. pub fn from_signed_bytes_be(digits: &[u8]) -> BigInt {
  860. let sign = match digits.first() {
  861. Some(v) if *v > 0x7f => Sign::Minus,
  862. Some(_) => Sign::Plus,
  863. None => return BigInt::zero(),
  864. };
  865. if sign == Sign::Minus {
  866. // two's-complement the content to retrieve the magnitude
  867. let mut digits = Vec::from(digits);
  868. twos_complement_be(&mut digits);
  869. BigInt::from_biguint(sign, BigUint::from_bytes_be(&*digits))
  870. } else {
  871. BigInt::from_biguint(sign, BigUint::from_bytes_be(digits))
  872. }
  873. }
  874. /// Creates and initializes a `BigInt` from an array of bytes in two's complement.
  875. ///
  876. /// The digits are in little-endian base 2^8.
  877. #[inline]
  878. pub fn from_signed_bytes_le(digits: &[u8]) -> BigInt {
  879. let sign = match digits.last() {
  880. Some(v) if *v > 0x7f => Sign::Minus,
  881. Some(_) => Sign::Plus,
  882. None => return BigInt::zero(),
  883. };
  884. if sign == Sign::Minus {
  885. // two's-complement the content to retrieve the magnitude
  886. let mut digits = Vec::from(digits);
  887. twos_complement_le(&mut digits);
  888. BigInt::from_biguint(sign, BigUint::from_bytes_le(&*digits))
  889. } else {
  890. BigInt::from_biguint(sign, BigUint::from_bytes_le(digits))
  891. }
  892. }
  893. /// Creates and initializes a `BigInt`.
  894. ///
  895. /// # Examples
  896. ///
  897. /// ```
  898. /// use num_bigint::{BigInt, ToBigInt};
  899. ///
  900. /// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234));
  901. /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD));
  902. /// assert_eq!(BigInt::parse_bytes(b"G", 16), None);
  903. /// ```
  904. #[inline]
  905. pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigInt> {
  906. str::from_utf8(buf).ok().and_then(|s| BigInt::from_str_radix(s, radix).ok())
  907. }
  908. /// Creates and initializes a `BigInt`. Each u8 of the input slice is
  909. /// interpreted as one digit of the number
  910. /// and must therefore be less than `radix`.
  911. ///
  912. /// The bytes are in big-endian byte order.
  913. /// `radix` must be in the range `2...256`.
  914. ///
  915. /// # Examples
  916. ///
  917. /// ```
  918. /// use num_bigint::{BigInt, Sign};
  919. ///
  920. /// let inbase190 = vec![15, 33, 125, 12, 14];
  921. /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap();
  922. /// assert_eq!(a.to_radix_be(190), (Sign:: Minus, inbase190));
  923. /// ```
  924. pub fn from_radix_be(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt> {
  925. BigUint::from_radix_be(buf, radix).map(|u| BigInt::from_biguint(sign, u))
  926. }
  927. /// Creates and initializes a `BigInt`. Each u8 of the input slice is
  928. /// interpreted as one digit of the number
  929. /// and must therefore be less than `radix`.
  930. ///
  931. /// The bytes are in little-endian byte order.
  932. /// `radix` must be in the range `2...256`.
  933. ///
  934. /// # Examples
  935. ///
  936. /// ```
  937. /// use num_bigint::{BigInt, Sign};
  938. ///
  939. /// let inbase190 = vec![14, 12, 125, 33, 15];
  940. /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap();
  941. /// assert_eq!(a.to_radix_be(190), (Sign::Minus, inbase190));
  942. /// ```
  943. pub fn from_radix_le(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt> {
  944. BigUint::from_radix_le(buf, radix).map(|u| BigInt::from_biguint(sign, u))
  945. }
  946. /// Returns the sign and the byte representation of the `BigInt` in big-endian byte order.
  947. ///
  948. /// # Examples
  949. ///
  950. /// ```
  951. /// use num_bigint::{ToBigInt, Sign};
  952. ///
  953. /// let i = -1125.to_bigint().unwrap();
  954. /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101]));
  955. /// ```
  956. #[inline]
  957. pub fn to_bytes_be(&self) -> (Sign, Vec<u8>) {
  958. (self.sign, self.data.to_bytes_be())
  959. }
  960. /// Returns the sign and the byte representation of the `BigInt` in little-endian byte order.
  961. ///
  962. /// # Examples
  963. ///
  964. /// ```
  965. /// use num_bigint::{ToBigInt, Sign};
  966. ///
  967. /// let i = -1125.to_bigint().unwrap();
  968. /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4]));
  969. /// ```
  970. #[inline]
  971. pub fn to_bytes_le(&self) -> (Sign, Vec<u8>) {
  972. (self.sign, self.data.to_bytes_le())
  973. }
  974. /// Returns the two's complement byte representation of the `BigInt` in big-endian byte order.
  975. ///
  976. /// # Examples
  977. ///
  978. /// ```
  979. /// use num_bigint::ToBigInt;
  980. ///
  981. /// let i = -1125.to_bigint().unwrap();
  982. /// assert_eq!(i.to_signed_bytes_be(), vec![251, 155]);
  983. /// ```
  984. #[inline]
  985. pub fn to_signed_bytes_be(&self) -> Vec<u8> {
  986. let mut bytes = self.data.to_bytes_be();
  987. let first_byte = bytes.first().map(|v| *v).unwrap_or(0);
  988. if first_byte > 0x7f && !(first_byte == 0x80 && bytes.iter().skip(1).all(Zero::is_zero)) {
  989. // msb used by magnitude, extend by 1 byte
  990. bytes.insert(0, 0);
  991. }
  992. if self.sign == Sign::Minus {
  993. twos_complement_be(&mut bytes);
  994. }
  995. bytes
  996. }
  997. /// Returns the two's complement byte representation of the `BigInt` in little-endian byte order.
  998. ///
  999. /// # Examples
  1000. ///
  1001. /// ```
  1002. /// use num_bigint::ToBigInt;
  1003. ///
  1004. /// let i = -1125.to_bigint().unwrap();
  1005. /// assert_eq!(i.to_signed_bytes_le(), vec![155, 251]);
  1006. /// ```
  1007. #[inline]
  1008. pub fn to_signed_bytes_le(&self) -> Vec<u8> {
  1009. let mut bytes = self.data.to_bytes_le();
  1010. let last_byte = bytes.last().map(|v| *v).unwrap_or(0);
  1011. if last_byte > 0x7f && !(last_byte == 0x80 && bytes.iter().rev().skip(1).all(Zero::is_zero)) {
  1012. // msb used by magnitude, extend by 1 byte
  1013. bytes.push(0);
  1014. }
  1015. if self.sign == Sign::Minus {
  1016. twos_complement_le(&mut bytes);
  1017. }
  1018. bytes
  1019. }
  1020. /// Returns the integer formatted as a string in the given radix.
  1021. /// `radix` must be in the range `2...36`.
  1022. ///
  1023. /// # Examples
  1024. ///
  1025. /// ```
  1026. /// use num_bigint::BigInt;
  1027. ///
  1028. /// let i = BigInt::parse_bytes(b"ff", 16).unwrap();
  1029. /// assert_eq!(i.to_str_radix(16), "ff");
  1030. /// ```
  1031. #[inline]
  1032. pub fn to_str_radix(&self, radix: u32) -> String {
  1033. let mut v = to_str_radix_reversed(&self.data, radix);
  1034. if self.is_negative() {
  1035. v.push(b'-');
  1036. }
  1037. v.reverse();
  1038. unsafe { String::from_utf8_unchecked(v) }
  1039. }
  1040. /// Returns the integer in the requested base in big-endian digit order.
  1041. /// The output is not given in a human readable alphabet but as a zero
  1042. /// based u8 number.
  1043. /// `radix` must be in the range `2...256`.
  1044. ///
  1045. /// # Examples
  1046. ///
  1047. /// ```
  1048. /// use num_bigint::{BigInt, Sign};
  1049. ///
  1050. /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_be(159),
  1051. /// (Sign::Minus, vec![2, 94, 27]));
  1052. /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27
  1053. /// ```
  1054. #[inline]
  1055. pub fn to_radix_be(&self, radix: u32) -> (Sign, Vec<u8>) {
  1056. (self.sign, self.data.to_radix_be(radix))
  1057. }
  1058. /// Returns the integer in the requested base in little-endian digit order.
  1059. /// The output is not given in a human readable alphabet but as a zero
  1060. /// based u8 number.
  1061. /// `radix` must be in the range `2...256`.
  1062. ///
  1063. /// # Examples
  1064. ///
  1065. /// ```
  1066. /// use num_bigint::{BigInt, Sign};
  1067. ///
  1068. /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_le(159),
  1069. /// (Sign::Minus, vec![27, 94, 2]));
  1070. /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2)
  1071. /// ```
  1072. #[inline]
  1073. pub fn to_radix_le(&self, radix: u32) -> (Sign, Vec<u8>) {
  1074. (self.sign, self.data.to_radix_le(radix))
  1075. }
  1076. /// Returns the sign of the `BigInt` as a `Sign`.
  1077. ///
  1078. /// # Examples
  1079. ///
  1080. /// ```
  1081. /// use num_bigint::{ToBigInt, Sign};
  1082. ///
  1083. /// assert_eq!(ToBigInt::to_bigint(&1234).unwrap().sign(), Sign::Plus);
  1084. /// assert_eq!(ToBigInt::to_bigint(&-4321).unwrap().sign(), Sign::Minus);
  1085. /// assert_eq!(ToBigInt::to_bigint(&0).unwrap().sign(), Sign::NoSign);
  1086. /// ```
  1087. #[inline]
  1088. pub fn sign(&self) -> Sign {
  1089. self.sign
  1090. }
  1091. /// Determines the fewest bits necessary to express the `BigInt`,
  1092. /// not including the sign.
  1093. #[inline]
  1094. pub fn bits(&self) -> usize {
  1095. self.data.bits()
  1096. }
  1097. /// Converts this `BigInt` into a `BigUint`, if it's not negative.
  1098. #[inline]
  1099. pub fn to_biguint(&self) -> Option<BigUint> {
  1100. match self.sign {
  1101. Plus => Some(self.data.clone()),
  1102. NoSign => Some(Zero::zero()),
  1103. Minus => None,
  1104. }
  1105. }
  1106. #[inline]
  1107. pub fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
  1108. return Some(self.add(v));
  1109. }
  1110. #[inline]
  1111. pub fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
  1112. return Some(self.sub(v));
  1113. }
  1114. #[inline]
  1115. pub fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
  1116. return Some(self.mul(v));
  1117. }
  1118. #[inline]
  1119. pub fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
  1120. if v.is_zero() {
  1121. return None;
  1122. }
  1123. return Some(self.div(v));
  1124. }
  1125. }
  1126. /// Perform in-place two's complement of the given binary representation,
  1127. /// in little-endian byte order.
  1128. #[inline]
  1129. fn twos_complement_le(digits: &mut [u8]) {
  1130. twos_complement(digits)
  1131. }
  1132. /// Perform in-place two's complement of the given binary representation
  1133. /// in big-endian byte order.
  1134. #[inline]
  1135. fn twos_complement_be(digits: &mut [u8]) {
  1136. twos_complement(digits.iter_mut().rev())
  1137. }
  1138. /// Perform in-place two's complement of the given digit iterator
  1139. /// starting from the least significant byte.
  1140. #[inline]
  1141. fn twos_complement<'a, I>(digits: I)
  1142. where I: IntoIterator<Item = &'a mut u8>
  1143. {
  1144. let mut carry = true;
  1145. for mut d in digits {
  1146. *d = d.not();
  1147. if carry {
  1148. *d = d.wrapping_add(1);
  1149. carry = d.is_zero();
  1150. }
  1151. }
  1152. }