bigint.rs 36 KB

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