biguint.rs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. use std::borrow::Cow;
  2. use std::default::Default;
  3. use std::iter::repeat;
  4. use std::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Rem, Shl, Shr, Sub};
  5. use std::str::{self, FromStr};
  6. use std::fmt;
  7. use std::cmp;
  8. use std::cmp::Ordering::{self, Less, Greater, Equal};
  9. use std::{f32, f64};
  10. use std::{u8, i64, u64};
  11. use std::ascii::AsciiExt;
  12. #[cfg(feature = "serde")]
  13. use serde;
  14. use integer::Integer;
  15. use traits::{ToPrimitive, FromPrimitive, Float, Num, Unsigned, CheckedAdd, CheckedSub, CheckedMul,
  16. CheckedDiv, Zero, One};
  17. #[path = "algorithms.rs"]
  18. mod algorithms;
  19. pub use self::algorithms::big_digit;
  20. pub use self::big_digit::{BigDigit, DoubleBigDigit, ZERO_BIG_DIGIT};
  21. use self::algorithms::{mac_with_carry, mul3, div_rem, div_rem_digit};
  22. use self::algorithms::{__add2, add2, sub2, sub2rev};
  23. use self::algorithms::{biguint_shl, biguint_shr};
  24. use self::algorithms::{cmp_slice, fls, ilog2};
  25. use ParseBigIntError;
  26. #[cfg(test)]
  27. #[path = "tests/biguint.rs"]
  28. mod biguint_tests;
  29. /// A big unsigned integer type.
  30. ///
  31. /// A `BigUint`-typed value `BigUint { data: vec!(a, b, c) }` represents a number
  32. /// `(a + b * big_digit::BASE + c * big_digit::BASE^2)`.
  33. #[derive(Clone, Debug, Hash)]
  34. #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
  35. pub struct BigUint {
  36. data: Vec<BigDigit>,
  37. }
  38. impl PartialEq for BigUint {
  39. #[inline]
  40. fn eq(&self, other: &BigUint) -> bool {
  41. match self.cmp(other) {
  42. Equal => true,
  43. _ => false,
  44. }
  45. }
  46. }
  47. impl Eq for BigUint {}
  48. impl PartialOrd for BigUint {
  49. #[inline]
  50. fn partial_cmp(&self, other: &BigUint) -> Option<Ordering> {
  51. Some(self.cmp(other))
  52. }
  53. }
  54. impl Ord for BigUint {
  55. #[inline]
  56. fn cmp(&self, other: &BigUint) -> Ordering {
  57. cmp_slice(&self.data[..], &other.data[..])
  58. }
  59. }
  60. impl Default for BigUint {
  61. #[inline]
  62. fn default() -> BigUint {
  63. Zero::zero()
  64. }
  65. }
  66. impl fmt::Display for BigUint {
  67. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  68. f.pad_integral(true, "", &self.to_str_radix(10))
  69. }
  70. }
  71. impl fmt::LowerHex for BigUint {
  72. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  73. f.pad_integral(true, "0x", &self.to_str_radix(16))
  74. }
  75. }
  76. impl fmt::UpperHex for BigUint {
  77. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  78. f.pad_integral(true, "0x", &self.to_str_radix(16).to_ascii_uppercase())
  79. }
  80. }
  81. impl fmt::Binary for BigUint {
  82. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  83. f.pad_integral(true, "0b", &self.to_str_radix(2))
  84. }
  85. }
  86. impl fmt::Octal for BigUint {
  87. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  88. f.pad_integral(true, "0o", &self.to_str_radix(8))
  89. }
  90. }
  91. impl FromStr for BigUint {
  92. type Err = ParseBigIntError;
  93. #[inline]
  94. fn from_str(s: &str) -> Result<BigUint, ParseBigIntError> {
  95. BigUint::from_str_radix(s, 10)
  96. }
  97. }
  98. // Convert from a power of two radix (bits == ilog2(radix)) where bits evenly divides
  99. // BigDigit::BITS
  100. fn from_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint {
  101. debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits == 0);
  102. debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits)));
  103. let digits_per_big_digit = big_digit::BITS / bits;
  104. let data = v.chunks(digits_per_big_digit)
  105. .map(|chunk| {
  106. chunk.iter().rev().fold(0, |acc, &c| (acc << bits) | c as BigDigit)
  107. })
  108. .collect();
  109. BigUint::new(data)
  110. }
  111. // Convert from a power of two radix (bits == ilog2(radix)) where bits doesn't evenly divide
  112. // BigDigit::BITS
  113. fn from_inexact_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint {
  114. debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits != 0);
  115. debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits)));
  116. let big_digits = (v.len() * bits + big_digit::BITS - 1) / big_digit::BITS;
  117. let mut data = Vec::with_capacity(big_digits);
  118. let mut d = 0;
  119. let mut dbits = 0; // number of bits we currently have in d
  120. // walk v accumululating bits in d; whenever we accumulate big_digit::BITS in d, spit out a
  121. // big_digit:
  122. for &c in v {
  123. d |= (c as BigDigit) << dbits;
  124. dbits += bits;
  125. if dbits >= big_digit::BITS {
  126. data.push(d);
  127. dbits -= big_digit::BITS;
  128. // if dbits was > big_digit::BITS, we dropped some of the bits in c (they couldn't fit
  129. // in d) - grab the bits we lost here:
  130. d = (c as BigDigit) >> (bits - dbits);
  131. }
  132. }
  133. if dbits > 0 {
  134. debug_assert!(dbits < big_digit::BITS);
  135. data.push(d as BigDigit);
  136. }
  137. BigUint::new(data)
  138. }
  139. // Read little-endian radix digits
  140. fn from_radix_digits_be(v: &[u8], radix: u32) -> BigUint {
  141. debug_assert!(!v.is_empty() && !radix.is_power_of_two());
  142. debug_assert!(v.iter().all(|&c| (c as u32) < radix));
  143. // Estimate how big the result will be, so we can pre-allocate it.
  144. let bits = (radix as f64).log2() * v.len() as f64;
  145. let big_digits = (bits / big_digit::BITS as f64).ceil();
  146. let mut data = Vec::with_capacity(big_digits as usize);
  147. let (base, power) = get_radix_base(radix);
  148. let radix = radix as BigDigit;
  149. let r = v.len() % power;
  150. let i = if r == 0 {
  151. power
  152. } else {
  153. r
  154. };
  155. let (head, tail) = v.split_at(i);
  156. let first = head.iter().fold(0, |acc, &d| acc * radix + d as BigDigit);
  157. data.push(first);
  158. debug_assert!(tail.len() % power == 0);
  159. for chunk in tail.chunks(power) {
  160. if data.last() != Some(&0) {
  161. data.push(0);
  162. }
  163. let mut carry = 0;
  164. for d in data.iter_mut() {
  165. *d = mac_with_carry(0, *d, base, &mut carry);
  166. }
  167. debug_assert!(carry == 0);
  168. let n = chunk.iter().fold(0, |acc, &d| acc * radix + d as BigDigit);
  169. add2(&mut data, &[n]);
  170. }
  171. BigUint::new(data)
  172. }
  173. impl Num for BigUint {
  174. type FromStrRadixErr = ParseBigIntError;
  175. /// Creates and initializes a `BigUint`.
  176. fn from_str_radix(s: &str, radix: u32) -> Result<BigUint, ParseBigIntError> {
  177. assert!(2 <= radix && radix <= 36, "The radix must be within 2...36");
  178. let mut s = s;
  179. if s.starts_with('+') {
  180. let tail = &s[1..];
  181. if !tail.starts_with('+') {
  182. s = tail
  183. }
  184. }
  185. if s.is_empty() {
  186. // create ParseIntError::Empty
  187. let e = u64::from_str_radix(s, radix).unwrap_err();
  188. return Err(e.into());
  189. }
  190. // First normalize all characters to plain digit values
  191. let mut v = Vec::with_capacity(s.len());
  192. for b in s.bytes() {
  193. let d = match b {
  194. b'0'...b'9' => b - b'0',
  195. b'a'...b'z' => b - b'a' + 10,
  196. b'A'...b'Z' => b - b'A' + 10,
  197. _ => u8::MAX,
  198. };
  199. if d < radix as u8 {
  200. v.push(d);
  201. } else {
  202. // create ParseIntError::InvalidDigit
  203. let e = u64::from_str_radix(&s[v.len()..], radix).unwrap_err();
  204. return Err(e.into());
  205. }
  206. }
  207. let res = if radix.is_power_of_two() {
  208. // Powers of two can use bitwise masks and shifting instead of multiplication
  209. let bits = ilog2(radix);
  210. v.reverse();
  211. if big_digit::BITS % bits == 0 {
  212. from_bitwise_digits_le(&v, bits)
  213. } else {
  214. from_inexact_bitwise_digits_le(&v, bits)
  215. }
  216. } else {
  217. from_radix_digits_be(&v, radix)
  218. };
  219. Ok(res)
  220. }
  221. }
  222. forward_all_binop_to_val_ref_commutative!(impl BitAnd for BigUint, bitand);
  223. impl<'a> BitAnd<&'a BigUint> for BigUint {
  224. type Output = BigUint;
  225. #[inline]
  226. fn bitand(self, other: &BigUint) -> BigUint {
  227. let mut data = self.data;
  228. for (ai, &bi) in data.iter_mut().zip(other.data.iter()) {
  229. *ai &= bi;
  230. }
  231. data.truncate(other.data.len());
  232. BigUint::new(data)
  233. }
  234. }
  235. forward_all_binop_to_val_ref_commutative!(impl BitOr for BigUint, bitor);
  236. impl<'a> BitOr<&'a BigUint> for BigUint {
  237. type Output = BigUint;
  238. fn bitor(self, other: &BigUint) -> BigUint {
  239. let mut data = self.data;
  240. for (ai, &bi) in data.iter_mut().zip(other.data.iter()) {
  241. *ai |= bi;
  242. }
  243. if other.data.len() > data.len() {
  244. let extra = &other.data[data.len()..];
  245. data.extend(extra.iter().cloned());
  246. }
  247. BigUint::new(data)
  248. }
  249. }
  250. forward_all_binop_to_val_ref_commutative!(impl BitXor for BigUint, bitxor);
  251. impl<'a> BitXor<&'a BigUint> for BigUint {
  252. type Output = BigUint;
  253. fn bitxor(self, other: &BigUint) -> BigUint {
  254. let mut data = self.data;
  255. for (ai, &bi) in data.iter_mut().zip(other.data.iter()) {
  256. *ai ^= bi;
  257. }
  258. if other.data.len() > data.len() {
  259. let extra = &other.data[data.len()..];
  260. data.extend(extra.iter().cloned());
  261. }
  262. BigUint::new(data)
  263. }
  264. }
  265. impl Shl<usize> for BigUint {
  266. type Output = BigUint;
  267. #[inline]
  268. fn shl(self, rhs: usize) -> BigUint {
  269. biguint_shl(Cow::Owned(self), rhs)
  270. }
  271. }
  272. impl<'a> Shl<usize> for &'a BigUint {
  273. type Output = BigUint;
  274. #[inline]
  275. fn shl(self, rhs: usize) -> BigUint {
  276. biguint_shl(Cow::Borrowed(self), rhs)
  277. }
  278. }
  279. impl Shr<usize> for BigUint {
  280. type Output = BigUint;
  281. #[inline]
  282. fn shr(self, rhs: usize) -> BigUint {
  283. biguint_shr(Cow::Owned(self), rhs)
  284. }
  285. }
  286. impl<'a> Shr<usize> for &'a BigUint {
  287. type Output = BigUint;
  288. #[inline]
  289. fn shr(self, rhs: usize) -> BigUint {
  290. biguint_shr(Cow::Borrowed(self), rhs)
  291. }
  292. }
  293. impl Zero for BigUint {
  294. #[inline]
  295. fn zero() -> BigUint {
  296. BigUint::new(Vec::new())
  297. }
  298. #[inline]
  299. fn is_zero(&self) -> bool {
  300. self.data.is_empty()
  301. }
  302. }
  303. impl One for BigUint {
  304. #[inline]
  305. fn one() -> BigUint {
  306. BigUint::new(vec![1])
  307. }
  308. }
  309. impl Unsigned for BigUint {}
  310. forward_all_binop_to_val_ref_commutative!(impl Add for BigUint, add);
  311. impl<'a> Add<&'a BigUint> for BigUint {
  312. type Output = BigUint;
  313. fn add(mut self, other: &BigUint) -> BigUint {
  314. if self.data.len() < other.data.len() {
  315. let extra = other.data.len() - self.data.len();
  316. self.data.extend(repeat(0).take(extra));
  317. }
  318. let carry = __add2(&mut self.data[..], &other.data[..]);
  319. if carry != 0 {
  320. self.data.push(carry);
  321. }
  322. self
  323. }
  324. }
  325. forward_val_val_binop!(impl Sub for BigUint, sub);
  326. forward_ref_ref_binop!(impl Sub for BigUint, sub);
  327. impl<'a> Sub<&'a BigUint> for BigUint {
  328. type Output = BigUint;
  329. fn sub(mut self, other: &BigUint) -> BigUint {
  330. sub2(&mut self.data[..], &other.data[..]);
  331. self.normalize()
  332. }
  333. }
  334. impl<'a> Sub<BigUint> for &'a BigUint {
  335. type Output = BigUint;
  336. fn sub(self, mut other: BigUint) -> BigUint {
  337. if other.data.len() < self.data.len() {
  338. let extra = self.data.len() - other.data.len();
  339. other.data.extend(repeat(0).take(extra));
  340. }
  341. sub2rev(&self.data[..], &mut other.data[..]);
  342. other.normalize()
  343. }
  344. }
  345. forward_all_binop_to_ref_ref!(impl Mul for BigUint, mul);
  346. impl<'a, 'b> Mul<&'b BigUint> for &'a BigUint {
  347. type Output = BigUint;
  348. #[inline]
  349. fn mul(self, other: &BigUint) -> BigUint {
  350. mul3(&self.data[..], &other.data[..])
  351. }
  352. }
  353. forward_all_binop_to_ref_ref!(impl Div for BigUint, div);
  354. impl<'a, 'b> Div<&'b BigUint> for &'a BigUint {
  355. type Output = BigUint;
  356. #[inline]
  357. fn div(self, other: &BigUint) -> BigUint {
  358. let (q, _) = self.div_rem(other);
  359. return q;
  360. }
  361. }
  362. forward_all_binop_to_ref_ref!(impl Rem for BigUint, rem);
  363. impl<'a, 'b> Rem<&'b BigUint> for &'a BigUint {
  364. type Output = BigUint;
  365. #[inline]
  366. fn rem(self, other: &BigUint) -> BigUint {
  367. let (_, r) = self.div_rem(other);
  368. return r;
  369. }
  370. }
  371. impl Neg for BigUint {
  372. type Output = BigUint;
  373. #[inline]
  374. fn neg(self) -> BigUint {
  375. panic!()
  376. }
  377. }
  378. impl<'a> Neg for &'a BigUint {
  379. type Output = BigUint;
  380. #[inline]
  381. fn neg(self) -> BigUint {
  382. panic!()
  383. }
  384. }
  385. impl CheckedAdd for BigUint {
  386. #[inline]
  387. fn checked_add(&self, v: &BigUint) -> Option<BigUint> {
  388. return Some(self.add(v));
  389. }
  390. }
  391. impl CheckedSub for BigUint {
  392. #[inline]
  393. fn checked_sub(&self, v: &BigUint) -> Option<BigUint> {
  394. match self.cmp(v) {
  395. Less => None,
  396. Equal => Some(Zero::zero()),
  397. Greater => Some(self.sub(v)),
  398. }
  399. }
  400. }
  401. impl CheckedMul for BigUint {
  402. #[inline]
  403. fn checked_mul(&self, v: &BigUint) -> Option<BigUint> {
  404. return Some(self.mul(v));
  405. }
  406. }
  407. impl CheckedDiv for BigUint {
  408. #[inline]
  409. fn checked_div(&self, v: &BigUint) -> Option<BigUint> {
  410. if v.is_zero() {
  411. return None;
  412. }
  413. return Some(self.div(v));
  414. }
  415. }
  416. impl Integer for BigUint {
  417. #[inline]
  418. fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) {
  419. div_rem(self, other)
  420. }
  421. #[inline]
  422. fn div_floor(&self, other: &BigUint) -> BigUint {
  423. let (d, _) = div_rem(self, other);
  424. d
  425. }
  426. #[inline]
  427. fn mod_floor(&self, other: &BigUint) -> BigUint {
  428. let (_, m) = div_rem(self, other);
  429. m
  430. }
  431. #[inline]
  432. fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) {
  433. div_rem(self, other)
  434. }
  435. /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
  436. ///
  437. /// The result is always positive.
  438. #[inline]
  439. fn gcd(&self, other: &BigUint) -> BigUint {
  440. // Use Euclid's algorithm
  441. let mut m = (*self).clone();
  442. let mut n = (*other).clone();
  443. while !m.is_zero() {
  444. let temp = m;
  445. m = n % &temp;
  446. n = temp;
  447. }
  448. return n;
  449. }
  450. /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
  451. #[inline]
  452. fn lcm(&self, other: &BigUint) -> BigUint {
  453. ((self * other) / self.gcd(other))
  454. }
  455. /// Deprecated, use `is_multiple_of` instead.
  456. #[inline]
  457. fn divides(&self, other: &BigUint) -> bool {
  458. self.is_multiple_of(other)
  459. }
  460. /// Returns `true` if the number is a multiple of `other`.
  461. #[inline]
  462. fn is_multiple_of(&self, other: &BigUint) -> bool {
  463. (self % other).is_zero()
  464. }
  465. /// Returns `true` if the number is divisible by `2`.
  466. #[inline]
  467. fn is_even(&self) -> bool {
  468. // Considering only the last digit.
  469. match self.data.first() {
  470. Some(x) => x.is_even(),
  471. None => true,
  472. }
  473. }
  474. /// Returns `true` if the number is not divisible by `2`.
  475. #[inline]
  476. fn is_odd(&self) -> bool {
  477. !self.is_even()
  478. }
  479. }
  480. fn high_bits_to_u64(v: &BigUint) -> u64 {
  481. match v.data.len() {
  482. 0 => 0,
  483. 1 => v.data[0] as u64,
  484. _ => {
  485. let mut bits = v.bits();
  486. let mut ret = 0u64;
  487. let mut ret_bits = 0;
  488. for d in v.data.iter().rev() {
  489. let digit_bits = (bits - 1) % big_digit::BITS + 1;
  490. let bits_want = cmp::min(64 - ret_bits, digit_bits);
  491. if bits_want != 64 {
  492. ret <<= bits_want;
  493. }
  494. ret |= *d as u64 >> (digit_bits - bits_want);
  495. ret_bits += bits_want;
  496. bits -= bits_want;
  497. if ret_bits == 64 {
  498. break;
  499. }
  500. }
  501. ret
  502. }
  503. }
  504. }
  505. impl ToPrimitive for BigUint {
  506. #[inline]
  507. fn to_i64(&self) -> Option<i64> {
  508. self.to_u64().and_then(|n| {
  509. // If top bit of u64 is set, it's too large to convert to i64.
  510. if n >> 63 == 0 {
  511. Some(n as i64)
  512. } else {
  513. None
  514. }
  515. })
  516. }
  517. #[inline]
  518. fn to_u64(&self) -> Option<u64> {
  519. let mut ret: u64 = 0;
  520. let mut bits = 0;
  521. for i in self.data.iter() {
  522. if bits >= 64 {
  523. return None;
  524. }
  525. ret += (*i as u64) << bits;
  526. bits += big_digit::BITS;
  527. }
  528. Some(ret)
  529. }
  530. #[inline]
  531. fn to_f32(&self) -> Option<f32> {
  532. let mantissa = high_bits_to_u64(self);
  533. let exponent = self.bits() - fls(mantissa);
  534. if exponent > f32::MAX_EXP as usize {
  535. None
  536. } else {
  537. let ret = (mantissa as f32) * 2.0f32.powi(exponent as i32);
  538. if ret.is_infinite() {
  539. None
  540. } else {
  541. Some(ret)
  542. }
  543. }
  544. }
  545. #[inline]
  546. fn to_f64(&self) -> Option<f64> {
  547. let mantissa = high_bits_to_u64(self);
  548. let exponent = self.bits() - fls(mantissa);
  549. if exponent > f64::MAX_EXP as usize {
  550. None
  551. } else {
  552. let ret = (mantissa as f64) * 2.0f64.powi(exponent as i32);
  553. if ret.is_infinite() {
  554. None
  555. } else {
  556. Some(ret)
  557. }
  558. }
  559. }
  560. }
  561. impl FromPrimitive for BigUint {
  562. #[inline]
  563. fn from_i64(n: i64) -> Option<BigUint> {
  564. if n >= 0 {
  565. Some(BigUint::from(n as u64))
  566. } else {
  567. None
  568. }
  569. }
  570. #[inline]
  571. fn from_u64(n: u64) -> Option<BigUint> {
  572. Some(BigUint::from(n))
  573. }
  574. #[inline]
  575. fn from_f64(mut n: f64) -> Option<BigUint> {
  576. // handle NAN, INFINITY, NEG_INFINITY
  577. if !n.is_finite() {
  578. return None;
  579. }
  580. // match the rounding of casting from float to int
  581. n = n.trunc();
  582. // handle 0.x, -0.x
  583. if n.is_zero() {
  584. return Some(BigUint::zero());
  585. }
  586. let (mantissa, exponent, sign) = Float::integer_decode(n);
  587. if sign == -1 {
  588. return None;
  589. }
  590. let mut ret = BigUint::from(mantissa);
  591. if exponent > 0 {
  592. ret = ret << exponent as usize;
  593. } else if exponent < 0 {
  594. ret = ret >> (-exponent) as usize;
  595. }
  596. Some(ret)
  597. }
  598. }
  599. impl From<u64> for BigUint {
  600. #[inline]
  601. fn from(mut n: u64) -> Self {
  602. let mut ret: BigUint = Zero::zero();
  603. while n != 0 {
  604. ret.data.push(n as BigDigit);
  605. // don't overflow if BITS is 64:
  606. n = (n >> 1) >> (big_digit::BITS - 1);
  607. }
  608. ret
  609. }
  610. }
  611. macro_rules! impl_biguint_from_uint {
  612. ($T:ty) => {
  613. impl From<$T> for BigUint {
  614. #[inline]
  615. fn from(n: $T) -> Self {
  616. BigUint::from(n as u64)
  617. }
  618. }
  619. }
  620. }
  621. impl_biguint_from_uint!(u8);
  622. impl_biguint_from_uint!(u16);
  623. impl_biguint_from_uint!(u32);
  624. impl_biguint_from_uint!(usize);
  625. /// A generic trait for converting a value to a `BigUint`.
  626. pub trait ToBigUint {
  627. /// Converts the value of `self` to a `BigUint`.
  628. fn to_biguint(&self) -> Option<BigUint>;
  629. }
  630. impl ToBigUint for BigUint {
  631. #[inline]
  632. fn to_biguint(&self) -> Option<BigUint> {
  633. Some(self.clone())
  634. }
  635. }
  636. macro_rules! impl_to_biguint {
  637. ($T:ty, $from_ty:path) => {
  638. impl ToBigUint for $T {
  639. #[inline]
  640. fn to_biguint(&self) -> Option<BigUint> {
  641. $from_ty(*self)
  642. }
  643. }
  644. }
  645. }
  646. impl_to_biguint!(isize, FromPrimitive::from_isize);
  647. impl_to_biguint!(i8, FromPrimitive::from_i8);
  648. impl_to_biguint!(i16, FromPrimitive::from_i16);
  649. impl_to_biguint!(i32, FromPrimitive::from_i32);
  650. impl_to_biguint!(i64, FromPrimitive::from_i64);
  651. impl_to_biguint!(usize, FromPrimitive::from_usize);
  652. impl_to_biguint!(u8, FromPrimitive::from_u8);
  653. impl_to_biguint!(u16, FromPrimitive::from_u16);
  654. impl_to_biguint!(u32, FromPrimitive::from_u32);
  655. impl_to_biguint!(u64, FromPrimitive::from_u64);
  656. impl_to_biguint!(f32, FromPrimitive::from_f32);
  657. impl_to_biguint!(f64, FromPrimitive::from_f64);
  658. // Extract bitwise digits that evenly divide BigDigit
  659. fn to_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec<u8> {
  660. debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits == 0);
  661. let last_i = u.data.len() - 1;
  662. let mask: BigDigit = (1 << bits) - 1;
  663. let digits_per_big_digit = big_digit::BITS / bits;
  664. let digits = (u.bits() + bits - 1) / bits;
  665. let mut res = Vec::with_capacity(digits);
  666. for mut r in u.data[..last_i].iter().cloned() {
  667. for _ in 0..digits_per_big_digit {
  668. res.push((r & mask) as u8);
  669. r >>= bits;
  670. }
  671. }
  672. let mut r = u.data[last_i];
  673. while r != 0 {
  674. res.push((r & mask) as u8);
  675. r >>= bits;
  676. }
  677. res
  678. }
  679. // Extract bitwise digits that don't evenly divide BigDigit
  680. fn to_inexact_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec<u8> {
  681. debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits != 0);
  682. let mask: BigDigit = (1 << bits) - 1;
  683. let digits = (u.bits() + bits - 1) / bits;
  684. let mut res = Vec::with_capacity(digits);
  685. let mut r = 0;
  686. let mut rbits = 0;
  687. for c in &u.data {
  688. r |= *c << rbits;
  689. rbits += big_digit::BITS;
  690. while rbits >= bits {
  691. res.push((r & mask) as u8);
  692. r >>= bits;
  693. // r had more bits than it could fit - grab the bits we lost
  694. if rbits > big_digit::BITS {
  695. r = *c >> (big_digit::BITS - (rbits - bits));
  696. }
  697. rbits -= bits;
  698. }
  699. }
  700. if rbits != 0 {
  701. res.push(r as u8);
  702. }
  703. while let Some(&0) = res.last() {
  704. res.pop();
  705. }
  706. res
  707. }
  708. // Extract little-endian radix digits
  709. #[inline(always)] // forced inline to get const-prop for radix=10
  710. fn to_radix_digits_le(u: &BigUint, radix: u32) -> Vec<u8> {
  711. debug_assert!(!u.is_zero() && !radix.is_power_of_two());
  712. // Estimate how big the result will be, so we can pre-allocate it.
  713. let radix_digits = ((u.bits() as f64) / (radix as f64).log2()).ceil();
  714. let mut res = Vec::with_capacity(radix_digits as usize);
  715. let mut digits = u.clone();
  716. let (base, power) = get_radix_base(radix);
  717. let radix = radix as BigDigit;
  718. while digits.data.len() > 1 {
  719. let (q, mut r) = div_rem_digit(digits, base);
  720. for _ in 0..power {
  721. res.push((r % radix) as u8);
  722. r /= radix;
  723. }
  724. digits = q;
  725. }
  726. let mut r = digits.data[0];
  727. while r != 0 {
  728. res.push((r % radix) as u8);
  729. r /= radix;
  730. }
  731. res
  732. }
  733. pub fn to_str_radix_reversed(u: &BigUint, radix: u32) -> Vec<u8> {
  734. assert!(2 <= radix && radix <= 36, "The radix must be within 2...36");
  735. if u.is_zero() {
  736. return vec![b'0'];
  737. }
  738. let mut res = if radix.is_power_of_two() {
  739. // Powers of two can use bitwise masks and shifting instead of division
  740. let bits = ilog2(radix);
  741. if big_digit::BITS % bits == 0 {
  742. to_bitwise_digits_le(u, bits)
  743. } else {
  744. to_inexact_bitwise_digits_le(u, bits)
  745. }
  746. } else if radix == 10 {
  747. // 10 is so common that it's worth separating out for const-propagation.
  748. // Optimizers can often turn constant division into a faster multiplication.
  749. to_radix_digits_le(u, 10)
  750. } else {
  751. to_radix_digits_le(u, radix)
  752. };
  753. // Now convert everything to ASCII digits.
  754. for r in &mut res {
  755. debug_assert!((*r as u32) < radix);
  756. if *r < 10 {
  757. *r += b'0';
  758. } else {
  759. *r += b'a' - 10;
  760. }
  761. }
  762. res
  763. }
  764. impl BigUint {
  765. /// Creates and initializes a `BigUint`.
  766. ///
  767. /// The digits are in little-endian base 2^32.
  768. #[inline]
  769. pub fn new(digits: Vec<BigDigit>) -> BigUint {
  770. BigUint { data: digits }.normalize()
  771. }
  772. /// Creates and initializes a `BigUint`.
  773. ///
  774. /// The digits are in little-endian base 2^32.
  775. #[inline]
  776. pub fn from_slice(slice: &[BigDigit]) -> BigUint {
  777. BigUint::new(slice.to_vec())
  778. }
  779. /// Creates and initializes a `BigUint`.
  780. ///
  781. /// The bytes are in big-endian byte order.
  782. ///
  783. /// # Examples
  784. ///
  785. /// ```
  786. /// use num_bigint::BigUint;
  787. ///
  788. /// assert_eq!(BigUint::from_bytes_be(b"A"),
  789. /// BigUint::parse_bytes(b"65", 10).unwrap());
  790. /// assert_eq!(BigUint::from_bytes_be(b"AA"),
  791. /// BigUint::parse_bytes(b"16705", 10).unwrap());
  792. /// assert_eq!(BigUint::from_bytes_be(b"AB"),
  793. /// BigUint::parse_bytes(b"16706", 10).unwrap());
  794. /// assert_eq!(BigUint::from_bytes_be(b"Hello world!"),
  795. /// BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
  796. /// ```
  797. #[inline]
  798. pub fn from_bytes_be(bytes: &[u8]) -> BigUint {
  799. if bytes.is_empty() {
  800. Zero::zero()
  801. } else {
  802. let mut v = bytes.to_vec();
  803. v.reverse();
  804. BigUint::from_bytes_le(&*v)
  805. }
  806. }
  807. /// Creates and initializes a `BigUint`.
  808. ///
  809. /// The bytes are in little-endian byte order.
  810. #[inline]
  811. pub fn from_bytes_le(bytes: &[u8]) -> BigUint {
  812. if bytes.is_empty() {
  813. Zero::zero()
  814. } else {
  815. from_bitwise_digits_le(bytes, 8)
  816. }
  817. }
  818. /// Returns the byte representation of the `BigUint` in little-endian byte order.
  819. ///
  820. /// # Examples
  821. ///
  822. /// ```
  823. /// use num_bigint::BigUint;
  824. ///
  825. /// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
  826. /// assert_eq!(i.to_bytes_le(), vec![101, 4]);
  827. /// ```
  828. #[inline]
  829. pub fn to_bytes_le(&self) -> Vec<u8> {
  830. if self.is_zero() {
  831. vec![0]
  832. } else {
  833. to_bitwise_digits_le(self, 8)
  834. }
  835. }
  836. /// Returns the byte representation of the `BigUint` in big-endian byte order.
  837. ///
  838. /// # Examples
  839. ///
  840. /// ```
  841. /// use num_bigint::BigUint;
  842. ///
  843. /// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
  844. /// assert_eq!(i.to_bytes_be(), vec![4, 101]);
  845. /// ```
  846. #[inline]
  847. pub fn to_bytes_be(&self) -> Vec<u8> {
  848. let mut v = self.to_bytes_le();
  849. v.reverse();
  850. v
  851. }
  852. /// Returns the integer formatted as a string in the given radix.
  853. /// `radix` must be in the range `[2, 36]`.
  854. ///
  855. /// # Examples
  856. ///
  857. /// ```
  858. /// use num_bigint::BigUint;
  859. ///
  860. /// let i = BigUint::parse_bytes(b"ff", 16).unwrap();
  861. /// assert_eq!(i.to_str_radix(16), "ff");
  862. /// ```
  863. #[inline]
  864. pub fn to_str_radix(&self, radix: u32) -> String {
  865. let mut v = to_str_radix_reversed(self, radix);
  866. v.reverse();
  867. unsafe { String::from_utf8_unchecked(v) }
  868. }
  869. /// Creates and initializes a `BigUint`.
  870. ///
  871. /// # Examples
  872. ///
  873. /// ```
  874. /// use num_bigint::{BigUint, ToBigUint};
  875. ///
  876. /// assert_eq!(BigUint::parse_bytes(b"1234", 10), ToBigUint::to_biguint(&1234));
  877. /// assert_eq!(BigUint::parse_bytes(b"ABCD", 16), ToBigUint::to_biguint(&0xABCD));
  878. /// assert_eq!(BigUint::parse_bytes(b"G", 16), None);
  879. /// ```
  880. #[inline]
  881. pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigUint> {
  882. str::from_utf8(buf).ok().and_then(|s| BigUint::from_str_radix(s, radix).ok())
  883. }
  884. /// Determines the fewest bits necessary to express the `BigUint`.
  885. #[inline]
  886. pub fn bits(&self) -> usize {
  887. if self.is_zero() {
  888. return 0;
  889. }
  890. let zeros = self.data.last().unwrap().leading_zeros();
  891. return self.data.len() * big_digit::BITS - zeros as usize;
  892. }
  893. /// Strips off trailing zero bigdigits - comparisons require the last element in the vector to
  894. /// be nonzero.
  895. #[inline]
  896. fn normalize(mut self) -> BigUint {
  897. while let Some(&0) = self.data.last() {
  898. self.data.pop();
  899. }
  900. self
  901. }
  902. }
  903. #[cfg(feature = "serde")]
  904. impl serde::Serialize for BigUint {
  905. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
  906. where S: serde::Serializer
  907. {
  908. self.data.serialize(serializer)
  909. }
  910. }
  911. #[cfg(feature = "serde")]
  912. impl serde::Deserialize for BigUint {
  913. fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
  914. where D: serde::Deserializer
  915. {
  916. let data = try!(Vec::deserialize(deserializer));
  917. Ok(BigUint { data: data })
  918. }
  919. }
  920. /// Returns the greatest power of the radix <= big_digit::BASE
  921. #[inline]
  922. fn get_radix_base(radix: u32) -> (BigDigit, usize) {
  923. debug_assert!(2 <= radix && radix <= 36, "The radix must be within 2...36");
  924. debug_assert!(!radix.is_power_of_two());
  925. // To generate this table:
  926. // for radix in 2u64..37 {
  927. // let mut power = big_digit::BITS / fls(radix as u64);
  928. // let mut base = radix.pow(power as u32);
  929. //
  930. // while let Some(b) = base.checked_mul(radix) {
  931. // if b > big_digit::MAX {
  932. // break;
  933. // }
  934. // base = b;
  935. // power += 1;
  936. // }
  937. //
  938. // println!("({:10}, {:2}), // {:2}", base, power, radix);
  939. // }
  940. match big_digit::BITS {
  941. 32 => {
  942. const BASES: [(u32, usize); 37] = [(0, 0), (0, 0),
  943. (0, 0), // 2
  944. (3486784401, 20),// 3
  945. (0, 0), // 4
  946. (1220703125, 13),// 5
  947. (2176782336, 12),// 6
  948. (1977326743, 11),// 7
  949. (0, 0), // 8
  950. (3486784401, 10),// 9
  951. (1000000000, 9), // 10
  952. (2357947691, 9), // 11
  953. (429981696, 8), // 12
  954. (815730721, 8), // 13
  955. (1475789056, 8), // 14
  956. (2562890625, 8), // 15
  957. (0, 0), // 16
  958. (410338673, 7), // 17
  959. (612220032, 7), // 18
  960. (893871739, 7), // 19
  961. (1280000000, 7), // 20
  962. (1801088541, 7), // 21
  963. (2494357888, 7), // 22
  964. (3404825447, 7), // 23
  965. (191102976, 6), // 24
  966. (244140625, 6), // 25
  967. (308915776, 6), // 26
  968. (387420489, 6), // 27
  969. (481890304, 6), // 28
  970. (594823321, 6), // 29
  971. (729000000, 6), // 30
  972. (887503681, 6), // 31
  973. (0, 0), // 32
  974. (1291467969, 6), // 33
  975. (1544804416, 6), // 34
  976. (1838265625, 6), // 35
  977. (2176782336, 6) // 36
  978. ];
  979. let (base, power) = BASES[radix as usize];
  980. (base as BigDigit, power)
  981. }
  982. 64 => {
  983. const BASES: [(u64, usize); 37] = [(0, 0), (0, 0),
  984. (9223372036854775808, 63), // 2
  985. (12157665459056928801, 40), // 3
  986. (4611686018427387904, 31), // 4
  987. (7450580596923828125, 27), // 5
  988. (4738381338321616896, 24), // 6
  989. (3909821048582988049, 22), // 7
  990. (9223372036854775808, 21), // 8
  991. (12157665459056928801, 20), // 9
  992. (10000000000000000000, 19), // 10
  993. (5559917313492231481, 18), // 11
  994. (2218611106740436992, 17), // 12
  995. (8650415919381337933, 17), // 13
  996. (2177953337809371136, 16), // 14
  997. (6568408355712890625, 16), // 15
  998. (1152921504606846976, 15), // 16
  999. (2862423051509815793, 15), // 17
  1000. (6746640616477458432, 15), // 18
  1001. (15181127029874798299, 15), // 19
  1002. (1638400000000000000, 14), // 20
  1003. (3243919932521508681, 14), // 21
  1004. (6221821273427820544, 14), // 22
  1005. (11592836324538749809, 14), // 23
  1006. (876488338465357824, 13), // 24
  1007. (1490116119384765625, 13), // 25
  1008. (2481152873203736576, 13), // 26
  1009. (4052555153018976267, 13), // 27
  1010. (6502111422497947648, 13), // 28
  1011. (10260628712958602189, 13), // 29
  1012. (15943230000000000000, 13), // 30
  1013. (787662783788549761, 12), // 31
  1014. (1152921504606846976, 12), // 32
  1015. (1667889514952984961, 12), // 33
  1016. (2386420683693101056, 12), // 34
  1017. (3379220508056640625, 12), // 35
  1018. (4738381338321616896, 12), // 36
  1019. ];
  1020. let (base, power) = BASES[radix as usize];
  1021. (base as BigDigit, power)
  1022. }
  1023. _ => panic!("Invalid bigdigit size")
  1024. }
  1025. }