biguint.rs 33 KB

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