bigint.rs 154 KB

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