bigint.rs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767
  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, DoubleBigDigit};
  22. use biguint;
  23. use biguint::to_str_radix_reversed;
  24. use biguint::BigUint;
  25. use UsizePromotion;
  26. use IsizePromotion;
  27. #[cfg(test)]
  28. #[path = "tests/bigint.rs"]
  29. mod bigint_tests;
  30. /// A Sign is a `BigInt`'s composing element.
  31. #[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone, Debug, Hash)]
  32. #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
  33. pub enum Sign {
  34. Minus,
  35. NoSign,
  36. Plus,
  37. }
  38. impl Neg for Sign {
  39. type Output = Sign;
  40. /// Negate Sign value.
  41. #[inline]
  42. fn neg(self) -> Sign {
  43. match self {
  44. Minus => Plus,
  45. NoSign => NoSign,
  46. Plus => Minus,
  47. }
  48. }
  49. }
  50. impl Mul<Sign> for Sign {
  51. type Output = Sign;
  52. #[inline]
  53. fn mul(self, other: Sign) -> Sign {
  54. match (self, other) {
  55. (NoSign, _) | (_, NoSign) => NoSign,
  56. (Plus, Plus) | (Minus, Minus) => Plus,
  57. (Plus, Minus) | (Minus, Plus) => Minus,
  58. }
  59. }
  60. }
  61. #[cfg(feature = "serde")]
  62. impl serde::Serialize for Sign {
  63. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
  64. where S: serde::Serializer
  65. {
  66. match *self {
  67. Sign::Minus => (-1i8).serialize(serializer),
  68. Sign::NoSign => 0i8.serialize(serializer),
  69. Sign::Plus => 1i8.serialize(serializer),
  70. }
  71. }
  72. }
  73. #[cfg(feature = "serde")]
  74. impl serde::Deserialize for Sign {
  75. fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
  76. where D: serde::Deserializer
  77. {
  78. use serde::de::Error;
  79. let sign: i8 = try!(serde::Deserialize::deserialize(deserializer));
  80. match sign {
  81. -1 => Ok(Sign::Minus),
  82. 0 => Ok(Sign::NoSign),
  83. 1 => Ok(Sign::Plus),
  84. _ => Err(D::Error::invalid_value("sign must be -1, 0, or 1")),
  85. }
  86. }
  87. }
  88. /// A big signed integer type.
  89. #[derive(Clone, Debug, Hash)]
  90. #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
  91. pub struct BigInt {
  92. sign: Sign,
  93. data: BigUint,
  94. }
  95. impl PartialEq for BigInt {
  96. #[inline]
  97. fn eq(&self, other: &BigInt) -> bool {
  98. self.cmp(other) == Equal
  99. }
  100. }
  101. impl Eq for BigInt {}
  102. impl PartialOrd for BigInt {
  103. #[inline]
  104. fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> {
  105. Some(self.cmp(other))
  106. }
  107. }
  108. impl Ord for BigInt {
  109. #[inline]
  110. fn cmp(&self, other: &BigInt) -> Ordering {
  111. let scmp = self.sign.cmp(&other.sign);
  112. if scmp != Equal {
  113. return scmp;
  114. }
  115. match self.sign {
  116. NoSign => Equal,
  117. Plus => self.data.cmp(&other.data),
  118. Minus => other.data.cmp(&self.data),
  119. }
  120. }
  121. }
  122. impl Default for BigInt {
  123. #[inline]
  124. fn default() -> BigInt {
  125. Zero::zero()
  126. }
  127. }
  128. impl fmt::Display for BigInt {
  129. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  130. f.pad_integral(!self.is_negative(), "", &self.data.to_str_radix(10))
  131. }
  132. }
  133. impl fmt::Binary for BigInt {
  134. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  135. f.pad_integral(!self.is_negative(), "0b", &self.data.to_str_radix(2))
  136. }
  137. }
  138. impl fmt::Octal for BigInt {
  139. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  140. f.pad_integral(!self.is_negative(), "0o", &self.data.to_str_radix(8))
  141. }
  142. }
  143. impl fmt::LowerHex for BigInt {
  144. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  145. f.pad_integral(!self.is_negative(), "0x", &self.data.to_str_radix(16))
  146. }
  147. }
  148. impl fmt::UpperHex for BigInt {
  149. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  150. f.pad_integral(!self.is_negative(),
  151. "0x",
  152. &self.data.to_str_radix(16).to_ascii_uppercase())
  153. }
  154. }
  155. impl FromStr for BigInt {
  156. type Err = ParseBigIntError;
  157. #[inline]
  158. fn from_str(s: &str) -> Result<BigInt, ParseBigIntError> {
  159. BigInt::from_str_radix(s, 10)
  160. }
  161. }
  162. impl Num for BigInt {
  163. type FromStrRadixErr = ParseBigIntError;
  164. /// Creates and initializes a BigInt.
  165. #[inline]
  166. fn from_str_radix(mut s: &str, radix: u32) -> Result<BigInt, ParseBigIntError> {
  167. let sign = if s.starts_with('-') {
  168. let tail = &s[1..];
  169. if !tail.starts_with('+') {
  170. s = tail
  171. }
  172. Minus
  173. } else {
  174. Plus
  175. };
  176. let bu = try!(BigUint::from_str_radix(s, radix));
  177. Ok(BigInt::from_biguint(sign, bu))
  178. }
  179. }
  180. impl Shl<usize> for BigInt {
  181. type Output = BigInt;
  182. #[inline]
  183. fn shl(self, rhs: usize) -> BigInt {
  184. (&self) << rhs
  185. }
  186. }
  187. impl<'a> Shl<usize> for &'a BigInt {
  188. type Output = BigInt;
  189. #[inline]
  190. fn shl(self, rhs: usize) -> BigInt {
  191. BigInt::from_biguint(self.sign, &self.data << rhs)
  192. }
  193. }
  194. impl Shr<usize> for BigInt {
  195. type Output = BigInt;
  196. #[inline]
  197. fn shr(self, rhs: usize) -> BigInt {
  198. BigInt::from_biguint(self.sign, self.data >> rhs)
  199. }
  200. }
  201. impl<'a> Shr<usize> for &'a BigInt {
  202. type Output = BigInt;
  203. #[inline]
  204. fn shr(self, rhs: usize) -> BigInt {
  205. BigInt::from_biguint(self.sign, &self.data >> rhs)
  206. }
  207. }
  208. impl Zero for BigInt {
  209. #[inline]
  210. fn zero() -> BigInt {
  211. BigInt::from_biguint(NoSign, Zero::zero())
  212. }
  213. #[inline]
  214. fn is_zero(&self) -> bool {
  215. self.sign == NoSign
  216. }
  217. }
  218. impl One for BigInt {
  219. #[inline]
  220. fn one() -> BigInt {
  221. BigInt::from_biguint(Plus, One::one())
  222. }
  223. }
  224. impl Signed for BigInt {
  225. #[inline]
  226. fn abs(&self) -> BigInt {
  227. match self.sign {
  228. Plus | NoSign => self.clone(),
  229. Minus => BigInt::from_biguint(Plus, self.data.clone()),
  230. }
  231. }
  232. #[inline]
  233. fn abs_sub(&self, other: &BigInt) -> BigInt {
  234. if *self <= *other {
  235. Zero::zero()
  236. } else {
  237. self - other
  238. }
  239. }
  240. #[inline]
  241. fn signum(&self) -> BigInt {
  242. match self.sign {
  243. Plus => BigInt::from_biguint(Plus, One::one()),
  244. Minus => BigInt::from_biguint(Minus, One::one()),
  245. NoSign => Zero::zero(),
  246. }
  247. }
  248. #[inline]
  249. fn is_positive(&self) -> bool {
  250. self.sign == Plus
  251. }
  252. #[inline]
  253. fn is_negative(&self) -> bool {
  254. self.sign == Minus
  255. }
  256. }
  257. // A convenience method for getting the absolute value of an i32 in a u32.
  258. #[inline]
  259. fn i32_abs_as_u32(a: i32) -> u32 {
  260. if a == i32::min_value() {
  261. a as u32
  262. } else {
  263. a.abs() as u32
  264. }
  265. }
  266. // A convenience method for getting the absolute value of an i64 in a u64.
  267. #[inline]
  268. fn i64_abs_as_u64(a: i64) -> u64 {
  269. if a == i64::min_value() {
  270. a as u64
  271. } else {
  272. a.abs() as u64
  273. }
  274. }
  275. // We want to forward to BigUint::add, but it's not clear how that will go until
  276. // we compare both sign and magnitude. So we duplicate this body for every
  277. // val/ref combination, deferring that decision to BigUint's own forwarding.
  278. macro_rules! bigint_add {
  279. ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
  280. match ($a.sign, $b.sign) {
  281. (_, NoSign) => $a_owned,
  282. (NoSign, _) => $b_owned,
  283. // same sign => keep the sign with the sum of magnitudes
  284. (Plus, Plus) | (Minus, Minus) =>
  285. BigInt::from_biguint($a.sign, $a_data + $b_data),
  286. // opposite signs => keep the sign of the larger with the difference of magnitudes
  287. (Plus, Minus) | (Minus, Plus) =>
  288. match $a.data.cmp(&$b.data) {
  289. Less => BigInt::from_biguint($b.sign, $b_data - $a_data),
  290. Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
  291. Equal => Zero::zero(),
  292. },
  293. }
  294. };
  295. }
  296. impl<'a, 'b> Add<&'b BigInt> for &'a BigInt {
  297. type Output = BigInt;
  298. #[inline]
  299. fn add(self, other: &BigInt) -> BigInt {
  300. bigint_add!(self,
  301. self.clone(),
  302. &self.data,
  303. other,
  304. other.clone(),
  305. &other.data)
  306. }
  307. }
  308. impl<'a> Add<BigInt> for &'a BigInt {
  309. type Output = BigInt;
  310. #[inline]
  311. fn add(self, other: BigInt) -> BigInt {
  312. bigint_add!(self, self.clone(), &self.data, other, other, other.data)
  313. }
  314. }
  315. impl<'a> Add<&'a BigInt> for BigInt {
  316. type Output = BigInt;
  317. #[inline]
  318. fn add(self, other: &BigInt) -> BigInt {
  319. bigint_add!(self, self, self.data, other, other.clone(), &other.data)
  320. }
  321. }
  322. impl Add<BigInt> for BigInt {
  323. type Output = BigInt;
  324. #[inline]
  325. fn add(self, other: BigInt) -> BigInt {
  326. bigint_add!(self, self, self.data, other, other, other.data)
  327. }
  328. }
  329. promote_all_scalars!(impl Add for BigInt, add);
  330. forward_all_scalar_binop_to_val_val_commutative!(impl Add<BigDigit> for BigInt, add);
  331. forward_all_scalar_binop_to_val_val_commutative!(impl Add<DoubleBigDigit> for BigInt, add);
  332. impl Add<BigDigit> for BigInt {
  333. type Output = BigInt;
  334. #[inline]
  335. fn add(self, other: BigDigit) -> BigInt {
  336. match self.sign {
  337. NoSign => From::from(other),
  338. Plus => BigInt::from_biguint(Plus, self.data + other),
  339. Minus =>
  340. match self.data.cmp(&From::from(other)) {
  341. Equal => Zero::zero(),
  342. Less => BigInt::from_biguint(Plus, other - self.data),
  343. Greater => BigInt::from_biguint(Minus, self.data - other),
  344. }
  345. }
  346. }
  347. }
  348. impl Add<DoubleBigDigit> for BigInt {
  349. type Output = BigInt;
  350. #[inline]
  351. fn add(self, other: DoubleBigDigit) -> BigInt {
  352. match self.sign {
  353. NoSign => From::from(other),
  354. Plus => BigInt::from_biguint(Plus, self.data + other),
  355. Minus =>
  356. match self.data.cmp(&From::from(other)) {
  357. Equal => Zero::zero(),
  358. Less => BigInt::from_biguint(Plus, other - self.data),
  359. Greater => BigInt::from_biguint(Minus, self.data - other),
  360. }
  361. }
  362. }
  363. }
  364. forward_all_scalar_binop_to_val_val_commutative!(impl Add<i32> for BigInt, add);
  365. forward_all_scalar_binop_to_val_val_commutative!(impl Add<i64> for BigInt, add);
  366. impl Add<i32> for BigInt {
  367. type Output = BigInt;
  368. #[inline]
  369. fn add(self, other: i32) -> BigInt {
  370. if other >= 0 {
  371. self + other as u32
  372. } else {
  373. self - i32_abs_as_u32(other)
  374. }
  375. }
  376. }
  377. impl Add<i64> for BigInt {
  378. type Output = BigInt;
  379. #[inline]
  380. fn add(self, other: i64) -> BigInt {
  381. if other >= 0 {
  382. self + other as u64
  383. } else {
  384. self - i64_abs_as_u64(other)
  385. }
  386. }
  387. }
  388. // We want to forward to BigUint::sub, but it's not clear how that will go until
  389. // we compare both sign and magnitude. So we duplicate this body for every
  390. // val/ref combination, deferring that decision to BigUint's own forwarding.
  391. macro_rules! bigint_sub {
  392. ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
  393. match ($a.sign, $b.sign) {
  394. (_, NoSign) => $a_owned,
  395. (NoSign, _) => -$b_owned,
  396. // opposite signs => keep the sign of the left with the sum of magnitudes
  397. (Plus, Minus) | (Minus, Plus) =>
  398. BigInt::from_biguint($a.sign, $a_data + $b_data),
  399. // same sign => keep or toggle the sign of the left with the difference of magnitudes
  400. (Plus, Plus) | (Minus, Minus) =>
  401. match $a.data.cmp(&$b.data) {
  402. Less => BigInt::from_biguint(-$a.sign, $b_data - $a_data),
  403. Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
  404. Equal => Zero::zero(),
  405. },
  406. }
  407. };
  408. }
  409. impl<'a, 'b> Sub<&'b BigInt> for &'a BigInt {
  410. type Output = BigInt;
  411. #[inline]
  412. fn sub(self, other: &BigInt) -> BigInt {
  413. bigint_sub!(self,
  414. self.clone(),
  415. &self.data,
  416. other,
  417. other.clone(),
  418. &other.data)
  419. }
  420. }
  421. impl<'a> Sub<BigInt> for &'a BigInt {
  422. type Output = BigInt;
  423. #[inline]
  424. fn sub(self, other: BigInt) -> BigInt {
  425. bigint_sub!(self, self.clone(), &self.data, other, other, other.data)
  426. }
  427. }
  428. impl<'a> Sub<&'a BigInt> for BigInt {
  429. type Output = BigInt;
  430. #[inline]
  431. fn sub(self, other: &BigInt) -> BigInt {
  432. bigint_sub!(self, self, self.data, other, other.clone(), &other.data)
  433. }
  434. }
  435. impl Sub<BigInt> for BigInt {
  436. type Output = BigInt;
  437. #[inline]
  438. fn sub(self, other: BigInt) -> BigInt {
  439. bigint_sub!(self, self, self.data, other, other, other.data)
  440. }
  441. }
  442. promote_all_scalars!(impl Sub for BigInt, sub);
  443. forward_all_scalar_binop_to_val_val!(impl Sub<BigDigit> for BigInt, sub);
  444. forward_all_scalar_binop_to_val_val!(impl Sub<DoubleBigDigit> for BigInt, sub);
  445. impl Sub<BigDigit> for BigInt {
  446. type Output = BigInt;
  447. #[inline]
  448. fn sub(self, other: BigDigit) -> BigInt {
  449. match self.sign {
  450. NoSign => BigInt::from_biguint(Minus, From::from(other)),
  451. Minus => BigInt::from_biguint(Minus, self.data + other),
  452. Plus =>
  453. match self.data.cmp(&From::from(other)) {
  454. Equal => Zero::zero(),
  455. Greater => BigInt::from_biguint(Plus, self.data - other),
  456. Less => BigInt::from_biguint(Minus, other - self.data),
  457. }
  458. }
  459. }
  460. }
  461. impl Sub<BigInt> for BigDigit {
  462. type Output = BigInt;
  463. #[inline]
  464. fn sub(self, other: BigInt) -> BigInt {
  465. -(other - self)
  466. }
  467. }
  468. impl Sub<DoubleBigDigit> for BigInt {
  469. type Output = BigInt;
  470. #[inline]
  471. fn sub(self, other: DoubleBigDigit) -> BigInt {
  472. match self.sign {
  473. NoSign => BigInt::from_biguint(Minus, From::from(other)),
  474. Minus => BigInt::from_biguint(Minus, self.data + other),
  475. Plus =>
  476. match self.data.cmp(&From::from(other)) {
  477. Equal => Zero::zero(),
  478. Greater => BigInt::from_biguint(Plus, self.data - other),
  479. Less => BigInt::from_biguint(Minus, other - self.data),
  480. }
  481. }
  482. }
  483. }
  484. impl Sub<BigInt> for DoubleBigDigit {
  485. type Output = BigInt;
  486. #[inline]
  487. fn sub(self, other: BigInt) -> BigInt {
  488. -(other - self)
  489. }
  490. }
  491. forward_all_scalar_binop_to_val_val!(impl Sub<i32> for BigInt, sub);
  492. forward_all_scalar_binop_to_val_val!(impl Sub<i64> for BigInt, sub);
  493. impl Sub<i32> for BigInt {
  494. type Output = BigInt;
  495. #[inline]
  496. fn sub(self, other: i32) -> BigInt {
  497. if other >= 0 {
  498. self - other as u32
  499. } else {
  500. self + i32_abs_as_u32(other)
  501. }
  502. }
  503. }
  504. impl Sub<BigInt> for i32 {
  505. type Output = BigInt;
  506. #[inline]
  507. fn sub(self, other: BigInt) -> BigInt {
  508. if self >= 0 {
  509. self as u32 - other
  510. } else {
  511. -other - i32_abs_as_u32(self)
  512. }
  513. }
  514. }
  515. impl Sub<i64> for BigInt {
  516. type Output = BigInt;
  517. #[inline]
  518. fn sub(self, other: i64) -> BigInt {
  519. if other >= 0 {
  520. self - other as u64
  521. } else {
  522. self + i64_abs_as_u64(other)
  523. }
  524. }
  525. }
  526. impl Sub<BigInt> for i64 {
  527. type Output = BigInt;
  528. #[inline]
  529. fn sub(self, other: BigInt) -> BigInt {
  530. if self >= 0 {
  531. self as u64 - other
  532. } else {
  533. -other - i64_abs_as_u64(self)
  534. }
  535. }
  536. }
  537. forward_all_binop_to_ref_ref!(impl Mul for BigInt, mul);
  538. impl<'a, 'b> Mul<&'b BigInt> for &'a BigInt {
  539. type Output = BigInt;
  540. #[inline]
  541. fn mul(self, other: &BigInt) -> BigInt {
  542. BigInt::from_biguint(self.sign * other.sign, &self.data * &other.data)
  543. }
  544. }
  545. promote_all_scalars!(impl Mul for BigInt, mul);
  546. forward_all_scalar_binop_to_val_val_commutative!(impl Mul<BigDigit> for BigInt, mul);
  547. forward_all_scalar_binop_to_val_val_commutative!(impl Mul<DoubleBigDigit> for BigInt, mul);
  548. impl Mul<BigDigit> for BigInt {
  549. type Output = BigInt;
  550. #[inline]
  551. fn mul(self, other: BigDigit) -> BigInt {
  552. BigInt::from_biguint(self.sign, self.data * other)
  553. }
  554. }
  555. impl Mul<DoubleBigDigit> for BigInt {
  556. type Output = BigInt;
  557. #[inline]
  558. fn mul(self, other: DoubleBigDigit) -> BigInt {
  559. BigInt::from_biguint(self.sign, self.data * other)
  560. }
  561. }
  562. forward_all_scalar_binop_to_val_val_commutative!(impl Mul<i32> for BigInt, mul);
  563. forward_all_scalar_binop_to_val_val_commutative!(impl Mul<i64> for BigInt, mul);
  564. impl Mul<i32> for BigInt {
  565. type Output = BigInt;
  566. #[inline]
  567. fn mul(self, other: i32) -> BigInt {
  568. if other >= 0 {
  569. self * other as u32
  570. } else {
  571. -(self * i32_abs_as_u32(other))
  572. }
  573. }
  574. }
  575. impl Mul<i64> for BigInt {
  576. type Output = BigInt;
  577. #[inline]
  578. fn mul(self, other: i64) -> BigInt {
  579. if other >= 0 {
  580. self * other as u64
  581. } else {
  582. -(self * i64_abs_as_u64(other))
  583. }
  584. }
  585. }
  586. forward_all_binop_to_ref_ref!(impl Div for BigInt, div);
  587. impl<'a, 'b> Div<&'b BigInt> for &'a BigInt {
  588. type Output = BigInt;
  589. #[inline]
  590. fn div(self, other: &BigInt) -> BigInt {
  591. let (q, _) = self.div_rem(other);
  592. q
  593. }
  594. }
  595. promote_all_scalars!(impl Div for BigInt, div);
  596. forward_all_scalar_binop_to_val_val!(impl Div<BigDigit> for BigInt, div);
  597. forward_all_scalar_binop_to_val_val!(impl Div<DoubleBigDigit> for BigInt, div);
  598. impl Div<BigDigit> for BigInt {
  599. type Output = BigInt;
  600. #[inline]
  601. fn div(self, other: BigDigit) -> BigInt {
  602. BigInt::from_biguint(self.sign, self.data / other)
  603. }
  604. }
  605. impl Div<BigInt> for BigDigit {
  606. type Output = BigInt;
  607. #[inline]
  608. fn div(self, other: BigInt) -> BigInt {
  609. BigInt::from_biguint(other.sign, self / other.data)
  610. }
  611. }
  612. impl Div<DoubleBigDigit> for BigInt {
  613. type Output = BigInt;
  614. #[inline]
  615. fn div(self, other: DoubleBigDigit) -> BigInt {
  616. BigInt::from_biguint(self.sign, self.data / other)
  617. }
  618. }
  619. impl Div<BigInt> for DoubleBigDigit {
  620. type Output = BigInt;
  621. #[inline]
  622. fn div(self, other: BigInt) -> BigInt {
  623. BigInt::from_biguint(other.sign, self / other.data)
  624. }
  625. }
  626. forward_all_scalar_binop_to_val_val!(impl Div<i32> for BigInt, div);
  627. forward_all_scalar_binop_to_val_val!(impl Div<i64> for BigInt, div);
  628. impl Div<i32> for BigInt {
  629. type Output = BigInt;
  630. #[inline]
  631. fn div(self, other: i32) -> BigInt {
  632. if other >= 0 {
  633. self / other as u32
  634. } else {
  635. -(self / i32_abs_as_u32(other))
  636. }
  637. }
  638. }
  639. impl Div<BigInt> for i32 {
  640. type Output = BigInt;
  641. #[inline]
  642. fn div(self, other: BigInt) -> BigInt {
  643. if self >= 0 {
  644. self as u32 / other
  645. } else {
  646. -(i32_abs_as_u32(self) / other)
  647. }
  648. }
  649. }
  650. impl Div<i64> for BigInt {
  651. type Output = BigInt;
  652. #[inline]
  653. fn div(self, other: i64) -> BigInt {
  654. if other >= 0 {
  655. self / other as u64
  656. } else {
  657. -(self / i64_abs_as_u64(other))
  658. }
  659. }
  660. }
  661. impl Div<BigInt> for i64 {
  662. type Output = BigInt;
  663. #[inline]
  664. fn div(self, other: BigInt) -> BigInt {
  665. if self >= 0 {
  666. self as u64 / other
  667. } else {
  668. -(i64_abs_as_u64(self) / other)
  669. }
  670. }
  671. }
  672. forward_all_binop_to_ref_ref!(impl Rem for BigInt, rem);
  673. impl<'a, 'b> Rem<&'b BigInt> for &'a BigInt {
  674. type Output = BigInt;
  675. #[inline]
  676. fn rem(self, other: &BigInt) -> BigInt {
  677. let (_, r) = self.div_rem(other);
  678. r
  679. }
  680. }
  681. promote_all_scalars!(impl Rem for BigInt, rem);
  682. forward_all_scalar_binop_to_val_val!(impl Rem<BigDigit> for BigInt, rem);
  683. forward_all_scalar_binop_to_val_val!(impl Rem<DoubleBigDigit> for BigInt, rem);
  684. impl Rem<BigDigit> for BigInt {
  685. type Output = BigInt;
  686. #[inline]
  687. fn rem(self, other: BigDigit) -> BigInt {
  688. BigInt::from_biguint(self.sign, self.data % other)
  689. }
  690. }
  691. impl Rem<BigInt> for BigDigit {
  692. type Output = BigInt;
  693. #[inline]
  694. fn rem(self, other: BigInt) -> BigInt {
  695. BigInt::from_biguint(Plus, self % other.data)
  696. }
  697. }
  698. impl Rem<DoubleBigDigit> for BigInt {
  699. type Output = BigInt;
  700. #[inline]
  701. fn rem(self, other: DoubleBigDigit) -> BigInt {
  702. BigInt::from_biguint(self.sign, self.data % other)
  703. }
  704. }
  705. impl Rem<BigInt> for DoubleBigDigit {
  706. type Output = BigInt;
  707. #[inline]
  708. fn rem(self, other: BigInt) -> BigInt {
  709. BigInt::from_biguint(Plus, self % other.data)
  710. }
  711. }
  712. forward_all_scalar_binop_to_val_val!(impl Rem<i32> for BigInt, rem);
  713. forward_all_scalar_binop_to_val_val!(impl Rem<i64> for BigInt, rem);
  714. impl Rem<i32> for BigInt {
  715. type Output = BigInt;
  716. #[inline]
  717. fn rem(self, other: i32) -> BigInt {
  718. if other >= 0 {
  719. self % other as u32
  720. } else {
  721. self % i32_abs_as_u32(other)
  722. }
  723. }
  724. }
  725. impl Rem<BigInt> for i32 {
  726. type Output = BigInt;
  727. #[inline]
  728. fn rem(self, other: BigInt) -> BigInt {
  729. if self >= 0 {
  730. self as u32 % other
  731. } else {
  732. -(i32_abs_as_u32(self) % other)
  733. }
  734. }
  735. }
  736. impl Rem<i64> for BigInt {
  737. type Output = BigInt;
  738. #[inline]
  739. fn rem(self, other: i64) -> BigInt {
  740. if other >= 0 {
  741. self % other as u64
  742. } else {
  743. self % i64_abs_as_u64(other)
  744. }
  745. }
  746. }
  747. impl Rem<BigInt> for i64 {
  748. type Output = BigInt;
  749. #[inline]
  750. fn rem(self, other: BigInt) -> BigInt {
  751. if self >= 0 {
  752. self as u64 % other
  753. } else {
  754. -(i64_abs_as_u64(self) % other)
  755. }
  756. }
  757. }
  758. impl Neg for BigInt {
  759. type Output = BigInt;
  760. #[inline]
  761. fn neg(mut self) -> BigInt {
  762. self.sign = -self.sign;
  763. self
  764. }
  765. }
  766. impl<'a> Neg for &'a BigInt {
  767. type Output = BigInt;
  768. #[inline]
  769. fn neg(self) -> BigInt {
  770. -self.clone()
  771. }
  772. }
  773. impl CheckedAdd for BigInt {
  774. #[inline]
  775. fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
  776. return Some(self.add(v));
  777. }
  778. }
  779. impl CheckedSub for BigInt {
  780. #[inline]
  781. fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
  782. return Some(self.sub(v));
  783. }
  784. }
  785. impl CheckedMul for BigInt {
  786. #[inline]
  787. fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
  788. return Some(self.mul(v));
  789. }
  790. }
  791. impl CheckedDiv for BigInt {
  792. #[inline]
  793. fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
  794. if v.is_zero() {
  795. return None;
  796. }
  797. return Some(self.div(v));
  798. }
  799. }
  800. impl Integer for BigInt {
  801. #[inline]
  802. fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) {
  803. // r.sign == self.sign
  804. let (d_ui, r_ui) = self.data.div_mod_floor(&other.data);
  805. let d = BigInt::from_biguint(self.sign, d_ui);
  806. let r = BigInt::from_biguint(self.sign, r_ui);
  807. if other.is_negative() {
  808. (-d, r)
  809. } else {
  810. (d, r)
  811. }
  812. }
  813. #[inline]
  814. fn div_floor(&self, other: &BigInt) -> BigInt {
  815. let (d, _) = self.div_mod_floor(other);
  816. d
  817. }
  818. #[inline]
  819. fn mod_floor(&self, other: &BigInt) -> BigInt {
  820. let (_, m) = self.div_mod_floor(other);
  821. m
  822. }
  823. fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) {
  824. // m.sign == other.sign
  825. let (d_ui, m_ui) = self.data.div_rem(&other.data);
  826. let d = BigInt::from_biguint(Plus, d_ui);
  827. let m = BigInt::from_biguint(Plus, m_ui);
  828. let one: BigInt = One::one();
  829. match (self.sign, other.sign) {
  830. (_, NoSign) => panic!(),
  831. (Plus, Plus) | (NoSign, Plus) => (d, m),
  832. (Plus, Minus) | (NoSign, Minus) => {
  833. if m.is_zero() {
  834. (-d, Zero::zero())
  835. } else {
  836. (-d - one, m + other)
  837. }
  838. }
  839. (Minus, Plus) => {
  840. if m.is_zero() {
  841. (-d, Zero::zero())
  842. } else {
  843. (-d - one, other - m)
  844. }
  845. }
  846. (Minus, Minus) => (d, -m),
  847. }
  848. }
  849. /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
  850. ///
  851. /// The result is always positive.
  852. #[inline]
  853. fn gcd(&self, other: &BigInt) -> BigInt {
  854. BigInt::from_biguint(Plus, self.data.gcd(&other.data))
  855. }
  856. /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
  857. #[inline]
  858. fn lcm(&self, other: &BigInt) -> BigInt {
  859. BigInt::from_biguint(Plus, self.data.lcm(&other.data))
  860. }
  861. /// Deprecated, use `is_multiple_of` instead.
  862. #[inline]
  863. fn divides(&self, other: &BigInt) -> bool {
  864. return self.is_multiple_of(other);
  865. }
  866. /// Returns `true` if the number is a multiple of `other`.
  867. #[inline]
  868. fn is_multiple_of(&self, other: &BigInt) -> bool {
  869. self.data.is_multiple_of(&other.data)
  870. }
  871. /// Returns `true` if the number is divisible by `2`.
  872. #[inline]
  873. fn is_even(&self) -> bool {
  874. self.data.is_even()
  875. }
  876. /// Returns `true` if the number is not divisible by `2`.
  877. #[inline]
  878. fn is_odd(&self) -> bool {
  879. self.data.is_odd()
  880. }
  881. }
  882. impl ToPrimitive for BigInt {
  883. #[inline]
  884. fn to_i64(&self) -> Option<i64> {
  885. match self.sign {
  886. Plus => self.data.to_i64(),
  887. NoSign => Some(0),
  888. Minus => {
  889. self.data.to_u64().and_then(|n| {
  890. let m: u64 = 1 << 63;
  891. if n < m {
  892. Some(-(n as i64))
  893. } else if n == m {
  894. Some(i64::MIN)
  895. } else {
  896. None
  897. }
  898. })
  899. }
  900. }
  901. }
  902. #[inline]
  903. fn to_u64(&self) -> Option<u64> {
  904. match self.sign {
  905. Plus => self.data.to_u64(),
  906. NoSign => Some(0),
  907. Minus => None,
  908. }
  909. }
  910. #[inline]
  911. fn to_f32(&self) -> Option<f32> {
  912. self.data.to_f32().map(|n| {
  913. if self.sign == Minus {
  914. -n
  915. } else {
  916. n
  917. }
  918. })
  919. }
  920. #[inline]
  921. fn to_f64(&self) -> Option<f64> {
  922. self.data.to_f64().map(|n| {
  923. if self.sign == Minus {
  924. -n
  925. } else {
  926. n
  927. }
  928. })
  929. }
  930. }
  931. impl FromPrimitive for BigInt {
  932. #[inline]
  933. fn from_i64(n: i64) -> Option<BigInt> {
  934. Some(BigInt::from(n))
  935. }
  936. #[inline]
  937. fn from_u64(n: u64) -> Option<BigInt> {
  938. Some(BigInt::from(n))
  939. }
  940. #[inline]
  941. fn from_f64(n: f64) -> Option<BigInt> {
  942. if n >= 0.0 {
  943. BigUint::from_f64(n).map(|x| BigInt::from_biguint(Plus, x))
  944. } else {
  945. BigUint::from_f64(-n).map(|x| BigInt::from_biguint(Minus, x))
  946. }
  947. }
  948. }
  949. impl From<i64> for BigInt {
  950. #[inline]
  951. fn from(n: i64) -> Self {
  952. if n >= 0 {
  953. BigInt::from(n as u64)
  954. } else {
  955. let u = u64::MAX - (n as u64) + 1;
  956. BigInt {
  957. sign: Minus,
  958. data: BigUint::from(u),
  959. }
  960. }
  961. }
  962. }
  963. macro_rules! impl_bigint_from_int {
  964. ($T:ty) => {
  965. impl From<$T> for BigInt {
  966. #[inline]
  967. fn from(n: $T) -> Self {
  968. BigInt::from(n as i64)
  969. }
  970. }
  971. }
  972. }
  973. impl_bigint_from_int!(i8);
  974. impl_bigint_from_int!(i16);
  975. impl_bigint_from_int!(i32);
  976. impl_bigint_from_int!(isize);
  977. impl From<u64> for BigInt {
  978. #[inline]
  979. fn from(n: u64) -> Self {
  980. if n > 0 {
  981. BigInt {
  982. sign: Plus,
  983. data: BigUint::from(n),
  984. }
  985. } else {
  986. BigInt::zero()
  987. }
  988. }
  989. }
  990. macro_rules! impl_bigint_from_uint {
  991. ($T:ty) => {
  992. impl From<$T> for BigInt {
  993. #[inline]
  994. fn from(n: $T) -> Self {
  995. BigInt::from(n as u64)
  996. }
  997. }
  998. }
  999. }
  1000. impl_bigint_from_uint!(u8);
  1001. impl_bigint_from_uint!(u16);
  1002. impl_bigint_from_uint!(u32);
  1003. impl_bigint_from_uint!(usize);
  1004. impl From<BigUint> for BigInt {
  1005. #[inline]
  1006. fn from(n: BigUint) -> Self {
  1007. if n.is_zero() {
  1008. BigInt::zero()
  1009. } else {
  1010. BigInt {
  1011. sign: Plus,
  1012. data: n,
  1013. }
  1014. }
  1015. }
  1016. }
  1017. #[cfg(feature = "serde")]
  1018. impl serde::Serialize for BigInt {
  1019. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
  1020. where S: serde::Serializer
  1021. {
  1022. (self.sign, &self.data).serialize(serializer)
  1023. }
  1024. }
  1025. #[cfg(feature = "serde")]
  1026. impl serde::Deserialize for BigInt {
  1027. fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
  1028. where D: serde::Deserializer
  1029. {
  1030. let (sign, data) = try!(serde::Deserialize::deserialize(deserializer));
  1031. Ok(BigInt {
  1032. sign: sign,
  1033. data: data,
  1034. })
  1035. }
  1036. }
  1037. /// A generic trait for converting a value to a `BigInt`.
  1038. pub trait ToBigInt {
  1039. /// Converts the value of `self` to a `BigInt`.
  1040. fn to_bigint(&self) -> Option<BigInt>;
  1041. }
  1042. impl ToBigInt for BigInt {
  1043. #[inline]
  1044. fn to_bigint(&self) -> Option<BigInt> {
  1045. Some(self.clone())
  1046. }
  1047. }
  1048. impl ToBigInt for BigUint {
  1049. #[inline]
  1050. fn to_bigint(&self) -> Option<BigInt> {
  1051. if self.is_zero() {
  1052. Some(Zero::zero())
  1053. } else {
  1054. Some(BigInt {
  1055. sign: Plus,
  1056. data: self.clone(),
  1057. })
  1058. }
  1059. }
  1060. }
  1061. impl biguint::ToBigUint for BigInt {
  1062. #[inline]
  1063. fn to_biguint(&self) -> Option<BigUint> {
  1064. match self.sign() {
  1065. Plus => Some(self.data.clone()),
  1066. NoSign => Some(Zero::zero()),
  1067. Minus => None,
  1068. }
  1069. }
  1070. }
  1071. macro_rules! impl_to_bigint {
  1072. ($T:ty, $from_ty:path) => {
  1073. impl ToBigInt for $T {
  1074. #[inline]
  1075. fn to_bigint(&self) -> Option<BigInt> {
  1076. $from_ty(*self)
  1077. }
  1078. }
  1079. }
  1080. }
  1081. impl_to_bigint!(isize, FromPrimitive::from_isize);
  1082. impl_to_bigint!(i8, FromPrimitive::from_i8);
  1083. impl_to_bigint!(i16, FromPrimitive::from_i16);
  1084. impl_to_bigint!(i32, FromPrimitive::from_i32);
  1085. impl_to_bigint!(i64, FromPrimitive::from_i64);
  1086. impl_to_bigint!(usize, FromPrimitive::from_usize);
  1087. impl_to_bigint!(u8, FromPrimitive::from_u8);
  1088. impl_to_bigint!(u16, FromPrimitive::from_u16);
  1089. impl_to_bigint!(u32, FromPrimitive::from_u32);
  1090. impl_to_bigint!(u64, FromPrimitive::from_u64);
  1091. impl_to_bigint!(f32, FromPrimitive::from_f32);
  1092. impl_to_bigint!(f64, FromPrimitive::from_f64);
  1093. pub trait RandBigInt {
  1094. /// Generate a random `BigUint` of the given bit size.
  1095. fn gen_biguint(&mut self, bit_size: usize) -> BigUint;
  1096. /// Generate a random BigInt of the given bit size.
  1097. fn gen_bigint(&mut self, bit_size: usize) -> BigInt;
  1098. /// Generate a random `BigUint` less than the given bound. Fails
  1099. /// when the bound is zero.
  1100. fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint;
  1101. /// Generate a random `BigUint` within the given range. The lower
  1102. /// bound is inclusive; the upper bound is exclusive. Fails when
  1103. /// the upper bound is not greater than the lower bound.
  1104. fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;
  1105. /// Generate a random `BigInt` within the given range. The lower
  1106. /// bound is inclusive; the upper bound is exclusive. Fails when
  1107. /// the upper bound is not greater than the lower bound.
  1108. fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt;
  1109. }
  1110. #[cfg(any(feature = "rand", test))]
  1111. impl<R: Rng> RandBigInt for R {
  1112. fn gen_biguint(&mut self, bit_size: usize) -> BigUint {
  1113. let (digits, rem) = bit_size.div_rem(&big_digit::BITS);
  1114. let mut data = Vec::with_capacity(digits + 1);
  1115. for _ in 0..digits {
  1116. data.push(self.gen());
  1117. }
  1118. if rem > 0 {
  1119. let final_digit: BigDigit = self.gen();
  1120. data.push(final_digit >> (big_digit::BITS - rem));
  1121. }
  1122. BigUint::new(data)
  1123. }
  1124. fn gen_bigint(&mut self, bit_size: usize) -> BigInt {
  1125. // Generate a random BigUint...
  1126. let biguint = self.gen_biguint(bit_size);
  1127. // ...and then randomly assign it a Sign...
  1128. let sign = if biguint.is_zero() {
  1129. // ...except that if the BigUint is zero, we need to try
  1130. // again with probability 0.5. This is because otherwise,
  1131. // the probability of generating a zero BigInt would be
  1132. // double that of any other number.
  1133. if self.gen() {
  1134. return self.gen_bigint(bit_size);
  1135. } else {
  1136. NoSign
  1137. }
  1138. } else if self.gen() {
  1139. Plus
  1140. } else {
  1141. Minus
  1142. };
  1143. BigInt::from_biguint(sign, biguint)
  1144. }
  1145. fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint {
  1146. assert!(!bound.is_zero());
  1147. let bits = bound.bits();
  1148. loop {
  1149. let n = self.gen_biguint(bits);
  1150. if n < *bound {
  1151. return n;
  1152. }
  1153. }
  1154. }
  1155. fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint {
  1156. assert!(*lbound < *ubound);
  1157. return lbound + self.gen_biguint_below(&(ubound - lbound));
  1158. }
  1159. fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt {
  1160. assert!(*lbound < *ubound);
  1161. let delta = (ubound - lbound).to_biguint().unwrap();
  1162. return lbound + self.gen_biguint_below(&delta).to_bigint().unwrap();
  1163. }
  1164. }
  1165. impl BigInt {
  1166. /// Creates and initializes a BigInt.
  1167. ///
  1168. /// The digits are in little-endian base 2<sup>32</sup>.
  1169. #[inline]
  1170. pub fn new(sign: Sign, digits: Vec<BigDigit>) -> BigInt {
  1171. BigInt::from_biguint(sign, BigUint::new(digits))
  1172. }
  1173. /// Creates and initializes a `BigInt`.
  1174. ///
  1175. /// The digits are in little-endian base 2<sup>32</sup>.
  1176. #[inline]
  1177. pub fn from_biguint(mut sign: Sign, mut data: BigUint) -> BigInt {
  1178. if sign == NoSign {
  1179. data.assign_from_slice(&[]);
  1180. } else if data.is_zero() {
  1181. sign = NoSign;
  1182. }
  1183. BigInt {
  1184. sign: sign,
  1185. data: data,
  1186. }
  1187. }
  1188. /// Creates and initializes a `BigInt`.
  1189. #[inline]
  1190. pub fn from_slice(sign: Sign, slice: &[BigDigit]) -> BigInt {
  1191. BigInt::from_biguint(sign, BigUint::from_slice(slice))
  1192. }
  1193. /// Reinitializes a `BigInt`.
  1194. #[inline]
  1195. pub fn assign_from_slice(&mut self, sign: Sign, slice: &[BigDigit]) {
  1196. if sign == NoSign {
  1197. self.data.assign_from_slice(&[]);
  1198. self.sign = NoSign;
  1199. } else {
  1200. self.data.assign_from_slice(slice);
  1201. self.sign = match self.data.is_zero() {
  1202. true => NoSign,
  1203. false => sign,
  1204. }
  1205. }
  1206. }
  1207. /// Creates and initializes a `BigInt`.
  1208. ///
  1209. /// The bytes are in big-endian byte order.
  1210. ///
  1211. /// # Examples
  1212. ///
  1213. /// ```
  1214. /// use num_bigint::{BigInt, Sign};
  1215. ///
  1216. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"A"),
  1217. /// BigInt::parse_bytes(b"65", 10).unwrap());
  1218. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AA"),
  1219. /// BigInt::parse_bytes(b"16705", 10).unwrap());
  1220. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AB"),
  1221. /// BigInt::parse_bytes(b"16706", 10).unwrap());
  1222. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"Hello world!"),
  1223. /// BigInt::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
  1224. /// ```
  1225. #[inline]
  1226. pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt {
  1227. BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes))
  1228. }
  1229. /// Creates and initializes a `BigInt`.
  1230. ///
  1231. /// The bytes are in little-endian byte order.
  1232. #[inline]
  1233. pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt {
  1234. BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes))
  1235. }
  1236. /// Creates and initializes a `BigInt` from an array of bytes in
  1237. /// two's complement binary representation.
  1238. ///
  1239. /// The digits are in big-endian base 2<sup>8</sup>.
  1240. #[inline]
  1241. pub fn from_signed_bytes_be(digits: &[u8]) -> BigInt {
  1242. let sign = match digits.first() {
  1243. Some(v) if *v > 0x7f => Sign::Minus,
  1244. Some(_) => Sign::Plus,
  1245. None => return BigInt::zero(),
  1246. };
  1247. if sign == Sign::Minus {
  1248. // two's-complement the content to retrieve the magnitude
  1249. let mut digits = Vec::from(digits);
  1250. twos_complement_be(&mut digits);
  1251. BigInt::from_biguint(sign, BigUint::from_bytes_be(&*digits))
  1252. } else {
  1253. BigInt::from_biguint(sign, BigUint::from_bytes_be(digits))
  1254. }
  1255. }
  1256. /// Creates and initializes a `BigInt` from an array of bytes in two's complement.
  1257. ///
  1258. /// The digits are in little-endian base 2<sup>8</sup>.
  1259. #[inline]
  1260. pub fn from_signed_bytes_le(digits: &[u8]) -> BigInt {
  1261. let sign = match digits.last() {
  1262. Some(v) if *v > 0x7f => Sign::Minus,
  1263. Some(_) => Sign::Plus,
  1264. None => return BigInt::zero(),
  1265. };
  1266. if sign == Sign::Minus {
  1267. // two's-complement the content to retrieve the magnitude
  1268. let mut digits = Vec::from(digits);
  1269. twos_complement_le(&mut digits);
  1270. BigInt::from_biguint(sign, BigUint::from_bytes_le(&*digits))
  1271. } else {
  1272. BigInt::from_biguint(sign, BigUint::from_bytes_le(digits))
  1273. }
  1274. }
  1275. /// Creates and initializes a `BigInt`.
  1276. ///
  1277. /// # Examples
  1278. ///
  1279. /// ```
  1280. /// use num_bigint::{BigInt, ToBigInt};
  1281. ///
  1282. /// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234));
  1283. /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD));
  1284. /// assert_eq!(BigInt::parse_bytes(b"G", 16), None);
  1285. /// ```
  1286. #[inline]
  1287. pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigInt> {
  1288. str::from_utf8(buf).ok().and_then(|s| BigInt::from_str_radix(s, radix).ok())
  1289. }
  1290. /// Creates and initializes a `BigInt`. Each u8 of the input slice is
  1291. /// interpreted as one digit of the number
  1292. /// and must therefore be less than `radix`.
  1293. ///
  1294. /// The bytes are in big-endian byte order.
  1295. /// `radix` must be in the range `2...256`.
  1296. ///
  1297. /// # Examples
  1298. ///
  1299. /// ```
  1300. /// use num_bigint::{BigInt, Sign};
  1301. ///
  1302. /// let inbase190 = vec![15, 33, 125, 12, 14];
  1303. /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap();
  1304. /// assert_eq!(a.to_radix_be(190), (Sign:: Minus, inbase190));
  1305. /// ```
  1306. pub fn from_radix_be(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt> {
  1307. BigUint::from_radix_be(buf, radix).map(|u| BigInt::from_biguint(sign, u))
  1308. }
  1309. /// Creates and initializes a `BigInt`. Each u8 of the input slice is
  1310. /// interpreted as one digit of the number
  1311. /// and must therefore be less than `radix`.
  1312. ///
  1313. /// The bytes are in little-endian byte order.
  1314. /// `radix` must be in the range `2...256`.
  1315. ///
  1316. /// # Examples
  1317. ///
  1318. /// ```
  1319. /// use num_bigint::{BigInt, Sign};
  1320. ///
  1321. /// let inbase190 = vec![14, 12, 125, 33, 15];
  1322. /// let a = BigInt::from_radix_be(Sign::Minus, &inbase190, 190).unwrap();
  1323. /// assert_eq!(a.to_radix_be(190), (Sign::Minus, inbase190));
  1324. /// ```
  1325. pub fn from_radix_le(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt> {
  1326. BigUint::from_radix_le(buf, radix).map(|u| BigInt::from_biguint(sign, u))
  1327. }
  1328. /// Returns the sign and the byte representation of the `BigInt` in big-endian byte order.
  1329. ///
  1330. /// # Examples
  1331. ///
  1332. /// ```
  1333. /// use num_bigint::{ToBigInt, Sign};
  1334. ///
  1335. /// let i = -1125.to_bigint().unwrap();
  1336. /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101]));
  1337. /// ```
  1338. #[inline]
  1339. pub fn to_bytes_be(&self) -> (Sign, Vec<u8>) {
  1340. (self.sign, self.data.to_bytes_be())
  1341. }
  1342. /// Returns the sign and the byte representation of the `BigInt` in little-endian byte order.
  1343. ///
  1344. /// # Examples
  1345. ///
  1346. /// ```
  1347. /// use num_bigint::{ToBigInt, Sign};
  1348. ///
  1349. /// let i = -1125.to_bigint().unwrap();
  1350. /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4]));
  1351. /// ```
  1352. #[inline]
  1353. pub fn to_bytes_le(&self) -> (Sign, Vec<u8>) {
  1354. (self.sign, self.data.to_bytes_le())
  1355. }
  1356. /// Returns the two's complement byte representation of the `BigInt` in big-endian byte order.
  1357. ///
  1358. /// # Examples
  1359. ///
  1360. /// ```
  1361. /// use num_bigint::ToBigInt;
  1362. ///
  1363. /// let i = -1125.to_bigint().unwrap();
  1364. /// assert_eq!(i.to_signed_bytes_be(), vec![251, 155]);
  1365. /// ```
  1366. #[inline]
  1367. pub fn to_signed_bytes_be(&self) -> Vec<u8> {
  1368. let mut bytes = self.data.to_bytes_be();
  1369. let first_byte = bytes.first().map(|v| *v).unwrap_or(0);
  1370. if first_byte > 0x7f && !(first_byte == 0x80 && bytes.iter().skip(1).all(Zero::is_zero)) {
  1371. // msb used by magnitude, extend by 1 byte
  1372. bytes.insert(0, 0);
  1373. }
  1374. if self.sign == Sign::Minus {
  1375. twos_complement_be(&mut bytes);
  1376. }
  1377. bytes
  1378. }
  1379. /// Returns the two's complement byte representation of the `BigInt` in little-endian byte order.
  1380. ///
  1381. /// # Examples
  1382. ///
  1383. /// ```
  1384. /// use num_bigint::ToBigInt;
  1385. ///
  1386. /// let i = -1125.to_bigint().unwrap();
  1387. /// assert_eq!(i.to_signed_bytes_le(), vec![155, 251]);
  1388. /// ```
  1389. #[inline]
  1390. pub fn to_signed_bytes_le(&self) -> Vec<u8> {
  1391. let mut bytes = self.data.to_bytes_le();
  1392. let last_byte = bytes.last().map(|v| *v).unwrap_or(0);
  1393. if last_byte > 0x7f && !(last_byte == 0x80 && bytes.iter().rev().skip(1).all(Zero::is_zero)) {
  1394. // msb used by magnitude, extend by 1 byte
  1395. bytes.push(0);
  1396. }
  1397. if self.sign == Sign::Minus {
  1398. twos_complement_le(&mut bytes);
  1399. }
  1400. bytes
  1401. }
  1402. /// Returns the integer formatted as a string in the given radix.
  1403. /// `radix` must be in the range `2...36`.
  1404. ///
  1405. /// # Examples
  1406. ///
  1407. /// ```
  1408. /// use num_bigint::BigInt;
  1409. ///
  1410. /// let i = BigInt::parse_bytes(b"ff", 16).unwrap();
  1411. /// assert_eq!(i.to_str_radix(16), "ff");
  1412. /// ```
  1413. #[inline]
  1414. pub fn to_str_radix(&self, radix: u32) -> String {
  1415. let mut v = to_str_radix_reversed(&self.data, radix);
  1416. if self.is_negative() {
  1417. v.push(b'-');
  1418. }
  1419. v.reverse();
  1420. unsafe { String::from_utf8_unchecked(v) }
  1421. }
  1422. /// Returns the integer in the requested base in big-endian digit order.
  1423. /// The output is not given in a human readable alphabet but as a zero
  1424. /// based u8 number.
  1425. /// `radix` must be in the range `2...256`.
  1426. ///
  1427. /// # Examples
  1428. ///
  1429. /// ```
  1430. /// use num_bigint::{BigInt, Sign};
  1431. ///
  1432. /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_be(159),
  1433. /// (Sign::Minus, vec![2, 94, 27]));
  1434. /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27
  1435. /// ```
  1436. #[inline]
  1437. pub fn to_radix_be(&self, radix: u32) -> (Sign, Vec<u8>) {
  1438. (self.sign, self.data.to_radix_be(radix))
  1439. }
  1440. /// Returns the integer in the requested base in little-endian digit order.
  1441. /// The output is not given in a human readable alphabet but as a zero
  1442. /// based u8 number.
  1443. /// `radix` must be in the range `2...256`.
  1444. ///
  1445. /// # Examples
  1446. ///
  1447. /// ```
  1448. /// use num_bigint::{BigInt, Sign};
  1449. ///
  1450. /// assert_eq!(BigInt::from(-0xFFFFi64).to_radix_le(159),
  1451. /// (Sign::Minus, vec![27, 94, 2]));
  1452. /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2)
  1453. /// ```
  1454. #[inline]
  1455. pub fn to_radix_le(&self, radix: u32) -> (Sign, Vec<u8>) {
  1456. (self.sign, self.data.to_radix_le(radix))
  1457. }
  1458. /// Returns the sign of the `BigInt` as a `Sign`.
  1459. ///
  1460. /// # Examples
  1461. ///
  1462. /// ```
  1463. /// use num_bigint::{ToBigInt, Sign};
  1464. ///
  1465. /// assert_eq!(ToBigInt::to_bigint(&1234).unwrap().sign(), Sign::Plus);
  1466. /// assert_eq!(ToBigInt::to_bigint(&-4321).unwrap().sign(), Sign::Minus);
  1467. /// assert_eq!(ToBigInt::to_bigint(&0).unwrap().sign(), Sign::NoSign);
  1468. /// ```
  1469. #[inline]
  1470. pub fn sign(&self) -> Sign {
  1471. self.sign
  1472. }
  1473. /// Determines the fewest bits necessary to express the `BigInt`,
  1474. /// not including the sign.
  1475. #[inline]
  1476. pub fn bits(&self) -> usize {
  1477. self.data.bits()
  1478. }
  1479. /// Converts this `BigInt` into a `BigUint`, if it's not negative.
  1480. #[inline]
  1481. pub fn to_biguint(&self) -> Option<BigUint> {
  1482. match self.sign {
  1483. Plus => Some(self.data.clone()),
  1484. NoSign => Some(Zero::zero()),
  1485. Minus => None,
  1486. }
  1487. }
  1488. #[inline]
  1489. pub fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
  1490. return Some(self.add(v));
  1491. }
  1492. #[inline]
  1493. pub fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
  1494. return Some(self.sub(v));
  1495. }
  1496. #[inline]
  1497. pub fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
  1498. return Some(self.mul(v));
  1499. }
  1500. #[inline]
  1501. pub fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
  1502. if v.is_zero() {
  1503. return None;
  1504. }
  1505. return Some(self.div(v));
  1506. }
  1507. }
  1508. /// Perform in-place two's complement of the given binary representation,
  1509. /// in little-endian byte order.
  1510. #[inline]
  1511. fn twos_complement_le(digits: &mut [u8]) {
  1512. twos_complement(digits)
  1513. }
  1514. /// Perform in-place two's complement of the given binary representation
  1515. /// in big-endian byte order.
  1516. #[inline]
  1517. fn twos_complement_be(digits: &mut [u8]) {
  1518. twos_complement(digits.iter_mut().rev())
  1519. }
  1520. /// Perform in-place two's complement of the given digit iterator
  1521. /// starting from the least significant byte.
  1522. #[inline]
  1523. fn twos_complement<'a, I>(digits: I)
  1524. where I: IntoIterator<Item = &'a mut u8>
  1525. {
  1526. let mut carry = true;
  1527. for d in digits {
  1528. *d = d.not();
  1529. if carry {
  1530. *d = d.wrapping_add(1);
  1531. carry = d.is_zero();
  1532. }
  1533. }
  1534. }