bigint.rs 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884
  1. // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
  2. // file at the top-level directory of this distribution and at
  3. // http://rust-lang.org/COPYRIGHT.
  4. //
  5. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  6. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  7. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  8. // option. This file may not be copied, modified, or distributed
  9. // except according to those terms.
  10. //! A Big integer (signed version: `BigInt`, unsigned version: `BigUint`).
  11. //!
  12. //! A `BigUint` is represented as a vector of `BigDigit`s.
  13. //! A `BigInt` is a combination of `BigUint` and `Sign`.
  14. //!
  15. //! Common numerical operations are overloaded, so we can treat them
  16. //! the same way we treat other numbers.
  17. //!
  18. //! ## Example
  19. //!
  20. //! ```rust
  21. //! use num::{BigUint, Zero, One};
  22. //! use std::mem::replace;
  23. //!
  24. //! // Calculate large fibonacci numbers.
  25. //! fn fib(n: usize) -> BigUint {
  26. //! let mut f0: BigUint = Zero::zero();
  27. //! let mut f1: BigUint = One::one();
  28. //! for _ in 0..n {
  29. //! let f2 = f0 + &f1;
  30. //! // This is a low cost way of swapping f0 with f1 and f1 with f2.
  31. //! f0 = replace(&mut f1, f2);
  32. //! }
  33. //! f0
  34. //! }
  35. //!
  36. //! // This is a very large number.
  37. //! println!("fib(1000) = {}", fib(1000));
  38. //! ```
  39. //!
  40. //! It's easy to generate large random numbers:
  41. //!
  42. //! ```rust
  43. //! extern crate rand;
  44. //! extern crate num;
  45. //!
  46. //! # #[cfg(feature = "rand")]
  47. //! # fn main() {
  48. //! use num::bigint::{ToBigInt, RandBigInt};
  49. //!
  50. //! let mut rng = rand::thread_rng();
  51. //! let a = rng.gen_bigint(1000);
  52. //!
  53. //! let low = -10000.to_bigint().unwrap();
  54. //! let high = 10000.to_bigint().unwrap();
  55. //! let b = rng.gen_bigint_range(&low, &high);
  56. //!
  57. //! // Probably an even larger number.
  58. //! println!("{}", a * b);
  59. //! # }
  60. //!
  61. //! # #[cfg(not(feature = "rand"))]
  62. //! # fn main() {
  63. //! # }
  64. //! ```
  65. use Integer;
  66. use std::default::Default;
  67. use std::error::Error;
  68. use std::iter::repeat;
  69. use std::num::ParseIntError;
  70. use std::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Rem, Shl, Shr, Sub};
  71. use std::str::{self, FromStr};
  72. use std::fmt;
  73. use std::cmp::Ordering::{self, Less, Greater, Equal};
  74. use std::{f32, f64};
  75. use std::{u8, i64, u64};
  76. use std::ascii::AsciiExt;
  77. // Some of the tests of non-RNG-based functionality are randomized using the
  78. // RNG-based functionality, so the RNG-based functionality needs to be enabled
  79. // for tests.
  80. #[cfg(any(feature = "rand", test))]
  81. use rand::Rng;
  82. use traits::{ToPrimitive, FromPrimitive};
  83. use traits::Float;
  84. use {Num, Unsigned, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, Signed, Zero, One};
  85. use self::Sign::{Minus, NoSign, Plus};
  86. /// A `BigDigit` is a `BigUint`'s composing element.
  87. pub type BigDigit = u32;
  88. /// A `DoubleBigDigit` is the internal type used to do the computations. Its
  89. /// size is the double of the size of `BigDigit`.
  90. pub type DoubleBigDigit = u64;
  91. pub const ZERO_BIG_DIGIT: BigDigit = 0;
  92. #[allow(non_snake_case)]
  93. pub mod big_digit {
  94. use super::BigDigit;
  95. use super::DoubleBigDigit;
  96. // `DoubleBigDigit` size dependent
  97. pub const BITS: usize = 32;
  98. pub const BASE: DoubleBigDigit = 1 << BITS;
  99. const LO_MASK: DoubleBigDigit = (-1i32 as DoubleBigDigit) >> BITS;
  100. #[inline]
  101. fn get_hi(n: DoubleBigDigit) -> BigDigit { (n >> BITS) as BigDigit }
  102. #[inline]
  103. fn get_lo(n: DoubleBigDigit) -> BigDigit { (n & LO_MASK) as BigDigit }
  104. /// Split one `DoubleBigDigit` into two `BigDigit`s.
  105. #[inline]
  106. pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) {
  107. (get_hi(n), get_lo(n))
  108. }
  109. /// Join two `BigDigit`s into one `DoubleBigDigit`
  110. #[inline]
  111. pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit {
  112. (lo as DoubleBigDigit) | ((hi as DoubleBigDigit) << BITS)
  113. }
  114. }
  115. /*
  116. * Generic functions for add/subtract/multiply with carry/borrow:
  117. */
  118. // Add with carry:
  119. #[inline]
  120. fn adc(a: BigDigit, b: BigDigit, carry: &mut BigDigit) -> BigDigit {
  121. let (hi, lo) = big_digit::from_doublebigdigit(
  122. (a as DoubleBigDigit) +
  123. (b as DoubleBigDigit) +
  124. (*carry as DoubleBigDigit));
  125. *carry = hi;
  126. lo
  127. }
  128. // Subtract with borrow:
  129. #[inline]
  130. fn sbb(a: BigDigit, b: BigDigit, borrow: &mut BigDigit) -> BigDigit {
  131. let (hi, lo) = big_digit::from_doublebigdigit(
  132. big_digit::BASE
  133. + (a as DoubleBigDigit)
  134. - (b as DoubleBigDigit)
  135. - (*borrow as DoubleBigDigit));
  136. /*
  137. hi * (base) + lo == 1*(base) + ai - bi - borrow
  138. => ai - bi - borrow < 0 <=> hi == 0
  139. */
  140. *borrow = if hi == 0 { 1 } else { 0 };
  141. lo
  142. }
  143. #[inline]
  144. fn mac_with_carry(a: BigDigit, b: BigDigit, c: BigDigit, carry: &mut BigDigit) -> BigDigit {
  145. let (hi, lo) = big_digit::from_doublebigdigit(
  146. (a as DoubleBigDigit) +
  147. (b as DoubleBigDigit) * (c as DoubleBigDigit) +
  148. (*carry as DoubleBigDigit));
  149. *carry = hi;
  150. lo
  151. }
  152. /// Divide a two digit numerator by a one digit divisor, returns quotient and remainder:
  153. ///
  154. /// Note: the caller must ensure that both the quotient and remainder will fit into a single digit.
  155. /// This is _not_ true for an arbitrary numerator/denominator.
  156. ///
  157. /// (This function also matches what the x86 divide instruction does).
  158. #[inline]
  159. fn div_wide(hi: BigDigit, lo: BigDigit, divisor: BigDigit) -> (BigDigit, BigDigit) {
  160. debug_assert!(hi < divisor);
  161. let lhs = big_digit::to_doublebigdigit(hi, lo);
  162. let rhs = divisor as DoubleBigDigit;
  163. ((lhs / rhs) as BigDigit, (lhs % rhs) as BigDigit)
  164. }
  165. /// A big unsigned integer type.
  166. ///
  167. /// A `BigUint`-typed value `BigUint { data: vec!(a, b, c) }` represents a number
  168. /// `(a + b * big_digit::BASE + c * big_digit::BASE^2)`.
  169. #[derive(Clone, Debug, Hash)]
  170. #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
  171. pub struct BigUint {
  172. data: Vec<BigDigit>
  173. }
  174. impl PartialEq for BigUint {
  175. #[inline]
  176. fn eq(&self, other: &BigUint) -> bool {
  177. match self.cmp(other) { Equal => true, _ => false }
  178. }
  179. }
  180. impl Eq for BigUint {}
  181. impl PartialOrd for BigUint {
  182. #[inline]
  183. fn partial_cmp(&self, other: &BigUint) -> Option<Ordering> {
  184. Some(self.cmp(other))
  185. }
  186. }
  187. fn cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering {
  188. debug_assert!(a.last() != Some(&0));
  189. debug_assert!(b.last() != Some(&0));
  190. let (a_len, b_len) = (a.len(), b.len());
  191. if a_len < b_len { return Less; }
  192. if a_len > b_len { return Greater; }
  193. for (&ai, &bi) in a.iter().rev().zip(b.iter().rev()) {
  194. if ai < bi { return Less; }
  195. if ai > bi { return Greater; }
  196. }
  197. return Equal;
  198. }
  199. impl Ord for BigUint {
  200. #[inline]
  201. fn cmp(&self, other: &BigUint) -> Ordering {
  202. cmp_slice(&self.data[..], &other.data[..])
  203. }
  204. }
  205. impl Default for BigUint {
  206. #[inline]
  207. fn default() -> BigUint { Zero::zero() }
  208. }
  209. impl fmt::Display for BigUint {
  210. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  211. f.pad_integral(true, "", &self.to_str_radix(10))
  212. }
  213. }
  214. impl fmt::LowerHex for BigUint {
  215. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  216. f.pad_integral(true, "0x", &self.to_str_radix(16))
  217. }
  218. }
  219. impl fmt::UpperHex for BigUint {
  220. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  221. f.pad_integral(true, "0x", &self.to_str_radix(16).to_ascii_uppercase())
  222. }
  223. }
  224. impl fmt::Binary for BigUint {
  225. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  226. f.pad_integral(true, "0b", &self.to_str_radix(2))
  227. }
  228. }
  229. impl fmt::Octal for BigUint {
  230. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  231. f.pad_integral(true, "0o", &self.to_str_radix(8))
  232. }
  233. }
  234. impl FromStr for BigUint {
  235. type Err = ParseBigIntError;
  236. #[inline]
  237. fn from_str(s: &str) -> Result<BigUint, ParseBigIntError> {
  238. BigUint::from_str_radix(s, 10)
  239. }
  240. }
  241. // Read bitwise digits that evenly divide BigDigit
  242. fn from_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint {
  243. debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits == 0);
  244. debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits)));
  245. let digits_per_big_digit = big_digit::BITS / bits;
  246. let data = v.chunks(digits_per_big_digit).map(|chunk| {
  247. chunk.iter().rev().fold(0u32, |acc, &c| (acc << bits) | c as BigDigit)
  248. }).collect();
  249. BigUint::new(data)
  250. }
  251. // Read bitwise digits that don't evenly divide BigDigit
  252. fn from_inexact_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint {
  253. debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits != 0);
  254. debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits)));
  255. let big_digits = (v.len() * bits + big_digit::BITS - 1) / big_digit::BITS;
  256. let mut data = Vec::with_capacity(big_digits);
  257. let mut d = 0;
  258. let mut dbits = 0;
  259. for &c in v {
  260. d |= (c as DoubleBigDigit) << dbits;
  261. dbits += bits;
  262. if dbits >= big_digit::BITS {
  263. let (hi, lo) = big_digit::from_doublebigdigit(d);
  264. data.push(lo);
  265. d = hi as DoubleBigDigit;
  266. dbits -= big_digit::BITS;
  267. }
  268. }
  269. if dbits > 0 {
  270. debug_assert!(dbits < big_digit::BITS);
  271. data.push(d as BigDigit);
  272. }
  273. BigUint::new(data)
  274. }
  275. // Read little-endian radix digits
  276. fn from_radix_digits_be(v: &[u8], radix: u32) -> BigUint {
  277. debug_assert!(!v.is_empty() && !radix.is_power_of_two());
  278. debug_assert!(v.iter().all(|&c| (c as u32) < radix));
  279. // Estimate how big the result will be, so we can pre-allocate it.
  280. let bits = (radix as f64).log2() * v.len() as f64;
  281. let big_digits = (bits / big_digit::BITS as f64).ceil();
  282. let mut data = Vec::with_capacity(big_digits as usize);
  283. let (base, power) = get_radix_base(radix);
  284. debug_assert!(base < (1 << 32));
  285. let base = base as BigDigit;
  286. let r = v.len() % power;
  287. let i = if r == 0 { power } else { r };
  288. let (head, tail) = v.split_at(i);
  289. let first = head.iter().fold(0, |acc, &d| acc * radix + d as BigDigit);
  290. data.push(first);
  291. debug_assert!(tail.len() % power == 0);
  292. for chunk in tail.chunks(power) {
  293. if data.last() != Some(&0) {
  294. data.push(0);
  295. }
  296. let mut carry = 0;
  297. for d in data.iter_mut() {
  298. *d = mac_with_carry(0, *d, base, &mut carry);
  299. }
  300. debug_assert!(carry == 0);
  301. let n = chunk.iter().fold(0, |acc, &d| acc * radix + d as BigDigit);
  302. add2(&mut data, &[n]);
  303. }
  304. BigUint::new(data)
  305. }
  306. impl Num for BigUint {
  307. type FromStrRadixErr = ParseBigIntError;
  308. /// Creates and initializes a `BigUint`.
  309. fn from_str_radix(s: &str, radix: u32) -> Result<BigUint, ParseBigIntError> {
  310. assert!(2 <= radix && radix <= 36, "The radix must be within 2...36");
  311. if s.is_empty() {
  312. // create ParseIntError::Empty
  313. let e = u64::from_str_radix(s, radix).unwrap_err();
  314. return Err(e.into());
  315. }
  316. // First normalize all characters to plain digit values
  317. let mut v = Vec::with_capacity(s.len());
  318. for b in s.bytes() {
  319. let d = match b {
  320. b'0' ... b'9' => b - b'0',
  321. b'a' ... b'z' => b - b'a' + 10,
  322. b'A' ... b'Z' => b - b'A' + 10,
  323. _ => u8::MAX,
  324. };
  325. if d < radix as u8 {
  326. v.push(d);
  327. } else {
  328. // create ParseIntError::InvalidDigit
  329. let e = u64::from_str_radix(&s[v.len()..], radix).unwrap_err();
  330. return Err(e.into());
  331. }
  332. }
  333. let res = if radix.is_power_of_two() {
  334. // Powers of two can use bitwise masks and shifting instead of multiplication
  335. let bits = radix.trailing_zeros() as usize;
  336. v.reverse();
  337. if big_digit::BITS % bits == 0 {
  338. from_bitwise_digits_le(&v, bits)
  339. } else {
  340. from_inexact_bitwise_digits_le(&v, bits)
  341. }
  342. } else {
  343. from_radix_digits_be(&v, radix)
  344. };
  345. Ok(res)
  346. }
  347. }
  348. macro_rules! forward_val_val_binop {
  349. (impl $imp:ident for $res:ty, $method:ident) => {
  350. impl $imp<$res> for $res {
  351. type Output = $res;
  352. #[inline]
  353. fn $method(self, other: $res) -> $res {
  354. // forward to val-ref
  355. $imp::$method(self, &other)
  356. }
  357. }
  358. }
  359. }
  360. macro_rules! forward_val_val_binop_commutative {
  361. (impl $imp:ident for $res:ty, $method:ident) => {
  362. impl $imp<$res> for $res {
  363. type Output = $res;
  364. #[inline]
  365. fn $method(self, other: $res) -> $res {
  366. // forward to val-ref, with the larger capacity as val
  367. if self.data.capacity() >= other.data.capacity() {
  368. $imp::$method(self, &other)
  369. } else {
  370. $imp::$method(other, &self)
  371. }
  372. }
  373. }
  374. }
  375. }
  376. macro_rules! forward_ref_val_binop {
  377. (impl $imp:ident for $res:ty, $method:ident) => {
  378. impl<'a> $imp<$res> for &'a $res {
  379. type Output = $res;
  380. #[inline]
  381. fn $method(self, other: $res) -> $res {
  382. // forward to ref-ref
  383. $imp::$method(self, &other)
  384. }
  385. }
  386. }
  387. }
  388. macro_rules! forward_ref_val_binop_commutative {
  389. (impl $imp:ident for $res:ty, $method:ident) => {
  390. impl<'a> $imp<$res> for &'a $res {
  391. type Output = $res;
  392. #[inline]
  393. fn $method(self, other: $res) -> $res {
  394. // reverse, forward to val-ref
  395. $imp::$method(other, self)
  396. }
  397. }
  398. }
  399. }
  400. macro_rules! forward_val_ref_binop {
  401. (impl $imp:ident for $res:ty, $method:ident) => {
  402. impl<'a> $imp<&'a $res> for $res {
  403. type Output = $res;
  404. #[inline]
  405. fn $method(self, other: &$res) -> $res {
  406. // forward to ref-ref
  407. $imp::$method(&self, other)
  408. }
  409. }
  410. }
  411. }
  412. macro_rules! forward_ref_ref_binop {
  413. (impl $imp:ident for $res:ty, $method:ident) => {
  414. impl<'a, 'b> $imp<&'b $res> for &'a $res {
  415. type Output = $res;
  416. #[inline]
  417. fn $method(self, other: &$res) -> $res {
  418. // forward to val-ref
  419. $imp::$method(self.clone(), other)
  420. }
  421. }
  422. }
  423. }
  424. macro_rules! forward_ref_ref_binop_commutative {
  425. (impl $imp:ident for $res:ty, $method:ident) => {
  426. impl<'a, 'b> $imp<&'b $res> for &'a $res {
  427. type Output = $res;
  428. #[inline]
  429. fn $method(self, other: &$res) -> $res {
  430. // forward to val-ref, choosing the larger to clone
  431. if self.data.len() >= other.data.len() {
  432. $imp::$method(self.clone(), other)
  433. } else {
  434. $imp::$method(other.clone(), self)
  435. }
  436. }
  437. }
  438. }
  439. }
  440. // Forward everything to ref-ref, when reusing storage is not helpful
  441. macro_rules! forward_all_binop_to_ref_ref {
  442. (impl $imp:ident for $res:ty, $method:ident) => {
  443. forward_val_val_binop!(impl $imp for $res, $method);
  444. forward_val_ref_binop!(impl $imp for $res, $method);
  445. forward_ref_val_binop!(impl $imp for $res, $method);
  446. };
  447. }
  448. // Forward everything to val-ref, so LHS storage can be reused
  449. macro_rules! forward_all_binop_to_val_ref {
  450. (impl $imp:ident for $res:ty, $method:ident) => {
  451. forward_val_val_binop!(impl $imp for $res, $method);
  452. forward_ref_val_binop!(impl $imp for $res, $method);
  453. forward_ref_ref_binop!(impl $imp for $res, $method);
  454. };
  455. }
  456. // Forward everything to val-ref, commutatively, so either LHS or RHS storage can be reused
  457. macro_rules! forward_all_binop_to_val_ref_commutative {
  458. (impl $imp:ident for $res:ty, $method:ident) => {
  459. forward_val_val_binop_commutative!(impl $imp for $res, $method);
  460. forward_ref_val_binop_commutative!(impl $imp for $res, $method);
  461. forward_ref_ref_binop_commutative!(impl $imp for $res, $method);
  462. };
  463. }
  464. forward_all_binop_to_val_ref_commutative!(impl BitAnd for BigUint, bitand);
  465. impl<'a> BitAnd<&'a BigUint> for BigUint {
  466. type Output = BigUint;
  467. #[inline]
  468. fn bitand(self, other: &BigUint) -> BigUint {
  469. let mut data = self.data;
  470. for (ai, &bi) in data.iter_mut().zip(other.data.iter()) {
  471. *ai &= bi;
  472. }
  473. data.truncate(other.data.len());
  474. BigUint::new(data)
  475. }
  476. }
  477. forward_all_binop_to_val_ref_commutative!(impl BitOr for BigUint, bitor);
  478. impl<'a> BitOr<&'a BigUint> for BigUint {
  479. type Output = BigUint;
  480. fn bitor(self, other: &BigUint) -> BigUint {
  481. let mut data = self.data;
  482. for (ai, &bi) in data.iter_mut().zip(other.data.iter()) {
  483. *ai |= bi;
  484. }
  485. if other.data.len() > data.len() {
  486. let extra = &other.data[data.len()..];
  487. data.extend(extra.iter().cloned());
  488. }
  489. BigUint::new(data)
  490. }
  491. }
  492. forward_all_binop_to_val_ref_commutative!(impl BitXor for BigUint, bitxor);
  493. impl<'a> BitXor<&'a BigUint> for BigUint {
  494. type Output = BigUint;
  495. fn bitxor(self, other: &BigUint) -> BigUint {
  496. let mut data = self.data;
  497. for (ai, &bi) in data.iter_mut().zip(other.data.iter()) {
  498. *ai ^= bi;
  499. }
  500. if other.data.len() > data.len() {
  501. let extra = &other.data[data.len()..];
  502. data.extend(extra.iter().cloned());
  503. }
  504. BigUint::new(data)
  505. }
  506. }
  507. impl Shl<usize> for BigUint {
  508. type Output = BigUint;
  509. #[inline]
  510. fn shl(self, rhs: usize) -> BigUint { (&self) << rhs }
  511. }
  512. impl<'a> Shl<usize> for &'a BigUint {
  513. type Output = BigUint;
  514. #[inline]
  515. fn shl(self, rhs: usize) -> BigUint {
  516. let n_unit = rhs / big_digit::BITS;
  517. let n_bits = rhs % big_digit::BITS;
  518. self.shl_unit(n_unit).shl_bits(n_bits)
  519. }
  520. }
  521. impl Shr<usize> for BigUint {
  522. type Output = BigUint;
  523. #[inline]
  524. fn shr(self, rhs: usize) -> BigUint { (&self) >> rhs }
  525. }
  526. impl<'a> Shr<usize> for &'a BigUint {
  527. type Output = BigUint;
  528. #[inline]
  529. fn shr(self, rhs: usize) -> BigUint {
  530. let n_unit = rhs / big_digit::BITS;
  531. let n_bits = rhs % big_digit::BITS;
  532. self.shr_unit(n_unit).shr_bits(n_bits)
  533. }
  534. }
  535. impl Zero for BigUint {
  536. #[inline]
  537. fn zero() -> BigUint { BigUint::new(Vec::new()) }
  538. #[inline]
  539. fn is_zero(&self) -> bool { self.data.is_empty() }
  540. }
  541. impl One for BigUint {
  542. #[inline]
  543. fn one() -> BigUint { BigUint::new(vec!(1)) }
  544. }
  545. impl Unsigned for BigUint {}
  546. forward_all_binop_to_val_ref_commutative!(impl Add for BigUint, add);
  547. // Only for the Add impl:
  548. #[must_use]
  549. #[inline]
  550. fn __add2(a: &mut [BigDigit], b: &[BigDigit]) -> BigDigit {
  551. let mut b_iter = b.iter();
  552. let mut carry = 0;
  553. for ai in a.iter_mut() {
  554. if let Some(bi) = b_iter.next() {
  555. *ai = adc(*ai, *bi, &mut carry);
  556. } else if carry != 0 {
  557. *ai = adc(*ai, 0, &mut carry);
  558. } else {
  559. break;
  560. }
  561. }
  562. debug_assert!(b_iter.next() == None);
  563. carry
  564. }
  565. /// /Two argument addition of raw slices:
  566. /// a += b
  567. ///
  568. /// The caller _must_ ensure that a is big enough to store the result - typically this means
  569. /// resizing a to max(a.len(), b.len()) + 1, to fit a possible carry.
  570. fn add2(a: &mut [BigDigit], b: &[BigDigit]) {
  571. let carry = __add2(a, b);
  572. debug_assert!(carry == 0);
  573. }
  574. /*
  575. * We'd really prefer to avoid using add2/sub2 directly as much as possible - since they make the
  576. * caller entirely responsible for ensuring a's vector is big enough, and that the result is
  577. * normalized, they're rather error prone and verbose:
  578. *
  579. * We could implement the Add and Sub traits for BigUint + BigDigit slices, like below - this works
  580. * great, except that then it becomes the module's public interface, which we probably don't want:
  581. *
  582. * I'm keeping the code commented out, because I think this is worth revisiting:
  583. impl<'a> Add<&'a [BigDigit]> for BigUint {
  584. type Output = BigUint;
  585. fn add(mut self, other: &[BigDigit]) -> BigUint {
  586. if self.data.len() < other.len() {
  587. let extra = other.len() - self.data.len();
  588. self.data.extend(repeat(0).take(extra));
  589. }
  590. let carry = __add2(&mut self.data[..], other);
  591. if carry != 0 {
  592. self.data.push(carry);
  593. }
  594. self
  595. }
  596. }
  597. */
  598. impl<'a> Add<&'a BigUint> for BigUint {
  599. type Output = BigUint;
  600. fn add(mut self, other: &BigUint) -> BigUint {
  601. if self.data.len() < other.data.len() {
  602. let extra = other.data.len() - self.data.len();
  603. self.data.extend(repeat(0).take(extra));
  604. }
  605. let carry = __add2(&mut self.data[..], &other.data[..]);
  606. if carry != 0 {
  607. self.data.push(carry);
  608. }
  609. self
  610. }
  611. }
  612. forward_all_binop_to_val_ref!(impl Sub for BigUint, sub);
  613. fn sub2(a: &mut [BigDigit], b: &[BigDigit]) {
  614. let mut b_iter = b.iter();
  615. let mut borrow = 0;
  616. for ai in a.iter_mut() {
  617. if let Some(bi) = b_iter.next() {
  618. *ai = sbb(*ai, *bi, &mut borrow);
  619. } else if borrow != 0 {
  620. *ai = sbb(*ai, 0, &mut borrow);
  621. } else {
  622. break;
  623. }
  624. }
  625. /* note: we're _required_ to fail on underflow */
  626. assert!(borrow == 0 && b_iter.all(|x| *x == 0),
  627. "Cannot subtract b from a because b is larger than a.");
  628. }
  629. impl<'a> Sub<&'a BigUint> for BigUint {
  630. type Output = BigUint;
  631. fn sub(mut self, other: &BigUint) -> BigUint {
  632. sub2(&mut self.data[..], &other.data[..]);
  633. self.normalize()
  634. }
  635. }
  636. fn sub_sign(a: &[BigDigit], b: &[BigDigit]) -> BigInt {
  637. // Normalize:
  638. let a = &a[..a.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
  639. let b = &b[..b.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
  640. match cmp_slice(a, b) {
  641. Greater => {
  642. let mut ret = BigUint::from_slice(a);
  643. sub2(&mut ret.data[..], b);
  644. BigInt::from_biguint(Plus, ret.normalize())
  645. },
  646. Less => {
  647. let mut ret = BigUint::from_slice(b);
  648. sub2(&mut ret.data[..], a);
  649. BigInt::from_biguint(Minus, ret.normalize())
  650. },
  651. _ => Zero::zero(),
  652. }
  653. }
  654. forward_all_binop_to_ref_ref!(impl Mul for BigUint, mul);
  655. /// Three argument multiply accumulate:
  656. /// acc += b * c
  657. fn mac_digit(acc: &mut [BigDigit], b: &[BigDigit], c: BigDigit) {
  658. if c == 0 { return; }
  659. let mut b_iter = b.iter();
  660. let mut carry = 0;
  661. for ai in acc.iter_mut() {
  662. if let Some(bi) = b_iter.next() {
  663. *ai = mac_with_carry(*ai, *bi, c, &mut carry);
  664. } else if carry != 0 {
  665. *ai = mac_with_carry(*ai, 0, c, &mut carry);
  666. } else {
  667. break;
  668. }
  669. }
  670. assert!(carry == 0);
  671. }
  672. /// Three argument multiply accumulate:
  673. /// acc += b * c
  674. fn mac3(acc: &mut [BigDigit], b: &[BigDigit], c: &[BigDigit]) {
  675. let (x, y) = if b.len() < c.len() { (b, c) } else { (c, b) };
  676. /*
  677. * Karatsuba multiplication is slower than long multiplication for small x and y:
  678. */
  679. if x.len() <= 4 {
  680. for (i, xi) in x.iter().enumerate() {
  681. mac_digit(&mut acc[i..], y, *xi);
  682. }
  683. } else {
  684. /*
  685. * Karatsuba multiplication:
  686. *
  687. * The idea is that we break x and y up into two smaller numbers that each have about half
  688. * as many digits, like so (note that multiplying by b is just a shift):
  689. *
  690. * x = x0 + x1 * b
  691. * y = y0 + y1 * b
  692. *
  693. * With some algebra, we can compute x * y with three smaller products, where the inputs to
  694. * each of the smaller products have only about half as many digits as x and y:
  695. *
  696. * x * y = (x0 + x1 * b) * (y0 + y1 * b)
  697. *
  698. * x * y = x0 * y0
  699. * + x0 * y1 * b
  700. * + x1 * y0 * b
  701. * + x1 * y1 * b^2
  702. *
  703. * Let p0 = x0 * y0 and p2 = x1 * y1:
  704. *
  705. * x * y = p0
  706. * + (x0 * y1 + x1 * p0) * b
  707. * + p2 * b^2
  708. *
  709. * The real trick is that middle term:
  710. *
  711. * x0 * y1 + x1 * y0
  712. *
  713. * = x0 * y1 + x1 * y0 - p0 + p0 - p2 + p2
  714. *
  715. * = x0 * y1 + x1 * y0 - x0 * y0 - x1 * y1 + p0 + p2
  716. *
  717. * Now we complete the square:
  718. *
  719. * = -(x0 * y0 - x0 * y1 - x1 * y0 + x1 * y1) + p0 + p2
  720. *
  721. * = -((x1 - x0) * (y1 - y0)) + p0 + p2
  722. *
  723. * Let p1 = (x1 - x0) * (y1 - y0), and substitute back into our original formula:
  724. *
  725. * x * y = p0
  726. * + (p0 + p2 - p1) * b
  727. * + p2 * b^2
  728. *
  729. * Where the three intermediate products are:
  730. *
  731. * p0 = x0 * y0
  732. * p1 = (x1 - x0) * (y1 - y0)
  733. * p2 = x1 * y1
  734. *
  735. * In doing the computation, we take great care to avoid unnecessary temporary variables
  736. * (since creating a BigUint requires a heap allocation): thus, we rearrange the formula a
  737. * bit so we can use the same temporary variable for all the intermediate products:
  738. *
  739. * x * y = p2 * b^2 + p2 * b
  740. * + p0 * b + p0
  741. * - p1 * b
  742. *
  743. * The other trick we use is instead of doing explicit shifts, we slice acc at the
  744. * appropriate offset when doing the add.
  745. */
  746. /*
  747. * When x is smaller than y, it's significantly faster to pick b such that x is split in
  748. * half, not y:
  749. */
  750. let b = x.len() / 2;
  751. let (x0, x1) = x.split_at(b);
  752. let (y0, y1) = y.split_at(b);
  753. /* We reuse the same BigUint for all the intermediate multiplies: */
  754. let len = y.len() + 1;
  755. let mut p = BigUint { data: vec![0; len] };
  756. // p2 = x1 * y1
  757. mac3(&mut p.data[..], x1, y1);
  758. // Not required, but the adds go faster if we drop any unneeded 0s from the end:
  759. p = p.normalize();
  760. add2(&mut acc[b..], &p.data[..]);
  761. add2(&mut acc[b * 2..], &p.data[..]);
  762. // Zero out p before the next multiply:
  763. p.data.truncate(0);
  764. p.data.extend(repeat(0).take(len));
  765. // p0 = x0 * y0
  766. mac3(&mut p.data[..], x0, y0);
  767. p = p.normalize();
  768. add2(&mut acc[..], &p.data[..]);
  769. add2(&mut acc[b..], &p.data[..]);
  770. // p1 = (x1 - x0) * (y1 - y0)
  771. // We do this one last, since it may be negative and acc can't ever be negative:
  772. let j0 = sub_sign(x1, x0);
  773. let j1 = sub_sign(y1, y0);
  774. match j0.sign * j1.sign {
  775. Plus => {
  776. p.data.truncate(0);
  777. p.data.extend(repeat(0).take(len));
  778. mac3(&mut p.data[..], &j0.data.data[..], &j1.data.data[..]);
  779. p = p.normalize();
  780. sub2(&mut acc[b..], &p.data[..]);
  781. },
  782. Minus => {
  783. mac3(&mut acc[b..], &j0.data.data[..], &j1.data.data[..]);
  784. },
  785. NoSign => (),
  786. }
  787. }
  788. }
  789. fn mul3(x: &[BigDigit], y: &[BigDigit]) -> BigUint {
  790. let len = x.len() + y.len() + 1;
  791. let mut prod = BigUint { data: vec![0; len] };
  792. mac3(&mut prod.data[..], x, y);
  793. prod.normalize()
  794. }
  795. impl<'a, 'b> Mul<&'b BigUint> for &'a BigUint {
  796. type Output = BigUint;
  797. #[inline]
  798. fn mul(self, other: &BigUint) -> BigUint {
  799. mul3(&self.data[..], &other.data[..])
  800. }
  801. }
  802. fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) {
  803. let mut rem = 0;
  804. for d in a.data.iter_mut().rev() {
  805. let (q, r) = div_wide(rem, *d, b);
  806. *d = q;
  807. rem = r;
  808. }
  809. (a.normalize(), rem)
  810. }
  811. forward_all_binop_to_ref_ref!(impl Div for BigUint, div);
  812. impl<'a, 'b> Div<&'b BigUint> for &'a BigUint {
  813. type Output = BigUint;
  814. #[inline]
  815. fn div(self, other: &BigUint) -> BigUint {
  816. let (q, _) = self.div_rem(other);
  817. return q;
  818. }
  819. }
  820. forward_all_binop_to_ref_ref!(impl Rem for BigUint, rem);
  821. impl<'a, 'b> Rem<&'b BigUint> for &'a BigUint {
  822. type Output = BigUint;
  823. #[inline]
  824. fn rem(self, other: &BigUint) -> BigUint {
  825. let (_, r) = self.div_rem(other);
  826. return r;
  827. }
  828. }
  829. impl Neg for BigUint {
  830. type Output = BigUint;
  831. #[inline]
  832. fn neg(self) -> BigUint { panic!() }
  833. }
  834. impl<'a> Neg for &'a BigUint {
  835. type Output = BigUint;
  836. #[inline]
  837. fn neg(self) -> BigUint { panic!() }
  838. }
  839. impl CheckedAdd for BigUint {
  840. #[inline]
  841. fn checked_add(&self, v: &BigUint) -> Option<BigUint> {
  842. return Some(self.add(v));
  843. }
  844. }
  845. impl CheckedSub for BigUint {
  846. #[inline]
  847. fn checked_sub(&self, v: &BigUint) -> Option<BigUint> {
  848. match self.cmp(v) {
  849. Less => None,
  850. Equal => Some(Zero::zero()),
  851. Greater => Some(self.sub(v)),
  852. }
  853. }
  854. }
  855. impl CheckedMul for BigUint {
  856. #[inline]
  857. fn checked_mul(&self, v: &BigUint) -> Option<BigUint> {
  858. return Some(self.mul(v));
  859. }
  860. }
  861. impl CheckedDiv for BigUint {
  862. #[inline]
  863. fn checked_div(&self, v: &BigUint) -> Option<BigUint> {
  864. if v.is_zero() {
  865. return None;
  866. }
  867. return Some(self.div(v));
  868. }
  869. }
  870. impl Integer for BigUint {
  871. #[inline]
  872. fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) {
  873. self.div_mod_floor(other)
  874. }
  875. #[inline]
  876. fn div_floor(&self, other: &BigUint) -> BigUint {
  877. let (d, _) = self.div_mod_floor(other);
  878. return d;
  879. }
  880. #[inline]
  881. fn mod_floor(&self, other: &BigUint) -> BigUint {
  882. let (_, m) = self.div_mod_floor(other);
  883. return m;
  884. }
  885. fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) {
  886. if other.is_zero() { panic!() }
  887. if self.is_zero() { return (Zero::zero(), Zero::zero()); }
  888. if *other == One::one() { return (self.clone(), Zero::zero()); }
  889. /* Required or the q_len calculation below can underflow: */
  890. match self.cmp(other) {
  891. Less => return (Zero::zero(), self.clone()),
  892. Equal => return (One::one(), Zero::zero()),
  893. Greater => {} // Do nothing
  894. }
  895. /*
  896. * This algorithm is from Knuth, TAOCP vol 2 section 4.3, algorithm D:
  897. *
  898. * First, normalize the arguments so the highest bit in the highest digit of the divisor is
  899. * set: the main loop uses the highest digit of the divisor for generating guesses, so we
  900. * want it to be the largest number we can efficiently divide by.
  901. */
  902. let shift = other.data.last().unwrap().leading_zeros() as usize;
  903. let mut a = self << shift;
  904. let b = other << shift;
  905. /*
  906. * The algorithm works by incrementally calculating "guesses", q0, for part of the
  907. * remainder. Once we have any number q0 such that q0 * b <= a, we can set
  908. *
  909. * q += q0
  910. * a -= q0 * b
  911. *
  912. * and then iterate until a < b. Then, (q, a) will be our desired quotient and remainder.
  913. *
  914. * q0, our guess, is calculated by dividing the last few digits of a by the last digit of b
  915. * - this should give us a guess that is "close" to the actual quotient, but is possibly
  916. * greater than the actual quotient. If q0 * b > a, we simply use iterated subtraction
  917. * until we have a guess such that q0 & b <= a.
  918. */
  919. let bn = *b.data.last().unwrap();
  920. let q_len = a.data.len() - b.data.len() + 1;
  921. let mut q = BigUint { data: vec![0; q_len] };
  922. /*
  923. * We reuse the same temporary to avoid hitting the allocator in our inner loop - this is
  924. * sized to hold a0 (in the common case; if a particular digit of the quotient is zero a0
  925. * can be bigger).
  926. */
  927. let mut tmp = BigUint { data: Vec::with_capacity(2) };
  928. for j in (0..q_len).rev() {
  929. /*
  930. * When calculating our next guess q0, we don't need to consider the digits below j
  931. * + b.data.len() - 1: we're guessing digit j of the quotient (i.e. q0 << j) from
  932. * digit bn of the divisor (i.e. bn << (b.data.len() - 1) - so the product of those
  933. * two numbers will be zero in all digits up to (j + b.data.len() - 1).
  934. */
  935. let offset = j + b.data.len() - 1;
  936. if offset >= a.data.len() {
  937. continue;
  938. }
  939. /* just avoiding a heap allocation: */
  940. let mut a0 = tmp;
  941. a0.data.truncate(0);
  942. a0.data.extend(a.data[offset..].iter().cloned());
  943. /*
  944. * q0 << j * big_digit::BITS is our actual quotient estimate - we do the shifts
  945. * implicitly at the end, when adding and subtracting to a and q. Not only do we
  946. * save the cost of the shifts, the rest of the arithmetic gets to work with
  947. * smaller numbers.
  948. */
  949. let (mut q0, _) = div_rem_digit(a0, bn);
  950. let mut prod = &b * &q0;
  951. while cmp_slice(&prod.data[..], &a.data[j..]) == Greater {
  952. let one: BigUint = One::one();
  953. q0 = q0 - one;
  954. prod = prod - &b;
  955. }
  956. add2(&mut q.data[j..], &q0.data[..]);
  957. sub2(&mut a.data[j..], &prod.data[..]);
  958. a = a.normalize();
  959. tmp = q0;
  960. }
  961. debug_assert!(a < b);
  962. (q.normalize(), a >> shift)
  963. }
  964. /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
  965. ///
  966. /// The result is always positive.
  967. #[inline]
  968. fn gcd(&self, other: &BigUint) -> BigUint {
  969. // Use Euclid's algorithm
  970. let mut m = (*self).clone();
  971. let mut n = (*other).clone();
  972. while !m.is_zero() {
  973. let temp = m;
  974. m = n % &temp;
  975. n = temp;
  976. }
  977. return n;
  978. }
  979. /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
  980. #[inline]
  981. fn lcm(&self, other: &BigUint) -> BigUint { ((self * other) / self.gcd(other)) }
  982. /// Deprecated, use `is_multiple_of` instead.
  983. #[inline]
  984. fn divides(&self, other: &BigUint) -> bool { self.is_multiple_of(other) }
  985. /// Returns `true` if the number is a multiple of `other`.
  986. #[inline]
  987. fn is_multiple_of(&self, other: &BigUint) -> bool { (self % other).is_zero() }
  988. /// Returns `true` if the number is divisible by `2`.
  989. #[inline]
  990. fn is_even(&self) -> bool {
  991. // Considering only the last digit.
  992. match self.data.first() {
  993. Some(x) => x.is_even(),
  994. None => true
  995. }
  996. }
  997. /// Returns `true` if the number is not divisible by `2`.
  998. #[inline]
  999. fn is_odd(&self) -> bool { !self.is_even() }
  1000. }
  1001. impl ToPrimitive for BigUint {
  1002. #[inline]
  1003. fn to_i64(&self) -> Option<i64> {
  1004. self.to_u64().and_then(|n| {
  1005. // If top bit of u64 is set, it's too large to convert to i64.
  1006. if n >> 63 == 0 {
  1007. Some(n as i64)
  1008. } else {
  1009. None
  1010. }
  1011. })
  1012. }
  1013. // `DoubleBigDigit` size dependent
  1014. #[inline]
  1015. fn to_u64(&self) -> Option<u64> {
  1016. match self.data.len() {
  1017. 0 => Some(0),
  1018. 1 => Some(self.data[0] as u64),
  1019. 2 => Some(big_digit::to_doublebigdigit(self.data[1], self.data[0])
  1020. as u64),
  1021. _ => None
  1022. }
  1023. }
  1024. // `DoubleBigDigit` size dependent
  1025. #[inline]
  1026. fn to_f32(&self) -> Option<f32> {
  1027. match self.data.len() {
  1028. 0 => Some(f32::zero()),
  1029. 1 => Some(self.data[0] as f32),
  1030. len => {
  1031. // this will prevent any overflow of exponent
  1032. if len > (f32::MAX_EXP as usize) / big_digit::BITS {
  1033. None
  1034. } else {
  1035. let exponent = (len - 2) * big_digit::BITS;
  1036. // we need 25 significant digits, 24 to be stored and 1 for rounding
  1037. // this gives at least 33 significant digits
  1038. let mantissa = big_digit::to_doublebigdigit(self.data[len - 1], self.data[len - 2]);
  1039. // this cast handles rounding
  1040. let ret = (mantissa as f32) * 2.0.powi(exponent as i32);
  1041. if ret.is_infinite() {
  1042. None
  1043. } else {
  1044. Some(ret)
  1045. }
  1046. }
  1047. }
  1048. }
  1049. }
  1050. // `DoubleBigDigit` size dependent
  1051. #[inline]
  1052. fn to_f64(&self) -> Option<f64> {
  1053. match self.data.len() {
  1054. 0 => Some(f64::zero()),
  1055. 1 => Some(self.data[0] as f64),
  1056. 2 => Some(big_digit::to_doublebigdigit(self.data[1], self.data[0]) as f64),
  1057. len => {
  1058. // this will prevent any overflow of exponent
  1059. if len > (f64::MAX_EXP as usize) / big_digit::BITS {
  1060. None
  1061. } else {
  1062. let mut exponent = (len - 2) * big_digit::BITS;
  1063. let mut mantissa = big_digit::to_doublebigdigit(self.data[len - 1], self.data[len - 2]);
  1064. // we need at least 54 significant bit digits, 53 to be stored and 1 for rounding
  1065. // so we take enough from the next BigDigit to make it up to 64
  1066. let shift = mantissa.leading_zeros() as usize;
  1067. if shift > 0 {
  1068. mantissa <<= shift;
  1069. mantissa |= self.data[len - 3] as u64 >> (big_digit::BITS - shift);
  1070. exponent -= shift;
  1071. }
  1072. // this cast handles rounding
  1073. let ret = (mantissa as f64) * 2.0.powi(exponent as i32);
  1074. if ret.is_infinite() {
  1075. None
  1076. } else {
  1077. Some(ret)
  1078. }
  1079. }
  1080. }
  1081. }
  1082. }
  1083. }
  1084. impl FromPrimitive for BigUint {
  1085. #[inline]
  1086. fn from_i64(n: i64) -> Option<BigUint> {
  1087. if n >= 0 {
  1088. Some(BigUint::from(n as u64))
  1089. } else {
  1090. None
  1091. }
  1092. }
  1093. #[inline]
  1094. fn from_u64(n: u64) -> Option<BigUint> {
  1095. Some(BigUint::from(n))
  1096. }
  1097. #[inline]
  1098. fn from_f64(mut n: f64) -> Option<BigUint> {
  1099. // handle NAN, INFINITY, NEG_INFINITY
  1100. if !n.is_finite() {
  1101. return None;
  1102. }
  1103. // match the rounding of casting from float to int
  1104. n = n.trunc();
  1105. // handle 0.x, -0.x
  1106. if n.is_zero() {
  1107. return Some(BigUint::zero());
  1108. }
  1109. let (mantissa, exponent, sign) = Float::integer_decode(n);
  1110. if sign == -1 {
  1111. return None;
  1112. }
  1113. let mut ret = BigUint::from(mantissa);
  1114. if exponent > 0 {
  1115. ret = ret << exponent as usize;
  1116. } else if exponent < 0 {
  1117. ret = ret >> (-exponent) as usize;
  1118. }
  1119. Some(ret)
  1120. }
  1121. }
  1122. impl From<u64> for BigUint {
  1123. // `DoubleBigDigit` size dependent
  1124. #[inline]
  1125. fn from(n: u64) -> Self {
  1126. match big_digit::from_doublebigdigit(n) {
  1127. (0, 0) => BigUint::zero(),
  1128. (0, n0) => BigUint { data: vec![n0] },
  1129. (n1, n0) => BigUint { data: vec![n0, n1] },
  1130. }
  1131. }
  1132. }
  1133. macro_rules! impl_biguint_from_uint {
  1134. ($T:ty) => {
  1135. impl From<$T> for BigUint {
  1136. #[inline]
  1137. fn from(n: $T) -> Self {
  1138. BigUint::from(n as u64)
  1139. }
  1140. }
  1141. }
  1142. }
  1143. impl_biguint_from_uint!(u8);
  1144. impl_biguint_from_uint!(u16);
  1145. impl_biguint_from_uint!(u32);
  1146. impl_biguint_from_uint!(usize);
  1147. /// A generic trait for converting a value to a `BigUint`.
  1148. pub trait ToBigUint {
  1149. /// Converts the value of `self` to a `BigUint`.
  1150. fn to_biguint(&self) -> Option<BigUint>;
  1151. }
  1152. impl ToBigUint for BigInt {
  1153. #[inline]
  1154. fn to_biguint(&self) -> Option<BigUint> {
  1155. if self.sign == Plus {
  1156. Some(self.data.clone())
  1157. } else if self.sign == NoSign {
  1158. Some(Zero::zero())
  1159. } else {
  1160. None
  1161. }
  1162. }
  1163. }
  1164. impl ToBigUint for BigUint {
  1165. #[inline]
  1166. fn to_biguint(&self) -> Option<BigUint> {
  1167. Some(self.clone())
  1168. }
  1169. }
  1170. macro_rules! impl_to_biguint {
  1171. ($T:ty, $from_ty:path) => {
  1172. impl ToBigUint for $T {
  1173. #[inline]
  1174. fn to_biguint(&self) -> Option<BigUint> {
  1175. $from_ty(*self)
  1176. }
  1177. }
  1178. }
  1179. }
  1180. impl_to_biguint!(isize, FromPrimitive::from_isize);
  1181. impl_to_biguint!(i8, FromPrimitive::from_i8);
  1182. impl_to_biguint!(i16, FromPrimitive::from_i16);
  1183. impl_to_biguint!(i32, FromPrimitive::from_i32);
  1184. impl_to_biguint!(i64, FromPrimitive::from_i64);
  1185. impl_to_biguint!(usize, FromPrimitive::from_usize);
  1186. impl_to_biguint!(u8, FromPrimitive::from_u8);
  1187. impl_to_biguint!(u16, FromPrimitive::from_u16);
  1188. impl_to_biguint!(u32, FromPrimitive::from_u32);
  1189. impl_to_biguint!(u64, FromPrimitive::from_u64);
  1190. impl_to_biguint!(f32, FromPrimitive::from_f32);
  1191. impl_to_biguint!(f64, FromPrimitive::from_f64);
  1192. // Extract bitwise digits that evenly divide BigDigit
  1193. fn to_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec<u8> {
  1194. debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits == 0);
  1195. let last_i = u.data.len() - 1;
  1196. let mask: BigDigit = (1 << bits) - 1;
  1197. let digits_per_big_digit = big_digit::BITS / bits;
  1198. let digits = (u.bits() + bits - 1) / bits;
  1199. let mut res = Vec::with_capacity(digits);
  1200. for mut r in u.data[..last_i].iter().cloned() {
  1201. for _ in 0..digits_per_big_digit {
  1202. res.push((r & mask) as u8);
  1203. r >>= bits;
  1204. }
  1205. }
  1206. let mut r = u.data[last_i];
  1207. while r != 0 {
  1208. res.push((r & mask) as u8);
  1209. r >>= bits;
  1210. }
  1211. res
  1212. }
  1213. // Extract bitwise digits that don't evenly divide BigDigit
  1214. fn to_inexact_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec<u8> {
  1215. debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits != 0);
  1216. let last_i = u.data.len() - 1;
  1217. let mask: DoubleBigDigit = (1 << bits) - 1;
  1218. let digits = (u.bits() + bits - 1) / bits;
  1219. let mut res = Vec::with_capacity(digits);
  1220. let mut r = 0;
  1221. let mut rbits = 0;
  1222. for hi in u.data[..last_i].iter().cloned() {
  1223. r |= (hi as DoubleBigDigit) << rbits;
  1224. rbits += big_digit::BITS;
  1225. while rbits >= bits {
  1226. res.push((r & mask) as u8);
  1227. r >>= bits;
  1228. rbits -= bits;
  1229. }
  1230. }
  1231. r |= (u.data[last_i] as DoubleBigDigit) << rbits;
  1232. while r != 0 {
  1233. res.push((r & mask) as u8);
  1234. r >>= bits;
  1235. }
  1236. res
  1237. }
  1238. // Extract little-endian radix digits
  1239. #[inline(always)] // forced inline to get const-prop for radix=10
  1240. fn to_radix_digits_le(u: &BigUint, radix: u32) -> Vec<u8> {
  1241. debug_assert!(!u.is_zero() && !radix.is_power_of_two());
  1242. // Estimate how big the result will be, so we can pre-allocate it.
  1243. let radix_digits = ((u.bits() as f64) / (radix as f64).log2()).ceil();
  1244. let mut res = Vec::with_capacity(radix_digits as usize);
  1245. let mut digits = u.clone();
  1246. let (base, power) = get_radix_base(radix);
  1247. debug_assert!(base < (1 << 32));
  1248. let base = base as BigDigit;
  1249. while digits.data.len() > 1 {
  1250. let (q, mut r) = div_rem_digit(digits, base);
  1251. for _ in 0..power {
  1252. res.push((r % radix) as u8);
  1253. r /= radix;
  1254. }
  1255. digits = q;
  1256. }
  1257. let mut r = digits.data[0];
  1258. while r != 0 {
  1259. res.push((r % radix) as u8);
  1260. r /= radix;
  1261. }
  1262. res
  1263. }
  1264. fn to_str_radix_reversed(u: &BigUint, radix: u32) -> Vec<u8> {
  1265. assert!(2 <= radix && radix <= 36, "The radix must be within 2...36");
  1266. if u.is_zero() {
  1267. return vec![b'0']
  1268. }
  1269. let mut res = if radix.is_power_of_two() {
  1270. // Powers of two can use bitwise masks and shifting instead of division
  1271. let bits = radix.trailing_zeros() as usize;
  1272. if big_digit::BITS % bits == 0 {
  1273. to_bitwise_digits_le(u, bits)
  1274. } else {
  1275. to_inexact_bitwise_digits_le(u, bits)
  1276. }
  1277. } else if radix == 10 {
  1278. // 10 is so common that it's worth separating out for const-propagation.
  1279. // Optimizers can often turn constant division into a faster multiplication.
  1280. to_radix_digits_le(u, 10)
  1281. } else {
  1282. to_radix_digits_le(u, radix)
  1283. };
  1284. // Now convert everything to ASCII digits.
  1285. for r in &mut res {
  1286. debug_assert!((*r as u32) < radix);
  1287. if *r < 10 {
  1288. *r += b'0';
  1289. } else {
  1290. *r += b'a' - 10;
  1291. }
  1292. }
  1293. res
  1294. }
  1295. impl BigUint {
  1296. /// Creates and initializes a `BigUint`.
  1297. ///
  1298. /// The digits are in little-endian base 2^32.
  1299. #[inline]
  1300. pub fn new(digits: Vec<BigDigit>) -> BigUint {
  1301. BigUint { data: digits }.normalize()
  1302. }
  1303. /// Creates and initializes a `BigUint`.
  1304. ///
  1305. /// The digits are in little-endian base 2^32.
  1306. #[inline]
  1307. pub fn from_slice(slice: &[BigDigit]) -> BigUint {
  1308. BigUint::new(slice.to_vec())
  1309. }
  1310. /// Creates and initializes a `BigUint`.
  1311. ///
  1312. /// The bytes are in big-endian byte order.
  1313. ///
  1314. /// # Examples
  1315. ///
  1316. /// ```
  1317. /// use num::bigint::BigUint;
  1318. ///
  1319. /// assert_eq!(BigUint::from_bytes_be(b"A"),
  1320. /// BigUint::parse_bytes(b"65", 10).unwrap());
  1321. /// assert_eq!(BigUint::from_bytes_be(b"AA"),
  1322. /// BigUint::parse_bytes(b"16705", 10).unwrap());
  1323. /// assert_eq!(BigUint::from_bytes_be(b"AB"),
  1324. /// BigUint::parse_bytes(b"16706", 10).unwrap());
  1325. /// assert_eq!(BigUint::from_bytes_be(b"Hello world!"),
  1326. /// BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
  1327. /// ```
  1328. #[inline]
  1329. pub fn from_bytes_be(bytes: &[u8]) -> BigUint {
  1330. if bytes.is_empty() {
  1331. Zero::zero()
  1332. } else {
  1333. let mut v = bytes.to_vec();
  1334. v.reverse();
  1335. BigUint::from_bytes_le(&*v)
  1336. }
  1337. }
  1338. /// Creates and initializes a `BigUint`.
  1339. ///
  1340. /// The bytes are in little-endian byte order.
  1341. #[inline]
  1342. pub fn from_bytes_le(bytes: &[u8]) -> BigUint {
  1343. if bytes.is_empty() {
  1344. Zero::zero()
  1345. } else {
  1346. from_bitwise_digits_le(bytes, 8)
  1347. }
  1348. }
  1349. /// Returns the byte representation of the `BigUint` in little-endian byte order.
  1350. ///
  1351. /// # Examples
  1352. ///
  1353. /// ```
  1354. /// use num::bigint::BigUint;
  1355. ///
  1356. /// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
  1357. /// assert_eq!(i.to_bytes_le(), vec![101, 4]);
  1358. /// ```
  1359. #[inline]
  1360. pub fn to_bytes_le(&self) -> Vec<u8> {
  1361. if self.is_zero() {
  1362. vec![0]
  1363. } else {
  1364. to_bitwise_digits_le(self, 8)
  1365. }
  1366. }
  1367. /// Returns the byte representation of the `BigUint` in big-endian byte order.
  1368. ///
  1369. /// # Examples
  1370. ///
  1371. /// ```
  1372. /// use num::bigint::BigUint;
  1373. ///
  1374. /// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
  1375. /// assert_eq!(i.to_bytes_be(), vec![4, 101]);
  1376. /// ```
  1377. #[inline]
  1378. pub fn to_bytes_be(&self) -> Vec<u8> {
  1379. let mut v = self.to_bytes_le();
  1380. v.reverse();
  1381. v
  1382. }
  1383. /// Returns the integer formatted as a string in the given radix.
  1384. /// `radix` must be in the range `[2, 36]`.
  1385. ///
  1386. /// # Examples
  1387. ///
  1388. /// ```
  1389. /// use num::bigint::BigUint;
  1390. ///
  1391. /// let i = BigUint::parse_bytes(b"ff", 16).unwrap();
  1392. /// assert_eq!(i.to_str_radix(16), "ff");
  1393. /// ```
  1394. #[inline]
  1395. pub fn to_str_radix(&self, radix: u32) -> String {
  1396. let mut v = to_str_radix_reversed(self, radix);
  1397. v.reverse();
  1398. unsafe { String::from_utf8_unchecked(v) }
  1399. }
  1400. /// Creates and initializes a `BigUint`.
  1401. ///
  1402. /// # Examples
  1403. ///
  1404. /// ```
  1405. /// use num::bigint::{BigUint, ToBigUint};
  1406. ///
  1407. /// assert_eq!(BigUint::parse_bytes(b"1234", 10), ToBigUint::to_biguint(&1234));
  1408. /// assert_eq!(BigUint::parse_bytes(b"ABCD", 16), ToBigUint::to_biguint(&0xABCD));
  1409. /// assert_eq!(BigUint::parse_bytes(b"G", 16), None);
  1410. /// ```
  1411. #[inline]
  1412. pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigUint> {
  1413. str::from_utf8(buf).ok().and_then(|s| BigUint::from_str_radix(s, radix).ok())
  1414. }
  1415. #[inline]
  1416. fn shl_unit(&self, n_unit: usize) -> BigUint {
  1417. if n_unit == 0 || self.is_zero() { return self.clone(); }
  1418. let mut v = vec![0; n_unit];
  1419. v.extend(self.data.iter().cloned());
  1420. BigUint::new(v)
  1421. }
  1422. #[inline]
  1423. fn shl_bits(self, n_bits: usize) -> BigUint {
  1424. if n_bits == 0 || self.is_zero() { return self; }
  1425. assert!(n_bits < big_digit::BITS);
  1426. let mut carry = 0;
  1427. let mut shifted = self.data;
  1428. for elem in shifted.iter_mut() {
  1429. let new_carry = *elem >> (big_digit::BITS - n_bits);
  1430. *elem = (*elem << n_bits) | carry;
  1431. carry = new_carry;
  1432. }
  1433. if carry != 0 {
  1434. shifted.push(carry);
  1435. }
  1436. BigUint::new(shifted)
  1437. }
  1438. #[inline]
  1439. fn shr_unit(&self, n_unit: usize) -> BigUint {
  1440. if n_unit == 0 { return self.clone(); }
  1441. if self.data.len() < n_unit { return Zero::zero(); }
  1442. BigUint::from_slice(&self.data[n_unit ..])
  1443. }
  1444. #[inline]
  1445. fn shr_bits(self, n_bits: usize) -> BigUint {
  1446. if n_bits == 0 || self.data.is_empty() { return self; }
  1447. assert!(n_bits < big_digit::BITS);
  1448. let mut borrow = 0;
  1449. let mut shifted = self.data;
  1450. for elem in shifted.iter_mut().rev() {
  1451. let new_borrow = *elem << (big_digit::BITS - n_bits);
  1452. *elem = (*elem >> n_bits) | borrow;
  1453. borrow = new_borrow;
  1454. }
  1455. BigUint::new(shifted)
  1456. }
  1457. /// Determines the fewest bits necessary to express the `BigUint`.
  1458. pub fn bits(&self) -> usize {
  1459. if self.is_zero() { return 0; }
  1460. let zeros = self.data.last().unwrap().leading_zeros();
  1461. return self.data.len()*big_digit::BITS - zeros as usize;
  1462. }
  1463. /// Strips off trailing zero bigdigits - comparisons require the last element in the vector to
  1464. /// be nonzero.
  1465. #[inline]
  1466. fn normalize(mut self) -> BigUint {
  1467. while let Some(&0) = self.data.last() {
  1468. self.data.pop();
  1469. }
  1470. self
  1471. }
  1472. }
  1473. // `DoubleBigDigit` size dependent
  1474. /// Returns the greatest power of the radix <= big_digit::BASE
  1475. #[inline]
  1476. fn get_radix_base(radix: u32) -> (DoubleBigDigit, usize) {
  1477. // To generate this table:
  1478. // let target = std::u32::max as u64 + 1;
  1479. // for radix in 2u64..37 {
  1480. // let power = (target as f64).log(radix as f64) as u32;
  1481. // let base = radix.pow(power);
  1482. // println!("({:10}, {:2}), // {:2}", base, power, radix);
  1483. // }
  1484. const BASES: [(DoubleBigDigit, usize); 37] = [
  1485. (0, 0), (0, 0),
  1486. (4294967296, 32), // 2
  1487. (3486784401, 20), // 3
  1488. (4294967296, 16), // 4
  1489. (1220703125, 13), // 5
  1490. (2176782336, 12), // 6
  1491. (1977326743, 11), // 7
  1492. (1073741824, 10), // 8
  1493. (3486784401, 10), // 9
  1494. (1000000000, 9), // 10
  1495. (2357947691, 9), // 11
  1496. ( 429981696, 8), // 12
  1497. ( 815730721, 8), // 13
  1498. (1475789056, 8), // 14
  1499. (2562890625, 8), // 15
  1500. (4294967296, 8), // 16
  1501. ( 410338673, 7), // 17
  1502. ( 612220032, 7), // 18
  1503. ( 893871739, 7), // 19
  1504. (1280000000, 7), // 20
  1505. (1801088541, 7), // 21
  1506. (2494357888, 7), // 22
  1507. (3404825447, 7), // 23
  1508. ( 191102976, 6), // 24
  1509. ( 244140625, 6), // 25
  1510. ( 308915776, 6), // 26
  1511. ( 387420489, 6), // 27
  1512. ( 481890304, 6), // 28
  1513. ( 594823321, 6), // 29
  1514. ( 729000000, 6), // 30
  1515. ( 887503681, 6), // 31
  1516. (1073741824, 6), // 32
  1517. (1291467969, 6), // 33
  1518. (1544804416, 6), // 34
  1519. (1838265625, 6), // 35
  1520. (2176782336, 6), // 36
  1521. ];
  1522. assert!(2 <= radix && radix <= 36, "The radix must be within 2...36");
  1523. BASES[radix as usize]
  1524. }
  1525. /// A Sign is a `BigInt`'s composing element.
  1526. #[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone, Debug, Hash)]
  1527. #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
  1528. pub enum Sign { Minus, NoSign, Plus }
  1529. impl Neg for Sign {
  1530. type Output = Sign;
  1531. /// Negate Sign value.
  1532. #[inline]
  1533. fn neg(self) -> Sign {
  1534. match self {
  1535. Minus => Plus,
  1536. NoSign => NoSign,
  1537. Plus => Minus
  1538. }
  1539. }
  1540. }
  1541. impl Mul<Sign> for Sign {
  1542. type Output = Sign;
  1543. #[inline]
  1544. fn mul(self, other: Sign) -> Sign {
  1545. match (self, other) {
  1546. (NoSign, _) | (_, NoSign) => NoSign,
  1547. (Plus, Plus) | (Minus, Minus) => Plus,
  1548. (Plus, Minus) | (Minus, Plus) => Minus,
  1549. }
  1550. }
  1551. }
  1552. /// A big signed integer type.
  1553. #[derive(Clone, Debug, Hash)]
  1554. #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
  1555. pub struct BigInt {
  1556. sign: Sign,
  1557. data: BigUint
  1558. }
  1559. impl PartialEq for BigInt {
  1560. #[inline]
  1561. fn eq(&self, other: &BigInt) -> bool {
  1562. self.cmp(other) == Equal
  1563. }
  1564. }
  1565. impl Eq for BigInt {}
  1566. impl PartialOrd for BigInt {
  1567. #[inline]
  1568. fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> {
  1569. Some(self.cmp(other))
  1570. }
  1571. }
  1572. impl Ord for BigInt {
  1573. #[inline]
  1574. fn cmp(&self, other: &BigInt) -> Ordering {
  1575. let scmp = self.sign.cmp(&other.sign);
  1576. if scmp != Equal { return scmp; }
  1577. match self.sign {
  1578. NoSign => Equal,
  1579. Plus => self.data.cmp(&other.data),
  1580. Minus => other.data.cmp(&self.data),
  1581. }
  1582. }
  1583. }
  1584. impl Default for BigInt {
  1585. #[inline]
  1586. fn default() -> BigInt { Zero::zero() }
  1587. }
  1588. impl fmt::Display for BigInt {
  1589. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  1590. f.pad_integral(!self.is_negative(), "", &self.data.to_str_radix(10))
  1591. }
  1592. }
  1593. impl fmt::Binary for BigInt {
  1594. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  1595. f.pad_integral(!self.is_negative(), "0b", &self.data.to_str_radix(2))
  1596. }
  1597. }
  1598. impl fmt::Octal for BigInt {
  1599. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  1600. f.pad_integral(!self.is_negative(), "0o", &self.data.to_str_radix(8))
  1601. }
  1602. }
  1603. impl fmt::LowerHex for BigInt {
  1604. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  1605. f.pad_integral(!self.is_negative(), "0x", &self.data.to_str_radix(16))
  1606. }
  1607. }
  1608. impl fmt::UpperHex for BigInt {
  1609. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  1610. f.pad_integral(!self.is_negative(), "0x", &self.data.to_str_radix(16).to_ascii_uppercase())
  1611. }
  1612. }
  1613. impl FromStr for BigInt {
  1614. type Err = ParseBigIntError;
  1615. #[inline]
  1616. fn from_str(s: &str) -> Result<BigInt, ParseBigIntError> {
  1617. BigInt::from_str_radix(s, 10)
  1618. }
  1619. }
  1620. impl Num for BigInt {
  1621. type FromStrRadixErr = ParseBigIntError;
  1622. /// Creates and initializes a BigInt.
  1623. #[inline]
  1624. fn from_str_radix(mut s: &str, radix: u32) -> Result<BigInt, ParseBigIntError> {
  1625. let sign = if s.starts_with('-') { s = &s[1..]; Minus } else { Plus };
  1626. let bu = try!(BigUint::from_str_radix(s, radix));
  1627. Ok(BigInt::from_biguint(sign, bu))
  1628. }
  1629. }
  1630. impl Shl<usize> for BigInt {
  1631. type Output = BigInt;
  1632. #[inline]
  1633. fn shl(self, rhs: usize) -> BigInt { (&self) << rhs }
  1634. }
  1635. impl<'a> Shl<usize> for &'a BigInt {
  1636. type Output = BigInt;
  1637. #[inline]
  1638. fn shl(self, rhs: usize) -> BigInt {
  1639. BigInt::from_biguint(self.sign, &self.data << rhs)
  1640. }
  1641. }
  1642. impl Shr<usize> for BigInt {
  1643. type Output = BigInt;
  1644. #[inline]
  1645. fn shr(self, rhs: usize) -> BigInt { (&self) >> rhs }
  1646. }
  1647. impl<'a> Shr<usize> for &'a BigInt {
  1648. type Output = BigInt;
  1649. #[inline]
  1650. fn shr(self, rhs: usize) -> BigInt {
  1651. BigInt::from_biguint(self.sign, &self.data >> rhs)
  1652. }
  1653. }
  1654. impl Zero for BigInt {
  1655. #[inline]
  1656. fn zero() -> BigInt {
  1657. BigInt::from_biguint(NoSign, Zero::zero())
  1658. }
  1659. #[inline]
  1660. fn is_zero(&self) -> bool { self.sign == NoSign }
  1661. }
  1662. impl One for BigInt {
  1663. #[inline]
  1664. fn one() -> BigInt {
  1665. BigInt::from_biguint(Plus, One::one())
  1666. }
  1667. }
  1668. impl Signed for BigInt {
  1669. #[inline]
  1670. fn abs(&self) -> BigInt {
  1671. match self.sign {
  1672. Plus | NoSign => self.clone(),
  1673. Minus => BigInt::from_biguint(Plus, self.data.clone())
  1674. }
  1675. }
  1676. #[inline]
  1677. fn abs_sub(&self, other: &BigInt) -> BigInt {
  1678. if *self <= *other { Zero::zero() } else { self - other }
  1679. }
  1680. #[inline]
  1681. fn signum(&self) -> BigInt {
  1682. match self.sign {
  1683. Plus => BigInt::from_biguint(Plus, One::one()),
  1684. Minus => BigInt::from_biguint(Minus, One::one()),
  1685. NoSign => Zero::zero(),
  1686. }
  1687. }
  1688. #[inline]
  1689. fn is_positive(&self) -> bool { self.sign == Plus }
  1690. #[inline]
  1691. fn is_negative(&self) -> bool { self.sign == Minus }
  1692. }
  1693. // We want to forward to BigUint::add, but it's not clear how that will go until
  1694. // we compare both sign and magnitude. So we duplicate this body for every
  1695. // val/ref combination, deferring that decision to BigUint's own forwarding.
  1696. macro_rules! bigint_add {
  1697. ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
  1698. match ($a.sign, $b.sign) {
  1699. (_, NoSign) => $a_owned,
  1700. (NoSign, _) => $b_owned,
  1701. // same sign => keep the sign with the sum of magnitudes
  1702. (Plus, Plus) | (Minus, Minus) =>
  1703. BigInt::from_biguint($a.sign, $a_data + $b_data),
  1704. // opposite signs => keep the sign of the larger with the difference of magnitudes
  1705. (Plus, Minus) | (Minus, Plus) =>
  1706. match $a.data.cmp(&$b.data) {
  1707. Less => BigInt::from_biguint($b.sign, $b_data - $a_data),
  1708. Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
  1709. Equal => Zero::zero(),
  1710. },
  1711. }
  1712. };
  1713. }
  1714. impl<'a, 'b> Add<&'b BigInt> for &'a BigInt {
  1715. type Output = BigInt;
  1716. #[inline]
  1717. fn add(self, other: &BigInt) -> BigInt {
  1718. bigint_add!(self, self.clone(), &self.data, other, other.clone(), &other.data)
  1719. }
  1720. }
  1721. impl<'a> Add<BigInt> for &'a BigInt {
  1722. type Output = BigInt;
  1723. #[inline]
  1724. fn add(self, other: BigInt) -> BigInt {
  1725. bigint_add!(self, self.clone(), &self.data, other, other, other.data)
  1726. }
  1727. }
  1728. impl<'a> Add<&'a BigInt> for BigInt {
  1729. type Output = BigInt;
  1730. #[inline]
  1731. fn add(self, other: &BigInt) -> BigInt {
  1732. bigint_add!(self, self, self.data, other, other.clone(), &other.data)
  1733. }
  1734. }
  1735. impl Add<BigInt> for BigInt {
  1736. type Output = BigInt;
  1737. #[inline]
  1738. fn add(self, other: BigInt) -> BigInt {
  1739. bigint_add!(self, self, self.data, other, other, other.data)
  1740. }
  1741. }
  1742. // We want to forward to BigUint::sub, but it's not clear how that will go until
  1743. // we compare both sign and magnitude. So we duplicate this body for every
  1744. // val/ref combination, deferring that decision to BigUint's own forwarding.
  1745. macro_rules! bigint_sub {
  1746. ($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
  1747. match ($a.sign, $b.sign) {
  1748. (_, NoSign) => $a_owned,
  1749. (NoSign, _) => -$b_owned,
  1750. // opposite signs => keep the sign of the left with the sum of magnitudes
  1751. (Plus, Minus) | (Minus, Plus) =>
  1752. BigInt::from_biguint($a.sign, $a_data + $b_data),
  1753. // same sign => keep or toggle the sign of the left with the difference of magnitudes
  1754. (Plus, Plus) | (Minus, Minus) =>
  1755. match $a.data.cmp(&$b.data) {
  1756. Less => BigInt::from_biguint(-$a.sign, $b_data - $a_data),
  1757. Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
  1758. Equal => Zero::zero(),
  1759. },
  1760. }
  1761. };
  1762. }
  1763. impl<'a, 'b> Sub<&'b BigInt> for &'a BigInt {
  1764. type Output = BigInt;
  1765. #[inline]
  1766. fn sub(self, other: &BigInt) -> BigInt {
  1767. bigint_sub!(self, self.clone(), &self.data, other, other.clone(), &other.data)
  1768. }
  1769. }
  1770. impl<'a> Sub<BigInt> for &'a BigInt {
  1771. type Output = BigInt;
  1772. #[inline]
  1773. fn sub(self, other: BigInt) -> BigInt {
  1774. bigint_sub!(self, self.clone(), &self.data, other, other, other.data)
  1775. }
  1776. }
  1777. impl<'a> Sub<&'a BigInt> for BigInt {
  1778. type Output = BigInt;
  1779. #[inline]
  1780. fn sub(self, other: &BigInt) -> BigInt {
  1781. bigint_sub!(self, self, self.data, other, other.clone(), &other.data)
  1782. }
  1783. }
  1784. impl Sub<BigInt> for BigInt {
  1785. type Output = BigInt;
  1786. #[inline]
  1787. fn sub(self, other: BigInt) -> BigInt {
  1788. bigint_sub!(self, self, self.data, other, other, other.data)
  1789. }
  1790. }
  1791. forward_all_binop_to_ref_ref!(impl Mul for BigInt, mul);
  1792. impl<'a, 'b> Mul<&'b BigInt> for &'a BigInt {
  1793. type Output = BigInt;
  1794. #[inline]
  1795. fn mul(self, other: &BigInt) -> BigInt {
  1796. BigInt::from_biguint(self.sign * other.sign,
  1797. &self.data * &other.data)
  1798. }
  1799. }
  1800. forward_all_binop_to_ref_ref!(impl Div for BigInt, div);
  1801. impl<'a, 'b> Div<&'b BigInt> for &'a BigInt {
  1802. type Output = BigInt;
  1803. #[inline]
  1804. fn div(self, other: &BigInt) -> BigInt {
  1805. let (q, _) = self.div_rem(other);
  1806. q
  1807. }
  1808. }
  1809. forward_all_binop_to_ref_ref!(impl Rem for BigInt, rem);
  1810. impl<'a, 'b> Rem<&'b BigInt> for &'a BigInt {
  1811. type Output = BigInt;
  1812. #[inline]
  1813. fn rem(self, other: &BigInt) -> BigInt {
  1814. let (_, r) = self.div_rem(other);
  1815. r
  1816. }
  1817. }
  1818. impl Neg for BigInt {
  1819. type Output = BigInt;
  1820. #[inline]
  1821. fn neg(mut self) -> BigInt {
  1822. self.sign = -self.sign;
  1823. self
  1824. }
  1825. }
  1826. impl<'a> Neg for &'a BigInt {
  1827. type Output = BigInt;
  1828. #[inline]
  1829. fn neg(self) -> BigInt {
  1830. -self.clone()
  1831. }
  1832. }
  1833. impl CheckedAdd for BigInt {
  1834. #[inline]
  1835. fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
  1836. return Some(self.add(v));
  1837. }
  1838. }
  1839. impl CheckedSub for BigInt {
  1840. #[inline]
  1841. fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
  1842. return Some(self.sub(v));
  1843. }
  1844. }
  1845. impl CheckedMul for BigInt {
  1846. #[inline]
  1847. fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
  1848. return Some(self.mul(v));
  1849. }
  1850. }
  1851. impl CheckedDiv for BigInt {
  1852. #[inline]
  1853. fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
  1854. if v.is_zero() {
  1855. return None;
  1856. }
  1857. return Some(self.div(v));
  1858. }
  1859. }
  1860. impl Integer for BigInt {
  1861. #[inline]
  1862. fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) {
  1863. // r.sign == self.sign
  1864. let (d_ui, r_ui) = self.data.div_mod_floor(&other.data);
  1865. let d = BigInt::from_biguint(self.sign, d_ui);
  1866. let r = BigInt::from_biguint(self.sign, r_ui);
  1867. if other.is_negative() { (-d, r) } else { (d, r) }
  1868. }
  1869. #[inline]
  1870. fn div_floor(&self, other: &BigInt) -> BigInt {
  1871. let (d, _) = self.div_mod_floor(other);
  1872. d
  1873. }
  1874. #[inline]
  1875. fn mod_floor(&self, other: &BigInt) -> BigInt {
  1876. let (_, m) = self.div_mod_floor(other);
  1877. m
  1878. }
  1879. fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) {
  1880. // m.sign == other.sign
  1881. let (d_ui, m_ui) = self.data.div_rem(&other.data);
  1882. let d = BigInt::from_biguint(Plus, d_ui);
  1883. let m = BigInt::from_biguint(Plus, m_ui);
  1884. let one: BigInt = One::one();
  1885. match (self.sign, other.sign) {
  1886. (_, NoSign) => panic!(),
  1887. (Plus, Plus) | (NoSign, Plus) => (d, m),
  1888. (Plus, Minus) | (NoSign, Minus) => {
  1889. if m.is_zero() {
  1890. (-d, Zero::zero())
  1891. } else {
  1892. (-d - one, m + other)
  1893. }
  1894. },
  1895. (Minus, Plus) => {
  1896. if m.is_zero() {
  1897. (-d, Zero::zero())
  1898. } else {
  1899. (-d - one, other - m)
  1900. }
  1901. }
  1902. (Minus, Minus) => (d, -m)
  1903. }
  1904. }
  1905. /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
  1906. ///
  1907. /// The result is always positive.
  1908. #[inline]
  1909. fn gcd(&self, other: &BigInt) -> BigInt {
  1910. BigInt::from_biguint(Plus, self.data.gcd(&other.data))
  1911. }
  1912. /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
  1913. #[inline]
  1914. fn lcm(&self, other: &BigInt) -> BigInt {
  1915. BigInt::from_biguint(Plus, self.data.lcm(&other.data))
  1916. }
  1917. /// Deprecated, use `is_multiple_of` instead.
  1918. #[inline]
  1919. fn divides(&self, other: &BigInt) -> bool { return self.is_multiple_of(other); }
  1920. /// Returns `true` if the number is a multiple of `other`.
  1921. #[inline]
  1922. fn is_multiple_of(&self, other: &BigInt) -> bool { self.data.is_multiple_of(&other.data) }
  1923. /// Returns `true` if the number is divisible by `2`.
  1924. #[inline]
  1925. fn is_even(&self) -> bool { self.data.is_even() }
  1926. /// Returns `true` if the number is not divisible by `2`.
  1927. #[inline]
  1928. fn is_odd(&self) -> bool { self.data.is_odd() }
  1929. }
  1930. impl ToPrimitive for BigInt {
  1931. #[inline]
  1932. fn to_i64(&self) -> Option<i64> {
  1933. match self.sign {
  1934. Plus => self.data.to_i64(),
  1935. NoSign => Some(0),
  1936. Minus => {
  1937. self.data.to_u64().and_then(|n| {
  1938. let m: u64 = 1 << 63;
  1939. if n < m {
  1940. Some(-(n as i64))
  1941. } else if n == m {
  1942. Some(i64::MIN)
  1943. } else {
  1944. None
  1945. }
  1946. })
  1947. }
  1948. }
  1949. }
  1950. #[inline]
  1951. fn to_u64(&self) -> Option<u64> {
  1952. match self.sign {
  1953. Plus => self.data.to_u64(),
  1954. NoSign => Some(0),
  1955. Minus => None
  1956. }
  1957. }
  1958. #[inline]
  1959. fn to_f32(&self) -> Option<f32> {
  1960. self.data.to_f32().map(|n| if self.sign == Minus { -n } else { n })
  1961. }
  1962. #[inline]
  1963. fn to_f64(&self) -> Option<f64> {
  1964. self.data.to_f64().map(|n| if self.sign == Minus { -n } else { n })
  1965. }
  1966. }
  1967. impl FromPrimitive for BigInt {
  1968. #[inline]
  1969. fn from_i64(n: i64) -> Option<BigInt> {
  1970. Some(BigInt::from(n))
  1971. }
  1972. #[inline]
  1973. fn from_u64(n: u64) -> Option<BigInt> {
  1974. Some(BigInt::from(n))
  1975. }
  1976. #[inline]
  1977. fn from_f64(n: f64) -> Option<BigInt> {
  1978. if n >= 0.0 {
  1979. BigUint::from_f64(n).map(|x| BigInt::from_biguint(Plus, x))
  1980. } else {
  1981. BigUint::from_f64(-n).map(|x| BigInt::from_biguint(Minus, x))
  1982. }
  1983. }
  1984. }
  1985. impl From<i64> for BigInt {
  1986. #[inline]
  1987. fn from(n: i64) -> Self {
  1988. if n >= 0 {
  1989. BigInt::from(n as u64)
  1990. } else {
  1991. let u = u64::MAX - (n as u64) + 1;
  1992. BigInt { sign: Minus, data: BigUint::from(u) }
  1993. }
  1994. }
  1995. }
  1996. macro_rules! impl_bigint_from_int {
  1997. ($T:ty) => {
  1998. impl From<$T> for BigInt {
  1999. #[inline]
  2000. fn from(n: $T) -> Self {
  2001. BigInt::from(n as i64)
  2002. }
  2003. }
  2004. }
  2005. }
  2006. impl_bigint_from_int!(i8);
  2007. impl_bigint_from_int!(i16);
  2008. impl_bigint_from_int!(i32);
  2009. impl_bigint_from_int!(isize);
  2010. impl From<u64> for BigInt {
  2011. #[inline]
  2012. fn from(n: u64) -> Self {
  2013. if n > 0 {
  2014. BigInt { sign: Plus, data: BigUint::from(n) }
  2015. } else {
  2016. BigInt::zero()
  2017. }
  2018. }
  2019. }
  2020. macro_rules! impl_bigint_from_uint {
  2021. ($T:ty) => {
  2022. impl From<$T> for BigInt {
  2023. #[inline]
  2024. fn from(n: $T) -> Self {
  2025. BigInt::from(n as u64)
  2026. }
  2027. }
  2028. }
  2029. }
  2030. impl_bigint_from_uint!(u8);
  2031. impl_bigint_from_uint!(u16);
  2032. impl_bigint_from_uint!(u32);
  2033. impl_bigint_from_uint!(usize);
  2034. impl From<BigUint> for BigInt {
  2035. #[inline]
  2036. fn from(n: BigUint) -> Self {
  2037. if n.is_zero() {
  2038. BigInt::zero()
  2039. } else {
  2040. BigInt { sign: Plus, data: n }
  2041. }
  2042. }
  2043. }
  2044. /// A generic trait for converting a value to a `BigInt`.
  2045. pub trait ToBigInt {
  2046. /// Converts the value of `self` to a `BigInt`.
  2047. fn to_bigint(&self) -> Option<BigInt>;
  2048. }
  2049. impl ToBigInt for BigInt {
  2050. #[inline]
  2051. fn to_bigint(&self) -> Option<BigInt> {
  2052. Some(self.clone())
  2053. }
  2054. }
  2055. impl ToBigInt for BigUint {
  2056. #[inline]
  2057. fn to_bigint(&self) -> Option<BigInt> {
  2058. if self.is_zero() {
  2059. Some(Zero::zero())
  2060. } else {
  2061. Some(BigInt { sign: Plus, data: self.clone() })
  2062. }
  2063. }
  2064. }
  2065. macro_rules! impl_to_bigint {
  2066. ($T:ty, $from_ty:path) => {
  2067. impl ToBigInt for $T {
  2068. #[inline]
  2069. fn to_bigint(&self) -> Option<BigInt> {
  2070. $from_ty(*self)
  2071. }
  2072. }
  2073. }
  2074. }
  2075. impl_to_bigint!(isize, FromPrimitive::from_isize);
  2076. impl_to_bigint!(i8, FromPrimitive::from_i8);
  2077. impl_to_bigint!(i16, FromPrimitive::from_i16);
  2078. impl_to_bigint!(i32, FromPrimitive::from_i32);
  2079. impl_to_bigint!(i64, FromPrimitive::from_i64);
  2080. impl_to_bigint!(usize, FromPrimitive::from_usize);
  2081. impl_to_bigint!(u8, FromPrimitive::from_u8);
  2082. impl_to_bigint!(u16, FromPrimitive::from_u16);
  2083. impl_to_bigint!(u32, FromPrimitive::from_u32);
  2084. impl_to_bigint!(u64, FromPrimitive::from_u64);
  2085. impl_to_bigint!(f32, FromPrimitive::from_f32);
  2086. impl_to_bigint!(f64, FromPrimitive::from_f64);
  2087. pub trait RandBigInt {
  2088. /// Generate a random `BigUint` of the given bit size.
  2089. fn gen_biguint(&mut self, bit_size: usize) -> BigUint;
  2090. /// Generate a random BigInt of the given bit size.
  2091. fn gen_bigint(&mut self, bit_size: usize) -> BigInt;
  2092. /// Generate a random `BigUint` less than the given bound. Fails
  2093. /// when the bound is zero.
  2094. fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint;
  2095. /// Generate a random `BigUint` within the given range. The lower
  2096. /// bound is inclusive; the upper bound is exclusive. Fails when
  2097. /// the upper bound is not greater than the lower bound.
  2098. fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;
  2099. /// Generate a random `BigInt` within the given range. The lower
  2100. /// bound is inclusive; the upper bound is exclusive. Fails when
  2101. /// the upper bound is not greater than the lower bound.
  2102. fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt;
  2103. }
  2104. #[cfg(any(feature = "rand", test))]
  2105. impl<R: Rng> RandBigInt for R {
  2106. fn gen_biguint(&mut self, bit_size: usize) -> BigUint {
  2107. let (digits, rem) = bit_size.div_rem(&big_digit::BITS);
  2108. let mut data = Vec::with_capacity(digits+1);
  2109. for _ in 0 .. digits {
  2110. data.push(self.gen());
  2111. }
  2112. if rem > 0 {
  2113. let final_digit: BigDigit = self.gen();
  2114. data.push(final_digit >> (big_digit::BITS - rem));
  2115. }
  2116. BigUint::new(data)
  2117. }
  2118. fn gen_bigint(&mut self, bit_size: usize) -> BigInt {
  2119. // Generate a random BigUint...
  2120. let biguint = self.gen_biguint(bit_size);
  2121. // ...and then randomly assign it a Sign...
  2122. let sign = if biguint.is_zero() {
  2123. // ...except that if the BigUint is zero, we need to try
  2124. // again with probability 0.5. This is because otherwise,
  2125. // the probability of generating a zero BigInt would be
  2126. // double that of any other number.
  2127. if self.gen() {
  2128. return self.gen_bigint(bit_size);
  2129. } else {
  2130. NoSign
  2131. }
  2132. } else if self.gen() {
  2133. Plus
  2134. } else {
  2135. Minus
  2136. };
  2137. BigInt::from_biguint(sign, biguint)
  2138. }
  2139. fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint {
  2140. assert!(!bound.is_zero());
  2141. let bits = bound.bits();
  2142. loop {
  2143. let n = self.gen_biguint(bits);
  2144. if n < *bound { return n; }
  2145. }
  2146. }
  2147. fn gen_biguint_range(&mut self,
  2148. lbound: &BigUint,
  2149. ubound: &BigUint)
  2150. -> BigUint {
  2151. assert!(*lbound < *ubound);
  2152. return lbound + self.gen_biguint_below(&(ubound - lbound));
  2153. }
  2154. fn gen_bigint_range(&mut self,
  2155. lbound: &BigInt,
  2156. ubound: &BigInt)
  2157. -> BigInt {
  2158. assert!(*lbound < *ubound);
  2159. let delta = (ubound - lbound).to_biguint().unwrap();
  2160. return lbound + self.gen_biguint_below(&delta).to_bigint().unwrap();
  2161. }
  2162. }
  2163. impl BigInt {
  2164. /// Creates and initializes a BigInt.
  2165. ///
  2166. /// The digits are in little-endian base 2^32.
  2167. #[inline]
  2168. pub fn new(sign: Sign, digits: Vec<BigDigit>) -> BigInt {
  2169. BigInt::from_biguint(sign, BigUint::new(digits))
  2170. }
  2171. /// Creates and initializes a `BigInt`.
  2172. ///
  2173. /// The digits are in little-endian base 2^32.
  2174. #[inline]
  2175. pub fn from_biguint(sign: Sign, data: BigUint) -> BigInt {
  2176. if sign == NoSign || data.is_zero() {
  2177. return BigInt { sign: NoSign, data: Zero::zero() };
  2178. }
  2179. BigInt { sign: sign, data: data }
  2180. }
  2181. /// Creates and initializes a `BigInt`.
  2182. #[inline]
  2183. pub fn from_slice(sign: Sign, slice: &[BigDigit]) -> BigInt {
  2184. BigInt::from_biguint(sign, BigUint::from_slice(slice))
  2185. }
  2186. /// Creates and initializes a `BigInt`.
  2187. ///
  2188. /// The bytes are in big-endian byte order.
  2189. ///
  2190. /// # Examples
  2191. ///
  2192. /// ```
  2193. /// use num::bigint::{BigInt, Sign};
  2194. ///
  2195. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"A"),
  2196. /// BigInt::parse_bytes(b"65", 10).unwrap());
  2197. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AA"),
  2198. /// BigInt::parse_bytes(b"16705", 10).unwrap());
  2199. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AB"),
  2200. /// BigInt::parse_bytes(b"16706", 10).unwrap());
  2201. /// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"Hello world!"),
  2202. /// BigInt::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
  2203. /// ```
  2204. #[inline]
  2205. pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt {
  2206. BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes))
  2207. }
  2208. /// Creates and initializes a `BigInt`.
  2209. ///
  2210. /// The bytes are in little-endian byte order.
  2211. #[inline]
  2212. pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt {
  2213. BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes))
  2214. }
  2215. /// Returns the sign and the byte representation of the `BigInt` in little-endian byte order.
  2216. ///
  2217. /// # Examples
  2218. ///
  2219. /// ```
  2220. /// use num::bigint::{ToBigInt, Sign};
  2221. ///
  2222. /// let i = -1125.to_bigint().unwrap();
  2223. /// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4]));
  2224. /// ```
  2225. #[inline]
  2226. pub fn to_bytes_le(&self) -> (Sign, Vec<u8>) {
  2227. (self.sign, self.data.to_bytes_le())
  2228. }
  2229. /// Returns the sign and the byte representation of the `BigInt` in big-endian byte order.
  2230. ///
  2231. /// # Examples
  2232. ///
  2233. /// ```
  2234. /// use num::bigint::{ToBigInt, Sign};
  2235. ///
  2236. /// let i = -1125.to_bigint().unwrap();
  2237. /// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101]));
  2238. /// ```
  2239. #[inline]
  2240. pub fn to_bytes_be(&self) -> (Sign, Vec<u8>) {
  2241. (self.sign, self.data.to_bytes_be())
  2242. }
  2243. /// Returns the integer formatted as a string in the given radix.
  2244. /// `radix` must be in the range `[2, 36]`.
  2245. ///
  2246. /// # Examples
  2247. ///
  2248. /// ```
  2249. /// use num::bigint::BigInt;
  2250. ///
  2251. /// let i = BigInt::parse_bytes(b"ff", 16).unwrap();
  2252. /// assert_eq!(i.to_str_radix(16), "ff");
  2253. /// ```
  2254. #[inline]
  2255. pub fn to_str_radix(&self, radix: u32) -> String {
  2256. let mut v = to_str_radix_reversed(&self.data, radix);
  2257. if self.is_negative() {
  2258. v.push(b'-');
  2259. }
  2260. v.reverse();
  2261. unsafe { String::from_utf8_unchecked(v) }
  2262. }
  2263. /// Returns the sign of the `BigInt` as a `Sign`.
  2264. ///
  2265. /// # Examples
  2266. ///
  2267. /// ```
  2268. /// use num::bigint::{ToBigInt, Sign};
  2269. ///
  2270. /// assert_eq!(ToBigInt::to_bigint(&1234).unwrap().sign(), Sign::Plus);
  2271. /// assert_eq!(ToBigInt::to_bigint(&-4321).unwrap().sign(), Sign::Minus);
  2272. /// assert_eq!(ToBigInt::to_bigint(&0).unwrap().sign(), Sign::NoSign);
  2273. /// ```
  2274. #[inline]
  2275. pub fn sign(&self) -> Sign {
  2276. self.sign
  2277. }
  2278. /// Creates and initializes a `BigInt`.
  2279. ///
  2280. /// # Examples
  2281. ///
  2282. /// ```
  2283. /// use num::bigint::{BigInt, ToBigInt};
  2284. ///
  2285. /// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234));
  2286. /// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD));
  2287. /// assert_eq!(BigInt::parse_bytes(b"G", 16), None);
  2288. /// ```
  2289. #[inline]
  2290. pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigInt> {
  2291. str::from_utf8(buf).ok().and_then(|s| BigInt::from_str_radix(s, radix).ok())
  2292. }
  2293. /// Converts this `BigInt` into a `BigUint`, if it's not negative.
  2294. #[inline]
  2295. pub fn to_biguint(&self) -> Option<BigUint> {
  2296. match self.sign {
  2297. Plus => Some(self.data.clone()),
  2298. NoSign => Some(Zero::zero()),
  2299. Minus => None
  2300. }
  2301. }
  2302. #[inline]
  2303. pub fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
  2304. return Some(self.add(v));
  2305. }
  2306. #[inline]
  2307. pub fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
  2308. return Some(self.sub(v));
  2309. }
  2310. #[inline]
  2311. pub fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
  2312. return Some(self.mul(v));
  2313. }
  2314. #[inline]
  2315. pub fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
  2316. if v.is_zero() {
  2317. return None;
  2318. }
  2319. return Some(self.div(v));
  2320. }
  2321. }
  2322. #[derive(Debug, PartialEq)]
  2323. pub enum ParseBigIntError {
  2324. ParseInt(ParseIntError),
  2325. Other,
  2326. }
  2327. impl fmt::Display for ParseBigIntError {
  2328. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  2329. match self {
  2330. &ParseBigIntError::ParseInt(ref e) => e.fmt(f),
  2331. &ParseBigIntError::Other => "failed to parse provided string".fmt(f)
  2332. }
  2333. }
  2334. }
  2335. impl Error for ParseBigIntError {
  2336. fn description(&self) -> &str { "failed to parse bigint/biguint" }
  2337. }
  2338. impl From<ParseIntError> for ParseBigIntError {
  2339. fn from(err: ParseIntError) -> ParseBigIntError {
  2340. ParseBigIntError::ParseInt(err)
  2341. }
  2342. }
  2343. #[cfg(test)]
  2344. mod biguint_tests {
  2345. use Integer;
  2346. use super::{BigDigit, BigUint, ToBigUint, big_digit};
  2347. use super::{BigInt, RandBigInt, ToBigInt};
  2348. use super::Sign::Plus;
  2349. use std::cmp::Ordering::{Less, Equal, Greater};
  2350. use std::{f32, f64};
  2351. use std::i64;
  2352. use std::iter::repeat;
  2353. use std::str::FromStr;
  2354. use std::{u8, u16, u32, u64, usize};
  2355. use rand::thread_rng;
  2356. use {Num, Zero, One, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv};
  2357. use {ToPrimitive, FromPrimitive};
  2358. use Float;
  2359. /// Assert that an op works for all val/ref combinations
  2360. macro_rules! assert_op {
  2361. ($left:ident $op:tt $right:ident == $expected:expr) => {
  2362. assert_eq!((&$left) $op (&$right), $expected);
  2363. assert_eq!((&$left) $op $right.clone(), $expected);
  2364. assert_eq!($left.clone() $op (&$right), $expected);
  2365. assert_eq!($left.clone() $op $right.clone(), $expected);
  2366. };
  2367. }
  2368. #[test]
  2369. fn test_from_slice() {
  2370. fn check(slice: &[BigDigit], data: &[BigDigit]) {
  2371. assert!(BigUint::from_slice(slice).data == data);
  2372. }
  2373. check(&[1], &[1]);
  2374. check(&[0, 0, 0], &[]);
  2375. check(&[1, 2, 0, 0], &[1, 2]);
  2376. check(&[0, 0, 1, 2], &[0, 0, 1, 2]);
  2377. check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]);
  2378. check(&[-1i32 as BigDigit], &[-1i32 as BigDigit]);
  2379. }
  2380. #[test]
  2381. fn test_from_bytes_be() {
  2382. fn check(s: &str, result: &str) {
  2383. assert_eq!(BigUint::from_bytes_be(s.as_bytes()),
  2384. BigUint::parse_bytes(result.as_bytes(), 10).unwrap());
  2385. }
  2386. check("A", "65");
  2387. check("AA", "16705");
  2388. check("AB", "16706");
  2389. check("Hello world!", "22405534230753963835153736737");
  2390. assert_eq!(BigUint::from_bytes_be(&[]), Zero::zero());
  2391. }
  2392. #[test]
  2393. fn test_to_bytes_be() {
  2394. fn check(s: &str, result: &str) {
  2395. let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap();
  2396. assert_eq!(b.to_bytes_be(), s.as_bytes());
  2397. }
  2398. check("A", "65");
  2399. check("AA", "16705");
  2400. check("AB", "16706");
  2401. check("Hello world!", "22405534230753963835153736737");
  2402. let b: BigUint = Zero::zero();
  2403. assert_eq!(b.to_bytes_be(), [0]);
  2404. // Test with leading/trailing zero bytes and a full BigDigit of value 0
  2405. let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap();
  2406. assert_eq!(b.to_bytes_be(), [1, 0, 0, 0, 0, 0, 0, 2, 0]);
  2407. }
  2408. #[test]
  2409. fn test_from_bytes_le() {
  2410. fn check(s: &str, result: &str) {
  2411. assert_eq!(BigUint::from_bytes_le(s.as_bytes()),
  2412. BigUint::parse_bytes(result.as_bytes(), 10).unwrap());
  2413. }
  2414. check("A", "65");
  2415. check("AA", "16705");
  2416. check("BA", "16706");
  2417. check("!dlrow olleH", "22405534230753963835153736737");
  2418. assert_eq!(BigUint::from_bytes_le(&[]), Zero::zero());
  2419. }
  2420. #[test]
  2421. fn test_to_bytes_le() {
  2422. fn check(s: &str, result: &str) {
  2423. let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap();
  2424. assert_eq!(b.to_bytes_le(), s.as_bytes());
  2425. }
  2426. check("A", "65");
  2427. check("AA", "16705");
  2428. check("BA", "16706");
  2429. check("!dlrow olleH", "22405534230753963835153736737");
  2430. let b: BigUint = Zero::zero();
  2431. assert_eq!(b.to_bytes_le(), [0]);
  2432. // Test with leading/trailing zero bytes and a full BigDigit of value 0
  2433. let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap();
  2434. assert_eq!(b.to_bytes_le(), [0, 2, 0, 0, 0, 0, 0, 0, 1]);
  2435. }
  2436. #[test]
  2437. fn test_cmp() {
  2438. let data: [&[_]; 7] = [ &[], &[1], &[2], &[!0], &[0, 1], &[2, 1], &[1, 1, 1] ];
  2439. let data: Vec<BigUint> = data.iter().map(|v| BigUint::from_slice(*v)).collect();
  2440. for (i, ni) in data.iter().enumerate() {
  2441. for (j0, nj) in data[i..].iter().enumerate() {
  2442. let j = j0 + i;
  2443. if i == j {
  2444. assert_eq!(ni.cmp(nj), Equal);
  2445. assert_eq!(nj.cmp(ni), Equal);
  2446. assert_eq!(ni, nj);
  2447. assert!(!(ni != nj));
  2448. assert!(ni <= nj);
  2449. assert!(ni >= nj);
  2450. assert!(!(ni < nj));
  2451. assert!(!(ni > nj));
  2452. } else {
  2453. assert_eq!(ni.cmp(nj), Less);
  2454. assert_eq!(nj.cmp(ni), Greater);
  2455. assert!(!(ni == nj));
  2456. assert!(ni != nj);
  2457. assert!(ni <= nj);
  2458. assert!(!(ni >= nj));
  2459. assert!(ni < nj);
  2460. assert!(!(ni > nj));
  2461. assert!(!(nj <= ni));
  2462. assert!(nj >= ni);
  2463. assert!(!(nj < ni));
  2464. assert!(nj > ni);
  2465. }
  2466. }
  2467. }
  2468. }
  2469. #[test]
  2470. fn test_hash() {
  2471. let a = BigUint::new(vec!());
  2472. let b = BigUint::new(vec!(0));
  2473. let c = BigUint::new(vec!(1));
  2474. let d = BigUint::new(vec!(1,0,0,0,0,0));
  2475. let e = BigUint::new(vec!(0,0,0,0,0,1));
  2476. assert!(::hash(&a) == ::hash(&b));
  2477. assert!(::hash(&b) != ::hash(&c));
  2478. assert!(::hash(&c) == ::hash(&d));
  2479. assert!(::hash(&d) != ::hash(&e));
  2480. }
  2481. const BIT_TESTS: &'static [(&'static [BigDigit],
  2482. &'static [BigDigit],
  2483. &'static [BigDigit],
  2484. &'static [BigDigit],
  2485. &'static [BigDigit])] = &[
  2486. // LEFT RIGHT AND OR XOR
  2487. ( &[], &[], &[], &[], &[] ),
  2488. ( &[268, 482, 17], &[964, 54], &[260, 34], &[972, 502, 17], &[712, 468, 17] ),
  2489. ];
  2490. #[test]
  2491. fn test_bitand() {
  2492. for elm in BIT_TESTS {
  2493. let (a_vec, b_vec, c_vec, _, _) = *elm;
  2494. let a = BigUint::from_slice(a_vec);
  2495. let b = BigUint::from_slice(b_vec);
  2496. let c = BigUint::from_slice(c_vec);
  2497. assert_op!(a & b == c);
  2498. assert_op!(b & a == c);
  2499. }
  2500. }
  2501. #[test]
  2502. fn test_bitor() {
  2503. for elm in BIT_TESTS {
  2504. let (a_vec, b_vec, _, c_vec, _) = *elm;
  2505. let a = BigUint::from_slice(a_vec);
  2506. let b = BigUint::from_slice(b_vec);
  2507. let c = BigUint::from_slice(c_vec);
  2508. assert_op!(a | b == c);
  2509. assert_op!(b | a == c);
  2510. }
  2511. }
  2512. #[test]
  2513. fn test_bitxor() {
  2514. for elm in BIT_TESTS {
  2515. let (a_vec, b_vec, _, _, c_vec) = *elm;
  2516. let a = BigUint::from_slice(a_vec);
  2517. let b = BigUint::from_slice(b_vec);
  2518. let c = BigUint::from_slice(c_vec);
  2519. assert_op!(a ^ b == c);
  2520. assert_op!(b ^ a == c);
  2521. assert_op!(a ^ c == b);
  2522. assert_op!(c ^ a == b);
  2523. assert_op!(b ^ c == a);
  2524. assert_op!(c ^ b == a);
  2525. }
  2526. }
  2527. #[test]
  2528. fn test_shl() {
  2529. fn check(s: &str, shift: usize, ans: &str) {
  2530. let opt_biguint = BigUint::from_str_radix(s, 16).ok();
  2531. let bu = (opt_biguint.unwrap() << shift).to_str_radix(16);
  2532. assert_eq!(bu, ans);
  2533. }
  2534. check("0", 3, "0");
  2535. check("1", 3, "8");
  2536. check("1\
  2537. 0000\
  2538. 0000\
  2539. 0000\
  2540. 0001\
  2541. 0000\
  2542. 0000\
  2543. 0000\
  2544. 0001",
  2545. 3,
  2546. "8\
  2547. 0000\
  2548. 0000\
  2549. 0000\
  2550. 0008\
  2551. 0000\
  2552. 0000\
  2553. 0000\
  2554. 0008");
  2555. check("1\
  2556. 0000\
  2557. 0001\
  2558. 0000\
  2559. 0001",
  2560. 2,
  2561. "4\
  2562. 0000\
  2563. 0004\
  2564. 0000\
  2565. 0004");
  2566. check("1\
  2567. 0001\
  2568. 0001",
  2569. 1,
  2570. "2\
  2571. 0002\
  2572. 0002");
  2573. check("\
  2574. 4000\
  2575. 0000\
  2576. 0000\
  2577. 0000",
  2578. 3,
  2579. "2\
  2580. 0000\
  2581. 0000\
  2582. 0000\
  2583. 0000");
  2584. check("4000\
  2585. 0000",
  2586. 2,
  2587. "1\
  2588. 0000\
  2589. 0000");
  2590. check("4000",
  2591. 2,
  2592. "1\
  2593. 0000");
  2594. check("4000\
  2595. 0000\
  2596. 0000\
  2597. 0000",
  2598. 67,
  2599. "2\
  2600. 0000\
  2601. 0000\
  2602. 0000\
  2603. 0000\
  2604. 0000\
  2605. 0000\
  2606. 0000\
  2607. 0000");
  2608. check("4000\
  2609. 0000",
  2610. 35,
  2611. "2\
  2612. 0000\
  2613. 0000\
  2614. 0000\
  2615. 0000");
  2616. check("4000",
  2617. 19,
  2618. "2\
  2619. 0000\
  2620. 0000");
  2621. check("fedc\
  2622. ba98\
  2623. 7654\
  2624. 3210\
  2625. fedc\
  2626. ba98\
  2627. 7654\
  2628. 3210",
  2629. 4,
  2630. "f\
  2631. edcb\
  2632. a987\
  2633. 6543\
  2634. 210f\
  2635. edcb\
  2636. a987\
  2637. 6543\
  2638. 2100");
  2639. check("88887777666655554444333322221111", 16,
  2640. "888877776666555544443333222211110000");
  2641. }
  2642. #[test]
  2643. fn test_shr() {
  2644. fn check(s: &str, shift: usize, ans: &str) {
  2645. let opt_biguint = BigUint::from_str_radix(s, 16).ok();
  2646. let bu = (opt_biguint.unwrap() >> shift).to_str_radix(16);
  2647. assert_eq!(bu, ans);
  2648. }
  2649. check("0", 3, "0");
  2650. check("f", 3, "1");
  2651. check("1\
  2652. 0000\
  2653. 0000\
  2654. 0000\
  2655. 0001\
  2656. 0000\
  2657. 0000\
  2658. 0000\
  2659. 0001",
  2660. 3,
  2661. "2000\
  2662. 0000\
  2663. 0000\
  2664. 0000\
  2665. 2000\
  2666. 0000\
  2667. 0000\
  2668. 0000");
  2669. check("1\
  2670. 0000\
  2671. 0001\
  2672. 0000\
  2673. 0001",
  2674. 2,
  2675. "4000\
  2676. 0000\
  2677. 4000\
  2678. 0000");
  2679. check("1\
  2680. 0001\
  2681. 0001",
  2682. 1,
  2683. "8000\
  2684. 8000");
  2685. check("2\
  2686. 0000\
  2687. 0000\
  2688. 0000\
  2689. 0001\
  2690. 0000\
  2691. 0000\
  2692. 0000\
  2693. 0001",
  2694. 67,
  2695. "4000\
  2696. 0000\
  2697. 0000\
  2698. 0000");
  2699. check("2\
  2700. 0000\
  2701. 0001\
  2702. 0000\
  2703. 0001",
  2704. 35,
  2705. "4000\
  2706. 0000");
  2707. check("2\
  2708. 0001\
  2709. 0001",
  2710. 19,
  2711. "4000");
  2712. check("1\
  2713. 0000\
  2714. 0000\
  2715. 0000\
  2716. 0000",
  2717. 1,
  2718. "8000\
  2719. 0000\
  2720. 0000\
  2721. 0000");
  2722. check("1\
  2723. 0000\
  2724. 0000",
  2725. 1,
  2726. "8000\
  2727. 0000");
  2728. check("1\
  2729. 0000",
  2730. 1,
  2731. "8000");
  2732. check("f\
  2733. edcb\
  2734. a987\
  2735. 6543\
  2736. 210f\
  2737. edcb\
  2738. a987\
  2739. 6543\
  2740. 2100",
  2741. 4,
  2742. "fedc\
  2743. ba98\
  2744. 7654\
  2745. 3210\
  2746. fedc\
  2747. ba98\
  2748. 7654\
  2749. 3210");
  2750. check("888877776666555544443333222211110000", 16,
  2751. "88887777666655554444333322221111");
  2752. }
  2753. const N1: BigDigit = -1i32 as BigDigit;
  2754. const N2: BigDigit = -2i32 as BigDigit;
  2755. // `DoubleBigDigit` size dependent
  2756. #[test]
  2757. fn test_convert_i64() {
  2758. fn check(b1: BigUint, i: i64) {
  2759. let b2: BigUint = FromPrimitive::from_i64(i).unwrap();
  2760. assert!(b1 == b2);
  2761. assert!(b1.to_i64().unwrap() == i);
  2762. }
  2763. check(Zero::zero(), 0);
  2764. check(One::one(), 1);
  2765. check(i64::MAX.to_biguint().unwrap(), i64::MAX);
  2766. check(BigUint::new(vec!( )), 0);
  2767. check(BigUint::new(vec!( 1 )), (1 << (0*big_digit::BITS)));
  2768. check(BigUint::new(vec!(N1 )), (1 << (1*big_digit::BITS)) - 1);
  2769. check(BigUint::new(vec!( 0, 1 )), (1 << (1*big_digit::BITS)));
  2770. check(BigUint::new(vec!(N1, N1 >> 1)), i64::MAX);
  2771. assert_eq!(i64::MIN.to_biguint(), None);
  2772. assert_eq!(BigUint::new(vec!(N1, N1 )).to_i64(), None);
  2773. assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_i64(), None);
  2774. assert_eq!(BigUint::new(vec!(N1, N1, N1)).to_i64(), None);
  2775. }
  2776. // `DoubleBigDigit` size dependent
  2777. #[test]
  2778. fn test_convert_u64() {
  2779. fn check(b1: BigUint, u: u64) {
  2780. let b2: BigUint = FromPrimitive::from_u64(u).unwrap();
  2781. assert!(b1 == b2);
  2782. assert!(b1.to_u64().unwrap() == u);
  2783. }
  2784. check(Zero::zero(), 0);
  2785. check(One::one(), 1);
  2786. check(u64::MIN.to_biguint().unwrap(), u64::MIN);
  2787. check(u64::MAX.to_biguint().unwrap(), u64::MAX);
  2788. check(BigUint::new(vec!( )), 0);
  2789. check(BigUint::new(vec!( 1 )), (1 << (0*big_digit::BITS)));
  2790. check(BigUint::new(vec!(N1 )), (1 << (1*big_digit::BITS)) - 1);
  2791. check(BigUint::new(vec!( 0, 1)), (1 << (1*big_digit::BITS)));
  2792. check(BigUint::new(vec!(N1, N1)), u64::MAX);
  2793. assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_u64(), None);
  2794. assert_eq!(BigUint::new(vec!(N1, N1, N1)).to_u64(), None);
  2795. }
  2796. #[test]
  2797. fn test_convert_f32() {
  2798. fn check(b1: &BigUint, f: f32) {
  2799. let b2 = BigUint::from_f32(f).unwrap();
  2800. assert_eq!(b1, &b2);
  2801. assert_eq!(b1.to_f32().unwrap(), f);
  2802. }
  2803. check(&BigUint::zero(), 0.0);
  2804. check(&BigUint::one(), 1.0);
  2805. check(&BigUint::from(u16::MAX), 2.0.powi(16) - 1.0);
  2806. check(&BigUint::from(1u64 << 32), 2.0.powi(32));
  2807. check(&BigUint::from_slice(&[0, 0, 1]), 2.0.powi(64));
  2808. check(&((BigUint::one() << 100) + (BigUint::one() << 123)), 2.0.powi(100) + 2.0.powi(123));
  2809. check(&(BigUint::one() << 127), 2.0.powi(127));
  2810. check(&(BigUint::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX);
  2811. // keeping all 24 digits with the bits at different offsets to the BigDigits
  2812. let x: u32 = 0b00000000101111011111011011011101;
  2813. let mut f = x as f32;
  2814. let mut b = BigUint::from(x);
  2815. for _ in 0..64 {
  2816. check(&b, f);
  2817. f *= 2.0;
  2818. b = b << 1;
  2819. }
  2820. // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32
  2821. let n: u64 = 0b0000000000111111111111111111111111011111111111111111111111111111;
  2822. assert!((n as f64) as f32 != n as f32);
  2823. assert_eq!(BigUint::from(n).to_f32(), Some(n as f32));
  2824. // test rounding up with the bits at different offsets to the BigDigits
  2825. let mut f = ((1u64 << 25) - 1) as f32;
  2826. let mut b = BigUint::from(1u64 << 25);
  2827. for _ in 0..64 {
  2828. assert_eq!(b.to_f32(), Some(f));
  2829. f *= 2.0;
  2830. b = b << 1;
  2831. }
  2832. // rounding
  2833. assert_eq!(BigUint::from_f32(-1.0), None);
  2834. assert_eq!(BigUint::from_f32(-0.99999), Some(BigUint::zero()));
  2835. assert_eq!(BigUint::from_f32(-0.5), Some(BigUint::zero()));
  2836. assert_eq!(BigUint::from_f32(-0.0), Some(BigUint::zero()));
  2837. assert_eq!(BigUint::from_f32(f32::MIN_POSITIVE / 2.0), Some(BigUint::zero()));
  2838. assert_eq!(BigUint::from_f32(f32::MIN_POSITIVE), Some(BigUint::zero()));
  2839. assert_eq!(BigUint::from_f32(0.5), Some(BigUint::zero()));
  2840. assert_eq!(BigUint::from_f32(0.99999), Some(BigUint::zero()));
  2841. assert_eq!(BigUint::from_f32(f32::consts::E), Some(BigUint::from(2u32)));
  2842. assert_eq!(BigUint::from_f32(f32::consts::PI), Some(BigUint::from(3u32)));
  2843. // special float values
  2844. assert_eq!(BigUint::from_f32(f32::NAN), None);
  2845. assert_eq!(BigUint::from_f32(f32::INFINITY), None);
  2846. assert_eq!(BigUint::from_f32(f32::NEG_INFINITY), None);
  2847. assert_eq!(BigUint::from_f32(f32::MIN), None);
  2848. // largest BigUint that will round to a finite f32 value
  2849. let big_num = (BigUint::one() << 128) - BigUint::one() - (BigUint::one() << (128 - 25));
  2850. assert_eq!(big_num.to_f32(), Some(f32::MAX));
  2851. assert_eq!((big_num + BigUint::one()).to_f32(), None);
  2852. assert_eq!(((BigUint::one() << 128) - BigUint::one()).to_f32(), None);
  2853. assert_eq!((BigUint::one() << 128).to_f32(), None);
  2854. }
  2855. #[test]
  2856. fn test_convert_f64() {
  2857. fn check(b1: &BigUint, f: f64) {
  2858. let b2 = BigUint::from_f64(f).unwrap();
  2859. assert_eq!(b1, &b2);
  2860. assert_eq!(b1.to_f64().unwrap(), f);
  2861. }
  2862. check(&BigUint::zero(), 0.0);
  2863. check(&BigUint::one(), 1.0);
  2864. check(&BigUint::from(u32::MAX), 2.0.powi(32) - 1.0);
  2865. check(&BigUint::from(1u64 << 32), 2.0.powi(32));
  2866. check(&BigUint::from_slice(&[0, 0, 1]), 2.0.powi(64));
  2867. check(&((BigUint::one() << 100) + (BigUint::one() << 152)), 2.0.powi(100) + 2.0.powi(152));
  2868. check(&(BigUint::one() << 1023), 2.0.powi(1023));
  2869. check(&(BigUint::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX);
  2870. // keeping all 53 digits with the bits at different offsets to the BigDigits
  2871. let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101;
  2872. let mut f = x as f64;
  2873. let mut b = BigUint::from(x);
  2874. for _ in 0..128 {
  2875. check(&b, f);
  2876. f *= 2.0;
  2877. b = b << 1;
  2878. }
  2879. // test rounding up with the bits at different offsets to the BigDigits
  2880. let mut f = ((1u64 << 54) - 1) as f64;
  2881. let mut b = BigUint::from(1u64 << 54);
  2882. for _ in 0..128 {
  2883. assert_eq!(b.to_f64(), Some(f));
  2884. f *= 2.0;
  2885. b = b << 1;
  2886. }
  2887. // rounding
  2888. assert_eq!(BigUint::from_f64(-1.0), None);
  2889. assert_eq!(BigUint::from_f64(-0.99999), Some(BigUint::zero()));
  2890. assert_eq!(BigUint::from_f64(-0.5), Some(BigUint::zero()));
  2891. assert_eq!(BigUint::from_f64(-0.0), Some(BigUint::zero()));
  2892. assert_eq!(BigUint::from_f64(f64::MIN_POSITIVE / 2.0), Some(BigUint::zero()));
  2893. assert_eq!(BigUint::from_f64(f64::MIN_POSITIVE), Some(BigUint::zero()));
  2894. assert_eq!(BigUint::from_f64(0.5), Some(BigUint::zero()));
  2895. assert_eq!(BigUint::from_f64(0.99999), Some(BigUint::zero()));
  2896. assert_eq!(BigUint::from_f64(f64::consts::E), Some(BigUint::from(2u32)));
  2897. assert_eq!(BigUint::from_f64(f64::consts::PI), Some(BigUint::from(3u32)));
  2898. // special float values
  2899. assert_eq!(BigUint::from_f64(f64::NAN), None);
  2900. assert_eq!(BigUint::from_f64(f64::INFINITY), None);
  2901. assert_eq!(BigUint::from_f64(f64::NEG_INFINITY), None);
  2902. assert_eq!(BigUint::from_f64(f64::MIN), None);
  2903. // largest BigUint that will round to a finite f64 value
  2904. let big_num = (BigUint::one() << 1024) - BigUint::one() - (BigUint::one() << (1024 - 54));
  2905. assert_eq!(big_num.to_f64(), Some(f64::MAX));
  2906. assert_eq!((big_num + BigUint::one()).to_f64(), None);
  2907. assert_eq!(((BigInt::one() << 1024) - BigInt::one()).to_f64(), None);
  2908. assert_eq!((BigUint::one() << 1024).to_f64(), None);
  2909. }
  2910. #[test]
  2911. fn test_convert_to_bigint() {
  2912. fn check(n: BigUint, ans: BigInt) {
  2913. assert_eq!(n.to_bigint().unwrap(), ans);
  2914. assert_eq!(n.to_bigint().unwrap().to_biguint().unwrap(), n);
  2915. }
  2916. check(Zero::zero(), Zero::zero());
  2917. check(BigUint::new(vec!(1,2,3)),
  2918. BigInt::from_biguint(Plus, BigUint::new(vec!(1,2,3))));
  2919. }
  2920. #[test]
  2921. fn test_convert_from_uint() {
  2922. macro_rules! check {
  2923. ($ty:ident, $max:expr) => {
  2924. assert_eq!(BigUint::from($ty::zero()), BigUint::zero());
  2925. assert_eq!(BigUint::from($ty::one()), BigUint::one());
  2926. assert_eq!(BigUint::from($ty::MAX - $ty::one()), $max - BigUint::one());
  2927. assert_eq!(BigUint::from($ty::MAX), $max);
  2928. }
  2929. }
  2930. check!(u8, BigUint::from_slice(&[u8::MAX as BigDigit]));
  2931. check!(u16, BigUint::from_slice(&[u16::MAX as BigDigit]));
  2932. check!(u32, BigUint::from_slice(&[u32::MAX]));
  2933. check!(u64, BigUint::from_slice(&[u32::MAX, u32::MAX]));
  2934. check!(usize, BigUint::from(usize::MAX as u64));
  2935. }
  2936. const SUM_TRIPLES: &'static [(&'static [BigDigit],
  2937. &'static [BigDigit],
  2938. &'static [BigDigit])] = &[
  2939. (&[], &[], &[]),
  2940. (&[], &[ 1], &[ 1]),
  2941. (&[ 1], &[ 1], &[ 2]),
  2942. (&[ 1], &[ 1, 1], &[ 2, 1]),
  2943. (&[ 1], &[N1], &[ 0, 1]),
  2944. (&[ 1], &[N1, N1], &[ 0, 0, 1]),
  2945. (&[N1, N1], &[N1, N1], &[N2, N1, 1]),
  2946. (&[ 1, 1, 1], &[N1, N1], &[ 0, 1, 2]),
  2947. (&[ 2, 2, 1], &[N1, N2], &[ 1, 1, 2])
  2948. ];
  2949. #[test]
  2950. fn test_add() {
  2951. for elm in SUM_TRIPLES.iter() {
  2952. let (a_vec, b_vec, c_vec) = *elm;
  2953. let a = BigUint::from_slice(a_vec);
  2954. let b = BigUint::from_slice(b_vec);
  2955. let c = BigUint::from_slice(c_vec);
  2956. assert_op!(a + b == c);
  2957. assert_op!(b + a == c);
  2958. }
  2959. }
  2960. #[test]
  2961. fn test_sub() {
  2962. for elm in SUM_TRIPLES.iter() {
  2963. let (a_vec, b_vec, c_vec) = *elm;
  2964. let a = BigUint::from_slice(a_vec);
  2965. let b = BigUint::from_slice(b_vec);
  2966. let c = BigUint::from_slice(c_vec);
  2967. assert_op!(c - a == b);
  2968. assert_op!(c - b == a);
  2969. }
  2970. }
  2971. #[test]
  2972. #[should_panic]
  2973. fn test_sub_fail_on_underflow() {
  2974. let (a, b) : (BigUint, BigUint) = (Zero::zero(), One::one());
  2975. a - b;
  2976. }
  2977. const M: u32 = ::std::u32::MAX;
  2978. const MUL_TRIPLES: &'static [(&'static [BigDigit],
  2979. &'static [BigDigit],
  2980. &'static [BigDigit])] = &[
  2981. (&[], &[], &[]),
  2982. (&[], &[ 1], &[]),
  2983. (&[ 2], &[], &[]),
  2984. (&[ 1], &[ 1], &[1]),
  2985. (&[ 2], &[ 3], &[ 6]),
  2986. (&[ 1], &[ 1, 1, 1], &[1, 1, 1]),
  2987. (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]),
  2988. (&[ 1, 1, 1], &[N1], &[N1, N1, N1]),
  2989. (&[ 1, 2, 3], &[N1], &[N1, N2, N2, 2]),
  2990. (&[ 1, 2, 3, 4], &[N1], &[N1, N2, N2, N2, 3]),
  2991. (&[N1], &[N1], &[ 1, N2]),
  2992. (&[N1, N1], &[N1], &[ 1, N1, N2]),
  2993. (&[N1, N1, N1], &[N1], &[ 1, N1, N1, N2]),
  2994. (&[N1, N1, N1, N1], &[N1], &[ 1, N1, N1, N1, N2]),
  2995. (&[ M/2 + 1], &[ 2], &[ 0, 1]),
  2996. (&[0, M/2 + 1], &[ 2], &[ 0, 0, 1]),
  2997. (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]),
  2998. (&[N1, N1], &[N1, N1, N1], &[1, 0, N1, N2, N1]),
  2999. (&[N1, N1, N1], &[N1, N1, N1, N1], &[1, 0, 0, N1, N2, N1, N1]),
  3000. (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]),
  3001. (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])
  3002. ];
  3003. const DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit],
  3004. &'static [BigDigit],
  3005. &'static [BigDigit],
  3006. &'static [BigDigit])]
  3007. = &[
  3008. (&[ 1], &[ 2], &[], &[1]),
  3009. (&[ 1, 1], &[ 2], &[ M/2+1], &[1]),
  3010. (&[ 1, 1, 1], &[ 2], &[ M/2+1, M/2+1], &[1]),
  3011. (&[ 0, 1], &[N1], &[1], &[1]),
  3012. (&[N1, N1], &[N2], &[2, 1], &[3])
  3013. ];
  3014. #[test]
  3015. fn test_mul() {
  3016. for elm in MUL_TRIPLES.iter() {
  3017. let (a_vec, b_vec, c_vec) = *elm;
  3018. let a = BigUint::from_slice(a_vec);
  3019. let b = BigUint::from_slice(b_vec);
  3020. let c = BigUint::from_slice(c_vec);
  3021. assert_op!(a * b == c);
  3022. assert_op!(b * a == c);
  3023. }
  3024. for elm in DIV_REM_QUADRUPLES.iter() {
  3025. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  3026. let a = BigUint::from_slice(a_vec);
  3027. let b = BigUint::from_slice(b_vec);
  3028. let c = BigUint::from_slice(c_vec);
  3029. let d = BigUint::from_slice(d_vec);
  3030. assert!(a == &b * &c + &d);
  3031. assert!(a == &c * &b + &d);
  3032. }
  3033. }
  3034. #[test]
  3035. fn test_div_rem() {
  3036. for elm in MUL_TRIPLES.iter() {
  3037. let (a_vec, b_vec, c_vec) = *elm;
  3038. let a = BigUint::from_slice(a_vec);
  3039. let b = BigUint::from_slice(b_vec);
  3040. let c = BigUint::from_slice(c_vec);
  3041. if !a.is_zero() {
  3042. assert_op!(c / a == b);
  3043. assert_op!(c % a == Zero::zero());
  3044. assert_eq!(c.div_rem(&a), (b.clone(), Zero::zero()));
  3045. }
  3046. if !b.is_zero() {
  3047. assert_op!(c / b == a);
  3048. assert_op!(c % b == Zero::zero());
  3049. assert_eq!(c.div_rem(&b), (a.clone(), Zero::zero()));
  3050. }
  3051. }
  3052. for elm in DIV_REM_QUADRUPLES.iter() {
  3053. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  3054. let a = BigUint::from_slice(a_vec);
  3055. let b = BigUint::from_slice(b_vec);
  3056. let c = BigUint::from_slice(c_vec);
  3057. let d = BigUint::from_slice(d_vec);
  3058. if !b.is_zero() {
  3059. assert_op!(a / b == c);
  3060. assert_op!(a % b == d);
  3061. assert!(a.div_rem(&b) == (c, d));
  3062. }
  3063. }
  3064. }
  3065. #[test]
  3066. fn test_checked_add() {
  3067. for elm in SUM_TRIPLES.iter() {
  3068. let (a_vec, b_vec, c_vec) = *elm;
  3069. let a = BigUint::from_slice(a_vec);
  3070. let b = BigUint::from_slice(b_vec);
  3071. let c = BigUint::from_slice(c_vec);
  3072. assert!(a.checked_add(&b).unwrap() == c);
  3073. assert!(b.checked_add(&a).unwrap() == c);
  3074. }
  3075. }
  3076. #[test]
  3077. fn test_checked_sub() {
  3078. for elm in SUM_TRIPLES.iter() {
  3079. let (a_vec, b_vec, c_vec) = *elm;
  3080. let a = BigUint::from_slice(a_vec);
  3081. let b = BigUint::from_slice(b_vec);
  3082. let c = BigUint::from_slice(c_vec);
  3083. assert!(c.checked_sub(&a).unwrap() == b);
  3084. assert!(c.checked_sub(&b).unwrap() == a);
  3085. if a > c {
  3086. assert!(a.checked_sub(&c).is_none());
  3087. }
  3088. if b > c {
  3089. assert!(b.checked_sub(&c).is_none());
  3090. }
  3091. }
  3092. }
  3093. #[test]
  3094. fn test_checked_mul() {
  3095. for elm in MUL_TRIPLES.iter() {
  3096. let (a_vec, b_vec, c_vec) = *elm;
  3097. let a = BigUint::from_slice(a_vec);
  3098. let b = BigUint::from_slice(b_vec);
  3099. let c = BigUint::from_slice(c_vec);
  3100. assert!(a.checked_mul(&b).unwrap() == c);
  3101. assert!(b.checked_mul(&a).unwrap() == c);
  3102. }
  3103. for elm in DIV_REM_QUADRUPLES.iter() {
  3104. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  3105. let a = BigUint::from_slice(a_vec);
  3106. let b = BigUint::from_slice(b_vec);
  3107. let c = BigUint::from_slice(c_vec);
  3108. let d = BigUint::from_slice(d_vec);
  3109. assert!(a == b.checked_mul(&c).unwrap() + &d);
  3110. assert!(a == c.checked_mul(&b).unwrap() + &d);
  3111. }
  3112. }
  3113. #[test]
  3114. fn test_checked_div() {
  3115. for elm in MUL_TRIPLES.iter() {
  3116. let (a_vec, b_vec, c_vec) = *elm;
  3117. let a = BigUint::from_slice(a_vec);
  3118. let b = BigUint::from_slice(b_vec);
  3119. let c = BigUint::from_slice(c_vec);
  3120. if !a.is_zero() {
  3121. assert!(c.checked_div(&a).unwrap() == b);
  3122. }
  3123. if !b.is_zero() {
  3124. assert!(c.checked_div(&b).unwrap() == a);
  3125. }
  3126. assert!(c.checked_div(&Zero::zero()).is_none());
  3127. }
  3128. }
  3129. #[test]
  3130. fn test_gcd() {
  3131. fn check(a: usize, b: usize, c: usize) {
  3132. let big_a: BigUint = FromPrimitive::from_usize(a).unwrap();
  3133. let big_b: BigUint = FromPrimitive::from_usize(b).unwrap();
  3134. let big_c: BigUint = FromPrimitive::from_usize(c).unwrap();
  3135. assert_eq!(big_a.gcd(&big_b), big_c);
  3136. }
  3137. check(10, 2, 2);
  3138. check(10, 3, 1);
  3139. check(0, 3, 3);
  3140. check(3, 3, 3);
  3141. check(56, 42, 14);
  3142. }
  3143. #[test]
  3144. fn test_lcm() {
  3145. fn check(a: usize, b: usize, c: usize) {
  3146. let big_a: BigUint = FromPrimitive::from_usize(a).unwrap();
  3147. let big_b: BigUint = FromPrimitive::from_usize(b).unwrap();
  3148. let big_c: BigUint = FromPrimitive::from_usize(c).unwrap();
  3149. assert_eq!(big_a.lcm(&big_b), big_c);
  3150. }
  3151. check(1, 0, 0);
  3152. check(0, 1, 0);
  3153. check(1, 1, 1);
  3154. check(8, 9, 72);
  3155. check(11, 5, 55);
  3156. check(99, 17, 1683);
  3157. }
  3158. #[test]
  3159. fn test_is_even() {
  3160. let one: BigUint = FromStr::from_str("1").unwrap();
  3161. let two: BigUint = FromStr::from_str("2").unwrap();
  3162. let thousand: BigUint = FromStr::from_str("1000").unwrap();
  3163. let big: BigUint = FromStr::from_str("1000000000000000000000").unwrap();
  3164. let bigger: BigUint = FromStr::from_str("1000000000000000000001").unwrap();
  3165. assert!(one.is_odd());
  3166. assert!(two.is_even());
  3167. assert!(thousand.is_even());
  3168. assert!(big.is_even());
  3169. assert!(bigger.is_odd());
  3170. assert!((&one << 64).is_even());
  3171. assert!(((&one << 64) + one).is_odd());
  3172. }
  3173. fn to_str_pairs() -> Vec<(BigUint, Vec<(u32, String)>)> {
  3174. let bits = big_digit::BITS;
  3175. vec!(( Zero::zero(), vec!(
  3176. (2, "0".to_string()), (3, "0".to_string())
  3177. )), ( BigUint::from_slice(&[ 0xff ]), vec!(
  3178. (2, "11111111".to_string()),
  3179. (3, "100110".to_string()),
  3180. (4, "3333".to_string()),
  3181. (5, "2010".to_string()),
  3182. (6, "1103".to_string()),
  3183. (7, "513".to_string()),
  3184. (8, "377".to_string()),
  3185. (9, "313".to_string()),
  3186. (10, "255".to_string()),
  3187. (11, "212".to_string()),
  3188. (12, "193".to_string()),
  3189. (13, "168".to_string()),
  3190. (14, "143".to_string()),
  3191. (15, "120".to_string()),
  3192. (16, "ff".to_string())
  3193. )), ( BigUint::from_slice(&[ 0xfff ]), vec!(
  3194. (2, "111111111111".to_string()),
  3195. (4, "333333".to_string()),
  3196. (16, "fff".to_string())
  3197. )), ( BigUint::from_slice(&[ 1, 2 ]), vec!(
  3198. (2,
  3199. format!("10{}1", repeat("0").take(bits - 1).collect::<String>())),
  3200. (4,
  3201. format!("2{}1", repeat("0").take(bits / 2 - 1).collect::<String>())),
  3202. (10, match bits {
  3203. 32 => "8589934593".to_string(),
  3204. 16 => "131073".to_string(),
  3205. _ => panic!()
  3206. }),
  3207. (16,
  3208. format!("2{}1", repeat("0").take(bits / 4 - 1).collect::<String>()))
  3209. )), ( BigUint::from_slice(&[ 1, 2, 3 ]), vec!(
  3210. (2,
  3211. format!("11{}10{}1",
  3212. repeat("0").take(bits - 2).collect::<String>(),
  3213. repeat("0").take(bits - 1).collect::<String>())),
  3214. (4,
  3215. format!("3{}2{}1",
  3216. repeat("0").take(bits / 2 - 1).collect::<String>(),
  3217. repeat("0").take(bits / 2 - 1).collect::<String>())),
  3218. (8, match bits {
  3219. 32 => "6000000000100000000001".to_string(),
  3220. 16 => "140000400001".to_string(),
  3221. _ => panic!()
  3222. }),
  3223. (10, match bits {
  3224. 32 => "55340232229718589441".to_string(),
  3225. 16 => "12885032961".to_string(),
  3226. _ => panic!()
  3227. }),
  3228. (16,
  3229. format!("3{}2{}1",
  3230. repeat("0").take(bits / 4 - 1).collect::<String>(),
  3231. repeat("0").take(bits / 4 - 1).collect::<String>()))
  3232. )) )
  3233. }
  3234. #[test]
  3235. fn test_to_str_radix() {
  3236. let r = to_str_pairs();
  3237. for num_pair in r.iter() {
  3238. let &(ref n, ref rs) = num_pair;
  3239. for str_pair in rs.iter() {
  3240. let &(ref radix, ref str) = str_pair;
  3241. assert_eq!(n.to_str_radix(*radix), *str);
  3242. }
  3243. }
  3244. }
  3245. #[test]
  3246. fn test_from_str_radix() {
  3247. let r = to_str_pairs();
  3248. for num_pair in r.iter() {
  3249. let &(ref n, ref rs) = num_pair;
  3250. for str_pair in rs.iter() {
  3251. let &(ref radix, ref str) = str_pair;
  3252. assert_eq!(n,
  3253. &BigUint::from_str_radix(str, *radix).unwrap());
  3254. }
  3255. }
  3256. let zed = BigUint::from_str_radix("Z", 10).ok();
  3257. assert_eq!(zed, None);
  3258. let blank = BigUint::from_str_radix("_", 2).ok();
  3259. assert_eq!(blank, None);
  3260. let minus_one = BigUint::from_str_radix("-1", 10).ok();
  3261. assert_eq!(minus_one, None);
  3262. }
  3263. #[test]
  3264. fn test_all_str_radix() {
  3265. use std::ascii::AsciiExt;
  3266. let n = BigUint::new((0..10).collect());
  3267. for radix in 2..37 {
  3268. let s = n.to_str_radix(radix);
  3269. let x = BigUint::from_str_radix(&s, radix);
  3270. assert_eq!(x.unwrap(), n);
  3271. let s = s.to_ascii_uppercase();
  3272. let x = BigUint::from_str_radix(&s, radix);
  3273. assert_eq!(x.unwrap(), n);
  3274. }
  3275. }
  3276. #[test]
  3277. fn test_lower_hex() {
  3278. let a = BigUint::parse_bytes(b"A", 16).unwrap();
  3279. let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap();
  3280. assert_eq!(format!("{:x}", a), "a");
  3281. assert_eq!(format!("{:x}", hello), "48656c6c6f20776f726c6421");
  3282. assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa");
  3283. }
  3284. #[test]
  3285. fn test_upper_hex() {
  3286. let a = BigUint::parse_bytes(b"A", 16).unwrap();
  3287. let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap();
  3288. assert_eq!(format!("{:X}", a), "A");
  3289. assert_eq!(format!("{:X}", hello), "48656C6C6F20776F726C6421");
  3290. assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA");
  3291. }
  3292. #[test]
  3293. fn test_binary() {
  3294. let a = BigUint::parse_bytes(b"A", 16).unwrap();
  3295. let hello = BigUint::parse_bytes("224055342307539".as_bytes(), 10).unwrap();
  3296. assert_eq!(format!("{:b}", a), "1010");
  3297. assert_eq!(format!("{:b}", hello), "110010111100011011110011000101101001100011010011");
  3298. assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010");
  3299. }
  3300. #[test]
  3301. fn test_octal() {
  3302. let a = BigUint::parse_bytes(b"A", 16).unwrap();
  3303. let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap();
  3304. assert_eq!(format!("{:o}", a), "12");
  3305. assert_eq!(format!("{:o}", hello), "22062554330674403566756233062041");
  3306. assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12");
  3307. }
  3308. #[test]
  3309. fn test_display() {
  3310. let a = BigUint::parse_bytes(b"A", 16).unwrap();
  3311. let hello = BigUint::parse_bytes("22405534230753963835153736737".as_bytes(), 10).unwrap();
  3312. assert_eq!(format!("{}", a), "10");
  3313. assert_eq!(format!("{}", hello), "22405534230753963835153736737");
  3314. assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10");
  3315. }
  3316. #[test]
  3317. fn test_factor() {
  3318. fn factor(n: usize) -> BigUint {
  3319. let mut f: BigUint = One::one();
  3320. for i in 2..n + 1 {
  3321. // FIXME(#5992): assignment operator overloads
  3322. // f *= FromPrimitive::from_usize(i);
  3323. let bu: BigUint = FromPrimitive::from_usize(i).unwrap();
  3324. f = f * bu;
  3325. }
  3326. return f;
  3327. }
  3328. fn check(n: usize, s: &str) {
  3329. let n = factor(n);
  3330. let ans = match BigUint::from_str_radix(s, 10) {
  3331. Ok(x) => x, Err(_) => panic!()
  3332. };
  3333. assert_eq!(n, ans);
  3334. }
  3335. check(3, "6");
  3336. check(10, "3628800");
  3337. check(20, "2432902008176640000");
  3338. check(30, "265252859812191058636308480000000");
  3339. }
  3340. #[test]
  3341. fn test_bits() {
  3342. assert_eq!(BigUint::new(vec!(0,0,0,0)).bits(), 0);
  3343. let n: BigUint = FromPrimitive::from_usize(0).unwrap();
  3344. assert_eq!(n.bits(), 0);
  3345. let n: BigUint = FromPrimitive::from_usize(1).unwrap();
  3346. assert_eq!(n.bits(), 1);
  3347. let n: BigUint = FromPrimitive::from_usize(3).unwrap();
  3348. assert_eq!(n.bits(), 2);
  3349. let n: BigUint = BigUint::from_str_radix("4000000000", 16).unwrap();
  3350. assert_eq!(n.bits(), 39);
  3351. let one: BigUint = One::one();
  3352. assert_eq!((one << 426).bits(), 427);
  3353. }
  3354. #[test]
  3355. fn test_rand() {
  3356. let mut rng = thread_rng();
  3357. let _n: BigUint = rng.gen_biguint(137);
  3358. assert!(rng.gen_biguint(0).is_zero());
  3359. }
  3360. #[test]
  3361. fn test_rand_range() {
  3362. let mut rng = thread_rng();
  3363. for _ in 0..10 {
  3364. assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_usize(236).unwrap(),
  3365. &FromPrimitive::from_usize(237).unwrap()),
  3366. FromPrimitive::from_usize(236).unwrap());
  3367. }
  3368. let l = FromPrimitive::from_usize(403469000 + 2352).unwrap();
  3369. let u = FromPrimitive::from_usize(403469000 + 3513).unwrap();
  3370. for _ in 0..1000 {
  3371. let n: BigUint = rng.gen_biguint_below(&u);
  3372. assert!(n < u);
  3373. let n: BigUint = rng.gen_biguint_range(&l, &u);
  3374. assert!(n >= l);
  3375. assert!(n < u);
  3376. }
  3377. }
  3378. #[test]
  3379. #[should_panic]
  3380. fn test_zero_rand_range() {
  3381. thread_rng().gen_biguint_range(&FromPrimitive::from_usize(54).unwrap(),
  3382. &FromPrimitive::from_usize(54).unwrap());
  3383. }
  3384. #[test]
  3385. #[should_panic]
  3386. fn test_negative_rand_range() {
  3387. let mut rng = thread_rng();
  3388. let l = FromPrimitive::from_usize(2352).unwrap();
  3389. let u = FromPrimitive::from_usize(3513).unwrap();
  3390. // Switching u and l should fail:
  3391. let _n: BigUint = rng.gen_biguint_range(&u, &l);
  3392. }
  3393. #[test]
  3394. fn test_sub_sign() {
  3395. use super::sub_sign;
  3396. let a = BigInt::from_str_radix("265252859812191058636308480000000", 10).unwrap();
  3397. let b = BigInt::from_str_radix("26525285981219105863630848000000", 10).unwrap();
  3398. assert_eq!(sub_sign(&a.data.data[..], &b.data.data[..]), &a - &b);
  3399. assert_eq!(sub_sign(&b.data.data[..], &a.data.data[..]), &b - &a);
  3400. }
  3401. fn test_mul_divide_torture_count(count: usize) {
  3402. use rand::{SeedableRng, StdRng, Rng};
  3403. let bits_max = 1 << 12;
  3404. let seed: &[_] = &[1, 2, 3, 4];
  3405. let mut rng: StdRng = SeedableRng::from_seed(seed);
  3406. for _ in 0..count {
  3407. /* Test with numbers of random sizes: */
  3408. let xbits = rng.gen_range(0, bits_max);
  3409. let ybits = rng.gen_range(0, bits_max);
  3410. let x = rng.gen_biguint(xbits);
  3411. let y = rng.gen_biguint(ybits);
  3412. if x.is_zero() || y.is_zero() {
  3413. continue;
  3414. }
  3415. let prod = &x * &y;
  3416. assert_eq!(&prod / &x, y);
  3417. assert_eq!(&prod / &y, x);
  3418. }
  3419. }
  3420. #[test]
  3421. fn test_mul_divide_torture() {
  3422. test_mul_divide_torture_count(1000);
  3423. }
  3424. #[test]
  3425. #[ignore]
  3426. fn test_mul_divide_torture_long() {
  3427. test_mul_divide_torture_count(1000000);
  3428. }
  3429. }
  3430. #[cfg(test)]
  3431. mod bigint_tests {
  3432. use Integer;
  3433. use super::{BigDigit, BigUint, ToBigUint};
  3434. use super::{Sign, BigInt, RandBigInt, ToBigInt, big_digit};
  3435. use super::Sign::{Minus, NoSign, Plus};
  3436. use std::cmp::Ordering::{Less, Equal, Greater};
  3437. use std::{f32, f64};
  3438. use std::{i8, i16, i32, i64, isize};
  3439. use std::iter::repeat;
  3440. use std::{u8, u16, u32, u64, usize};
  3441. use std::ops::{Neg};
  3442. use rand::thread_rng;
  3443. use {Zero, One, Signed, ToPrimitive, FromPrimitive, Num};
  3444. use Float;
  3445. /// Assert that an op works for all val/ref combinations
  3446. macro_rules! assert_op {
  3447. ($left:ident $op:tt $right:ident == $expected:expr) => {
  3448. assert_eq!((&$left) $op (&$right), $expected);
  3449. assert_eq!((&$left) $op $right.clone(), $expected);
  3450. assert_eq!($left.clone() $op (&$right), $expected);
  3451. assert_eq!($left.clone() $op $right.clone(), $expected);
  3452. };
  3453. }
  3454. #[test]
  3455. fn test_from_biguint() {
  3456. fn check(inp_s: Sign, inp_n: usize, ans_s: Sign, ans_n: usize) {
  3457. let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_usize(inp_n).unwrap());
  3458. let ans = BigInt { sign: ans_s, data: FromPrimitive::from_usize(ans_n).unwrap()};
  3459. assert_eq!(inp, ans);
  3460. }
  3461. check(Plus, 1, Plus, 1);
  3462. check(Plus, 0, NoSign, 0);
  3463. check(Minus, 1, Minus, 1);
  3464. check(NoSign, 1, NoSign, 0);
  3465. }
  3466. #[test]
  3467. fn test_from_bytes_be() {
  3468. fn check(s: &str, result: &str) {
  3469. assert_eq!(BigInt::from_bytes_be(Plus, s.as_bytes()),
  3470. BigInt::parse_bytes(result.as_bytes(), 10).unwrap());
  3471. }
  3472. check("A", "65");
  3473. check("AA", "16705");
  3474. check("AB", "16706");
  3475. check("Hello world!", "22405534230753963835153736737");
  3476. assert_eq!(BigInt::from_bytes_be(Plus, &[]), Zero::zero());
  3477. assert_eq!(BigInt::from_bytes_be(Minus, &[]), Zero::zero());
  3478. }
  3479. #[test]
  3480. fn test_to_bytes_be() {
  3481. fn check(s: &str, result: &str) {
  3482. let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap();
  3483. let (sign, v) = b.to_bytes_be();
  3484. assert_eq!((Plus, s.as_bytes()), (sign, &*v));
  3485. }
  3486. check("A", "65");
  3487. check("AA", "16705");
  3488. check("AB", "16706");
  3489. check("Hello world!", "22405534230753963835153736737");
  3490. let b: BigInt = Zero::zero();
  3491. assert_eq!(b.to_bytes_be(), (NoSign, vec![0]));
  3492. // Test with leading/trailing zero bytes and a full BigDigit of value 0
  3493. let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap();
  3494. assert_eq!(b.to_bytes_be(), (Plus, vec![1, 0, 0, 0, 0, 0, 0, 2, 0]));
  3495. }
  3496. #[test]
  3497. fn test_from_bytes_le() {
  3498. fn check(s: &str, result: &str) {
  3499. assert_eq!(BigInt::from_bytes_le(Plus, s.as_bytes()),
  3500. BigInt::parse_bytes(result.as_bytes(), 10).unwrap());
  3501. }
  3502. check("A", "65");
  3503. check("AA", "16705");
  3504. check("BA", "16706");
  3505. check("!dlrow olleH", "22405534230753963835153736737");
  3506. assert_eq!(BigInt::from_bytes_le(Plus, &[]), Zero::zero());
  3507. assert_eq!(BigInt::from_bytes_le(Minus, &[]), Zero::zero());
  3508. }
  3509. #[test]
  3510. fn test_to_bytes_le() {
  3511. fn check(s: &str, result: &str) {
  3512. let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap();
  3513. let (sign, v) = b.to_bytes_le();
  3514. assert_eq!((Plus, s.as_bytes()), (sign, &*v));
  3515. }
  3516. check("A", "65");
  3517. check("AA", "16705");
  3518. check("BA", "16706");
  3519. check("!dlrow olleH", "22405534230753963835153736737");
  3520. let b: BigInt = Zero::zero();
  3521. assert_eq!(b.to_bytes_le(), (NoSign, vec![0]));
  3522. // Test with leading/trailing zero bytes and a full BigDigit of value 0
  3523. let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap();
  3524. assert_eq!(b.to_bytes_le(), (Plus, vec![0, 2, 0, 0, 0, 0, 0, 0, 1]));
  3525. }
  3526. #[test]
  3527. fn test_cmp() {
  3528. let vs: [&[BigDigit]; 4] = [ &[2 as BigDigit], &[1, 1], &[2, 1], &[1, 1, 1] ];
  3529. let mut nums = Vec::new();
  3530. for s in vs.iter().rev() {
  3531. nums.push(BigInt::from_slice(Minus, *s));
  3532. }
  3533. nums.push(Zero::zero());
  3534. nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s)));
  3535. for (i, ni) in nums.iter().enumerate() {
  3536. for (j0, nj) in nums[i..].iter().enumerate() {
  3537. let j = i + j0;
  3538. if i == j {
  3539. assert_eq!(ni.cmp(nj), Equal);
  3540. assert_eq!(nj.cmp(ni), Equal);
  3541. assert_eq!(ni, nj);
  3542. assert!(!(ni != nj));
  3543. assert!(ni <= nj);
  3544. assert!(ni >= nj);
  3545. assert!(!(ni < nj));
  3546. assert!(!(ni > nj));
  3547. } else {
  3548. assert_eq!(ni.cmp(nj), Less);
  3549. assert_eq!(nj.cmp(ni), Greater);
  3550. assert!(!(ni == nj));
  3551. assert!(ni != nj);
  3552. assert!(ni <= nj);
  3553. assert!(!(ni >= nj));
  3554. assert!(ni < nj);
  3555. assert!(!(ni > nj));
  3556. assert!(!(nj <= ni));
  3557. assert!(nj >= ni);
  3558. assert!(!(nj < ni));
  3559. assert!(nj > ni);
  3560. }
  3561. }
  3562. }
  3563. }
  3564. #[test]
  3565. fn test_hash() {
  3566. let a = BigInt::new(NoSign, vec!());
  3567. let b = BigInt::new(NoSign, vec!(0));
  3568. let c = BigInt::new(Plus, vec!(1));
  3569. let d = BigInt::new(Plus, vec!(1,0,0,0,0,0));
  3570. let e = BigInt::new(Plus, vec!(0,0,0,0,0,1));
  3571. let f = BigInt::new(Minus, vec!(1));
  3572. assert!(::hash(&a) == ::hash(&b));
  3573. assert!(::hash(&b) != ::hash(&c));
  3574. assert!(::hash(&c) == ::hash(&d));
  3575. assert!(::hash(&d) != ::hash(&e));
  3576. assert!(::hash(&c) != ::hash(&f));
  3577. }
  3578. #[test]
  3579. fn test_convert_i64() {
  3580. fn check(b1: BigInt, i: i64) {
  3581. let b2: BigInt = FromPrimitive::from_i64(i).unwrap();
  3582. assert!(b1 == b2);
  3583. assert!(b1.to_i64().unwrap() == i);
  3584. }
  3585. check(Zero::zero(), 0);
  3586. check(One::one(), 1);
  3587. check(i64::MIN.to_bigint().unwrap(), i64::MIN);
  3588. check(i64::MAX.to_bigint().unwrap(), i64::MAX);
  3589. assert_eq!(
  3590. (i64::MAX as u64 + 1).to_bigint().unwrap().to_i64(),
  3591. None);
  3592. assert_eq!(
  3593. BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(),
  3594. None);
  3595. assert_eq!(
  3596. BigInt::from_biguint(Minus, BigUint::new(vec!(1,0,0,1<<(big_digit::BITS-1)))).to_i64(),
  3597. None);
  3598. assert_eq!(
  3599. BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(),
  3600. None);
  3601. }
  3602. #[test]
  3603. fn test_convert_u64() {
  3604. fn check(b1: BigInt, u: u64) {
  3605. let b2: BigInt = FromPrimitive::from_u64(u).unwrap();
  3606. assert!(b1 == b2);
  3607. assert!(b1.to_u64().unwrap() == u);
  3608. }
  3609. check(Zero::zero(), 0);
  3610. check(One::one(), 1);
  3611. check(u64::MIN.to_bigint().unwrap(), u64::MIN);
  3612. check(u64::MAX.to_bigint().unwrap(), u64::MAX);
  3613. assert_eq!(
  3614. BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(),
  3615. None);
  3616. let max_value: BigUint = FromPrimitive::from_u64(u64::MAX).unwrap();
  3617. assert_eq!(BigInt::from_biguint(Minus, max_value).to_u64(), None);
  3618. assert_eq!(BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(), None);
  3619. }
  3620. #[test]
  3621. fn test_convert_f32() {
  3622. fn check(b1: &BigInt, f: f32) {
  3623. let b2 = BigInt::from_f32(f).unwrap();
  3624. assert_eq!(b1, &b2);
  3625. assert_eq!(b1.to_f32().unwrap(), f);
  3626. let neg_b1 = -b1;
  3627. let neg_b2 = BigInt::from_f32(-f).unwrap();
  3628. assert_eq!(neg_b1, neg_b2);
  3629. assert_eq!(neg_b1.to_f32().unwrap(), -f);
  3630. }
  3631. check(&BigInt::zero(), 0.0);
  3632. check(&BigInt::one(), 1.0);
  3633. check(&BigInt::from(u16::MAX), 2.0.powi(16) - 1.0);
  3634. check(&BigInt::from(1u64 << 32), 2.0.powi(32));
  3635. check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64));
  3636. check(&((BigInt::one() << 100) + (BigInt::one() << 123)), 2.0.powi(100) + 2.0.powi(123));
  3637. check(&(BigInt::one() << 127), 2.0.powi(127));
  3638. check(&(BigInt::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX);
  3639. // keeping all 24 digits with the bits at different offsets to the BigDigits
  3640. let x: u32 = 0b00000000101111011111011011011101;
  3641. let mut f = x as f32;
  3642. let mut b = BigInt::from(x);
  3643. for _ in 0..64 {
  3644. check(&b, f);
  3645. f *= 2.0;
  3646. b = b << 1;
  3647. }
  3648. // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32
  3649. let mut n: i64 = 0b0000000000111111111111111111111111011111111111111111111111111111;
  3650. assert!((n as f64) as f32 != n as f32);
  3651. assert_eq!(BigInt::from(n).to_f32(), Some(n as f32));
  3652. n = -n;
  3653. assert!((n as f64) as f32 != n as f32);
  3654. assert_eq!(BigInt::from(n).to_f32(), Some(n as f32));
  3655. // test rounding up with the bits at different offsets to the BigDigits
  3656. let mut f = ((1u64 << 25) - 1) as f32;
  3657. let mut b = BigInt::from(1u64 << 25);
  3658. for _ in 0..64 {
  3659. assert_eq!(b.to_f32(), Some(f));
  3660. f *= 2.0;
  3661. b = b << 1;
  3662. }
  3663. // rounding
  3664. assert_eq!(BigInt::from_f32(-f32::consts::PI), Some(BigInt::from(-3i32)));
  3665. assert_eq!(BigInt::from_f32(-f32::consts::E), Some(BigInt::from(-2i32)));
  3666. assert_eq!(BigInt::from_f32(-0.99999), Some(BigInt::zero()));
  3667. assert_eq!(BigInt::from_f32(-0.5), Some(BigInt::zero()));
  3668. assert_eq!(BigInt::from_f32(-0.0), Some(BigInt::zero()));
  3669. assert_eq!(BigInt::from_f32(f32::MIN_POSITIVE / 2.0), Some(BigInt::zero()));
  3670. assert_eq!(BigInt::from_f32(f32::MIN_POSITIVE), Some(BigInt::zero()));
  3671. assert_eq!(BigInt::from_f32(0.5), Some(BigInt::zero()));
  3672. assert_eq!(BigInt::from_f32(0.99999), Some(BigInt::zero()));
  3673. assert_eq!(BigInt::from_f32(f32::consts::E), Some(BigInt::from(2u32)));
  3674. assert_eq!(BigInt::from_f32(f32::consts::PI), Some(BigInt::from(3u32)));
  3675. // special float values
  3676. assert_eq!(BigInt::from_f32(f32::NAN), None);
  3677. assert_eq!(BigInt::from_f32(f32::INFINITY), None);
  3678. assert_eq!(BigInt::from_f32(f32::NEG_INFINITY), None);
  3679. // largest BigInt that will round to a finite f32 value
  3680. let big_num = (BigInt::one() << 128) - BigInt::one() - (BigInt::one() << (128 - 25));
  3681. assert_eq!(big_num.to_f32(), Some(f32::MAX));
  3682. assert_eq!((&big_num + BigInt::one()).to_f32(), None);
  3683. assert_eq!((-&big_num).to_f32(), Some(f32::MIN));
  3684. assert_eq!(((-&big_num) - BigInt::one()).to_f32(), None);
  3685. assert_eq!(((BigInt::one() << 128) - BigInt::one()).to_f32(), None);
  3686. assert_eq!((BigInt::one() << 128).to_f32(), None);
  3687. assert_eq!((-((BigInt::one() << 128) - BigInt::one())).to_f32(), None);
  3688. assert_eq!((-(BigInt::one() << 128)).to_f32(), None);
  3689. }
  3690. #[test]
  3691. fn test_convert_f64() {
  3692. fn check(b1: &BigInt, f: f64) {
  3693. let b2 = BigInt::from_f64(f).unwrap();
  3694. assert_eq!(b1, &b2);
  3695. assert_eq!(b1.to_f64().unwrap(), f);
  3696. let neg_b1 = -b1;
  3697. let neg_b2 = BigInt::from_f64(-f).unwrap();
  3698. assert_eq!(neg_b1, neg_b2);
  3699. assert_eq!(neg_b1.to_f64().unwrap(), -f);
  3700. }
  3701. check(&BigInt::zero(), 0.0);
  3702. check(&BigInt::one(), 1.0);
  3703. check(&BigInt::from(u32::MAX), 2.0.powi(32) - 1.0);
  3704. check(&BigInt::from(1u64 << 32), 2.0.powi(32));
  3705. check(&BigInt::from_slice(Plus, &[0, 0, 1]), 2.0.powi(64));
  3706. check(&((BigInt::one() << 100) + (BigInt::one() << 152)), 2.0.powi(100) + 2.0.powi(152));
  3707. check(&(BigInt::one() << 1023), 2.0.powi(1023));
  3708. check(&(BigInt::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX);
  3709. // keeping all 53 digits with the bits at different offsets to the BigDigits
  3710. let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101;
  3711. let mut f = x as f64;
  3712. let mut b = BigInt::from(x);
  3713. for _ in 0..128 {
  3714. check(&b, f);
  3715. f *= 2.0;
  3716. b = b << 1;
  3717. }
  3718. // test rounding up with the bits at different offsets to the BigDigits
  3719. let mut f = ((1u64 << 54) - 1) as f64;
  3720. let mut b = BigInt::from(1u64 << 54);
  3721. for _ in 0..128 {
  3722. assert_eq!(b.to_f64(), Some(f));
  3723. f *= 2.0;
  3724. b = b << 1;
  3725. }
  3726. // rounding
  3727. assert_eq!(BigInt::from_f64(-f64::consts::PI), Some(BigInt::from(-3i32)));
  3728. assert_eq!(BigInt::from_f64(-f64::consts::E), Some(BigInt::from(-2i32)));
  3729. assert_eq!(BigInt::from_f64(-0.99999), Some(BigInt::zero()));
  3730. assert_eq!(BigInt::from_f64(-0.5), Some(BigInt::zero()));
  3731. assert_eq!(BigInt::from_f64(-0.0), Some(BigInt::zero()));
  3732. assert_eq!(BigInt::from_f64(f64::MIN_POSITIVE / 2.0), Some(BigInt::zero()));
  3733. assert_eq!(BigInt::from_f64(f64::MIN_POSITIVE), Some(BigInt::zero()));
  3734. assert_eq!(BigInt::from_f64(0.5), Some(BigInt::zero()));
  3735. assert_eq!(BigInt::from_f64(0.99999), Some(BigInt::zero()));
  3736. assert_eq!(BigInt::from_f64(f64::consts::E), Some(BigInt::from(2u32)));
  3737. assert_eq!(BigInt::from_f64(f64::consts::PI), Some(BigInt::from(3u32)));
  3738. // special float values
  3739. assert_eq!(BigInt::from_f64(f64::NAN), None);
  3740. assert_eq!(BigInt::from_f64(f64::INFINITY), None);
  3741. assert_eq!(BigInt::from_f64(f64::NEG_INFINITY), None);
  3742. // largest BigInt that will round to a finite f64 value
  3743. let big_num = (BigInt::one() << 1024) - BigInt::one() - (BigInt::one() << (1024 - 54));
  3744. assert_eq!(big_num.to_f64(), Some(f64::MAX));
  3745. assert_eq!((&big_num + BigInt::one()).to_f64(), None);
  3746. assert_eq!((-&big_num).to_f64(), Some(f64::MIN));
  3747. assert_eq!(((-&big_num) - BigInt::one()).to_f64(), None);
  3748. assert_eq!(((BigInt::one() << 1024) - BigInt::one()).to_f64(), None);
  3749. assert_eq!((BigInt::one() << 1024).to_f64(), None);
  3750. assert_eq!((-((BigInt::one() << 1024) - BigInt::one())).to_f64(), None);
  3751. assert_eq!((-(BigInt::one() << 1024)).to_f64(), None);
  3752. }
  3753. #[test]
  3754. fn test_convert_to_biguint() {
  3755. fn check(n: BigInt, ans_1: BigUint) {
  3756. assert_eq!(n.to_biguint().unwrap(), ans_1);
  3757. assert_eq!(n.to_biguint().unwrap().to_bigint().unwrap(), n);
  3758. }
  3759. let zero: BigInt = Zero::zero();
  3760. let unsigned_zero: BigUint = Zero::zero();
  3761. let positive = BigInt::from_biguint(
  3762. Plus, BigUint::new(vec!(1,2,3)));
  3763. let negative = -&positive;
  3764. check(zero, unsigned_zero);
  3765. check(positive, BigUint::new(vec!(1,2,3)));
  3766. assert_eq!(negative.to_biguint(), None);
  3767. }
  3768. #[test]
  3769. fn test_convert_from_uint() {
  3770. macro_rules! check {
  3771. ($ty:ident, $max:expr) => {
  3772. assert_eq!(BigInt::from($ty::zero()), BigInt::zero());
  3773. assert_eq!(BigInt::from($ty::one()), BigInt::one());
  3774. assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one());
  3775. assert_eq!(BigInt::from($ty::MAX), $max);
  3776. }
  3777. }
  3778. check!(u8, BigInt::from_slice(Plus, &[u8::MAX as BigDigit]));
  3779. check!(u16, BigInt::from_slice(Plus, &[u16::MAX as BigDigit]));
  3780. check!(u32, BigInt::from_slice(Plus, &[u32::MAX as BigDigit]));
  3781. check!(u64, BigInt::from_slice(Plus, &[u32::MAX as BigDigit, u32::MAX as BigDigit]));
  3782. check!(usize, BigInt::from(usize::MAX as u64));
  3783. }
  3784. #[test]
  3785. fn test_convert_from_int() {
  3786. macro_rules! check {
  3787. ($ty:ident, $min:expr, $max:expr) => {
  3788. assert_eq!(BigInt::from($ty::MIN), $min);
  3789. assert_eq!(BigInt::from($ty::MIN + $ty::one()), $min + BigInt::one());
  3790. assert_eq!(BigInt::from(-$ty::one()), -BigInt::one());
  3791. assert_eq!(BigInt::from($ty::zero()), BigInt::zero());
  3792. assert_eq!(BigInt::from($ty::one()), BigInt::one());
  3793. assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one());
  3794. assert_eq!(BigInt::from($ty::MAX), $max);
  3795. }
  3796. }
  3797. check!(i8, BigInt::from_slice(Minus, &[1 << 7]),
  3798. BigInt::from_slice(Plus, &[i8::MAX as BigDigit]));
  3799. check!(i16, BigInt::from_slice(Minus, &[1 << 15]),
  3800. BigInt::from_slice(Plus, &[i16::MAX as BigDigit]));
  3801. check!(i32, BigInt::from_slice(Minus, &[1 << 31]),
  3802. BigInt::from_slice(Plus, &[i32::MAX as BigDigit]));
  3803. check!(i64, BigInt::from_slice(Minus, &[0, 1 << 31]),
  3804. BigInt::from_slice(Plus, &[u32::MAX as BigDigit, i32::MAX as BigDigit]));
  3805. check!(isize, BigInt::from(isize::MIN as i64),
  3806. BigInt::from(isize::MAX as i64));
  3807. }
  3808. #[test]
  3809. fn test_convert_from_biguint() {
  3810. assert_eq!(BigInt::from(BigUint::zero()), BigInt::zero());
  3811. assert_eq!(BigInt::from(BigUint::one()), BigInt::one());
  3812. assert_eq!(BigInt::from(BigUint::from_slice(&[1, 2, 3])), BigInt::from_slice(Plus, &[1, 2, 3]));
  3813. }
  3814. const N1: BigDigit = -1i32 as BigDigit;
  3815. const N2: BigDigit = -2i32 as BigDigit;
  3816. const SUM_TRIPLES: &'static [(&'static [BigDigit],
  3817. &'static [BigDigit],
  3818. &'static [BigDigit])] = &[
  3819. (&[], &[], &[]),
  3820. (&[], &[ 1], &[ 1]),
  3821. (&[ 1], &[ 1], &[ 2]),
  3822. (&[ 1], &[ 1, 1], &[ 2, 1]),
  3823. (&[ 1], &[N1], &[ 0, 1]),
  3824. (&[ 1], &[N1, N1], &[ 0, 0, 1]),
  3825. (&[N1, N1], &[N1, N1], &[N2, N1, 1]),
  3826. (&[ 1, 1, 1], &[N1, N1], &[ 0, 1, 2]),
  3827. (&[ 2, 2, 1], &[N1, N2], &[ 1, 1, 2])
  3828. ];
  3829. #[test]
  3830. fn test_add() {
  3831. for elm in SUM_TRIPLES.iter() {
  3832. let (a_vec, b_vec, c_vec) = *elm;
  3833. let a = BigInt::from_slice(Plus, a_vec);
  3834. let b = BigInt::from_slice(Plus, b_vec);
  3835. let c = BigInt::from_slice(Plus, c_vec);
  3836. let (na, nb, nc) = (-&a, -&b, -&c);
  3837. assert_op!(a + b == c);
  3838. assert_op!(b + a == c);
  3839. assert_op!(c + na == b);
  3840. assert_op!(c + nb == a);
  3841. assert_op!(a + nc == nb);
  3842. assert_op!(b + nc == na);
  3843. assert_op!(na + nb == nc);
  3844. assert_op!(a + na == Zero::zero());
  3845. }
  3846. }
  3847. #[test]
  3848. fn test_sub() {
  3849. for elm in SUM_TRIPLES.iter() {
  3850. let (a_vec, b_vec, c_vec) = *elm;
  3851. let a = BigInt::from_slice(Plus, a_vec);
  3852. let b = BigInt::from_slice(Plus, b_vec);
  3853. let c = BigInt::from_slice(Plus, c_vec);
  3854. let (na, nb, nc) = (-&a, -&b, -&c);
  3855. assert_op!(c - a == b);
  3856. assert_op!(c - b == a);
  3857. assert_op!(nb - a == nc);
  3858. assert_op!(na - b == nc);
  3859. assert_op!(b - na == c);
  3860. assert_op!(a - nb == c);
  3861. assert_op!(nc - na == nb);
  3862. assert_op!(a - a == Zero::zero());
  3863. }
  3864. }
  3865. const M: u32 = ::std::u32::MAX;
  3866. static MUL_TRIPLES: &'static [(&'static [BigDigit],
  3867. &'static [BigDigit],
  3868. &'static [BigDigit])] = &[
  3869. (&[], &[], &[]),
  3870. (&[], &[ 1], &[]),
  3871. (&[ 2], &[], &[]),
  3872. (&[ 1], &[ 1], &[1]),
  3873. (&[ 2], &[ 3], &[ 6]),
  3874. (&[ 1], &[ 1, 1, 1], &[1, 1, 1]),
  3875. (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]),
  3876. (&[ 1, 1, 1], &[N1], &[N1, N1, N1]),
  3877. (&[ 1, 2, 3], &[N1], &[N1, N2, N2, 2]),
  3878. (&[ 1, 2, 3, 4], &[N1], &[N1, N2, N2, N2, 3]),
  3879. (&[N1], &[N1], &[ 1, N2]),
  3880. (&[N1, N1], &[N1], &[ 1, N1, N2]),
  3881. (&[N1, N1, N1], &[N1], &[ 1, N1, N1, N2]),
  3882. (&[N1, N1, N1, N1], &[N1], &[ 1, N1, N1, N1, N2]),
  3883. (&[ M/2 + 1], &[ 2], &[ 0, 1]),
  3884. (&[0, M/2 + 1], &[ 2], &[ 0, 0, 1]),
  3885. (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]),
  3886. (&[N1, N1], &[N1, N1, N1], &[1, 0, N1, N2, N1]),
  3887. (&[N1, N1, N1], &[N1, N1, N1, N1], &[1, 0, 0, N1, N2, N1, N1]),
  3888. (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]),
  3889. (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])
  3890. ];
  3891. static DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit],
  3892. &'static [BigDigit],
  3893. &'static [BigDigit],
  3894. &'static [BigDigit])]
  3895. = &[
  3896. (&[ 1], &[ 2], &[], &[1]),
  3897. (&[ 1, 1], &[ 2], &[ M/2+1], &[1]),
  3898. (&[ 1, 1, 1], &[ 2], &[ M/2+1, M/2+1], &[1]),
  3899. (&[ 0, 1], &[N1], &[1], &[1]),
  3900. (&[N1, N1], &[N2], &[2, 1], &[3])
  3901. ];
  3902. #[test]
  3903. fn test_mul() {
  3904. for elm in MUL_TRIPLES.iter() {
  3905. let (a_vec, b_vec, c_vec) = *elm;
  3906. let a = BigInt::from_slice(Plus, a_vec);
  3907. let b = BigInt::from_slice(Plus, b_vec);
  3908. let c = BigInt::from_slice(Plus, c_vec);
  3909. let (na, nb, nc) = (-&a, -&b, -&c);
  3910. assert_op!(a * b == c);
  3911. assert_op!(b * a == c);
  3912. assert_op!(na * nb == c);
  3913. assert_op!(na * b == nc);
  3914. assert_op!(nb * a == nc);
  3915. }
  3916. for elm in DIV_REM_QUADRUPLES.iter() {
  3917. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  3918. let a = BigInt::from_slice(Plus, a_vec);
  3919. let b = BigInt::from_slice(Plus, b_vec);
  3920. let c = BigInt::from_slice(Plus, c_vec);
  3921. let d = BigInt::from_slice(Plus, d_vec);
  3922. assert!(a == &b * &c + &d);
  3923. assert!(a == &c * &b + &d);
  3924. }
  3925. }
  3926. #[test]
  3927. fn test_div_mod_floor() {
  3928. fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) {
  3929. let (d, m) = a.div_mod_floor(b);
  3930. if !m.is_zero() {
  3931. assert_eq!(m.sign, b.sign);
  3932. }
  3933. assert!(m.abs() <= b.abs());
  3934. assert!(*a == b * &d + &m);
  3935. assert!(d == *ans_d);
  3936. assert!(m == *ans_m);
  3937. }
  3938. fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) {
  3939. if m.is_zero() {
  3940. check_sub(a, b, d, m);
  3941. check_sub(a, &b.neg(), &d.neg(), m);
  3942. check_sub(&a.neg(), b, &d.neg(), m);
  3943. check_sub(&a.neg(), &b.neg(), d, m);
  3944. } else {
  3945. let one: BigInt = One::one();
  3946. check_sub(a, b, d, m);
  3947. check_sub(a, &b.neg(), &(d.neg() - &one), &(m - b));
  3948. check_sub(&a.neg(), b, &(d.neg() - &one), &(b - m));
  3949. check_sub(&a.neg(), &b.neg(), d, &m.neg());
  3950. }
  3951. }
  3952. for elm in MUL_TRIPLES.iter() {
  3953. let (a_vec, b_vec, c_vec) = *elm;
  3954. let a = BigInt::from_slice(Plus, a_vec);
  3955. let b = BigInt::from_slice(Plus, b_vec);
  3956. let c = BigInt::from_slice(Plus, c_vec);
  3957. if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); }
  3958. if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); }
  3959. }
  3960. for elm in DIV_REM_QUADRUPLES.iter() {
  3961. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  3962. let a = BigInt::from_slice(Plus, a_vec);
  3963. let b = BigInt::from_slice(Plus, b_vec);
  3964. let c = BigInt::from_slice(Plus, c_vec);
  3965. let d = BigInt::from_slice(Plus, d_vec);
  3966. if !b.is_zero() {
  3967. check(&a, &b, &c, &d);
  3968. }
  3969. }
  3970. }
  3971. #[test]
  3972. fn test_div_rem() {
  3973. fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) {
  3974. let (q, r) = a.div_rem(b);
  3975. if !r.is_zero() {
  3976. assert_eq!(r.sign, a.sign);
  3977. }
  3978. assert!(r.abs() <= b.abs());
  3979. assert!(*a == b * &q + &r);
  3980. assert!(q == *ans_q);
  3981. assert!(r == *ans_r);
  3982. let (a, b, ans_q, ans_r) = (a.clone(), b.clone(), ans_q.clone(), ans_r.clone());
  3983. assert_op!(a / b == ans_q);
  3984. assert_op!(a % b == ans_r);
  3985. }
  3986. fn check(a: &BigInt, b: &BigInt, q: &BigInt, r: &BigInt) {
  3987. check_sub(a, b, q, r);
  3988. check_sub(a, &b.neg(), &q.neg(), r);
  3989. check_sub(&a.neg(), b, &q.neg(), &r.neg());
  3990. check_sub(&a.neg(), &b.neg(), q, &r.neg());
  3991. }
  3992. for elm in MUL_TRIPLES.iter() {
  3993. let (a_vec, b_vec, c_vec) = *elm;
  3994. let a = BigInt::from_slice(Plus, a_vec);
  3995. let b = BigInt::from_slice(Plus, b_vec);
  3996. let c = BigInt::from_slice(Plus, c_vec);
  3997. if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); }
  3998. if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); }
  3999. }
  4000. for elm in DIV_REM_QUADRUPLES.iter() {
  4001. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  4002. let a = BigInt::from_slice(Plus, a_vec);
  4003. let b = BigInt::from_slice(Plus, b_vec);
  4004. let c = BigInt::from_slice(Plus, c_vec);
  4005. let d = BigInt::from_slice(Plus, d_vec);
  4006. if !b.is_zero() {
  4007. check(&a, &b, &c, &d);
  4008. }
  4009. }
  4010. }
  4011. #[test]
  4012. fn test_checked_add() {
  4013. for elm in SUM_TRIPLES.iter() {
  4014. let (a_vec, b_vec, c_vec) = *elm;
  4015. let a = BigInt::from_slice(Plus, a_vec);
  4016. let b = BigInt::from_slice(Plus, b_vec);
  4017. let c = BigInt::from_slice(Plus, c_vec);
  4018. assert!(a.checked_add(&b).unwrap() == c);
  4019. assert!(b.checked_add(&a).unwrap() == c);
  4020. assert!(c.checked_add(&(-&a)).unwrap() == b);
  4021. assert!(c.checked_add(&(-&b)).unwrap() == a);
  4022. assert!(a.checked_add(&(-&c)).unwrap() == (-&b));
  4023. assert!(b.checked_add(&(-&c)).unwrap() == (-&a));
  4024. assert!((-&a).checked_add(&(-&b)).unwrap() == (-&c));
  4025. assert!(a.checked_add(&(-&a)).unwrap() == Zero::zero());
  4026. }
  4027. }
  4028. #[test]
  4029. fn test_checked_sub() {
  4030. for elm in SUM_TRIPLES.iter() {
  4031. let (a_vec, b_vec, c_vec) = *elm;
  4032. let a = BigInt::from_slice(Plus, a_vec);
  4033. let b = BigInt::from_slice(Plus, b_vec);
  4034. let c = BigInt::from_slice(Plus, c_vec);
  4035. assert!(c.checked_sub(&a).unwrap() == b);
  4036. assert!(c.checked_sub(&b).unwrap() == a);
  4037. assert!((-&b).checked_sub(&a).unwrap() == (-&c));
  4038. assert!((-&a).checked_sub(&b).unwrap() == (-&c));
  4039. assert!(b.checked_sub(&(-&a)).unwrap() == c);
  4040. assert!(a.checked_sub(&(-&b)).unwrap() == c);
  4041. assert!((-&c).checked_sub(&(-&a)).unwrap() == (-&b));
  4042. assert!(a.checked_sub(&a).unwrap() == Zero::zero());
  4043. }
  4044. }
  4045. #[test]
  4046. fn test_checked_mul() {
  4047. for elm in MUL_TRIPLES.iter() {
  4048. let (a_vec, b_vec, c_vec) = *elm;
  4049. let a = BigInt::from_slice(Plus, a_vec);
  4050. let b = BigInt::from_slice(Plus, b_vec);
  4051. let c = BigInt::from_slice(Plus, c_vec);
  4052. assert!(a.checked_mul(&b).unwrap() == c);
  4053. assert!(b.checked_mul(&a).unwrap() == c);
  4054. assert!((-&a).checked_mul(&b).unwrap() == -&c);
  4055. assert!((-&b).checked_mul(&a).unwrap() == -&c);
  4056. }
  4057. for elm in DIV_REM_QUADRUPLES.iter() {
  4058. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  4059. let a = BigInt::from_slice(Plus, a_vec);
  4060. let b = BigInt::from_slice(Plus, b_vec);
  4061. let c = BigInt::from_slice(Plus, c_vec);
  4062. let d = BigInt::from_slice(Plus, d_vec);
  4063. assert!(a == b.checked_mul(&c).unwrap() + &d);
  4064. assert!(a == c.checked_mul(&b).unwrap() + &d);
  4065. }
  4066. }
  4067. #[test]
  4068. fn test_checked_div() {
  4069. for elm in MUL_TRIPLES.iter() {
  4070. let (a_vec, b_vec, c_vec) = *elm;
  4071. let a = BigInt::from_slice(Plus, a_vec);
  4072. let b = BigInt::from_slice(Plus, b_vec);
  4073. let c = BigInt::from_slice(Plus, c_vec);
  4074. if !a.is_zero() {
  4075. assert!(c.checked_div(&a).unwrap() == b);
  4076. assert!((-&c).checked_div(&(-&a)).unwrap() == b);
  4077. assert!((-&c).checked_div(&a).unwrap() == -&b);
  4078. }
  4079. if !b.is_zero() {
  4080. assert!(c.checked_div(&b).unwrap() == a);
  4081. assert!((-&c).checked_div(&(-&b)).unwrap() == a);
  4082. assert!((-&c).checked_div(&b).unwrap() == -&a);
  4083. }
  4084. assert!(c.checked_div(&Zero::zero()).is_none());
  4085. assert!((-&c).checked_div(&Zero::zero()).is_none());
  4086. }
  4087. }
  4088. #[test]
  4089. fn test_gcd() {
  4090. fn check(a: isize, b: isize, c: isize) {
  4091. let big_a: BigInt = FromPrimitive::from_isize(a).unwrap();
  4092. let big_b: BigInt = FromPrimitive::from_isize(b).unwrap();
  4093. let big_c: BigInt = FromPrimitive::from_isize(c).unwrap();
  4094. assert_eq!(big_a.gcd(&big_b), big_c);
  4095. }
  4096. check(10, 2, 2);
  4097. check(10, 3, 1);
  4098. check(0, 3, 3);
  4099. check(3, 3, 3);
  4100. check(56, 42, 14);
  4101. check(3, -3, 3);
  4102. check(-6, 3, 3);
  4103. check(-4, -2, 2);
  4104. }
  4105. #[test]
  4106. fn test_lcm() {
  4107. fn check(a: isize, b: isize, c: isize) {
  4108. let big_a: BigInt = FromPrimitive::from_isize(a).unwrap();
  4109. let big_b: BigInt = FromPrimitive::from_isize(b).unwrap();
  4110. let big_c: BigInt = FromPrimitive::from_isize(c).unwrap();
  4111. assert_eq!(big_a.lcm(&big_b), big_c);
  4112. }
  4113. check(1, 0, 0);
  4114. check(0, 1, 0);
  4115. check(1, 1, 1);
  4116. check(-1, 1, 1);
  4117. check(1, -1, 1);
  4118. check(-1, -1, 1);
  4119. check(8, 9, 72);
  4120. check(11, 5, 55);
  4121. }
  4122. #[test]
  4123. fn test_abs_sub() {
  4124. let zero: BigInt = Zero::zero();
  4125. let one: BigInt = One::one();
  4126. assert_eq!((-&one).abs_sub(&one), zero);
  4127. let one: BigInt = One::one();
  4128. let zero: BigInt = Zero::zero();
  4129. assert_eq!(one.abs_sub(&one), zero);
  4130. let one: BigInt = One::one();
  4131. let zero: BigInt = Zero::zero();
  4132. assert_eq!(one.abs_sub(&zero), one);
  4133. let one: BigInt = One::one();
  4134. let two: BigInt = FromPrimitive::from_isize(2).unwrap();
  4135. assert_eq!(one.abs_sub(&-&one), two);
  4136. }
  4137. #[test]
  4138. fn test_from_str_radix() {
  4139. fn check(s: &str, ans: Option<isize>) {
  4140. let ans = ans.map(|n| {
  4141. let x: BigInt = FromPrimitive::from_isize(n).unwrap();
  4142. x
  4143. });
  4144. assert_eq!(BigInt::from_str_radix(s, 10).ok(), ans);
  4145. }
  4146. check("10", Some(10));
  4147. check("1", Some(1));
  4148. check("0", Some(0));
  4149. check("-1", Some(-1));
  4150. check("-10", Some(-10));
  4151. check("Z", None);
  4152. check("_", None);
  4153. // issue 10522, this hit an edge case that caused it to
  4154. // attempt to allocate a vector of size (-1u) == huge.
  4155. let x: BigInt =
  4156. format!("1{}", repeat("0").take(36).collect::<String>()).parse().unwrap();
  4157. let _y = x.to_string();
  4158. }
  4159. #[test]
  4160. fn test_lower_hex() {
  4161. let a = BigInt::parse_bytes(b"A", 16).unwrap();
  4162. let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap();
  4163. assert_eq!(format!("{:x}", a), "a");
  4164. assert_eq!(format!("{:x}", hello), "-48656c6c6f20776f726c6421");
  4165. assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa");
  4166. }
  4167. #[test]
  4168. fn test_upper_hex() {
  4169. let a = BigInt::parse_bytes(b"A", 16).unwrap();
  4170. let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap();
  4171. assert_eq!(format!("{:X}", a), "A");
  4172. assert_eq!(format!("{:X}", hello), "-48656C6C6F20776F726C6421");
  4173. assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA");
  4174. }
  4175. #[test]
  4176. fn test_binary() {
  4177. let a = BigInt::parse_bytes(b"A", 16).unwrap();
  4178. let hello = BigInt::parse_bytes("-224055342307539".as_bytes(), 10).unwrap();
  4179. assert_eq!(format!("{:b}", a), "1010");
  4180. assert_eq!(format!("{:b}", hello), "-110010111100011011110011000101101001100011010011");
  4181. assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010");
  4182. }
  4183. #[test]
  4184. fn test_octal() {
  4185. let a = BigInt::parse_bytes(b"A", 16).unwrap();
  4186. let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap();
  4187. assert_eq!(format!("{:o}", a), "12");
  4188. assert_eq!(format!("{:o}", hello), "-22062554330674403566756233062041");
  4189. assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12");
  4190. }
  4191. #[test]
  4192. fn test_display() {
  4193. let a = BigInt::parse_bytes(b"A", 16).unwrap();
  4194. let hello = BigInt::parse_bytes("-22405534230753963835153736737".as_bytes(), 10).unwrap();
  4195. assert_eq!(format!("{}", a), "10");
  4196. assert_eq!(format!("{}", hello), "-22405534230753963835153736737");
  4197. assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10");
  4198. }
  4199. #[test]
  4200. fn test_neg() {
  4201. assert!(-BigInt::new(Plus, vec!(1, 1, 1)) ==
  4202. BigInt::new(Minus, vec!(1, 1, 1)));
  4203. assert!(-BigInt::new(Minus, vec!(1, 1, 1)) ==
  4204. BigInt::new(Plus, vec!(1, 1, 1)));
  4205. let zero: BigInt = Zero::zero();
  4206. assert_eq!(-&zero, zero);
  4207. }
  4208. #[test]
  4209. fn test_rand() {
  4210. let mut rng = thread_rng();
  4211. let _n: BigInt = rng.gen_bigint(137);
  4212. assert!(rng.gen_bigint(0).is_zero());
  4213. }
  4214. #[test]
  4215. fn test_rand_range() {
  4216. let mut rng = thread_rng();
  4217. for _ in 0..10 {
  4218. assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_usize(236).unwrap(),
  4219. &FromPrimitive::from_usize(237).unwrap()),
  4220. FromPrimitive::from_usize(236).unwrap());
  4221. }
  4222. fn check(l: BigInt, u: BigInt) {
  4223. let mut rng = thread_rng();
  4224. for _ in 0..1000 {
  4225. let n: BigInt = rng.gen_bigint_range(&l, &u);
  4226. assert!(n >= l);
  4227. assert!(n < u);
  4228. }
  4229. }
  4230. let l: BigInt = FromPrimitive::from_usize(403469000 + 2352).unwrap();
  4231. let u: BigInt = FromPrimitive::from_usize(403469000 + 3513).unwrap();
  4232. check( l.clone(), u.clone());
  4233. check(-l.clone(), u.clone());
  4234. check(-u.clone(), -l.clone());
  4235. }
  4236. #[test]
  4237. #[should_panic]
  4238. fn test_zero_rand_range() {
  4239. thread_rng().gen_bigint_range(&FromPrimitive::from_isize(54).unwrap(),
  4240. &FromPrimitive::from_isize(54).unwrap());
  4241. }
  4242. #[test]
  4243. #[should_panic]
  4244. fn test_negative_rand_range() {
  4245. let mut rng = thread_rng();
  4246. let l = FromPrimitive::from_usize(2352).unwrap();
  4247. let u = FromPrimitive::from_usize(3513).unwrap();
  4248. // Switching u and l should fail:
  4249. let _n: BigInt = rng.gen_bigint_range(&u, &l);
  4250. }
  4251. }