longobject.c 199 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392
  1. /* Long (arbitrary precision) integer object implementation */
  2. /* XXX The functional organization of this file is terrible */
  3. #include "Python.h"
  4. #include "pycore_bitutils.h" // _Py_popcount32()
  5. #include "pycore_initconfig.h" // _PyStatus_OK()
  6. #include "pycore_long.h" // _Py_SmallInts
  7. #include "pycore_object.h" // _PyObject_Init()
  8. #include "pycore_runtime.h" // _PY_NSMALLPOSINTS
  9. #include "pycore_structseq.h" // _PyStructSequence_FiniBuiltin()
  10. #include <ctype.h>
  11. #include <float.h>
  12. #include <stddef.h>
  13. #include <stdlib.h> // abs()
  14. #include "clinic/longobject.c.h"
  15. /*[clinic input]
  16. class int "PyObject *" "&PyLong_Type"
  17. [clinic start generated code]*/
  18. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=ec0275e3422a36e3]*/
  19. #define medium_value(x) ((stwodigits)_PyLong_CompactValue(x))
  20. #define IS_SMALL_INT(ival) (-_PY_NSMALLNEGINTS <= (ival) && (ival) < _PY_NSMALLPOSINTS)
  21. #define IS_SMALL_UINT(ival) ((ival) < _PY_NSMALLPOSINTS)
  22. #define _MAX_STR_DIGITS_ERROR_FMT_TO_INT "Exceeds the limit (%d digits) for integer string conversion: value has %zd digits; use sys.set_int_max_str_digits() to increase the limit"
  23. #define _MAX_STR_DIGITS_ERROR_FMT_TO_STR "Exceeds the limit (%d digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit"
  24. /* If defined, use algorithms from the _pylong.py module */
  25. #define WITH_PYLONG_MODULE 1
  26. static inline void
  27. _Py_DECREF_INT(PyLongObject *op)
  28. {
  29. assert(PyLong_CheckExact(op));
  30. _Py_DECREF_SPECIALIZED((PyObject *)op, (destructor)PyObject_Free);
  31. }
  32. static inline int
  33. is_medium_int(stwodigits x)
  34. {
  35. /* Take care that we are comparing unsigned values. */
  36. twodigits x_plus_mask = ((twodigits)x) + PyLong_MASK;
  37. return x_plus_mask < ((twodigits)PyLong_MASK) + PyLong_BASE;
  38. }
  39. static PyObject *
  40. get_small_int(sdigit ival)
  41. {
  42. assert(IS_SMALL_INT(ival));
  43. return (PyObject *)&_PyLong_SMALL_INTS[_PY_NSMALLNEGINTS + ival];
  44. }
  45. static PyLongObject *
  46. maybe_small_long(PyLongObject *v)
  47. {
  48. if (v && _PyLong_IsCompact(v)) {
  49. stwodigits ival = medium_value(v);
  50. if (IS_SMALL_INT(ival)) {
  51. _Py_DECREF_INT(v);
  52. return (PyLongObject *)get_small_int((sdigit)ival);
  53. }
  54. }
  55. return v;
  56. }
  57. /* For int multiplication, use the O(N**2) school algorithm unless
  58. * both operands contain more than KARATSUBA_CUTOFF digits (this
  59. * being an internal Python int digit, in base BASE).
  60. */
  61. #define KARATSUBA_CUTOFF 70
  62. #define KARATSUBA_SQUARE_CUTOFF (2 * KARATSUBA_CUTOFF)
  63. /* For exponentiation, use the binary left-to-right algorithm unless the
  64. ^ exponent contains more than HUGE_EXP_CUTOFF bits. In that case, do
  65. * (no more than) EXP_WINDOW_SIZE bits at a time. The potential drawback is
  66. * that a table of 2**(EXP_WINDOW_SIZE - 1) intermediate results is
  67. * precomputed.
  68. */
  69. #define EXP_WINDOW_SIZE 5
  70. #define EXP_TABLE_LEN (1 << (EXP_WINDOW_SIZE - 1))
  71. /* Suppose the exponent has bit length e. All ways of doing this
  72. * need e squarings. The binary method also needs a multiply for
  73. * each bit set. In a k-ary method with window width w, a multiply
  74. * for each non-zero window, so at worst (and likely!)
  75. * ceiling(e/w). The k-ary sliding window method has the same
  76. * worst case, but the window slides so it can sometimes skip
  77. * over an all-zero window that the fixed-window method can't
  78. * exploit. In addition, the windowing methods need multiplies
  79. * to precompute a table of small powers.
  80. *
  81. * For the sliding window method with width 5, 16 precomputation
  82. * multiplies are needed. Assuming about half the exponent bits
  83. * are set, then, the binary method needs about e/2 extra mults
  84. * and the window method about 16 + e/5.
  85. *
  86. * The latter is smaller for e > 53 1/3. We don't have direct
  87. * access to the bit length, though, so call it 60, which is a
  88. * multiple of a long digit's max bit length (15 or 30 so far).
  89. */
  90. #define HUGE_EXP_CUTOFF 60
  91. #define SIGCHECK(PyTryBlock) \
  92. do { \
  93. if (PyErr_CheckSignals()) PyTryBlock \
  94. } while(0)
  95. /* Normalize (remove leading zeros from) an int object.
  96. Doesn't attempt to free the storage--in most cases, due to the nature
  97. of the algorithms used, this could save at most be one word anyway. */
  98. static PyLongObject *
  99. long_normalize(PyLongObject *v)
  100. {
  101. Py_ssize_t j = _PyLong_DigitCount(v);
  102. Py_ssize_t i = j;
  103. while (i > 0 && v->long_value.ob_digit[i-1] == 0)
  104. --i;
  105. if (i != j) {
  106. if (i == 0) {
  107. _PyLong_SetSignAndDigitCount(v, 0, 0);
  108. }
  109. else {
  110. _PyLong_SetDigitCount(v, i);
  111. }
  112. }
  113. return v;
  114. }
  115. /* Allocate a new int object with size digits.
  116. Return NULL and set exception if we run out of memory. */
  117. #define MAX_LONG_DIGITS \
  118. ((PY_SSIZE_T_MAX - offsetof(PyLongObject, long_value.ob_digit))/sizeof(digit))
  119. PyLongObject *
  120. _PyLong_New(Py_ssize_t size)
  121. {
  122. assert(size >= 0);
  123. PyLongObject *result;
  124. if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
  125. PyErr_SetString(PyExc_OverflowError,
  126. "too many digits in integer");
  127. return NULL;
  128. }
  129. /* Fast operations for single digit integers (including zero)
  130. * assume that there is always at least one digit present. */
  131. Py_ssize_t ndigits = size ? size : 1;
  132. /* Number of bytes needed is: offsetof(PyLongObject, ob_digit) +
  133. sizeof(digit)*size. Previous incarnations of this code used
  134. sizeof() instead of the offsetof, but this risks being
  135. incorrect in the presence of padding between the header
  136. and the digits. */
  137. result = PyObject_Malloc(offsetof(PyLongObject, long_value.ob_digit) +
  138. ndigits*sizeof(digit));
  139. if (!result) {
  140. PyErr_NoMemory();
  141. return NULL;
  142. }
  143. _PyLong_SetSignAndDigitCount(result, size != 0, size);
  144. _PyObject_Init((PyObject*)result, &PyLong_Type);
  145. /* The digit has to be initialized explicitly to avoid
  146. * use-of-uninitialized-value. */
  147. result->long_value.ob_digit[0] = 0;
  148. return result;
  149. }
  150. PyLongObject *
  151. _PyLong_FromDigits(int negative, Py_ssize_t digit_count, digit *digits)
  152. {
  153. assert(digit_count >= 0);
  154. if (digit_count == 0) {
  155. return (PyLongObject *)Py_NewRef(_PyLong_GetZero());
  156. }
  157. PyLongObject *result = _PyLong_New(digit_count);
  158. if (result == NULL) {
  159. PyErr_NoMemory();
  160. return NULL;
  161. }
  162. _PyLong_SetSignAndDigitCount(result, negative?-1:1, digit_count);
  163. memcpy(result->long_value.ob_digit, digits, digit_count * sizeof(digit));
  164. return result;
  165. }
  166. PyObject *
  167. _PyLong_Copy(PyLongObject *src)
  168. {
  169. assert(src != NULL);
  170. if (_PyLong_IsCompact(src)) {
  171. stwodigits ival = medium_value(src);
  172. if (IS_SMALL_INT(ival)) {
  173. return get_small_int((sdigit)ival);
  174. }
  175. }
  176. Py_ssize_t size = _PyLong_DigitCount(src);
  177. return (PyObject *)_PyLong_FromDigits(_PyLong_IsNegative(src), size, src->long_value.ob_digit);
  178. }
  179. static PyObject *
  180. _PyLong_FromMedium(sdigit x)
  181. {
  182. assert(!IS_SMALL_INT(x));
  183. assert(is_medium_int(x));
  184. /* We could use a freelist here */
  185. PyLongObject *v = PyObject_Malloc(sizeof(PyLongObject));
  186. if (v == NULL) {
  187. PyErr_NoMemory();
  188. return NULL;
  189. }
  190. digit abs_x = x < 0 ? -x : x;
  191. _PyLong_SetSignAndDigitCount(v, x<0?-1:1, 1);
  192. _PyObject_Init((PyObject*)v, &PyLong_Type);
  193. v->long_value.ob_digit[0] = abs_x;
  194. return (PyObject*)v;
  195. }
  196. static PyObject *
  197. _PyLong_FromLarge(stwodigits ival)
  198. {
  199. twodigits abs_ival;
  200. int sign;
  201. assert(!is_medium_int(ival));
  202. if (ival < 0) {
  203. /* negate: can't write this as abs_ival = -ival since that
  204. invokes undefined behaviour when ival is LONG_MIN */
  205. abs_ival = 0U-(twodigits)ival;
  206. sign = -1;
  207. }
  208. else {
  209. abs_ival = (twodigits)ival;
  210. sign = 1;
  211. }
  212. /* Must be at least two digits */
  213. assert(abs_ival >> PyLong_SHIFT != 0);
  214. twodigits t = abs_ival >> (PyLong_SHIFT * 2);
  215. Py_ssize_t ndigits = 2;
  216. while (t) {
  217. ++ndigits;
  218. t >>= PyLong_SHIFT;
  219. }
  220. PyLongObject *v = _PyLong_New(ndigits);
  221. if (v != NULL) {
  222. digit *p = v->long_value.ob_digit;
  223. _PyLong_SetSignAndDigitCount(v, sign, ndigits);
  224. t = abs_ival;
  225. while (t) {
  226. *p++ = Py_SAFE_DOWNCAST(
  227. t & PyLong_MASK, twodigits, digit);
  228. t >>= PyLong_SHIFT;
  229. }
  230. }
  231. return (PyObject *)v;
  232. }
  233. /* Create a new int object from a C word-sized int */
  234. static inline PyObject *
  235. _PyLong_FromSTwoDigits(stwodigits x)
  236. {
  237. if (IS_SMALL_INT(x)) {
  238. return get_small_int((sdigit)x);
  239. }
  240. assert(x != 0);
  241. if (is_medium_int(x)) {
  242. return _PyLong_FromMedium((sdigit)x);
  243. }
  244. return _PyLong_FromLarge(x);
  245. }
  246. /* If a freshly-allocated int is already shared, it must
  247. be a small integer, so negating it must go to PyLong_FromLong */
  248. Py_LOCAL_INLINE(void)
  249. _PyLong_Negate(PyLongObject **x_p)
  250. {
  251. PyLongObject *x;
  252. x = (PyLongObject *)*x_p;
  253. if (Py_REFCNT(x) == 1) {
  254. _PyLong_FlipSign(x);
  255. return;
  256. }
  257. *x_p = (PyLongObject *)_PyLong_FromSTwoDigits(-medium_value(x));
  258. Py_DECREF(x);
  259. }
  260. /* Create a new int object from a C long int */
  261. PyObject *
  262. PyLong_FromLong(long ival)
  263. {
  264. PyLongObject *v;
  265. unsigned long abs_ival, t;
  266. int ndigits;
  267. /* Handle small and medium cases. */
  268. if (IS_SMALL_INT(ival)) {
  269. return get_small_int((sdigit)ival);
  270. }
  271. if (-(long)PyLong_MASK <= ival && ival <= (long)PyLong_MASK) {
  272. return _PyLong_FromMedium((sdigit)ival);
  273. }
  274. /* Count digits (at least two - smaller cases were handled above). */
  275. abs_ival = ival < 0 ? 0U-(unsigned long)ival : (unsigned long)ival;
  276. /* Do shift in two steps to avoid possible undefined behavior. */
  277. t = abs_ival >> PyLong_SHIFT >> PyLong_SHIFT;
  278. ndigits = 2;
  279. while (t) {
  280. ++ndigits;
  281. t >>= PyLong_SHIFT;
  282. }
  283. /* Construct output value. */
  284. v = _PyLong_New(ndigits);
  285. if (v != NULL) {
  286. digit *p = v->long_value.ob_digit;
  287. _PyLong_SetSignAndDigitCount(v, ival < 0 ? -1 : 1, ndigits);
  288. t = abs_ival;
  289. while (t) {
  290. *p++ = (digit)(t & PyLong_MASK);
  291. t >>= PyLong_SHIFT;
  292. }
  293. }
  294. return (PyObject *)v;
  295. }
  296. #define PYLONG_FROM_UINT(INT_TYPE, ival) \
  297. do { \
  298. if (IS_SMALL_UINT(ival)) { \
  299. return get_small_int((sdigit)(ival)); \
  300. } \
  301. /* Count the number of Python digits. */ \
  302. Py_ssize_t ndigits = 0; \
  303. INT_TYPE t = (ival); \
  304. while (t) { \
  305. ++ndigits; \
  306. t >>= PyLong_SHIFT; \
  307. } \
  308. PyLongObject *v = _PyLong_New(ndigits); \
  309. if (v == NULL) { \
  310. return NULL; \
  311. } \
  312. digit *p = v->long_value.ob_digit; \
  313. while ((ival)) { \
  314. *p++ = (digit)((ival) & PyLong_MASK); \
  315. (ival) >>= PyLong_SHIFT; \
  316. } \
  317. return (PyObject *)v; \
  318. } while(0)
  319. /* Create a new int object from a C unsigned long int */
  320. PyObject *
  321. PyLong_FromUnsignedLong(unsigned long ival)
  322. {
  323. PYLONG_FROM_UINT(unsigned long, ival);
  324. }
  325. /* Create a new int object from a C unsigned long long int. */
  326. PyObject *
  327. PyLong_FromUnsignedLongLong(unsigned long long ival)
  328. {
  329. PYLONG_FROM_UINT(unsigned long long, ival);
  330. }
  331. /* Create a new int object from a C size_t. */
  332. PyObject *
  333. PyLong_FromSize_t(size_t ival)
  334. {
  335. PYLONG_FROM_UINT(size_t, ival);
  336. }
  337. /* Create a new int object from a C double */
  338. PyObject *
  339. PyLong_FromDouble(double dval)
  340. {
  341. /* Try to get out cheap if this fits in a long. When a finite value of real
  342. * floating type is converted to an integer type, the value is truncated
  343. * toward zero. If the value of the integral part cannot be represented by
  344. * the integer type, the behavior is undefined. Thus, we must check that
  345. * value is in range (LONG_MIN - 1, LONG_MAX + 1). If a long has more bits
  346. * of precision than a double, casting LONG_MIN - 1 to double may yield an
  347. * approximation, but LONG_MAX + 1 is a power of two and can be represented
  348. * as double exactly (assuming FLT_RADIX is 2 or 16), so for simplicity
  349. * check against [-(LONG_MAX + 1), LONG_MAX + 1).
  350. */
  351. const double int_max = (unsigned long)LONG_MAX + 1;
  352. if (-int_max < dval && dval < int_max) {
  353. return PyLong_FromLong((long)dval);
  354. }
  355. PyLongObject *v;
  356. double frac;
  357. int i, ndig, expo, neg;
  358. neg = 0;
  359. if (Py_IS_INFINITY(dval)) {
  360. PyErr_SetString(PyExc_OverflowError,
  361. "cannot convert float infinity to integer");
  362. return NULL;
  363. }
  364. if (Py_IS_NAN(dval)) {
  365. PyErr_SetString(PyExc_ValueError,
  366. "cannot convert float NaN to integer");
  367. return NULL;
  368. }
  369. if (dval < 0.0) {
  370. neg = 1;
  371. dval = -dval;
  372. }
  373. frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
  374. assert(expo > 0);
  375. ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
  376. v = _PyLong_New(ndig);
  377. if (v == NULL)
  378. return NULL;
  379. frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
  380. for (i = ndig; --i >= 0; ) {
  381. digit bits = (digit)frac;
  382. v->long_value.ob_digit[i] = bits;
  383. frac = frac - (double)bits;
  384. frac = ldexp(frac, PyLong_SHIFT);
  385. }
  386. if (neg) {
  387. _PyLong_FlipSign(v);
  388. }
  389. return (PyObject *)v;
  390. }
  391. /* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
  392. * anything about what happens when a signed integer operation overflows,
  393. * and some compilers think they're doing you a favor by being "clever"
  394. * then. The bit pattern for the largest positive signed long is
  395. * (unsigned long)LONG_MAX, and for the smallest negative signed long
  396. * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
  397. * However, some other compilers warn about applying unary minus to an
  398. * unsigned operand. Hence the weird "0-".
  399. */
  400. #define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
  401. #define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
  402. /* Get a C long int from an int object or any object that has an __index__
  403. method.
  404. On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
  405. the result. Otherwise *overflow is 0.
  406. For other errors (e.g., TypeError), return -1 and set an error condition.
  407. In this case *overflow will be 0.
  408. */
  409. long
  410. PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
  411. {
  412. /* This version by Tim Peters */
  413. PyLongObject *v;
  414. unsigned long x, prev;
  415. long res;
  416. Py_ssize_t i;
  417. int sign;
  418. int do_decref = 0; /* if PyNumber_Index was called */
  419. *overflow = 0;
  420. if (vv == NULL) {
  421. PyErr_BadInternalCall();
  422. return -1;
  423. }
  424. if (PyLong_Check(vv)) {
  425. v = (PyLongObject *)vv;
  426. }
  427. else {
  428. v = (PyLongObject *)_PyNumber_Index(vv);
  429. if (v == NULL)
  430. return -1;
  431. do_decref = 1;
  432. }
  433. if (_PyLong_IsCompact(v)) {
  434. #if SIZEOF_LONG < SIZEOF_VOID_P
  435. intptr_t tmp = _PyLong_CompactValue(v);
  436. res = (long)tmp;
  437. if (res != tmp) {
  438. *overflow = tmp < 0 ? -1 : 1;
  439. }
  440. #else
  441. res = _PyLong_CompactValue(v);
  442. #endif
  443. }
  444. else {
  445. res = -1;
  446. i = _PyLong_DigitCount(v);
  447. sign = _PyLong_NonCompactSign(v);
  448. x = 0;
  449. while (--i >= 0) {
  450. prev = x;
  451. x = (x << PyLong_SHIFT) | v->long_value.ob_digit[i];
  452. if ((x >> PyLong_SHIFT) != prev) {
  453. *overflow = sign;
  454. goto exit;
  455. }
  456. }
  457. /* Haven't lost any bits, but casting to long requires extra
  458. * care (see comment above).
  459. */
  460. if (x <= (unsigned long)LONG_MAX) {
  461. res = (long)x * sign;
  462. }
  463. else if (sign < 0 && x == PY_ABS_LONG_MIN) {
  464. res = LONG_MIN;
  465. }
  466. else {
  467. *overflow = sign;
  468. /* res is already set to -1 */
  469. }
  470. }
  471. exit:
  472. if (do_decref) {
  473. Py_DECREF(v);
  474. }
  475. return res;
  476. }
  477. /* Get a C long int from an int object or any object that has an __index__
  478. method. Return -1 and set an error if overflow occurs. */
  479. long
  480. PyLong_AsLong(PyObject *obj)
  481. {
  482. int overflow;
  483. long result = PyLong_AsLongAndOverflow(obj, &overflow);
  484. if (overflow) {
  485. /* XXX: could be cute and give a different
  486. message for overflow == -1 */
  487. PyErr_SetString(PyExc_OverflowError,
  488. "Python int too large to convert to C long");
  489. }
  490. return result;
  491. }
  492. /* Get a C int from an int object or any object that has an __index__
  493. method. Return -1 and set an error if overflow occurs. */
  494. int
  495. _PyLong_AsInt(PyObject *obj)
  496. {
  497. int overflow;
  498. long result = PyLong_AsLongAndOverflow(obj, &overflow);
  499. if (overflow || result > INT_MAX || result < INT_MIN) {
  500. /* XXX: could be cute and give a different
  501. message for overflow == -1 */
  502. PyErr_SetString(PyExc_OverflowError,
  503. "Python int too large to convert to C int");
  504. return -1;
  505. }
  506. return (int)result;
  507. }
  508. /* Get a Py_ssize_t from an int object.
  509. Returns -1 and sets an error condition if overflow occurs. */
  510. Py_ssize_t
  511. PyLong_AsSsize_t(PyObject *vv) {
  512. PyLongObject *v;
  513. size_t x, prev;
  514. Py_ssize_t i;
  515. int sign;
  516. if (vv == NULL) {
  517. PyErr_BadInternalCall();
  518. return -1;
  519. }
  520. if (!PyLong_Check(vv)) {
  521. PyErr_SetString(PyExc_TypeError, "an integer is required");
  522. return -1;
  523. }
  524. v = (PyLongObject *)vv;
  525. if (_PyLong_IsCompact(v)) {
  526. return _PyLong_CompactValue(v);
  527. }
  528. i = _PyLong_DigitCount(v);
  529. sign = _PyLong_NonCompactSign(v);
  530. x = 0;
  531. while (--i >= 0) {
  532. prev = x;
  533. x = (x << PyLong_SHIFT) | v->long_value.ob_digit[i];
  534. if ((x >> PyLong_SHIFT) != prev)
  535. goto overflow;
  536. }
  537. /* Haven't lost any bits, but casting to a signed type requires
  538. * extra care (see comment above).
  539. */
  540. if (x <= (size_t)PY_SSIZE_T_MAX) {
  541. return (Py_ssize_t)x * sign;
  542. }
  543. else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
  544. return PY_SSIZE_T_MIN;
  545. }
  546. /* else overflow */
  547. overflow:
  548. PyErr_SetString(PyExc_OverflowError,
  549. "Python int too large to convert to C ssize_t");
  550. return -1;
  551. }
  552. /* Get a C unsigned long int from an int object.
  553. Returns -1 and sets an error condition if overflow occurs. */
  554. unsigned long
  555. PyLong_AsUnsignedLong(PyObject *vv)
  556. {
  557. PyLongObject *v;
  558. unsigned long x, prev;
  559. Py_ssize_t i;
  560. if (vv == NULL) {
  561. PyErr_BadInternalCall();
  562. return (unsigned long)-1;
  563. }
  564. if (!PyLong_Check(vv)) {
  565. PyErr_SetString(PyExc_TypeError, "an integer is required");
  566. return (unsigned long)-1;
  567. }
  568. v = (PyLongObject *)vv;
  569. if (_PyLong_IsNonNegativeCompact(v)) {
  570. #if SIZEOF_LONG < SIZEOF_VOID_P
  571. intptr_t tmp = _PyLong_CompactValue(v);
  572. unsigned long res = (unsigned long)tmp;
  573. if (res != tmp) {
  574. goto overflow;
  575. }
  576. #else
  577. return _PyLong_CompactValue(v);
  578. #endif
  579. }
  580. if (_PyLong_IsNegative(v)) {
  581. PyErr_SetString(PyExc_OverflowError,
  582. "can't convert negative value to unsigned int");
  583. return (unsigned long) -1;
  584. }
  585. i = _PyLong_DigitCount(v);
  586. x = 0;
  587. while (--i >= 0) {
  588. prev = x;
  589. x = (x << PyLong_SHIFT) | v->long_value.ob_digit[i];
  590. if ((x >> PyLong_SHIFT) != prev) {
  591. goto overflow;
  592. }
  593. }
  594. return x;
  595. overflow:
  596. PyErr_SetString(PyExc_OverflowError,
  597. "Python int too large to convert "
  598. "to C unsigned long");
  599. return (unsigned long) -1;
  600. }
  601. /* Get a C size_t from an int object. Returns (size_t)-1 and sets
  602. an error condition if overflow occurs. */
  603. size_t
  604. PyLong_AsSize_t(PyObject *vv)
  605. {
  606. PyLongObject *v;
  607. size_t x, prev;
  608. Py_ssize_t i;
  609. if (vv == NULL) {
  610. PyErr_BadInternalCall();
  611. return (size_t) -1;
  612. }
  613. if (!PyLong_Check(vv)) {
  614. PyErr_SetString(PyExc_TypeError, "an integer is required");
  615. return (size_t)-1;
  616. }
  617. v = (PyLongObject *)vv;
  618. if (_PyLong_IsNonNegativeCompact(v)) {
  619. return _PyLong_CompactValue(v);
  620. }
  621. if (_PyLong_IsNegative(v)) {
  622. PyErr_SetString(PyExc_OverflowError,
  623. "can't convert negative value to size_t");
  624. return (size_t) -1;
  625. }
  626. i = _PyLong_DigitCount(v);
  627. x = 0;
  628. while (--i >= 0) {
  629. prev = x;
  630. x = (x << PyLong_SHIFT) | v->long_value.ob_digit[i];
  631. if ((x >> PyLong_SHIFT) != prev) {
  632. PyErr_SetString(PyExc_OverflowError,
  633. "Python int too large to convert to C size_t");
  634. return (size_t) -1;
  635. }
  636. }
  637. return x;
  638. }
  639. /* Get a C unsigned long int from an int object, ignoring the high bits.
  640. Returns -1 and sets an error condition if an error occurs. */
  641. static unsigned long
  642. _PyLong_AsUnsignedLongMask(PyObject *vv)
  643. {
  644. PyLongObject *v;
  645. unsigned long x;
  646. Py_ssize_t i;
  647. if (vv == NULL || !PyLong_Check(vv)) {
  648. PyErr_BadInternalCall();
  649. return (unsigned long) -1;
  650. }
  651. v = (PyLongObject *)vv;
  652. if (_PyLong_IsCompact(v)) {
  653. return (unsigned long)_PyLong_CompactValue(v);
  654. }
  655. i = _PyLong_DigitCount(v);
  656. int sign = _PyLong_NonCompactSign(v);
  657. x = 0;
  658. while (--i >= 0) {
  659. x = (x << PyLong_SHIFT) | v->long_value.ob_digit[i];
  660. }
  661. return x * sign;
  662. }
  663. unsigned long
  664. PyLong_AsUnsignedLongMask(PyObject *op)
  665. {
  666. PyLongObject *lo;
  667. unsigned long val;
  668. if (op == NULL) {
  669. PyErr_BadInternalCall();
  670. return (unsigned long)-1;
  671. }
  672. if (PyLong_Check(op)) {
  673. return _PyLong_AsUnsignedLongMask(op);
  674. }
  675. lo = (PyLongObject *)_PyNumber_Index(op);
  676. if (lo == NULL)
  677. return (unsigned long)-1;
  678. val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
  679. Py_DECREF(lo);
  680. return val;
  681. }
  682. int
  683. _PyLong_Sign(PyObject *vv)
  684. {
  685. PyLongObject *v = (PyLongObject *)vv;
  686. assert(v != NULL);
  687. assert(PyLong_Check(v));
  688. if (_PyLong_IsCompact(v)) {
  689. return _PyLong_CompactSign(v);
  690. }
  691. return _PyLong_NonCompactSign(v);
  692. }
  693. static int
  694. bit_length_digit(digit x)
  695. {
  696. // digit can be larger than unsigned long, but only PyLong_SHIFT bits
  697. // of it will be ever used.
  698. static_assert(PyLong_SHIFT <= sizeof(unsigned long) * 8,
  699. "digit is larger than unsigned long");
  700. return _Py_bit_length((unsigned long)x);
  701. }
  702. size_t
  703. _PyLong_NumBits(PyObject *vv)
  704. {
  705. PyLongObject *v = (PyLongObject *)vv;
  706. size_t result = 0;
  707. Py_ssize_t ndigits;
  708. int msd_bits;
  709. assert(v != NULL);
  710. assert(PyLong_Check(v));
  711. ndigits = _PyLong_DigitCount(v);
  712. assert(ndigits == 0 || v->long_value.ob_digit[ndigits - 1] != 0);
  713. if (ndigits > 0) {
  714. digit msd = v->long_value.ob_digit[ndigits - 1];
  715. if ((size_t)(ndigits - 1) > SIZE_MAX / (size_t)PyLong_SHIFT)
  716. goto Overflow;
  717. result = (size_t)(ndigits - 1) * (size_t)PyLong_SHIFT;
  718. msd_bits = bit_length_digit(msd);
  719. if (SIZE_MAX - msd_bits < result)
  720. goto Overflow;
  721. result += msd_bits;
  722. }
  723. return result;
  724. Overflow:
  725. PyErr_SetString(PyExc_OverflowError, "int has too many bits "
  726. "to express in a platform size_t");
  727. return (size_t)-1;
  728. }
  729. PyObject *
  730. _PyLong_FromByteArray(const unsigned char* bytes, size_t n,
  731. int little_endian, int is_signed)
  732. {
  733. const unsigned char* pstartbyte; /* LSB of bytes */
  734. int incr; /* direction to move pstartbyte */
  735. const unsigned char* pendbyte; /* MSB of bytes */
  736. size_t numsignificantbytes; /* number of bytes that matter */
  737. Py_ssize_t ndigits; /* number of Python int digits */
  738. PyLongObject* v; /* result */
  739. Py_ssize_t idigit = 0; /* next free index in v->long_value.ob_digit */
  740. if (n == 0)
  741. return PyLong_FromLong(0L);
  742. if (little_endian) {
  743. pstartbyte = bytes;
  744. pendbyte = bytes + n - 1;
  745. incr = 1;
  746. }
  747. else {
  748. pstartbyte = bytes + n - 1;
  749. pendbyte = bytes;
  750. incr = -1;
  751. }
  752. if (is_signed)
  753. is_signed = *pendbyte >= 0x80;
  754. /* Compute numsignificantbytes. This consists of finding the most
  755. significant byte. Leading 0 bytes are insignificant if the number
  756. is positive, and leading 0xff bytes if negative. */
  757. {
  758. size_t i;
  759. const unsigned char* p = pendbyte;
  760. const int pincr = -incr; /* search MSB to LSB */
  761. const unsigned char insignificant = is_signed ? 0xff : 0x00;
  762. for (i = 0; i < n; ++i, p += pincr) {
  763. if (*p != insignificant)
  764. break;
  765. }
  766. numsignificantbytes = n - i;
  767. /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
  768. actually has 2 significant bytes. OTOH, 0xff0001 ==
  769. -0x00ffff, so we wouldn't *need* to bump it there; but we
  770. do for 0xffff = -0x0001. To be safe without bothering to
  771. check every case, bump it regardless. */
  772. if (is_signed && numsignificantbytes < n)
  773. ++numsignificantbytes;
  774. }
  775. /* How many Python int digits do we need? We have
  776. 8*numsignificantbytes bits, and each Python int digit has
  777. PyLong_SHIFT bits, so it's the ceiling of the quotient. */
  778. /* catch overflow before it happens */
  779. if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
  780. PyErr_SetString(PyExc_OverflowError,
  781. "byte array too long to convert to int");
  782. return NULL;
  783. }
  784. ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
  785. v = _PyLong_New(ndigits);
  786. if (v == NULL)
  787. return NULL;
  788. /* Copy the bits over. The tricky parts are computing 2's-comp on
  789. the fly for signed numbers, and dealing with the mismatch between
  790. 8-bit bytes and (probably) 15-bit Python digits.*/
  791. {
  792. size_t i;
  793. twodigits carry = 1; /* for 2's-comp calculation */
  794. twodigits accum = 0; /* sliding register */
  795. unsigned int accumbits = 0; /* number of bits in accum */
  796. const unsigned char* p = pstartbyte;
  797. for (i = 0; i < numsignificantbytes; ++i, p += incr) {
  798. twodigits thisbyte = *p;
  799. /* Compute correction for 2's comp, if needed. */
  800. if (is_signed) {
  801. thisbyte = (0xff ^ thisbyte) + carry;
  802. carry = thisbyte >> 8;
  803. thisbyte &= 0xff;
  804. }
  805. /* Because we're going LSB to MSB, thisbyte is
  806. more significant than what's already in accum,
  807. so needs to be prepended to accum. */
  808. accum |= thisbyte << accumbits;
  809. accumbits += 8;
  810. if (accumbits >= PyLong_SHIFT) {
  811. /* There's enough to fill a Python digit. */
  812. assert(idigit < ndigits);
  813. v->long_value.ob_digit[idigit] = (digit)(accum & PyLong_MASK);
  814. ++idigit;
  815. accum >>= PyLong_SHIFT;
  816. accumbits -= PyLong_SHIFT;
  817. assert(accumbits < PyLong_SHIFT);
  818. }
  819. }
  820. assert(accumbits < PyLong_SHIFT);
  821. if (accumbits) {
  822. assert(idigit < ndigits);
  823. v->long_value.ob_digit[idigit] = (digit)accum;
  824. ++idigit;
  825. }
  826. }
  827. int sign = is_signed ? -1: 1;
  828. if (idigit == 0) {
  829. sign = 0;
  830. }
  831. _PyLong_SetSignAndDigitCount(v, sign, idigit);
  832. return (PyObject *)maybe_small_long(long_normalize(v));
  833. }
  834. int
  835. _PyLong_AsByteArray(PyLongObject* v,
  836. unsigned char* bytes, size_t n,
  837. int little_endian, int is_signed)
  838. {
  839. Py_ssize_t i; /* index into v->long_value.ob_digit */
  840. Py_ssize_t ndigits; /* number of digits */
  841. twodigits accum; /* sliding register */
  842. unsigned int accumbits; /* # bits in accum */
  843. int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
  844. digit carry; /* for computing 2's-comp */
  845. size_t j; /* # bytes filled */
  846. unsigned char* p; /* pointer to next byte in bytes */
  847. int pincr; /* direction to move p */
  848. assert(v != NULL && PyLong_Check(v));
  849. ndigits = _PyLong_DigitCount(v);
  850. if (_PyLong_IsNegative(v)) {
  851. if (!is_signed) {
  852. PyErr_SetString(PyExc_OverflowError,
  853. "can't convert negative int to unsigned");
  854. return -1;
  855. }
  856. do_twos_comp = 1;
  857. }
  858. else {
  859. do_twos_comp = 0;
  860. }
  861. if (little_endian) {
  862. p = bytes;
  863. pincr = 1;
  864. }
  865. else {
  866. p = bytes + n - 1;
  867. pincr = -1;
  868. }
  869. /* Copy over all the Python digits.
  870. It's crucial that every Python digit except for the MSD contribute
  871. exactly PyLong_SHIFT bits to the total, so first assert that the int is
  872. normalized. */
  873. assert(ndigits == 0 || v->long_value.ob_digit[ndigits - 1] != 0);
  874. j = 0;
  875. accum = 0;
  876. accumbits = 0;
  877. carry = do_twos_comp ? 1 : 0;
  878. for (i = 0; i < ndigits; ++i) {
  879. digit thisdigit = v->long_value.ob_digit[i];
  880. if (do_twos_comp) {
  881. thisdigit = (thisdigit ^ PyLong_MASK) + carry;
  882. carry = thisdigit >> PyLong_SHIFT;
  883. thisdigit &= PyLong_MASK;
  884. }
  885. /* Because we're going LSB to MSB, thisdigit is more
  886. significant than what's already in accum, so needs to be
  887. prepended to accum. */
  888. accum |= (twodigits)thisdigit << accumbits;
  889. /* The most-significant digit may be (probably is) at least
  890. partly empty. */
  891. if (i == ndigits - 1) {
  892. /* Count # of sign bits -- they needn't be stored,
  893. * although for signed conversion we need later to
  894. * make sure at least one sign bit gets stored. */
  895. digit s = do_twos_comp ? thisdigit ^ PyLong_MASK : thisdigit;
  896. while (s != 0) {
  897. s >>= 1;
  898. accumbits++;
  899. }
  900. }
  901. else
  902. accumbits += PyLong_SHIFT;
  903. /* Store as many bytes as possible. */
  904. while (accumbits >= 8) {
  905. if (j >= n)
  906. goto Overflow;
  907. ++j;
  908. *p = (unsigned char)(accum & 0xff);
  909. p += pincr;
  910. accumbits -= 8;
  911. accum >>= 8;
  912. }
  913. }
  914. /* Store the straggler (if any). */
  915. assert(accumbits < 8);
  916. assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
  917. if (accumbits > 0) {
  918. if (j >= n)
  919. goto Overflow;
  920. ++j;
  921. if (do_twos_comp) {
  922. /* Fill leading bits of the byte with sign bits
  923. (appropriately pretending that the int had an
  924. infinite supply of sign bits). */
  925. accum |= (~(twodigits)0) << accumbits;
  926. }
  927. *p = (unsigned char)(accum & 0xff);
  928. p += pincr;
  929. }
  930. else if (j == n && n > 0 && is_signed) {
  931. /* The main loop filled the byte array exactly, so the code
  932. just above didn't get to ensure there's a sign bit, and the
  933. loop below wouldn't add one either. Make sure a sign bit
  934. exists. */
  935. unsigned char msb = *(p - pincr);
  936. int sign_bit_set = msb >= 0x80;
  937. assert(accumbits == 0);
  938. if (sign_bit_set == do_twos_comp)
  939. return 0;
  940. else
  941. goto Overflow;
  942. }
  943. /* Fill remaining bytes with copies of the sign bit. */
  944. {
  945. unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
  946. for ( ; j < n; ++j, p += pincr)
  947. *p = signbyte;
  948. }
  949. return 0;
  950. Overflow:
  951. PyErr_SetString(PyExc_OverflowError, "int too big to convert");
  952. return -1;
  953. }
  954. /* Create a new int object from a C pointer */
  955. PyObject *
  956. PyLong_FromVoidPtr(void *p)
  957. {
  958. #if SIZEOF_VOID_P <= SIZEOF_LONG
  959. return PyLong_FromUnsignedLong((unsigned long)(uintptr_t)p);
  960. #else
  961. #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
  962. # error "PyLong_FromVoidPtr: sizeof(long long) < sizeof(void*)"
  963. #endif
  964. return PyLong_FromUnsignedLongLong((unsigned long long)(uintptr_t)p);
  965. #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
  966. }
  967. /* Get a C pointer from an int object. */
  968. void *
  969. PyLong_AsVoidPtr(PyObject *vv)
  970. {
  971. #if SIZEOF_VOID_P <= SIZEOF_LONG
  972. long x;
  973. if (PyLong_Check(vv) && _PyLong_IsNegative((PyLongObject *)vv)) {
  974. x = PyLong_AsLong(vv);
  975. }
  976. else {
  977. x = PyLong_AsUnsignedLong(vv);
  978. }
  979. #else
  980. #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
  981. # error "PyLong_AsVoidPtr: sizeof(long long) < sizeof(void*)"
  982. #endif
  983. long long x;
  984. if (PyLong_Check(vv) && _PyLong_IsNegative((PyLongObject *)vv)) {
  985. x = PyLong_AsLongLong(vv);
  986. }
  987. else {
  988. x = PyLong_AsUnsignedLongLong(vv);
  989. }
  990. #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
  991. if (x == -1 && PyErr_Occurred())
  992. return NULL;
  993. return (void *)x;
  994. }
  995. /* Initial long long support by Chris Herborth (chrish@qnx.com), later
  996. * rewritten to use the newer PyLong_{As,From}ByteArray API.
  997. */
  998. #define PY_ABS_LLONG_MIN (0-(unsigned long long)LLONG_MIN)
  999. /* Create a new int object from a C long long int. */
  1000. PyObject *
  1001. PyLong_FromLongLong(long long ival)
  1002. {
  1003. PyLongObject *v;
  1004. unsigned long long abs_ival, t;
  1005. int ndigits;
  1006. /* Handle small and medium cases. */
  1007. if (IS_SMALL_INT(ival)) {
  1008. return get_small_int((sdigit)ival);
  1009. }
  1010. if (-(long long)PyLong_MASK <= ival && ival <= (long long)PyLong_MASK) {
  1011. return _PyLong_FromMedium((sdigit)ival);
  1012. }
  1013. /* Count digits (at least two - smaller cases were handled above). */
  1014. abs_ival = ival < 0 ? 0U-(unsigned long long)ival : (unsigned long long)ival;
  1015. /* Do shift in two steps to avoid possible undefined behavior. */
  1016. t = abs_ival >> PyLong_SHIFT >> PyLong_SHIFT;
  1017. ndigits = 2;
  1018. while (t) {
  1019. ++ndigits;
  1020. t >>= PyLong_SHIFT;
  1021. }
  1022. /* Construct output value. */
  1023. v = _PyLong_New(ndigits);
  1024. if (v != NULL) {
  1025. digit *p = v->long_value.ob_digit;
  1026. _PyLong_SetSignAndDigitCount(v, ival < 0 ? -1 : 1, ndigits);
  1027. t = abs_ival;
  1028. while (t) {
  1029. *p++ = (digit)(t & PyLong_MASK);
  1030. t >>= PyLong_SHIFT;
  1031. }
  1032. }
  1033. return (PyObject *)v;
  1034. }
  1035. /* Create a new int object from a C Py_ssize_t. */
  1036. PyObject *
  1037. PyLong_FromSsize_t(Py_ssize_t ival)
  1038. {
  1039. PyLongObject *v;
  1040. size_t abs_ival;
  1041. size_t t; /* unsigned so >> doesn't propagate sign bit */
  1042. int ndigits = 0;
  1043. int negative = 0;
  1044. if (IS_SMALL_INT(ival)) {
  1045. return get_small_int((sdigit)ival);
  1046. }
  1047. if (ival < 0) {
  1048. /* avoid signed overflow when ival = SIZE_T_MIN */
  1049. abs_ival = (size_t)(-1-ival)+1;
  1050. negative = 1;
  1051. }
  1052. else {
  1053. abs_ival = (size_t)ival;
  1054. }
  1055. /* Count the number of Python digits. */
  1056. t = abs_ival;
  1057. while (t) {
  1058. ++ndigits;
  1059. t >>= PyLong_SHIFT;
  1060. }
  1061. v = _PyLong_New(ndigits);
  1062. if (v != NULL) {
  1063. digit *p = v->long_value.ob_digit;
  1064. _PyLong_SetSignAndDigitCount(v, negative ? -1 : 1, ndigits);
  1065. t = abs_ival;
  1066. while (t) {
  1067. *p++ = (digit)(t & PyLong_MASK);
  1068. t >>= PyLong_SHIFT;
  1069. }
  1070. }
  1071. return (PyObject *)v;
  1072. }
  1073. /* Get a C long long int from an int object or any object that has an
  1074. __index__ method. Return -1 and set an error if overflow occurs. */
  1075. long long
  1076. PyLong_AsLongLong(PyObject *vv)
  1077. {
  1078. PyLongObject *v;
  1079. long long bytes;
  1080. int res;
  1081. int do_decref = 0; /* if PyNumber_Index was called */
  1082. if (vv == NULL) {
  1083. PyErr_BadInternalCall();
  1084. return -1;
  1085. }
  1086. if (PyLong_Check(vv)) {
  1087. v = (PyLongObject *)vv;
  1088. }
  1089. else {
  1090. v = (PyLongObject *)_PyNumber_Index(vv);
  1091. if (v == NULL)
  1092. return -1;
  1093. do_decref = 1;
  1094. }
  1095. if (_PyLong_IsCompact(v)) {
  1096. res = 0;
  1097. bytes = _PyLong_CompactValue(v);
  1098. }
  1099. else {
  1100. res = _PyLong_AsByteArray((PyLongObject *)v, (unsigned char *)&bytes,
  1101. SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 1);
  1102. }
  1103. if (do_decref) {
  1104. Py_DECREF(v);
  1105. }
  1106. /* Plan 9 can't handle long long in ? : expressions */
  1107. if (res < 0)
  1108. return (long long)-1;
  1109. else
  1110. return bytes;
  1111. }
  1112. /* Get a C unsigned long long int from an int object.
  1113. Return -1 and set an error if overflow occurs. */
  1114. unsigned long long
  1115. PyLong_AsUnsignedLongLong(PyObject *vv)
  1116. {
  1117. PyLongObject *v;
  1118. unsigned long long bytes;
  1119. int res;
  1120. if (vv == NULL) {
  1121. PyErr_BadInternalCall();
  1122. return (unsigned long long)-1;
  1123. }
  1124. if (!PyLong_Check(vv)) {
  1125. PyErr_SetString(PyExc_TypeError, "an integer is required");
  1126. return (unsigned long long)-1;
  1127. }
  1128. v = (PyLongObject*)vv;
  1129. if (_PyLong_IsNonNegativeCompact(v)) {
  1130. res = 0;
  1131. bytes = _PyLong_CompactValue(v);
  1132. }
  1133. else {
  1134. res = _PyLong_AsByteArray((PyLongObject *)vv, (unsigned char *)&bytes,
  1135. SIZEOF_LONG_LONG, PY_LITTLE_ENDIAN, 0);
  1136. }
  1137. /* Plan 9 can't handle long long in ? : expressions */
  1138. if (res < 0)
  1139. return (unsigned long long)res;
  1140. else
  1141. return bytes;
  1142. }
  1143. /* Get a C unsigned long int from an int object, ignoring the high bits.
  1144. Returns -1 and sets an error condition if an error occurs. */
  1145. static unsigned long long
  1146. _PyLong_AsUnsignedLongLongMask(PyObject *vv)
  1147. {
  1148. PyLongObject *v;
  1149. unsigned long long x;
  1150. Py_ssize_t i;
  1151. int sign;
  1152. if (vv == NULL || !PyLong_Check(vv)) {
  1153. PyErr_BadInternalCall();
  1154. return (unsigned long long) -1;
  1155. }
  1156. v = (PyLongObject *)vv;
  1157. if (_PyLong_IsCompact(v)) {
  1158. return (unsigned long long)(signed long long)_PyLong_CompactValue(v);
  1159. }
  1160. i = _PyLong_DigitCount(v);
  1161. sign = _PyLong_NonCompactSign(v);
  1162. x = 0;
  1163. while (--i >= 0) {
  1164. x = (x << PyLong_SHIFT) | v->long_value.ob_digit[i];
  1165. }
  1166. return x * sign;
  1167. }
  1168. unsigned long long
  1169. PyLong_AsUnsignedLongLongMask(PyObject *op)
  1170. {
  1171. PyLongObject *lo;
  1172. unsigned long long val;
  1173. if (op == NULL) {
  1174. PyErr_BadInternalCall();
  1175. return (unsigned long long)-1;
  1176. }
  1177. if (PyLong_Check(op)) {
  1178. return _PyLong_AsUnsignedLongLongMask(op);
  1179. }
  1180. lo = (PyLongObject *)_PyNumber_Index(op);
  1181. if (lo == NULL)
  1182. return (unsigned long long)-1;
  1183. val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
  1184. Py_DECREF(lo);
  1185. return val;
  1186. }
  1187. /* Get a C long long int from an int object or any object that has an
  1188. __index__ method.
  1189. On overflow, return -1 and set *overflow to 1 or -1 depending on the sign of
  1190. the result. Otherwise *overflow is 0.
  1191. For other errors (e.g., TypeError), return -1 and set an error condition.
  1192. In this case *overflow will be 0.
  1193. */
  1194. long long
  1195. PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
  1196. {
  1197. /* This version by Tim Peters */
  1198. PyLongObject *v;
  1199. unsigned long long x, prev;
  1200. long long res;
  1201. Py_ssize_t i;
  1202. int sign;
  1203. int do_decref = 0; /* if PyNumber_Index was called */
  1204. *overflow = 0;
  1205. if (vv == NULL) {
  1206. PyErr_BadInternalCall();
  1207. return -1;
  1208. }
  1209. if (PyLong_Check(vv)) {
  1210. v = (PyLongObject *)vv;
  1211. }
  1212. else {
  1213. v = (PyLongObject *)_PyNumber_Index(vv);
  1214. if (v == NULL)
  1215. return -1;
  1216. do_decref = 1;
  1217. }
  1218. if (_PyLong_IsCompact(v)) {
  1219. res = _PyLong_CompactValue(v);
  1220. }
  1221. else {
  1222. i = _PyLong_DigitCount(v);
  1223. sign = _PyLong_NonCompactSign(v);
  1224. x = 0;
  1225. while (--i >= 0) {
  1226. prev = x;
  1227. x = (x << PyLong_SHIFT) + v->long_value.ob_digit[i];
  1228. if ((x >> PyLong_SHIFT) != prev) {
  1229. *overflow = sign;
  1230. res = -1;
  1231. goto exit;
  1232. }
  1233. }
  1234. /* Haven't lost any bits, but casting to long requires extra
  1235. * care (see comment above).
  1236. */
  1237. if (x <= (unsigned long long)LLONG_MAX) {
  1238. res = (long long)x * sign;
  1239. }
  1240. else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
  1241. res = LLONG_MIN;
  1242. }
  1243. else {
  1244. *overflow = sign;
  1245. res = -1;
  1246. }
  1247. }
  1248. exit:
  1249. if (do_decref) {
  1250. Py_DECREF(v);
  1251. }
  1252. return res;
  1253. }
  1254. int
  1255. _PyLong_UnsignedShort_Converter(PyObject *obj, void *ptr)
  1256. {
  1257. unsigned long uval;
  1258. if (PyLong_Check(obj) && _PyLong_IsNegative((PyLongObject *)obj)) {
  1259. PyErr_SetString(PyExc_ValueError, "value must be positive");
  1260. return 0;
  1261. }
  1262. uval = PyLong_AsUnsignedLong(obj);
  1263. if (uval == (unsigned long)-1 && PyErr_Occurred())
  1264. return 0;
  1265. if (uval > USHRT_MAX) {
  1266. PyErr_SetString(PyExc_OverflowError,
  1267. "Python int too large for C unsigned short");
  1268. return 0;
  1269. }
  1270. *(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
  1271. return 1;
  1272. }
  1273. int
  1274. _PyLong_UnsignedInt_Converter(PyObject *obj, void *ptr)
  1275. {
  1276. unsigned long uval;
  1277. if (PyLong_Check(obj) && _PyLong_IsNegative((PyLongObject *)obj)) {
  1278. PyErr_SetString(PyExc_ValueError, "value must be positive");
  1279. return 0;
  1280. }
  1281. uval = PyLong_AsUnsignedLong(obj);
  1282. if (uval == (unsigned long)-1 && PyErr_Occurred())
  1283. return 0;
  1284. if (uval > UINT_MAX) {
  1285. PyErr_SetString(PyExc_OverflowError,
  1286. "Python int too large for C unsigned int");
  1287. return 0;
  1288. }
  1289. *(unsigned int *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned int);
  1290. return 1;
  1291. }
  1292. int
  1293. _PyLong_UnsignedLong_Converter(PyObject *obj, void *ptr)
  1294. {
  1295. unsigned long uval;
  1296. if (PyLong_Check(obj) && _PyLong_IsNegative((PyLongObject *)obj)) {
  1297. PyErr_SetString(PyExc_ValueError, "value must be positive");
  1298. return 0;
  1299. }
  1300. uval = PyLong_AsUnsignedLong(obj);
  1301. if (uval == (unsigned long)-1 && PyErr_Occurred())
  1302. return 0;
  1303. *(unsigned long *)ptr = uval;
  1304. return 1;
  1305. }
  1306. int
  1307. _PyLong_UnsignedLongLong_Converter(PyObject *obj, void *ptr)
  1308. {
  1309. unsigned long long uval;
  1310. if (PyLong_Check(obj) && _PyLong_IsNegative((PyLongObject *)obj)) {
  1311. PyErr_SetString(PyExc_ValueError, "value must be positive");
  1312. return 0;
  1313. }
  1314. uval = PyLong_AsUnsignedLongLong(obj);
  1315. if (uval == (unsigned long long)-1 && PyErr_Occurred())
  1316. return 0;
  1317. *(unsigned long long *)ptr = uval;
  1318. return 1;
  1319. }
  1320. int
  1321. _PyLong_Size_t_Converter(PyObject *obj, void *ptr)
  1322. {
  1323. size_t uval;
  1324. if (PyLong_Check(obj) && _PyLong_IsNegative((PyLongObject *)obj)) {
  1325. PyErr_SetString(PyExc_ValueError, "value must be positive");
  1326. return 0;
  1327. }
  1328. uval = PyLong_AsSize_t(obj);
  1329. if (uval == (size_t)-1 && PyErr_Occurred())
  1330. return 0;
  1331. *(size_t *)ptr = uval;
  1332. return 1;
  1333. }
  1334. #define CHECK_BINOP(v,w) \
  1335. do { \
  1336. if (!PyLong_Check(v) || !PyLong_Check(w)) \
  1337. Py_RETURN_NOTIMPLEMENTED; \
  1338. } while(0)
  1339. /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
  1340. * is modified in place, by adding y to it. Carries are propagated as far as
  1341. * x[m-1], and the remaining carry (0 or 1) is returned.
  1342. */
  1343. static digit
  1344. v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
  1345. {
  1346. Py_ssize_t i;
  1347. digit carry = 0;
  1348. assert(m >= n);
  1349. for (i = 0; i < n; ++i) {
  1350. carry += x[i] + y[i];
  1351. x[i] = carry & PyLong_MASK;
  1352. carry >>= PyLong_SHIFT;
  1353. assert((carry & 1) == carry);
  1354. }
  1355. for (; carry && i < m; ++i) {
  1356. carry += x[i];
  1357. x[i] = carry & PyLong_MASK;
  1358. carry >>= PyLong_SHIFT;
  1359. assert((carry & 1) == carry);
  1360. }
  1361. return carry;
  1362. }
  1363. /* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
  1364. * is modified in place, by subtracting y from it. Borrows are propagated as
  1365. * far as x[m-1], and the remaining borrow (0 or 1) is returned.
  1366. */
  1367. static digit
  1368. v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
  1369. {
  1370. Py_ssize_t i;
  1371. digit borrow = 0;
  1372. assert(m >= n);
  1373. for (i = 0; i < n; ++i) {
  1374. borrow = x[i] - y[i] - borrow;
  1375. x[i] = borrow & PyLong_MASK;
  1376. borrow >>= PyLong_SHIFT;
  1377. borrow &= 1; /* keep only 1 sign bit */
  1378. }
  1379. for (; borrow && i < m; ++i) {
  1380. borrow = x[i] - borrow;
  1381. x[i] = borrow & PyLong_MASK;
  1382. borrow >>= PyLong_SHIFT;
  1383. borrow &= 1;
  1384. }
  1385. return borrow;
  1386. }
  1387. /* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
  1388. * result in z[0:m], and return the d bits shifted out of the top.
  1389. */
  1390. static digit
  1391. v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
  1392. {
  1393. Py_ssize_t i;
  1394. digit carry = 0;
  1395. assert(0 <= d && d < PyLong_SHIFT);
  1396. for (i=0; i < m; i++) {
  1397. twodigits acc = (twodigits)a[i] << d | carry;
  1398. z[i] = (digit)acc & PyLong_MASK;
  1399. carry = (digit)(acc >> PyLong_SHIFT);
  1400. }
  1401. return carry;
  1402. }
  1403. /* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
  1404. * result in z[0:m], and return the d bits shifted out of the bottom.
  1405. */
  1406. static digit
  1407. v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
  1408. {
  1409. Py_ssize_t i;
  1410. digit carry = 0;
  1411. digit mask = ((digit)1 << d) - 1U;
  1412. assert(0 <= d && d < PyLong_SHIFT);
  1413. for (i=m; i-- > 0;) {
  1414. twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
  1415. carry = (digit)acc & mask;
  1416. z[i] = (digit)(acc >> d);
  1417. }
  1418. return carry;
  1419. }
  1420. /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
  1421. in pout, and returning the remainder. pin and pout point at the LSD.
  1422. It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
  1423. _PyLong_Format, but that should be done with great care since ints are
  1424. immutable.
  1425. This version of the code can be 20% faster than the pre-2022 version
  1426. on todays compilers on architectures like amd64. It evolved from Mark
  1427. Dickinson observing that a 128:64 divide instruction was always being
  1428. generated by the compiler despite us working with 30-bit digit values.
  1429. See the thread for full context:
  1430. https://mail.python.org/archives/list/python-dev@python.org/thread/ZICIMX5VFCX4IOFH5NUPVHCUJCQ4Q7QM/#NEUNFZU3TQU4CPTYZNF3WCN7DOJBBTK5
  1431. If you ever want to change this code, pay attention to performance using
  1432. different compilers, optimization levels, and cpu architectures. Beware of
  1433. PGO/FDO builds doing value specialization such as a fast path for //10. :)
  1434. Verify that 17 isn't specialized and this works as a quick test:
  1435. python -m timeit -s 'x = 10**1000; r=x//10; assert r == 10**999, r' 'x//17'
  1436. */
  1437. static digit
  1438. inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
  1439. {
  1440. digit remainder = 0;
  1441. assert(n > 0 && n <= PyLong_MASK);
  1442. while (--size >= 0) {
  1443. twodigits dividend;
  1444. dividend = ((twodigits)remainder << PyLong_SHIFT) | pin[size];
  1445. digit quotient;
  1446. quotient = (digit)(dividend / n);
  1447. remainder = dividend % n;
  1448. pout[size] = quotient;
  1449. }
  1450. return remainder;
  1451. }
  1452. /* Divide an integer by a digit, returning both the quotient
  1453. (as function result) and the remainder (through *prem).
  1454. The sign of a is ignored; n should not be zero. */
  1455. static PyLongObject *
  1456. divrem1(PyLongObject *a, digit n, digit *prem)
  1457. {
  1458. const Py_ssize_t size = _PyLong_DigitCount(a);
  1459. PyLongObject *z;
  1460. assert(n > 0 && n <= PyLong_MASK);
  1461. z = _PyLong_New(size);
  1462. if (z == NULL)
  1463. return NULL;
  1464. *prem = inplace_divrem1(z->long_value.ob_digit, a->long_value.ob_digit, size, n);
  1465. return long_normalize(z);
  1466. }
  1467. /* Remainder of long pin, w/ size digits, by non-zero digit n,
  1468. returning the remainder. pin points at the LSD. */
  1469. static digit
  1470. inplace_rem1(digit *pin, Py_ssize_t size, digit n)
  1471. {
  1472. twodigits rem = 0;
  1473. assert(n > 0 && n <= PyLong_MASK);
  1474. while (--size >= 0)
  1475. rem = ((rem << PyLong_SHIFT) | pin[size]) % n;
  1476. return (digit)rem;
  1477. }
  1478. /* Get the remainder of an integer divided by a digit, returning
  1479. the remainder as the result of the function. The sign of a is
  1480. ignored; n should not be zero. */
  1481. static PyLongObject *
  1482. rem1(PyLongObject *a, digit n)
  1483. {
  1484. const Py_ssize_t size = _PyLong_DigitCount(a);
  1485. assert(n > 0 && n <= PyLong_MASK);
  1486. return (PyLongObject *)PyLong_FromLong(
  1487. (long)inplace_rem1(a->long_value.ob_digit, size, n)
  1488. );
  1489. }
  1490. #ifdef WITH_PYLONG_MODULE
  1491. /* asymptotically faster long_to_decimal_string, using _pylong.py */
  1492. static int
  1493. pylong_int_to_decimal_string(PyObject *aa,
  1494. PyObject **p_output,
  1495. _PyUnicodeWriter *writer,
  1496. _PyBytesWriter *bytes_writer,
  1497. char **bytes_str)
  1498. {
  1499. PyObject *s = NULL;
  1500. PyObject *mod = PyImport_ImportModule("_pylong");
  1501. if (mod == NULL) {
  1502. return -1;
  1503. }
  1504. s = PyObject_CallMethod(mod, "int_to_decimal_string", "O", aa);
  1505. if (s == NULL) {
  1506. goto error;
  1507. }
  1508. if (!PyUnicode_Check(s)) {
  1509. PyErr_SetString(PyExc_TypeError,
  1510. "_pylong.int_to_decimal_string did not return a str");
  1511. goto error;
  1512. }
  1513. if (writer) {
  1514. Py_ssize_t size = PyUnicode_GET_LENGTH(s);
  1515. if (_PyUnicodeWriter_Prepare(writer, size, '9') == -1) {
  1516. goto error;
  1517. }
  1518. if (_PyUnicodeWriter_WriteStr(writer, s) < 0) {
  1519. goto error;
  1520. }
  1521. goto success;
  1522. }
  1523. else if (bytes_writer) {
  1524. Py_ssize_t size = PyUnicode_GET_LENGTH(s);
  1525. const void *data = PyUnicode_DATA(s);
  1526. int kind = PyUnicode_KIND(s);
  1527. *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, size);
  1528. if (*bytes_str == NULL) {
  1529. goto error;
  1530. }
  1531. char *p = *bytes_str;
  1532. for (Py_ssize_t i=0; i < size; i++) {
  1533. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  1534. *p++ = (char) ch;
  1535. }
  1536. (*bytes_str) = p;
  1537. goto success;
  1538. }
  1539. else {
  1540. *p_output = Py_NewRef(s);
  1541. goto success;
  1542. }
  1543. error:
  1544. Py_DECREF(mod);
  1545. Py_XDECREF(s);
  1546. return -1;
  1547. success:
  1548. Py_DECREF(mod);
  1549. Py_DECREF(s);
  1550. return 0;
  1551. }
  1552. #endif /* WITH_PYLONG_MODULE */
  1553. /* Convert an integer to a base 10 string. Returns a new non-shared
  1554. string. (Return value is non-shared so that callers can modify the
  1555. returned value if necessary.) */
  1556. static int
  1557. long_to_decimal_string_internal(PyObject *aa,
  1558. PyObject **p_output,
  1559. _PyUnicodeWriter *writer,
  1560. _PyBytesWriter *bytes_writer,
  1561. char **bytes_str)
  1562. {
  1563. PyLongObject *scratch, *a;
  1564. PyObject *str = NULL;
  1565. Py_ssize_t size, strlen, size_a, i, j;
  1566. digit *pout, *pin, rem, tenpow;
  1567. int negative;
  1568. int d;
  1569. // writer or bytes_writer can be used, but not both at the same time.
  1570. assert(writer == NULL || bytes_writer == NULL);
  1571. a = (PyLongObject *)aa;
  1572. if (a == NULL || !PyLong_Check(a)) {
  1573. PyErr_BadInternalCall();
  1574. return -1;
  1575. }
  1576. size_a = _PyLong_DigitCount(a);
  1577. negative = _PyLong_IsNegative(a);
  1578. /* quick and dirty pre-check for overflowing the decimal digit limit,
  1579. based on the inequality 10/3 >= log2(10)
  1580. explanation in https://github.com/python/cpython/pull/96537
  1581. */
  1582. if (size_a >= 10 * _PY_LONG_MAX_STR_DIGITS_THRESHOLD
  1583. / (3 * PyLong_SHIFT) + 2) {
  1584. PyInterpreterState *interp = _PyInterpreterState_GET();
  1585. int max_str_digits = interp->long_state.max_str_digits;
  1586. if ((max_str_digits > 0) &&
  1587. (max_str_digits / (3 * PyLong_SHIFT) <= (size_a - 11) / 10)) {
  1588. PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_STR,
  1589. max_str_digits);
  1590. return -1;
  1591. }
  1592. }
  1593. #if WITH_PYLONG_MODULE
  1594. if (size_a > 1000) {
  1595. /* Switch to _pylong.int_to_decimal_string(). */
  1596. return pylong_int_to_decimal_string(aa,
  1597. p_output,
  1598. writer,
  1599. bytes_writer,
  1600. bytes_str);
  1601. }
  1602. #endif
  1603. /* quick and dirty upper bound for the number of digits
  1604. required to express a in base _PyLong_DECIMAL_BASE:
  1605. #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
  1606. But log2(a) < size_a * PyLong_SHIFT, and
  1607. log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
  1608. > 3.3 * _PyLong_DECIMAL_SHIFT
  1609. size_a * PyLong_SHIFT / (3.3 * _PyLong_DECIMAL_SHIFT) =
  1610. size_a + size_a / d < size_a + size_a / floor(d),
  1611. where d = (3.3 * _PyLong_DECIMAL_SHIFT) /
  1612. (PyLong_SHIFT - 3.3 * _PyLong_DECIMAL_SHIFT)
  1613. */
  1614. d = (33 * _PyLong_DECIMAL_SHIFT) /
  1615. (10 * PyLong_SHIFT - 33 * _PyLong_DECIMAL_SHIFT);
  1616. assert(size_a < PY_SSIZE_T_MAX/2);
  1617. size = 1 + size_a + size_a / d;
  1618. scratch = _PyLong_New(size);
  1619. if (scratch == NULL)
  1620. return -1;
  1621. /* convert array of base _PyLong_BASE digits in pin to an array of
  1622. base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
  1623. Volume 2 (3rd edn), section 4.4, Method 1b). */
  1624. pin = a->long_value.ob_digit;
  1625. pout = scratch->long_value.ob_digit;
  1626. size = 0;
  1627. for (i = size_a; --i >= 0; ) {
  1628. digit hi = pin[i];
  1629. for (j = 0; j < size; j++) {
  1630. twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
  1631. hi = (digit)(z / _PyLong_DECIMAL_BASE);
  1632. pout[j] = (digit)(z - (twodigits)hi *
  1633. _PyLong_DECIMAL_BASE);
  1634. }
  1635. while (hi) {
  1636. pout[size++] = hi % _PyLong_DECIMAL_BASE;
  1637. hi /= _PyLong_DECIMAL_BASE;
  1638. }
  1639. /* check for keyboard interrupt */
  1640. SIGCHECK({
  1641. Py_DECREF(scratch);
  1642. return -1;
  1643. });
  1644. }
  1645. /* pout should have at least one digit, so that the case when a = 0
  1646. works correctly */
  1647. if (size == 0)
  1648. pout[size++] = 0;
  1649. /* calculate exact length of output string, and allocate */
  1650. strlen = negative + 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
  1651. tenpow = 10;
  1652. rem = pout[size-1];
  1653. while (rem >= tenpow) {
  1654. tenpow *= 10;
  1655. strlen++;
  1656. }
  1657. if (strlen > _PY_LONG_MAX_STR_DIGITS_THRESHOLD) {
  1658. PyInterpreterState *interp = _PyInterpreterState_GET();
  1659. int max_str_digits = interp->long_state.max_str_digits;
  1660. Py_ssize_t strlen_nosign = strlen - negative;
  1661. if ((max_str_digits > 0) && (strlen_nosign > max_str_digits)) {
  1662. Py_DECREF(scratch);
  1663. PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_STR,
  1664. max_str_digits);
  1665. return -1;
  1666. }
  1667. }
  1668. if (writer) {
  1669. if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
  1670. Py_DECREF(scratch);
  1671. return -1;
  1672. }
  1673. }
  1674. else if (bytes_writer) {
  1675. *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, strlen);
  1676. if (*bytes_str == NULL) {
  1677. Py_DECREF(scratch);
  1678. return -1;
  1679. }
  1680. }
  1681. else {
  1682. str = PyUnicode_New(strlen, '9');
  1683. if (str == NULL) {
  1684. Py_DECREF(scratch);
  1685. return -1;
  1686. }
  1687. }
  1688. #define WRITE_DIGITS(p) \
  1689. do { \
  1690. /* pout[0] through pout[size-2] contribute exactly \
  1691. _PyLong_DECIMAL_SHIFT digits each */ \
  1692. for (i=0; i < size - 1; i++) { \
  1693. rem = pout[i]; \
  1694. for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) { \
  1695. *--p = '0' + rem % 10; \
  1696. rem /= 10; \
  1697. } \
  1698. } \
  1699. /* pout[size-1]: always produce at least one decimal digit */ \
  1700. rem = pout[i]; \
  1701. do { \
  1702. *--p = '0' + rem % 10; \
  1703. rem /= 10; \
  1704. } while (rem != 0); \
  1705. \
  1706. /* and sign */ \
  1707. if (negative) \
  1708. *--p = '-'; \
  1709. } while (0)
  1710. #define WRITE_UNICODE_DIGITS(TYPE) \
  1711. do { \
  1712. if (writer) \
  1713. p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + strlen; \
  1714. else \
  1715. p = (TYPE*)PyUnicode_DATA(str) + strlen; \
  1716. \
  1717. WRITE_DIGITS(p); \
  1718. \
  1719. /* check we've counted correctly */ \
  1720. if (writer) \
  1721. assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
  1722. else \
  1723. assert(p == (TYPE*)PyUnicode_DATA(str)); \
  1724. } while (0)
  1725. /* fill the string right-to-left */
  1726. if (bytes_writer) {
  1727. char *p = *bytes_str + strlen;
  1728. WRITE_DIGITS(p);
  1729. assert(p == *bytes_str);
  1730. }
  1731. else {
  1732. int kind = writer ? writer->kind : PyUnicode_KIND(str);
  1733. if (kind == PyUnicode_1BYTE_KIND) {
  1734. Py_UCS1 *p;
  1735. WRITE_UNICODE_DIGITS(Py_UCS1);
  1736. }
  1737. else if (kind == PyUnicode_2BYTE_KIND) {
  1738. Py_UCS2 *p;
  1739. WRITE_UNICODE_DIGITS(Py_UCS2);
  1740. }
  1741. else {
  1742. assert (kind == PyUnicode_4BYTE_KIND);
  1743. Py_UCS4 *p;
  1744. WRITE_UNICODE_DIGITS(Py_UCS4);
  1745. }
  1746. }
  1747. #undef WRITE_DIGITS
  1748. #undef WRITE_UNICODE_DIGITS
  1749. _Py_DECREF_INT(scratch);
  1750. if (writer) {
  1751. writer->pos += strlen;
  1752. }
  1753. else if (bytes_writer) {
  1754. (*bytes_str) += strlen;
  1755. }
  1756. else {
  1757. assert(_PyUnicode_CheckConsistency(str, 1));
  1758. *p_output = (PyObject *)str;
  1759. }
  1760. return 0;
  1761. }
  1762. static PyObject *
  1763. long_to_decimal_string(PyObject *aa)
  1764. {
  1765. PyObject *v;
  1766. if (long_to_decimal_string_internal(aa, &v, NULL, NULL, NULL) == -1)
  1767. return NULL;
  1768. return v;
  1769. }
  1770. /* Convert an int object to a string, using a given conversion base,
  1771. which should be one of 2, 8 or 16. Return a string object.
  1772. If base is 2, 8 or 16, add the proper prefix '0b', '0o' or '0x'
  1773. if alternate is nonzero. */
  1774. static int
  1775. long_format_binary(PyObject *aa, int base, int alternate,
  1776. PyObject **p_output, _PyUnicodeWriter *writer,
  1777. _PyBytesWriter *bytes_writer, char **bytes_str)
  1778. {
  1779. PyLongObject *a = (PyLongObject *)aa;
  1780. PyObject *v = NULL;
  1781. Py_ssize_t sz;
  1782. Py_ssize_t size_a;
  1783. int negative;
  1784. int bits;
  1785. assert(base == 2 || base == 8 || base == 16);
  1786. // writer or bytes_writer can be used, but not both at the same time.
  1787. assert(writer == NULL || bytes_writer == NULL);
  1788. if (a == NULL || !PyLong_Check(a)) {
  1789. PyErr_BadInternalCall();
  1790. return -1;
  1791. }
  1792. size_a = _PyLong_DigitCount(a);
  1793. negative = _PyLong_IsNegative(a);
  1794. /* Compute a rough upper bound for the length of the string */
  1795. switch (base) {
  1796. case 16:
  1797. bits = 4;
  1798. break;
  1799. case 8:
  1800. bits = 3;
  1801. break;
  1802. case 2:
  1803. bits = 1;
  1804. break;
  1805. default:
  1806. Py_UNREACHABLE();
  1807. }
  1808. /* Compute exact length 'sz' of output string. */
  1809. if (size_a == 0) {
  1810. sz = 1;
  1811. }
  1812. else {
  1813. Py_ssize_t size_a_in_bits;
  1814. /* Ensure overflow doesn't occur during computation of sz. */
  1815. if (size_a > (PY_SSIZE_T_MAX - 3) / PyLong_SHIFT) {
  1816. PyErr_SetString(PyExc_OverflowError,
  1817. "int too large to format");
  1818. return -1;
  1819. }
  1820. size_a_in_bits = (size_a - 1) * PyLong_SHIFT +
  1821. bit_length_digit(a->long_value.ob_digit[size_a - 1]);
  1822. /* Allow 1 character for a '-' sign. */
  1823. sz = negative + (size_a_in_bits + (bits - 1)) / bits;
  1824. }
  1825. if (alternate) {
  1826. /* 2 characters for prefix */
  1827. sz += 2;
  1828. }
  1829. if (writer) {
  1830. if (_PyUnicodeWriter_Prepare(writer, sz, 'x') == -1)
  1831. return -1;
  1832. }
  1833. else if (bytes_writer) {
  1834. *bytes_str = _PyBytesWriter_Prepare(bytes_writer, *bytes_str, sz);
  1835. if (*bytes_str == NULL)
  1836. return -1;
  1837. }
  1838. else {
  1839. v = PyUnicode_New(sz, 'x');
  1840. if (v == NULL)
  1841. return -1;
  1842. }
  1843. #define WRITE_DIGITS(p) \
  1844. do { \
  1845. if (size_a == 0) { \
  1846. *--p = '0'; \
  1847. } \
  1848. else { \
  1849. /* JRH: special case for power-of-2 bases */ \
  1850. twodigits accum = 0; \
  1851. int accumbits = 0; /* # of bits in accum */ \
  1852. Py_ssize_t i; \
  1853. for (i = 0; i < size_a; ++i) { \
  1854. accum |= (twodigits)a->long_value.ob_digit[i] << accumbits; \
  1855. accumbits += PyLong_SHIFT; \
  1856. assert(accumbits >= bits); \
  1857. do { \
  1858. char cdigit; \
  1859. cdigit = (char)(accum & (base - 1)); \
  1860. cdigit += (cdigit < 10) ? '0' : 'a'-10; \
  1861. *--p = cdigit; \
  1862. accumbits -= bits; \
  1863. accum >>= bits; \
  1864. } while (i < size_a-1 ? accumbits >= bits : accum > 0); \
  1865. } \
  1866. } \
  1867. \
  1868. if (alternate) { \
  1869. if (base == 16) \
  1870. *--p = 'x'; \
  1871. else if (base == 8) \
  1872. *--p = 'o'; \
  1873. else /* (base == 2) */ \
  1874. *--p = 'b'; \
  1875. *--p = '0'; \
  1876. } \
  1877. if (negative) \
  1878. *--p = '-'; \
  1879. } while (0)
  1880. #define WRITE_UNICODE_DIGITS(TYPE) \
  1881. do { \
  1882. if (writer) \
  1883. p = (TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos + sz; \
  1884. else \
  1885. p = (TYPE*)PyUnicode_DATA(v) + sz; \
  1886. \
  1887. WRITE_DIGITS(p); \
  1888. \
  1889. if (writer) \
  1890. assert(p == ((TYPE*)PyUnicode_DATA(writer->buffer) + writer->pos)); \
  1891. else \
  1892. assert(p == (TYPE*)PyUnicode_DATA(v)); \
  1893. } while (0)
  1894. if (bytes_writer) {
  1895. char *p = *bytes_str + sz;
  1896. WRITE_DIGITS(p);
  1897. assert(p == *bytes_str);
  1898. }
  1899. else {
  1900. int kind = writer ? writer->kind : PyUnicode_KIND(v);
  1901. if (kind == PyUnicode_1BYTE_KIND) {
  1902. Py_UCS1 *p;
  1903. WRITE_UNICODE_DIGITS(Py_UCS1);
  1904. }
  1905. else if (kind == PyUnicode_2BYTE_KIND) {
  1906. Py_UCS2 *p;
  1907. WRITE_UNICODE_DIGITS(Py_UCS2);
  1908. }
  1909. else {
  1910. assert (kind == PyUnicode_4BYTE_KIND);
  1911. Py_UCS4 *p;
  1912. WRITE_UNICODE_DIGITS(Py_UCS4);
  1913. }
  1914. }
  1915. #undef WRITE_DIGITS
  1916. #undef WRITE_UNICODE_DIGITS
  1917. if (writer) {
  1918. writer->pos += sz;
  1919. }
  1920. else if (bytes_writer) {
  1921. (*bytes_str) += sz;
  1922. }
  1923. else {
  1924. assert(_PyUnicode_CheckConsistency(v, 1));
  1925. *p_output = v;
  1926. }
  1927. return 0;
  1928. }
  1929. PyObject *
  1930. _PyLong_Format(PyObject *obj, int base)
  1931. {
  1932. PyObject *str;
  1933. int err;
  1934. if (base == 10)
  1935. err = long_to_decimal_string_internal(obj, &str, NULL, NULL, NULL);
  1936. else
  1937. err = long_format_binary(obj, base, 1, &str, NULL, NULL, NULL);
  1938. if (err == -1)
  1939. return NULL;
  1940. return str;
  1941. }
  1942. int
  1943. _PyLong_FormatWriter(_PyUnicodeWriter *writer,
  1944. PyObject *obj,
  1945. int base, int alternate)
  1946. {
  1947. if (base == 10)
  1948. return long_to_decimal_string_internal(obj, NULL, writer,
  1949. NULL, NULL);
  1950. else
  1951. return long_format_binary(obj, base, alternate, NULL, writer,
  1952. NULL, NULL);
  1953. }
  1954. char*
  1955. _PyLong_FormatBytesWriter(_PyBytesWriter *writer, char *str,
  1956. PyObject *obj,
  1957. int base, int alternate)
  1958. {
  1959. char *str2;
  1960. int res;
  1961. str2 = str;
  1962. if (base == 10)
  1963. res = long_to_decimal_string_internal(obj, NULL, NULL,
  1964. writer, &str2);
  1965. else
  1966. res = long_format_binary(obj, base, alternate, NULL, NULL,
  1967. writer, &str2);
  1968. if (res < 0)
  1969. return NULL;
  1970. assert(str2 != NULL);
  1971. return str2;
  1972. }
  1973. /* Table of digit values for 8-bit string -> integer conversion.
  1974. * '0' maps to 0, ..., '9' maps to 9.
  1975. * 'a' and 'A' map to 10, ..., 'z' and 'Z' map to 35.
  1976. * All other indices map to 37.
  1977. * Note that when converting a base B string, a char c is a legitimate
  1978. * base B digit iff _PyLong_DigitValue[Py_CHARPyLong_MASK(c)] < B.
  1979. */
  1980. unsigned char _PyLong_DigitValue[256] = {
  1981. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1982. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1983. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1984. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
  1985. 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  1986. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
  1987. 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  1988. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
  1989. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1990. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1991. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1992. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1993. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1994. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1995. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1996. 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
  1997. };
  1998. /* `start` and `end` point to the start and end of a string of base `base`
  1999. * digits. base is a power of 2 (2, 4, 8, 16, or 32). An unnormalized int is
  2000. * returned in *res. The string should be already validated by the caller and
  2001. * consists only of valid digit characters and underscores. `digits` gives the
  2002. * number of digit characters.
  2003. *
  2004. * The point to this routine is that it takes time linear in the
  2005. * number of string characters.
  2006. *
  2007. * Return values:
  2008. * -1 on syntax error (exception needs to be set, *res is untouched)
  2009. * 0 else (exception may be set, in that case *res is set to NULL)
  2010. */
  2011. static int
  2012. long_from_binary_base(const char *start, const char *end, Py_ssize_t digits, int base, PyLongObject **res)
  2013. {
  2014. const char *p;
  2015. int bits_per_char;
  2016. Py_ssize_t n;
  2017. PyLongObject *z;
  2018. twodigits accum;
  2019. int bits_in_accum;
  2020. digit *pdigit;
  2021. assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
  2022. n = base;
  2023. for (bits_per_char = -1; n; ++bits_per_char) {
  2024. n >>= 1;
  2025. }
  2026. /* n <- the number of Python digits needed,
  2027. = ceiling((digits * bits_per_char) / PyLong_SHIFT). */
  2028. if (digits > (PY_SSIZE_T_MAX - (PyLong_SHIFT - 1)) / bits_per_char) {
  2029. PyErr_SetString(PyExc_ValueError,
  2030. "int string too large to convert");
  2031. *res = NULL;
  2032. return 0;
  2033. }
  2034. n = (digits * bits_per_char + PyLong_SHIFT - 1) / PyLong_SHIFT;
  2035. z = _PyLong_New(n);
  2036. if (z == NULL) {
  2037. *res = NULL;
  2038. return 0;
  2039. }
  2040. /* Read string from right, and fill in int from left; i.e.,
  2041. * from least to most significant in both.
  2042. */
  2043. accum = 0;
  2044. bits_in_accum = 0;
  2045. pdigit = z->long_value.ob_digit;
  2046. p = end;
  2047. while (--p >= start) {
  2048. int k;
  2049. if (*p == '_') {
  2050. continue;
  2051. }
  2052. k = (int)_PyLong_DigitValue[Py_CHARMASK(*p)];
  2053. assert(k >= 0 && k < base);
  2054. accum |= (twodigits)k << bits_in_accum;
  2055. bits_in_accum += bits_per_char;
  2056. if (bits_in_accum >= PyLong_SHIFT) {
  2057. *pdigit++ = (digit)(accum & PyLong_MASK);
  2058. assert(pdigit - z->long_value.ob_digit <= n);
  2059. accum >>= PyLong_SHIFT;
  2060. bits_in_accum -= PyLong_SHIFT;
  2061. assert(bits_in_accum < PyLong_SHIFT);
  2062. }
  2063. }
  2064. if (bits_in_accum) {
  2065. assert(bits_in_accum <= PyLong_SHIFT);
  2066. *pdigit++ = (digit)accum;
  2067. assert(pdigit - z->long_value.ob_digit <= n);
  2068. }
  2069. while (pdigit - z->long_value.ob_digit < n)
  2070. *pdigit++ = 0;
  2071. *res = z;
  2072. return 0;
  2073. }
  2074. static PyObject *long_neg(PyLongObject *v);
  2075. #ifdef WITH_PYLONG_MODULE
  2076. /* asymptotically faster str-to-long conversion for base 10, using _pylong.py */
  2077. static int
  2078. pylong_int_from_string(const char *start, const char *end, PyLongObject **res)
  2079. {
  2080. PyObject *mod = PyImport_ImportModule("_pylong");
  2081. if (mod == NULL) {
  2082. goto error;
  2083. }
  2084. PyObject *s = PyUnicode_FromStringAndSize(start, end-start);
  2085. if (s == NULL) {
  2086. Py_DECREF(mod);
  2087. goto error;
  2088. }
  2089. PyObject *result = PyObject_CallMethod(mod, "int_from_string", "O", s);
  2090. Py_DECREF(s);
  2091. Py_DECREF(mod);
  2092. if (result == NULL) {
  2093. goto error;
  2094. }
  2095. if (!PyLong_Check(result)) {
  2096. Py_DECREF(result);
  2097. PyErr_SetString(PyExc_TypeError,
  2098. "_pylong.int_from_string did not return an int");
  2099. goto error;
  2100. }
  2101. *res = (PyLongObject *)result;
  2102. return 0;
  2103. error:
  2104. *res = NULL;
  2105. return 0; // See the long_from_string_base() API comment.
  2106. }
  2107. #endif /* WITH_PYLONG_MODULE */
  2108. /***
  2109. long_from_non_binary_base: parameters and return values are the same as
  2110. long_from_binary_base.
  2111. Binary bases can be converted in time linear in the number of digits, because
  2112. Python's representation base is binary. Other bases (including decimal!) use
  2113. the simple quadratic-time algorithm below, complicated by some speed tricks.
  2114. First some math: the largest integer that can be expressed in N base-B digits
  2115. is B**N-1. Consequently, if we have an N-digit input in base B, the worst-
  2116. case number of Python digits needed to hold it is the smallest integer n s.t.
  2117. BASE**n-1 >= B**N-1 [or, adding 1 to both sides]
  2118. BASE**n >= B**N [taking logs to base BASE]
  2119. n >= log(B**N)/log(BASE) = N * log(B)/log(BASE)
  2120. The static array log_base_BASE[base] == log(base)/log(BASE) so we can compute
  2121. this quickly. A Python int with that much space is reserved near the start,
  2122. and the result is computed into it.
  2123. The input string is actually treated as being in base base**i (i.e., i digits
  2124. are processed at a time), where two more static arrays hold:
  2125. convwidth_base[base] = the largest integer i such that base**i <= BASE
  2126. convmultmax_base[base] = base ** convwidth_base[base]
  2127. The first of these is the largest i such that i consecutive input digits
  2128. must fit in a single Python digit. The second is effectively the input
  2129. base we're really using.
  2130. Viewing the input as a sequence <c0, c1, ..., c_n-1> of digits in base
  2131. convmultmax_base[base], the result is "simply"
  2132. (((c0*B + c1)*B + c2)*B + c3)*B + ... ))) + c_n-1
  2133. where B = convmultmax_base[base].
  2134. Error analysis: as above, the number of Python digits `n` needed is worst-
  2135. case
  2136. n >= N * log(B)/log(BASE)
  2137. where `N` is the number of input digits in base `B`. This is computed via
  2138. size_z = (Py_ssize_t)((scan - str) * log_base_BASE[base]) + 1;
  2139. below. Two numeric concerns are how much space this can waste, and whether
  2140. the computed result can be too small. To be concrete, assume BASE = 2**15,
  2141. which is the default (and it's unlikely anyone changes that).
  2142. Waste isn't a problem: provided the first input digit isn't 0, the difference
  2143. between the worst-case input with N digits and the smallest input with N
  2144. digits is about a factor of B, but B is small compared to BASE so at most
  2145. one allocated Python digit can remain unused on that count. If
  2146. N*log(B)/log(BASE) is mathematically an exact integer, then truncating that
  2147. and adding 1 returns a result 1 larger than necessary. However, that can't
  2148. happen: whenever B is a power of 2, long_from_binary_base() is called
  2149. instead, and it's impossible for B**i to be an integer power of 2**15 when
  2150. B is not a power of 2 (i.e., it's impossible for N*log(B)/log(BASE) to be
  2151. an exact integer when B is not a power of 2, since B**i has a prime factor
  2152. other than 2 in that case, but (2**15)**j's only prime factor is 2).
  2153. The computed result can be too small if the true value of N*log(B)/log(BASE)
  2154. is a little bit larger than an exact integer, but due to roundoff errors (in
  2155. computing log(B), log(BASE), their quotient, and/or multiplying that by N)
  2156. yields a numeric result a little less than that integer. Unfortunately, "how
  2157. close can a transcendental function get to an integer over some range?"
  2158. questions are generally theoretically intractable. Computer analysis via
  2159. continued fractions is practical: expand log(B)/log(BASE) via continued
  2160. fractions, giving a sequence i/j of "the best" rational approximations. Then
  2161. j*log(B)/log(BASE) is approximately equal to (the integer) i. This shows that
  2162. we can get very close to being in trouble, but very rarely. For example,
  2163. 76573 is a denominator in one of the continued-fraction approximations to
  2164. log(10)/log(2**15), and indeed:
  2165. >>> log(10)/log(2**15)*76573
  2166. 16958.000000654003
  2167. is very close to an integer. If we were working with IEEE single-precision,
  2168. rounding errors could kill us. Finding worst cases in IEEE double-precision
  2169. requires better-than-double-precision log() functions, and Tim didn't bother.
  2170. Instead the code checks to see whether the allocated space is enough as each
  2171. new Python digit is added, and copies the whole thing to a larger int if not.
  2172. This should happen extremely rarely, and in fact I don't have a test case
  2173. that triggers it(!). Instead the code was tested by artificially allocating
  2174. just 1 digit at the start, so that the copying code was exercised for every
  2175. digit beyond the first.
  2176. ***/
  2177. static int
  2178. long_from_non_binary_base(const char *start, const char *end, Py_ssize_t digits, int base, PyLongObject **res)
  2179. {
  2180. twodigits c; /* current input character */
  2181. Py_ssize_t size_z;
  2182. int i;
  2183. int convwidth;
  2184. twodigits convmultmax, convmult;
  2185. digit *pz, *pzstop;
  2186. PyLongObject *z;
  2187. const char *p;
  2188. static double log_base_BASE[37] = {0.0e0,};
  2189. static int convwidth_base[37] = {0,};
  2190. static twodigits convmultmax_base[37] = {0,};
  2191. if (log_base_BASE[base] == 0.0) {
  2192. twodigits convmax = base;
  2193. int i = 1;
  2194. log_base_BASE[base] = (log((double)base) /
  2195. log((double)PyLong_BASE));
  2196. for (;;) {
  2197. twodigits next = convmax * base;
  2198. if (next > PyLong_BASE) {
  2199. break;
  2200. }
  2201. convmax = next;
  2202. ++i;
  2203. }
  2204. convmultmax_base[base] = convmax;
  2205. assert(i > 0);
  2206. convwidth_base[base] = i;
  2207. }
  2208. /* Create an int object that can contain the largest possible
  2209. * integer with this base and length. Note that there's no
  2210. * need to initialize z->long_value.ob_digit -- no slot is read up before
  2211. * being stored into.
  2212. */
  2213. double fsize_z = (double)digits * log_base_BASE[base] + 1.0;
  2214. if (fsize_z > (double)MAX_LONG_DIGITS) {
  2215. /* The same exception as in _PyLong_New(). */
  2216. PyErr_SetString(PyExc_OverflowError,
  2217. "too many digits in integer");
  2218. *res = NULL;
  2219. return 0;
  2220. }
  2221. size_z = (Py_ssize_t)fsize_z;
  2222. /* Uncomment next line to test exceedingly rare copy code */
  2223. /* size_z = 1; */
  2224. assert(size_z > 0);
  2225. z = _PyLong_New(size_z);
  2226. if (z == NULL) {
  2227. *res = NULL;
  2228. return 0;
  2229. }
  2230. _PyLong_SetSignAndDigitCount(z, 0, 0);
  2231. /* `convwidth` consecutive input digits are treated as a single
  2232. * digit in base `convmultmax`.
  2233. */
  2234. convwidth = convwidth_base[base];
  2235. convmultmax = convmultmax_base[base];
  2236. /* Work ;-) */
  2237. p = start;
  2238. while (p < end) {
  2239. if (*p == '_') {
  2240. p++;
  2241. continue;
  2242. }
  2243. /* grab up to convwidth digits from the input string */
  2244. c = (digit)_PyLong_DigitValue[Py_CHARMASK(*p++)];
  2245. for (i = 1; i < convwidth && p != end; ++p) {
  2246. if (*p == '_') {
  2247. continue;
  2248. }
  2249. i++;
  2250. c = (twodigits)(c * base +
  2251. (int)_PyLong_DigitValue[Py_CHARMASK(*p)]);
  2252. assert(c < PyLong_BASE);
  2253. }
  2254. convmult = convmultmax;
  2255. /* Calculate the shift only if we couldn't get
  2256. * convwidth digits.
  2257. */
  2258. if (i != convwidth) {
  2259. convmult = base;
  2260. for ( ; i > 1; --i) {
  2261. convmult *= base;
  2262. }
  2263. }
  2264. /* Multiply z by convmult, and add c. */
  2265. pz = z->long_value.ob_digit;
  2266. pzstop = pz + _PyLong_DigitCount(z);
  2267. for (; pz < pzstop; ++pz) {
  2268. c += (twodigits)*pz * convmult;
  2269. *pz = (digit)(c & PyLong_MASK);
  2270. c >>= PyLong_SHIFT;
  2271. }
  2272. /* carry off the current end? */
  2273. if (c) {
  2274. assert(c < PyLong_BASE);
  2275. if (_PyLong_DigitCount(z) < size_z) {
  2276. *pz = (digit)c;
  2277. assert(!_PyLong_IsNegative(z));
  2278. _PyLong_SetSignAndDigitCount(z, 1, _PyLong_DigitCount(z) + 1);
  2279. }
  2280. else {
  2281. PyLongObject *tmp;
  2282. /* Extremely rare. Get more space. */
  2283. assert(_PyLong_DigitCount(z) == size_z);
  2284. tmp = _PyLong_New(size_z + 1);
  2285. if (tmp == NULL) {
  2286. Py_DECREF(z);
  2287. *res = NULL;
  2288. return 0;
  2289. }
  2290. memcpy(tmp->long_value.ob_digit,
  2291. z->long_value.ob_digit,
  2292. sizeof(digit) * size_z);
  2293. Py_SETREF(z, tmp);
  2294. z->long_value.ob_digit[size_z] = (digit)c;
  2295. ++size_z;
  2296. }
  2297. }
  2298. }
  2299. *res = z;
  2300. return 0;
  2301. }
  2302. /* *str points to the first digit in a string of base `base` digits. base is an
  2303. * integer from 2 to 36 inclusive. Here we don't need to worry about prefixes
  2304. * like 0x or leading +- signs. The string should be null terminated consisting
  2305. * of ASCII digits and separating underscores possibly with trailing whitespace
  2306. * but we have to validate all of those points here.
  2307. *
  2308. * If base is a power of 2 then the complexity is linear in the number of
  2309. * characters in the string. Otherwise a quadratic algorithm is used for
  2310. * non-binary bases.
  2311. *
  2312. * Return values:
  2313. *
  2314. * - Returns -1 on syntax error (exception needs to be set, *res is untouched)
  2315. * - Returns 0 and sets *res to NULL for MemoryError, OverflowError, or
  2316. * _pylong.int_from_string() errors.
  2317. * - Returns 0 and sets *res to an unsigned, unnormalized PyLong (success!).
  2318. *
  2319. * Afterwards *str is set to point to the first non-digit (which may be *str!).
  2320. */
  2321. static int
  2322. long_from_string_base(const char **str, int base, PyLongObject **res)
  2323. {
  2324. const char *start, *end, *p;
  2325. char prev = 0;
  2326. Py_ssize_t digits = 0;
  2327. int is_binary_base = (base & (base - 1)) == 0;
  2328. /* Here we do four things:
  2329. *
  2330. * - Find the `end` of the string.
  2331. * - Validate the string.
  2332. * - Count the number of `digits` (rather than underscores)
  2333. * - Point *str to the end-of-string or first invalid character.
  2334. */
  2335. start = p = *str;
  2336. /* Leading underscore not allowed. */
  2337. if (*start == '_') {
  2338. return -1;
  2339. }
  2340. /* Verify all characters are digits and underscores. */
  2341. while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base || *p == '_') {
  2342. if (*p == '_') {
  2343. /* Double underscore not allowed. */
  2344. if (prev == '_') {
  2345. *str = p - 1;
  2346. return -1;
  2347. }
  2348. } else {
  2349. ++digits;
  2350. }
  2351. prev = *p;
  2352. ++p;
  2353. }
  2354. /* Trailing underscore not allowed. */
  2355. if (prev == '_') {
  2356. *str = p - 1;
  2357. return -1;
  2358. }
  2359. *str = end = p;
  2360. /* Reject empty strings */
  2361. if (start == end) {
  2362. return -1;
  2363. }
  2364. /* Allow only trailing whitespace after `end` */
  2365. while (*p && Py_ISSPACE(*p)) {
  2366. p++;
  2367. }
  2368. *str = p;
  2369. if (*p != '\0') {
  2370. return -1;
  2371. }
  2372. /*
  2373. * Pass a validated string consisting of only valid digits and underscores
  2374. * to long_from_xxx_base.
  2375. */
  2376. if (is_binary_base) {
  2377. /* Use the linear algorithm for binary bases. */
  2378. return long_from_binary_base(start, end, digits, base, res);
  2379. }
  2380. else {
  2381. /* Limit the size to avoid excessive computation attacks exploiting the
  2382. * quadratic algorithm. */
  2383. if (digits > _PY_LONG_MAX_STR_DIGITS_THRESHOLD) {
  2384. PyInterpreterState *interp = _PyInterpreterState_GET();
  2385. int max_str_digits = interp->long_state.max_str_digits;
  2386. if ((max_str_digits > 0) && (digits > max_str_digits)) {
  2387. PyErr_Format(PyExc_ValueError, _MAX_STR_DIGITS_ERROR_FMT_TO_INT,
  2388. max_str_digits, digits);
  2389. *res = NULL;
  2390. return 0;
  2391. }
  2392. }
  2393. #if WITH_PYLONG_MODULE
  2394. if (digits > 6000 && base == 10) {
  2395. /* Switch to _pylong.int_from_string() */
  2396. return pylong_int_from_string(start, end, res);
  2397. }
  2398. #endif
  2399. /* Use the quadratic algorithm for non binary bases. */
  2400. return long_from_non_binary_base(start, end, digits, base, res);
  2401. }
  2402. }
  2403. /* Parses an int from a bytestring. Leading and trailing whitespace will be
  2404. * ignored.
  2405. *
  2406. * If successful, a PyLong object will be returned and 'pend' will be pointing
  2407. * to the first unused byte unless it's NULL.
  2408. *
  2409. * If unsuccessful, NULL will be returned.
  2410. */
  2411. PyObject *
  2412. PyLong_FromString(const char *str, char **pend, int base)
  2413. {
  2414. int sign = 1, error_if_nonzero = 0;
  2415. const char *orig_str = str;
  2416. PyLongObject *z = NULL;
  2417. PyObject *strobj;
  2418. Py_ssize_t slen;
  2419. if ((base != 0 && base < 2) || base > 36) {
  2420. PyErr_SetString(PyExc_ValueError,
  2421. "int() arg 2 must be >= 2 and <= 36");
  2422. return NULL;
  2423. }
  2424. while (*str != '\0' && Py_ISSPACE(*str)) {
  2425. ++str;
  2426. }
  2427. if (*str == '+') {
  2428. ++str;
  2429. }
  2430. else if (*str == '-') {
  2431. ++str;
  2432. sign = -1;
  2433. }
  2434. if (base == 0) {
  2435. if (str[0] != '0') {
  2436. base = 10;
  2437. }
  2438. else if (str[1] == 'x' || str[1] == 'X') {
  2439. base = 16;
  2440. }
  2441. else if (str[1] == 'o' || str[1] == 'O') {
  2442. base = 8;
  2443. }
  2444. else if (str[1] == 'b' || str[1] == 'B') {
  2445. base = 2;
  2446. }
  2447. else {
  2448. /* "old" (C-style) octal literal, now invalid.
  2449. it might still be zero though */
  2450. error_if_nonzero = 1;
  2451. base = 10;
  2452. }
  2453. }
  2454. if (str[0] == '0' &&
  2455. ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
  2456. (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
  2457. (base == 2 && (str[1] == 'b' || str[1] == 'B')))) {
  2458. str += 2;
  2459. /* One underscore allowed here. */
  2460. if (*str == '_') {
  2461. ++str;
  2462. }
  2463. }
  2464. /* long_from_string_base is the main workhorse here. */
  2465. int ret = long_from_string_base(&str, base, &z);
  2466. if (ret == -1) {
  2467. /* Syntax error. */
  2468. goto onError;
  2469. }
  2470. if (z == NULL) {
  2471. /* Error. exception already set. */
  2472. return NULL;
  2473. }
  2474. if (error_if_nonzero) {
  2475. /* reset the base to 0, else the exception message
  2476. doesn't make too much sense */
  2477. base = 0;
  2478. if (!_PyLong_IsZero(z)) {
  2479. goto onError;
  2480. }
  2481. /* there might still be other problems, therefore base
  2482. remains zero here for the same reason */
  2483. }
  2484. /* Set sign and normalize */
  2485. if (sign < 0) {
  2486. _PyLong_FlipSign(z);
  2487. }
  2488. long_normalize(z);
  2489. z = maybe_small_long(z);
  2490. if (pend != NULL) {
  2491. *pend = (char *)str;
  2492. }
  2493. return (PyObject *) z;
  2494. onError:
  2495. if (pend != NULL) {
  2496. *pend = (char *)str;
  2497. }
  2498. Py_XDECREF(z);
  2499. slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
  2500. strobj = PyUnicode_FromStringAndSize(orig_str, slen);
  2501. if (strobj == NULL) {
  2502. return NULL;
  2503. }
  2504. PyErr_Format(PyExc_ValueError,
  2505. "invalid literal for int() with base %d: %.200R",
  2506. base, strobj);
  2507. Py_DECREF(strobj);
  2508. return NULL;
  2509. }
  2510. /* Since PyLong_FromString doesn't have a length parameter,
  2511. * check here for possible NULs in the string.
  2512. *
  2513. * Reports an invalid literal as a bytes object.
  2514. */
  2515. PyObject *
  2516. _PyLong_FromBytes(const char *s, Py_ssize_t len, int base)
  2517. {
  2518. PyObject *result, *strobj;
  2519. char *end = NULL;
  2520. result = PyLong_FromString(s, &end, base);
  2521. if (end == NULL || (result != NULL && end == s + len))
  2522. return result;
  2523. Py_XDECREF(result);
  2524. strobj = PyBytes_FromStringAndSize(s, Py_MIN(len, 200));
  2525. if (strobj != NULL) {
  2526. PyErr_Format(PyExc_ValueError,
  2527. "invalid literal for int() with base %d: %.200R",
  2528. base, strobj);
  2529. Py_DECREF(strobj);
  2530. }
  2531. return NULL;
  2532. }
  2533. PyObject *
  2534. PyLong_FromUnicodeObject(PyObject *u, int base)
  2535. {
  2536. PyObject *result, *asciidig;
  2537. const char *buffer;
  2538. char *end = NULL;
  2539. Py_ssize_t buflen;
  2540. asciidig = _PyUnicode_TransformDecimalAndSpaceToASCII(u);
  2541. if (asciidig == NULL)
  2542. return NULL;
  2543. assert(PyUnicode_IS_ASCII(asciidig));
  2544. /* Simply get a pointer to existing ASCII characters. */
  2545. buffer = PyUnicode_AsUTF8AndSize(asciidig, &buflen);
  2546. assert(buffer != NULL);
  2547. result = PyLong_FromString(buffer, &end, base);
  2548. if (end == NULL || (result != NULL && end == buffer + buflen)) {
  2549. Py_DECREF(asciidig);
  2550. return result;
  2551. }
  2552. Py_DECREF(asciidig);
  2553. Py_XDECREF(result);
  2554. PyErr_Format(PyExc_ValueError,
  2555. "invalid literal for int() with base %d: %.200R",
  2556. base, u);
  2557. return NULL;
  2558. }
  2559. /* forward */
  2560. static PyLongObject *x_divrem
  2561. (PyLongObject *, PyLongObject *, PyLongObject **);
  2562. static PyObject *long_long(PyObject *v);
  2563. /* Int division with remainder, top-level routine */
  2564. static int
  2565. long_divrem(PyLongObject *a, PyLongObject *b,
  2566. PyLongObject **pdiv, PyLongObject **prem)
  2567. {
  2568. Py_ssize_t size_a = _PyLong_DigitCount(a), size_b = _PyLong_DigitCount(b);
  2569. PyLongObject *z;
  2570. if (size_b == 0) {
  2571. PyErr_SetString(PyExc_ZeroDivisionError,
  2572. "integer division or modulo by zero");
  2573. return -1;
  2574. }
  2575. if (size_a < size_b ||
  2576. (size_a == size_b &&
  2577. a->long_value.ob_digit[size_a-1] < b->long_value.ob_digit[size_b-1])) {
  2578. /* |a| < |b|. */
  2579. *prem = (PyLongObject *)long_long((PyObject *)a);
  2580. if (*prem == NULL) {
  2581. return -1;
  2582. }
  2583. PyObject *zero = _PyLong_GetZero();
  2584. *pdiv = (PyLongObject*)Py_NewRef(zero);
  2585. return 0;
  2586. }
  2587. if (size_b == 1) {
  2588. digit rem = 0;
  2589. z = divrem1(a, b->long_value.ob_digit[0], &rem);
  2590. if (z == NULL)
  2591. return -1;
  2592. *prem = (PyLongObject *) PyLong_FromLong((long)rem);
  2593. if (*prem == NULL) {
  2594. Py_DECREF(z);
  2595. return -1;
  2596. }
  2597. }
  2598. else {
  2599. z = x_divrem(a, b, prem);
  2600. *prem = maybe_small_long(*prem);
  2601. if (z == NULL)
  2602. return -1;
  2603. }
  2604. /* Set the signs.
  2605. The quotient z has the sign of a*b;
  2606. the remainder r has the sign of a,
  2607. so a = b*z + r. */
  2608. if ((_PyLong_IsNegative(a)) != (_PyLong_IsNegative(b))) {
  2609. _PyLong_Negate(&z);
  2610. if (z == NULL) {
  2611. Py_CLEAR(*prem);
  2612. return -1;
  2613. }
  2614. }
  2615. if (_PyLong_IsNegative(a) && !_PyLong_IsZero(*prem)) {
  2616. _PyLong_Negate(prem);
  2617. if (*prem == NULL) {
  2618. Py_DECREF(z);
  2619. Py_CLEAR(*prem);
  2620. return -1;
  2621. }
  2622. }
  2623. *pdiv = maybe_small_long(z);
  2624. return 0;
  2625. }
  2626. /* Int remainder, top-level routine */
  2627. static int
  2628. long_rem(PyLongObject *a, PyLongObject *b, PyLongObject **prem)
  2629. {
  2630. Py_ssize_t size_a = _PyLong_DigitCount(a), size_b = _PyLong_DigitCount(b);
  2631. if (size_b == 0) {
  2632. PyErr_SetString(PyExc_ZeroDivisionError,
  2633. "integer modulo by zero");
  2634. return -1;
  2635. }
  2636. if (size_a < size_b ||
  2637. (size_a == size_b &&
  2638. a->long_value.ob_digit[size_a-1] < b->long_value.ob_digit[size_b-1])) {
  2639. /* |a| < |b|. */
  2640. *prem = (PyLongObject *)long_long((PyObject *)a);
  2641. return -(*prem == NULL);
  2642. }
  2643. if (size_b == 1) {
  2644. *prem = rem1(a, b->long_value.ob_digit[0]);
  2645. if (*prem == NULL)
  2646. return -1;
  2647. }
  2648. else {
  2649. /* Slow path using divrem. */
  2650. Py_XDECREF(x_divrem(a, b, prem));
  2651. *prem = maybe_small_long(*prem);
  2652. if (*prem == NULL)
  2653. return -1;
  2654. }
  2655. /* Set the sign. */
  2656. if (_PyLong_IsNegative(a) && !_PyLong_IsZero(*prem)) {
  2657. _PyLong_Negate(prem);
  2658. if (*prem == NULL) {
  2659. Py_CLEAR(*prem);
  2660. return -1;
  2661. }
  2662. }
  2663. return 0;
  2664. }
  2665. /* Unsigned int division with remainder -- the algorithm. The arguments v1
  2666. and w1 should satisfy 2 <= _PyLong_DigitCount(w1) <= _PyLong_DigitCount(v1). */
  2667. static PyLongObject *
  2668. x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
  2669. {
  2670. PyLongObject *v, *w, *a;
  2671. Py_ssize_t i, k, size_v, size_w;
  2672. int d;
  2673. digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
  2674. twodigits vv;
  2675. sdigit zhi;
  2676. stwodigits z;
  2677. /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
  2678. edn.), section 4.3.1, Algorithm D], except that we don't explicitly
  2679. handle the special case when the initial estimate q for a quotient
  2680. digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
  2681. that won't overflow a digit. */
  2682. /* allocate space; w will also be used to hold the final remainder */
  2683. size_v = _PyLong_DigitCount(v1);
  2684. size_w = _PyLong_DigitCount(w1);
  2685. assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
  2686. v = _PyLong_New(size_v+1);
  2687. if (v == NULL) {
  2688. *prem = NULL;
  2689. return NULL;
  2690. }
  2691. w = _PyLong_New(size_w);
  2692. if (w == NULL) {
  2693. Py_DECREF(v);
  2694. *prem = NULL;
  2695. return NULL;
  2696. }
  2697. /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
  2698. shift v1 left by the same amount. Results go into w and v. */
  2699. d = PyLong_SHIFT - bit_length_digit(w1->long_value.ob_digit[size_w-1]);
  2700. carry = v_lshift(w->long_value.ob_digit, w1->long_value.ob_digit, size_w, d);
  2701. assert(carry == 0);
  2702. carry = v_lshift(v->long_value.ob_digit, v1->long_value.ob_digit, size_v, d);
  2703. if (carry != 0 || v->long_value.ob_digit[size_v-1] >= w->long_value.ob_digit[size_w-1]) {
  2704. v->long_value.ob_digit[size_v] = carry;
  2705. size_v++;
  2706. }
  2707. /* Now v->long_value.ob_digit[size_v-1] < w->long_value.ob_digit[size_w-1], so quotient has
  2708. at most (and usually exactly) k = size_v - size_w digits. */
  2709. k = size_v - size_w;
  2710. assert(k >= 0);
  2711. a = _PyLong_New(k);
  2712. if (a == NULL) {
  2713. Py_DECREF(w);
  2714. Py_DECREF(v);
  2715. *prem = NULL;
  2716. return NULL;
  2717. }
  2718. v0 = v->long_value.ob_digit;
  2719. w0 = w->long_value.ob_digit;
  2720. wm1 = w0[size_w-1];
  2721. wm2 = w0[size_w-2];
  2722. for (vk = v0+k, ak = a->long_value.ob_digit + k; vk-- > v0;) {
  2723. /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
  2724. single-digit quotient q, remainder in vk[0:size_w]. */
  2725. SIGCHECK({
  2726. Py_DECREF(a);
  2727. Py_DECREF(w);
  2728. Py_DECREF(v);
  2729. *prem = NULL;
  2730. return NULL;
  2731. });
  2732. /* estimate quotient digit q; may overestimate by 1 (rare) */
  2733. vtop = vk[size_w];
  2734. assert(vtop <= wm1);
  2735. vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
  2736. /* The code used to compute the remainder via
  2737. * r = (digit)(vv - (twodigits)wm1 * q);
  2738. * and compilers generally generated code to do the * and -.
  2739. * But modern processors generally compute q and r with a single
  2740. * instruction, and modern optimizing compilers exploit that if we
  2741. * _don't_ try to optimize it.
  2742. */
  2743. q = (digit)(vv / wm1);
  2744. r = (digit)(vv % wm1);
  2745. while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
  2746. | vk[size_w-2])) {
  2747. --q;
  2748. r += wm1;
  2749. if (r >= PyLong_BASE)
  2750. break;
  2751. }
  2752. assert(q <= PyLong_BASE);
  2753. /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
  2754. zhi = 0;
  2755. for (i = 0; i < size_w; ++i) {
  2756. /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
  2757. -PyLong_BASE * q <= z < PyLong_BASE */
  2758. z = (sdigit)vk[i] + zhi -
  2759. (stwodigits)q * (stwodigits)w0[i];
  2760. vk[i] = (digit)z & PyLong_MASK;
  2761. zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
  2762. z, PyLong_SHIFT);
  2763. }
  2764. /* add w back if q was too large (this branch taken rarely) */
  2765. assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
  2766. if ((sdigit)vtop + zhi < 0) {
  2767. carry = 0;
  2768. for (i = 0; i < size_w; ++i) {
  2769. carry += vk[i] + w0[i];
  2770. vk[i] = carry & PyLong_MASK;
  2771. carry >>= PyLong_SHIFT;
  2772. }
  2773. --q;
  2774. }
  2775. /* store quotient digit */
  2776. assert(q < PyLong_BASE);
  2777. *--ak = q;
  2778. }
  2779. /* unshift remainder; we reuse w to store the result */
  2780. carry = v_rshift(w0, v0, size_w, d);
  2781. assert(carry==0);
  2782. Py_DECREF(v);
  2783. *prem = long_normalize(w);
  2784. return long_normalize(a);
  2785. }
  2786. /* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
  2787. abs(x) < 1.0 and e >= 0; return x and put e in *e. Here x is
  2788. rounded to DBL_MANT_DIG significant bits using round-half-to-even.
  2789. If a == 0, return 0.0 and set *e = 0. If the resulting exponent
  2790. e is larger than PY_SSIZE_T_MAX, raise OverflowError and return
  2791. -1.0. */
  2792. /* attempt to define 2.0**DBL_MANT_DIG as a compile-time constant */
  2793. #if DBL_MANT_DIG == 53
  2794. #define EXP2_DBL_MANT_DIG 9007199254740992.0
  2795. #else
  2796. #define EXP2_DBL_MANT_DIG (ldexp(1.0, DBL_MANT_DIG))
  2797. #endif
  2798. double
  2799. _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
  2800. {
  2801. Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
  2802. /* See below for why x_digits is always large enough. */
  2803. digit rem;
  2804. digit x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT] = {0,};
  2805. double dx;
  2806. /* Correction term for round-half-to-even rounding. For a digit x,
  2807. "x + half_even_correction[x & 7]" gives x rounded to the nearest
  2808. multiple of 4, rounding ties to a multiple of 8. */
  2809. static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
  2810. a_size = _PyLong_DigitCount(a);
  2811. if (a_size == 0) {
  2812. /* Special case for 0: significand 0.0, exponent 0. */
  2813. *e = 0;
  2814. return 0.0;
  2815. }
  2816. a_bits = bit_length_digit(a->long_value.ob_digit[a_size-1]);
  2817. /* The following is an overflow-free version of the check
  2818. "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
  2819. if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
  2820. (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
  2821. a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
  2822. goto overflow;
  2823. a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
  2824. /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
  2825. (shifting left if a_bits <= DBL_MANT_DIG + 2).
  2826. Number of digits needed for result: write // for floor division.
  2827. Then if shifting left, we end up using
  2828. 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
  2829. digits. If shifting right, we use
  2830. a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
  2831. digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
  2832. the inequalities
  2833. m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
  2834. m // PyLong_SHIFT - n // PyLong_SHIFT <=
  2835. 1 + (m - n - 1) // PyLong_SHIFT,
  2836. valid for any integers m and n, we find that x_size satisfies
  2837. x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
  2838. in both cases.
  2839. */
  2840. if (a_bits <= DBL_MANT_DIG + 2) {
  2841. shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
  2842. shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
  2843. x_size = shift_digits;
  2844. rem = v_lshift(x_digits + x_size, a->long_value.ob_digit, a_size,
  2845. (int)shift_bits);
  2846. x_size += a_size;
  2847. x_digits[x_size++] = rem;
  2848. }
  2849. else {
  2850. shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
  2851. shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
  2852. rem = v_rshift(x_digits, a->long_value.ob_digit + shift_digits,
  2853. a_size - shift_digits, (int)shift_bits);
  2854. x_size = a_size - shift_digits;
  2855. /* For correct rounding below, we need the least significant
  2856. bit of x to be 'sticky' for this shift: if any of the bits
  2857. shifted out was nonzero, we set the least significant bit
  2858. of x. */
  2859. if (rem)
  2860. x_digits[0] |= 1;
  2861. else
  2862. while (shift_digits > 0)
  2863. if (a->long_value.ob_digit[--shift_digits]) {
  2864. x_digits[0] |= 1;
  2865. break;
  2866. }
  2867. }
  2868. assert(1 <= x_size && x_size <= (Py_ssize_t)Py_ARRAY_LENGTH(x_digits));
  2869. /* Round, and convert to double. */
  2870. x_digits[0] += half_even_correction[x_digits[0] & 7];
  2871. dx = x_digits[--x_size];
  2872. while (x_size > 0)
  2873. dx = dx * PyLong_BASE + x_digits[--x_size];
  2874. /* Rescale; make correction if result is 1.0. */
  2875. dx /= 4.0 * EXP2_DBL_MANT_DIG;
  2876. if (dx == 1.0) {
  2877. if (a_bits == PY_SSIZE_T_MAX)
  2878. goto overflow;
  2879. dx = 0.5;
  2880. a_bits += 1;
  2881. }
  2882. *e = a_bits;
  2883. return _PyLong_IsNegative(a) ? -dx : dx;
  2884. overflow:
  2885. /* exponent > PY_SSIZE_T_MAX */
  2886. PyErr_SetString(PyExc_OverflowError,
  2887. "huge integer: number of bits overflows a Py_ssize_t");
  2888. *e = 0;
  2889. return -1.0;
  2890. }
  2891. /* Get a C double from an int object. Rounds to the nearest double,
  2892. using the round-half-to-even rule in the case of a tie. */
  2893. double
  2894. PyLong_AsDouble(PyObject *v)
  2895. {
  2896. Py_ssize_t exponent;
  2897. double x;
  2898. if (v == NULL) {
  2899. PyErr_BadInternalCall();
  2900. return -1.0;
  2901. }
  2902. if (!PyLong_Check(v)) {
  2903. PyErr_SetString(PyExc_TypeError, "an integer is required");
  2904. return -1.0;
  2905. }
  2906. if (_PyLong_IsCompact((PyLongObject *)v)) {
  2907. /* Fast path; single digit long (31 bits) will cast safely
  2908. to double. This improves performance of FP/long operations
  2909. by 20%.
  2910. */
  2911. return (double)medium_value((PyLongObject *)v);
  2912. }
  2913. x = _PyLong_Frexp((PyLongObject *)v, &exponent);
  2914. if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
  2915. PyErr_SetString(PyExc_OverflowError,
  2916. "int too large to convert to float");
  2917. return -1.0;
  2918. }
  2919. return ldexp(x, (int)exponent);
  2920. }
  2921. /* Methods */
  2922. /* if a < b, return a negative number
  2923. if a == b, return 0
  2924. if a > b, return a positive number */
  2925. static Py_ssize_t
  2926. long_compare(PyLongObject *a, PyLongObject *b)
  2927. {
  2928. if (_PyLong_BothAreCompact(a, b)) {
  2929. return _PyLong_CompactValue(a) - _PyLong_CompactValue(b);
  2930. }
  2931. Py_ssize_t sign = _PyLong_SignedDigitCount(a) - _PyLong_SignedDigitCount(b);
  2932. if (sign == 0) {
  2933. Py_ssize_t i = _PyLong_DigitCount(a);
  2934. sdigit diff = 0;
  2935. while (--i >= 0) {
  2936. diff = (sdigit) a->long_value.ob_digit[i] - (sdigit) b->long_value.ob_digit[i];
  2937. if (diff) {
  2938. break;
  2939. }
  2940. }
  2941. sign = _PyLong_IsNegative(a) ? -diff : diff;
  2942. }
  2943. return sign;
  2944. }
  2945. static PyObject *
  2946. long_richcompare(PyObject *self, PyObject *other, int op)
  2947. {
  2948. Py_ssize_t result;
  2949. CHECK_BINOP(self, other);
  2950. if (self == other)
  2951. result = 0;
  2952. else
  2953. result = long_compare((PyLongObject*)self, (PyLongObject*)other);
  2954. Py_RETURN_RICHCOMPARE(result, 0, op);
  2955. }
  2956. static void
  2957. long_dealloc(PyObject *self)
  2958. {
  2959. /* This should never get called, but we also don't want to SEGV if
  2960. * we accidentally decref small Ints out of existence. Instead,
  2961. * since small Ints are immortal, re-set the reference count.
  2962. */
  2963. PyLongObject *pylong = (PyLongObject*)self;
  2964. if (pylong && _PyLong_IsCompact(pylong)) {
  2965. stwodigits ival = medium_value(pylong);
  2966. if (IS_SMALL_INT(ival)) {
  2967. PyLongObject *small_pylong = (PyLongObject *)get_small_int((sdigit)ival);
  2968. if (pylong == small_pylong) {
  2969. _Py_SetImmortal(self);
  2970. return;
  2971. }
  2972. }
  2973. }
  2974. Py_TYPE(self)->tp_free(self);
  2975. }
  2976. static Py_hash_t
  2977. long_hash(PyLongObject *v)
  2978. {
  2979. Py_uhash_t x;
  2980. Py_ssize_t i;
  2981. int sign;
  2982. if (_PyLong_IsCompact(v)) {
  2983. x = _PyLong_CompactValue(v);
  2984. if (x == (Py_uhash_t)-1) {
  2985. x = (Py_uhash_t)-2;
  2986. }
  2987. return x;
  2988. }
  2989. i = _PyLong_DigitCount(v);
  2990. sign = _PyLong_NonCompactSign(v);
  2991. x = 0;
  2992. while (--i >= 0) {
  2993. /* Here x is a quantity in the range [0, _PyHASH_MODULUS); we
  2994. want to compute x * 2**PyLong_SHIFT + v->long_value.ob_digit[i] modulo
  2995. _PyHASH_MODULUS.
  2996. The computation of x * 2**PyLong_SHIFT % _PyHASH_MODULUS
  2997. amounts to a rotation of the bits of x. To see this, write
  2998. x * 2**PyLong_SHIFT = y * 2**_PyHASH_BITS + z
  2999. where y = x >> (_PyHASH_BITS - PyLong_SHIFT) gives the top
  3000. PyLong_SHIFT bits of x (those that are shifted out of the
  3001. original _PyHASH_BITS bits, and z = (x << PyLong_SHIFT) &
  3002. _PyHASH_MODULUS gives the bottom _PyHASH_BITS - PyLong_SHIFT
  3003. bits of x, shifted up. Then since 2**_PyHASH_BITS is
  3004. congruent to 1 modulo _PyHASH_MODULUS, y*2**_PyHASH_BITS is
  3005. congruent to y modulo _PyHASH_MODULUS. So
  3006. x * 2**PyLong_SHIFT = y + z (mod _PyHASH_MODULUS).
  3007. The right-hand side is just the result of rotating the
  3008. _PyHASH_BITS bits of x left by PyLong_SHIFT places; since
  3009. not all _PyHASH_BITS bits of x are 1s, the same is true
  3010. after rotation, so 0 <= y+z < _PyHASH_MODULUS and y + z is
  3011. the reduction of x*2**PyLong_SHIFT modulo
  3012. _PyHASH_MODULUS. */
  3013. x = ((x << PyLong_SHIFT) & _PyHASH_MODULUS) |
  3014. (x >> (_PyHASH_BITS - PyLong_SHIFT));
  3015. x += v->long_value.ob_digit[i];
  3016. if (x >= _PyHASH_MODULUS)
  3017. x -= _PyHASH_MODULUS;
  3018. }
  3019. x = x * sign;
  3020. if (x == (Py_uhash_t)-1)
  3021. x = (Py_uhash_t)-2;
  3022. return (Py_hash_t)x;
  3023. }
  3024. /* Add the absolute values of two integers. */
  3025. static PyLongObject *
  3026. x_add(PyLongObject *a, PyLongObject *b)
  3027. {
  3028. Py_ssize_t size_a = _PyLong_DigitCount(a), size_b = _PyLong_DigitCount(b);
  3029. PyLongObject *z;
  3030. Py_ssize_t i;
  3031. digit carry = 0;
  3032. /* Ensure a is the larger of the two: */
  3033. if (size_a < size_b) {
  3034. { PyLongObject *temp = a; a = b; b = temp; }
  3035. { Py_ssize_t size_temp = size_a;
  3036. size_a = size_b;
  3037. size_b = size_temp; }
  3038. }
  3039. z = _PyLong_New(size_a+1);
  3040. if (z == NULL)
  3041. return NULL;
  3042. for (i = 0; i < size_b; ++i) {
  3043. carry += a->long_value.ob_digit[i] + b->long_value.ob_digit[i];
  3044. z->long_value.ob_digit[i] = carry & PyLong_MASK;
  3045. carry >>= PyLong_SHIFT;
  3046. }
  3047. for (; i < size_a; ++i) {
  3048. carry += a->long_value.ob_digit[i];
  3049. z->long_value.ob_digit[i] = carry & PyLong_MASK;
  3050. carry >>= PyLong_SHIFT;
  3051. }
  3052. z->long_value.ob_digit[i] = carry;
  3053. return long_normalize(z);
  3054. }
  3055. /* Subtract the absolute values of two integers. */
  3056. static PyLongObject *
  3057. x_sub(PyLongObject *a, PyLongObject *b)
  3058. {
  3059. Py_ssize_t size_a = _PyLong_DigitCount(a), size_b = _PyLong_DigitCount(b);
  3060. PyLongObject *z;
  3061. Py_ssize_t i;
  3062. int sign = 1;
  3063. digit borrow = 0;
  3064. /* Ensure a is the larger of the two: */
  3065. if (size_a < size_b) {
  3066. sign = -1;
  3067. { PyLongObject *temp = a; a = b; b = temp; }
  3068. { Py_ssize_t size_temp = size_a;
  3069. size_a = size_b;
  3070. size_b = size_temp; }
  3071. }
  3072. else if (size_a == size_b) {
  3073. /* Find highest digit where a and b differ: */
  3074. i = size_a;
  3075. while (--i >= 0 && a->long_value.ob_digit[i] == b->long_value.ob_digit[i])
  3076. ;
  3077. if (i < 0)
  3078. return (PyLongObject *)PyLong_FromLong(0);
  3079. if (a->long_value.ob_digit[i] < b->long_value.ob_digit[i]) {
  3080. sign = -1;
  3081. { PyLongObject *temp = a; a = b; b = temp; }
  3082. }
  3083. size_a = size_b = i+1;
  3084. }
  3085. z = _PyLong_New(size_a);
  3086. if (z == NULL)
  3087. return NULL;
  3088. for (i = 0; i < size_b; ++i) {
  3089. /* The following assumes unsigned arithmetic
  3090. works module 2**N for some N>PyLong_SHIFT. */
  3091. borrow = a->long_value.ob_digit[i] - b->long_value.ob_digit[i] - borrow;
  3092. z->long_value.ob_digit[i] = borrow & PyLong_MASK;
  3093. borrow >>= PyLong_SHIFT;
  3094. borrow &= 1; /* Keep only one sign bit */
  3095. }
  3096. for (; i < size_a; ++i) {
  3097. borrow = a->long_value.ob_digit[i] - borrow;
  3098. z->long_value.ob_digit[i] = borrow & PyLong_MASK;
  3099. borrow >>= PyLong_SHIFT;
  3100. borrow &= 1; /* Keep only one sign bit */
  3101. }
  3102. assert(borrow == 0);
  3103. if (sign < 0) {
  3104. _PyLong_FlipSign(z);
  3105. }
  3106. return maybe_small_long(long_normalize(z));
  3107. }
  3108. PyObject *
  3109. _PyLong_Add(PyLongObject *a, PyLongObject *b)
  3110. {
  3111. if (_PyLong_BothAreCompact(a, b)) {
  3112. return _PyLong_FromSTwoDigits(medium_value(a) + medium_value(b));
  3113. }
  3114. PyLongObject *z;
  3115. if (_PyLong_IsNegative(a)) {
  3116. if (_PyLong_IsNegative(b)) {
  3117. z = x_add(a, b);
  3118. if (z != NULL) {
  3119. /* x_add received at least one multiple-digit int,
  3120. and thus z must be a multiple-digit int.
  3121. That also means z is not an element of
  3122. small_ints, so negating it in-place is safe. */
  3123. assert(Py_REFCNT(z) == 1);
  3124. _PyLong_FlipSign(z);
  3125. }
  3126. }
  3127. else
  3128. z = x_sub(b, a);
  3129. }
  3130. else {
  3131. if (_PyLong_IsNegative(b))
  3132. z = x_sub(a, b);
  3133. else
  3134. z = x_add(a, b);
  3135. }
  3136. return (PyObject *)z;
  3137. }
  3138. static PyObject *
  3139. long_add(PyLongObject *a, PyLongObject *b)
  3140. {
  3141. CHECK_BINOP(a, b);
  3142. return _PyLong_Add(a, b);
  3143. }
  3144. PyObject *
  3145. _PyLong_Subtract(PyLongObject *a, PyLongObject *b)
  3146. {
  3147. PyLongObject *z;
  3148. if (_PyLong_BothAreCompact(a, b)) {
  3149. return _PyLong_FromSTwoDigits(medium_value(a) - medium_value(b));
  3150. }
  3151. if (_PyLong_IsNegative(a)) {
  3152. if (_PyLong_IsNegative(b)) {
  3153. z = x_sub(b, a);
  3154. }
  3155. else {
  3156. z = x_add(a, b);
  3157. if (z != NULL) {
  3158. assert(_PyLong_IsZero(z) || Py_REFCNT(z) == 1);
  3159. _PyLong_FlipSign(z);
  3160. }
  3161. }
  3162. }
  3163. else {
  3164. if (_PyLong_IsNegative(b))
  3165. z = x_add(a, b);
  3166. else
  3167. z = x_sub(a, b);
  3168. }
  3169. return (PyObject *)z;
  3170. }
  3171. static PyObject *
  3172. long_sub(PyLongObject *a, PyLongObject *b)
  3173. {
  3174. CHECK_BINOP(a, b);
  3175. return _PyLong_Subtract(a, b);
  3176. }
  3177. /* Grade school multiplication, ignoring the signs.
  3178. * Returns the absolute value of the product, or NULL if error.
  3179. */
  3180. static PyLongObject *
  3181. x_mul(PyLongObject *a, PyLongObject *b)
  3182. {
  3183. PyLongObject *z;
  3184. Py_ssize_t size_a = _PyLong_DigitCount(a);
  3185. Py_ssize_t size_b = _PyLong_DigitCount(b);
  3186. Py_ssize_t i;
  3187. z = _PyLong_New(size_a + size_b);
  3188. if (z == NULL)
  3189. return NULL;
  3190. memset(z->long_value.ob_digit, 0, _PyLong_DigitCount(z) * sizeof(digit));
  3191. if (a == b) {
  3192. /* Efficient squaring per HAC, Algorithm 14.16:
  3193. * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
  3194. * Gives slightly less than a 2x speedup when a == b,
  3195. * via exploiting that each entry in the multiplication
  3196. * pyramid appears twice (except for the size_a squares).
  3197. */
  3198. digit *paend = a->long_value.ob_digit + size_a;
  3199. for (i = 0; i < size_a; ++i) {
  3200. twodigits carry;
  3201. twodigits f = a->long_value.ob_digit[i];
  3202. digit *pz = z->long_value.ob_digit + (i << 1);
  3203. digit *pa = a->long_value.ob_digit + i + 1;
  3204. SIGCHECK({
  3205. Py_DECREF(z);
  3206. return NULL;
  3207. });
  3208. carry = *pz + f * f;
  3209. *pz++ = (digit)(carry & PyLong_MASK);
  3210. carry >>= PyLong_SHIFT;
  3211. assert(carry <= PyLong_MASK);
  3212. /* Now f is added in twice in each column of the
  3213. * pyramid it appears. Same as adding f<<1 once.
  3214. */
  3215. f <<= 1;
  3216. while (pa < paend) {
  3217. carry += *pz + *pa++ * f;
  3218. *pz++ = (digit)(carry & PyLong_MASK);
  3219. carry >>= PyLong_SHIFT;
  3220. assert(carry <= (PyLong_MASK << 1));
  3221. }
  3222. if (carry) {
  3223. /* See comment below. pz points at the highest possible
  3224. * carry position from the last outer loop iteration, so
  3225. * *pz is at most 1.
  3226. */
  3227. assert(*pz <= 1);
  3228. carry += *pz;
  3229. *pz = (digit)(carry & PyLong_MASK);
  3230. carry >>= PyLong_SHIFT;
  3231. if (carry) {
  3232. /* If there's still a carry, it must be into a position
  3233. * that still holds a 0. Where the base
  3234. ^ B is 1 << PyLong_SHIFT, the last add was of a carry no
  3235. * more than 2*B - 2 to a stored digit no more than 1.
  3236. * So the sum was no more than 2*B - 1, so the current
  3237. * carry no more than floor((2*B - 1)/B) = 1.
  3238. */
  3239. assert(carry == 1);
  3240. assert(pz[1] == 0);
  3241. pz[1] = (digit)carry;
  3242. }
  3243. }
  3244. }
  3245. }
  3246. else { /* a is not the same as b -- gradeschool int mult */
  3247. for (i = 0; i < size_a; ++i) {
  3248. twodigits carry = 0;
  3249. twodigits f = a->long_value.ob_digit[i];
  3250. digit *pz = z->long_value.ob_digit + i;
  3251. digit *pb = b->long_value.ob_digit;
  3252. digit *pbend = b->long_value.ob_digit + size_b;
  3253. SIGCHECK({
  3254. Py_DECREF(z);
  3255. return NULL;
  3256. });
  3257. while (pb < pbend) {
  3258. carry += *pz + *pb++ * f;
  3259. *pz++ = (digit)(carry & PyLong_MASK);
  3260. carry >>= PyLong_SHIFT;
  3261. assert(carry <= PyLong_MASK);
  3262. }
  3263. if (carry)
  3264. *pz += (digit)(carry & PyLong_MASK);
  3265. assert((carry >> PyLong_SHIFT) == 0);
  3266. }
  3267. }
  3268. return long_normalize(z);
  3269. }
  3270. /* A helper for Karatsuba multiplication (k_mul).
  3271. Takes an int "n" and an integer "size" representing the place to
  3272. split, and sets low and high such that abs(n) == (high << size) + low,
  3273. viewing the shift as being by digits. The sign bit is ignored, and
  3274. the return values are >= 0.
  3275. Returns 0 on success, -1 on failure.
  3276. */
  3277. static int
  3278. kmul_split(PyLongObject *n,
  3279. Py_ssize_t size,
  3280. PyLongObject **high,
  3281. PyLongObject **low)
  3282. {
  3283. PyLongObject *hi, *lo;
  3284. Py_ssize_t size_lo, size_hi;
  3285. const Py_ssize_t size_n = _PyLong_DigitCount(n);
  3286. size_lo = Py_MIN(size_n, size);
  3287. size_hi = size_n - size_lo;
  3288. if ((hi = _PyLong_New(size_hi)) == NULL)
  3289. return -1;
  3290. if ((lo = _PyLong_New(size_lo)) == NULL) {
  3291. Py_DECREF(hi);
  3292. return -1;
  3293. }
  3294. memcpy(lo->long_value.ob_digit, n->long_value.ob_digit, size_lo * sizeof(digit));
  3295. memcpy(hi->long_value.ob_digit, n->long_value.ob_digit + size_lo, size_hi * sizeof(digit));
  3296. *high = long_normalize(hi);
  3297. *low = long_normalize(lo);
  3298. return 0;
  3299. }
  3300. static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
  3301. /* Karatsuba multiplication. Ignores the input signs, and returns the
  3302. * absolute value of the product (or NULL if error).
  3303. * See Knuth Vol. 2 Chapter 4.3.3 (Pp. 294-295).
  3304. */
  3305. static PyLongObject *
  3306. k_mul(PyLongObject *a, PyLongObject *b)
  3307. {
  3308. Py_ssize_t asize = _PyLong_DigitCount(a);
  3309. Py_ssize_t bsize = _PyLong_DigitCount(b);
  3310. PyLongObject *ah = NULL;
  3311. PyLongObject *al = NULL;
  3312. PyLongObject *bh = NULL;
  3313. PyLongObject *bl = NULL;
  3314. PyLongObject *ret = NULL;
  3315. PyLongObject *t1, *t2, *t3;
  3316. Py_ssize_t shift; /* the number of digits we split off */
  3317. Py_ssize_t i;
  3318. /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
  3319. * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
  3320. * Then the original product is
  3321. * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
  3322. * By picking X to be a power of 2, "*X" is just shifting, and it's
  3323. * been reduced to 3 multiplies on numbers half the size.
  3324. */
  3325. /* We want to split based on the larger number; fiddle so that b
  3326. * is largest.
  3327. */
  3328. if (asize > bsize) {
  3329. t1 = a;
  3330. a = b;
  3331. b = t1;
  3332. i = asize;
  3333. asize = bsize;
  3334. bsize = i;
  3335. }
  3336. /* Use gradeschool math when either number is too small. */
  3337. i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
  3338. if (asize <= i) {
  3339. if (asize == 0)
  3340. return (PyLongObject *)PyLong_FromLong(0);
  3341. else
  3342. return x_mul(a, b);
  3343. }
  3344. /* If a is small compared to b, splitting on b gives a degenerate
  3345. * case with ah==0, and Karatsuba may be (even much) less efficient
  3346. * than "grade school" then. However, we can still win, by viewing
  3347. * b as a string of "big digits", each of the same width as a. That
  3348. * leads to a sequence of balanced calls to k_mul.
  3349. */
  3350. if (2 * asize <= bsize)
  3351. return k_lopsided_mul(a, b);
  3352. /* Split a & b into hi & lo pieces. */
  3353. shift = bsize >> 1;
  3354. if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
  3355. assert(_PyLong_IsPositive(ah)); /* the split isn't degenerate */
  3356. if (a == b) {
  3357. bh = (PyLongObject*)Py_NewRef(ah);
  3358. bl = (PyLongObject*)Py_NewRef(al);
  3359. }
  3360. else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
  3361. /* The plan:
  3362. * 1. Allocate result space (asize + bsize digits: that's always
  3363. * enough).
  3364. * 2. Compute ah*bh, and copy into result at 2*shift.
  3365. * 3. Compute al*bl, and copy into result at 0. Note that this
  3366. * can't overlap with #2.
  3367. * 4. Subtract al*bl from the result, starting at shift. This may
  3368. * underflow (borrow out of the high digit), but we don't care:
  3369. * we're effectively doing unsigned arithmetic mod
  3370. * BASE**(sizea + sizeb), and so long as the *final* result fits,
  3371. * borrows and carries out of the high digit can be ignored.
  3372. * 5. Subtract ah*bh from the result, starting at shift.
  3373. * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
  3374. * at shift.
  3375. */
  3376. /* 1. Allocate result space. */
  3377. ret = _PyLong_New(asize + bsize);
  3378. if (ret == NULL) goto fail;
  3379. #ifdef Py_DEBUG
  3380. /* Fill with trash, to catch reference to uninitialized digits. */
  3381. memset(ret->long_value.ob_digit, 0xDF, _PyLong_DigitCount(ret) * sizeof(digit));
  3382. #endif
  3383. /* 2. t1 <- ah*bh, and copy into high digits of result. */
  3384. if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
  3385. assert(!_PyLong_IsNegative(t1));
  3386. assert(2*shift + _PyLong_DigitCount(t1) <= _PyLong_DigitCount(ret));
  3387. memcpy(ret->long_value.ob_digit + 2*shift, t1->long_value.ob_digit,
  3388. _PyLong_DigitCount(t1) * sizeof(digit));
  3389. /* Zero-out the digits higher than the ah*bh copy. */
  3390. i = _PyLong_DigitCount(ret) - 2*shift - _PyLong_DigitCount(t1);
  3391. if (i)
  3392. memset(ret->long_value.ob_digit + 2*shift + _PyLong_DigitCount(t1), 0,
  3393. i * sizeof(digit));
  3394. /* 3. t2 <- al*bl, and copy into the low digits. */
  3395. if ((t2 = k_mul(al, bl)) == NULL) {
  3396. Py_DECREF(t1);
  3397. goto fail;
  3398. }
  3399. assert(!_PyLong_IsNegative(t2));
  3400. assert(_PyLong_DigitCount(t2) <= 2*shift); /* no overlap with high digits */
  3401. memcpy(ret->long_value.ob_digit, t2->long_value.ob_digit, _PyLong_DigitCount(t2) * sizeof(digit));
  3402. /* Zero out remaining digits. */
  3403. i = 2*shift - _PyLong_DigitCount(t2); /* number of uninitialized digits */
  3404. if (i)
  3405. memset(ret->long_value.ob_digit + _PyLong_DigitCount(t2), 0, i * sizeof(digit));
  3406. /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
  3407. * because it's fresher in cache.
  3408. */
  3409. i = _PyLong_DigitCount(ret) - shift; /* # digits after shift */
  3410. (void)v_isub(ret->long_value.ob_digit + shift, i, t2->long_value.ob_digit, _PyLong_DigitCount(t2));
  3411. _Py_DECREF_INT(t2);
  3412. (void)v_isub(ret->long_value.ob_digit + shift, i, t1->long_value.ob_digit, _PyLong_DigitCount(t1));
  3413. _Py_DECREF_INT(t1);
  3414. /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
  3415. if ((t1 = x_add(ah, al)) == NULL) goto fail;
  3416. _Py_DECREF_INT(ah);
  3417. _Py_DECREF_INT(al);
  3418. ah = al = NULL;
  3419. if (a == b) {
  3420. t2 = (PyLongObject*)Py_NewRef(t1);
  3421. }
  3422. else if ((t2 = x_add(bh, bl)) == NULL) {
  3423. Py_DECREF(t1);
  3424. goto fail;
  3425. }
  3426. _Py_DECREF_INT(bh);
  3427. _Py_DECREF_INT(bl);
  3428. bh = bl = NULL;
  3429. t3 = k_mul(t1, t2);
  3430. _Py_DECREF_INT(t1);
  3431. _Py_DECREF_INT(t2);
  3432. if (t3 == NULL) goto fail;
  3433. assert(!_PyLong_IsNegative(t3));
  3434. /* Add t3. It's not obvious why we can't run out of room here.
  3435. * See the (*) comment after this function.
  3436. */
  3437. (void)v_iadd(ret->long_value.ob_digit + shift, i, t3->long_value.ob_digit, _PyLong_DigitCount(t3));
  3438. _Py_DECREF_INT(t3);
  3439. return long_normalize(ret);
  3440. fail:
  3441. Py_XDECREF(ret);
  3442. Py_XDECREF(ah);
  3443. Py_XDECREF(al);
  3444. Py_XDECREF(bh);
  3445. Py_XDECREF(bl);
  3446. return NULL;
  3447. }
  3448. /* (*) Why adding t3 can't "run out of room" above.
  3449. Let f(x) mean the floor of x and c(x) mean the ceiling of x. Some facts
  3450. to start with:
  3451. 1. For any integer i, i = c(i/2) + f(i/2). In particular,
  3452. bsize = c(bsize/2) + f(bsize/2).
  3453. 2. shift = f(bsize/2)
  3454. 3. asize <= bsize
  3455. 4. Since we call k_lopsided_mul if asize*2 <= bsize, asize*2 > bsize in this
  3456. routine, so asize > bsize/2 >= f(bsize/2) in this routine.
  3457. We allocated asize + bsize result digits, and add t3 into them at an offset
  3458. of shift. This leaves asize+bsize-shift allocated digit positions for t3
  3459. to fit into, = (by #1 and #2) asize + f(bsize/2) + c(bsize/2) - f(bsize/2) =
  3460. asize + c(bsize/2) available digit positions.
  3461. bh has c(bsize/2) digits, and bl at most f(size/2) digits. So bh+hl has
  3462. at most c(bsize/2) digits + 1 bit.
  3463. If asize == bsize, ah has c(bsize/2) digits, else ah has at most f(bsize/2)
  3464. digits, and al has at most f(bsize/2) digits in any case. So ah+al has at
  3465. most (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 1 bit.
  3466. The product (ah+al)*(bh+bl) therefore has at most
  3467. c(bsize/2) + (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits
  3468. and we have asize + c(bsize/2) available digit positions. We need to show
  3469. this is always enough. An instance of c(bsize/2) cancels out in both, so
  3470. the question reduces to whether asize digits is enough to hold
  3471. (asize == bsize ? c(bsize/2) : f(bsize/2)) digits + 2 bits. If asize < bsize,
  3472. then we're asking whether asize digits >= f(bsize/2) digits + 2 bits. By #4,
  3473. asize is at least f(bsize/2)+1 digits, so this in turn reduces to whether 1
  3474. digit is enough to hold 2 bits. This is so since PyLong_SHIFT=15 >= 2. If
  3475. asize == bsize, then we're asking whether bsize digits is enough to hold
  3476. c(bsize/2) digits + 2 bits, or equivalently (by #1) whether f(bsize/2) digits
  3477. is enough to hold 2 bits. This is so if bsize >= 2, which holds because
  3478. bsize >= KARATSUBA_CUTOFF >= 2.
  3479. Note that since there's always enough room for (ah+al)*(bh+bl), and that's
  3480. clearly >= each of ah*bh and al*bl, there's always enough room to subtract
  3481. ah*bh and al*bl too.
  3482. */
  3483. /* b has at least twice the digits of a, and a is big enough that Karatsuba
  3484. * would pay off *if* the inputs had balanced sizes. View b as a sequence
  3485. * of slices, each with the same number of digits as a, and multiply the
  3486. * slices by a, one at a time. This gives k_mul balanced inputs to work with,
  3487. * and is also cache-friendly (we compute one double-width slice of the result
  3488. * at a time, then move on, never backtracking except for the helpful
  3489. * single-width slice overlap between successive partial sums).
  3490. */
  3491. static PyLongObject *
  3492. k_lopsided_mul(PyLongObject *a, PyLongObject *b)
  3493. {
  3494. const Py_ssize_t asize = _PyLong_DigitCount(a);
  3495. Py_ssize_t bsize = _PyLong_DigitCount(b);
  3496. Py_ssize_t nbdone; /* # of b digits already multiplied */
  3497. PyLongObject *ret;
  3498. PyLongObject *bslice = NULL;
  3499. assert(asize > KARATSUBA_CUTOFF);
  3500. assert(2 * asize <= bsize);
  3501. /* Allocate result space, and zero it out. */
  3502. ret = _PyLong_New(asize + bsize);
  3503. if (ret == NULL)
  3504. return NULL;
  3505. memset(ret->long_value.ob_digit, 0, _PyLong_DigitCount(ret) * sizeof(digit));
  3506. /* Successive slices of b are copied into bslice. */
  3507. bslice = _PyLong_New(asize);
  3508. if (bslice == NULL)
  3509. goto fail;
  3510. nbdone = 0;
  3511. while (bsize > 0) {
  3512. PyLongObject *product;
  3513. const Py_ssize_t nbtouse = Py_MIN(bsize, asize);
  3514. /* Multiply the next slice of b by a. */
  3515. memcpy(bslice->long_value.ob_digit, b->long_value.ob_digit + nbdone,
  3516. nbtouse * sizeof(digit));
  3517. assert(nbtouse >= 0);
  3518. _PyLong_SetSignAndDigitCount(bslice, 1, nbtouse);
  3519. product = k_mul(a, bslice);
  3520. if (product == NULL)
  3521. goto fail;
  3522. /* Add into result. */
  3523. (void)v_iadd(ret->long_value.ob_digit + nbdone, _PyLong_DigitCount(ret) - nbdone,
  3524. product->long_value.ob_digit, _PyLong_DigitCount(product));
  3525. _Py_DECREF_INT(product);
  3526. bsize -= nbtouse;
  3527. nbdone += nbtouse;
  3528. }
  3529. _Py_DECREF_INT(bslice);
  3530. return long_normalize(ret);
  3531. fail:
  3532. Py_DECREF(ret);
  3533. Py_XDECREF(bslice);
  3534. return NULL;
  3535. }
  3536. PyObject *
  3537. _PyLong_Multiply(PyLongObject *a, PyLongObject *b)
  3538. {
  3539. PyLongObject *z;
  3540. /* fast path for single-digit multiplication */
  3541. if (_PyLong_BothAreCompact(a, b)) {
  3542. stwodigits v = medium_value(a) * medium_value(b);
  3543. return _PyLong_FromSTwoDigits(v);
  3544. }
  3545. z = k_mul(a, b);
  3546. /* Negate if exactly one of the inputs is negative. */
  3547. if (!_PyLong_SameSign(a, b) && z) {
  3548. _PyLong_Negate(&z);
  3549. if (z == NULL)
  3550. return NULL;
  3551. }
  3552. return (PyObject *)z;
  3553. }
  3554. static PyObject *
  3555. long_mul(PyLongObject *a, PyLongObject *b)
  3556. {
  3557. CHECK_BINOP(a, b);
  3558. return _PyLong_Multiply(a, b);
  3559. }
  3560. /* Fast modulo division for single-digit longs. */
  3561. static PyObject *
  3562. fast_mod(PyLongObject *a, PyLongObject *b)
  3563. {
  3564. sdigit left = a->long_value.ob_digit[0];
  3565. sdigit right = b->long_value.ob_digit[0];
  3566. sdigit mod;
  3567. assert(_PyLong_DigitCount(a) == 1);
  3568. assert(_PyLong_DigitCount(b) == 1);
  3569. sdigit sign = _PyLong_CompactSign(b);
  3570. if (_PyLong_SameSign(a, b)) {
  3571. mod = left % right;
  3572. }
  3573. else {
  3574. /* Either 'a' or 'b' is negative. */
  3575. mod = right - 1 - (left - 1) % right;
  3576. }
  3577. return PyLong_FromLong(mod * sign);
  3578. }
  3579. /* Fast floor division for single-digit longs. */
  3580. static PyObject *
  3581. fast_floor_div(PyLongObject *a, PyLongObject *b)
  3582. {
  3583. sdigit left = a->long_value.ob_digit[0];
  3584. sdigit right = b->long_value.ob_digit[0];
  3585. sdigit div;
  3586. assert(_PyLong_DigitCount(a) == 1);
  3587. assert(_PyLong_DigitCount(b) == 1);
  3588. if (_PyLong_SameSign(a, b)) {
  3589. div = left / right;
  3590. }
  3591. else {
  3592. /* Either 'a' or 'b' is negative. */
  3593. div = -1 - (left - 1) / right;
  3594. }
  3595. return PyLong_FromLong(div);
  3596. }
  3597. #ifdef WITH_PYLONG_MODULE
  3598. /* asymptotically faster divmod, using _pylong.py */
  3599. static int
  3600. pylong_int_divmod(PyLongObject *v, PyLongObject *w,
  3601. PyLongObject **pdiv, PyLongObject **pmod)
  3602. {
  3603. PyObject *mod = PyImport_ImportModule("_pylong");
  3604. if (mod == NULL) {
  3605. return -1;
  3606. }
  3607. PyObject *result = PyObject_CallMethod(mod, "int_divmod", "OO", v, w);
  3608. Py_DECREF(mod);
  3609. if (result == NULL) {
  3610. return -1;
  3611. }
  3612. if (!PyTuple_Check(result)) {
  3613. Py_DECREF(result);
  3614. PyErr_SetString(PyExc_ValueError,
  3615. "tuple is required from int_divmod()");
  3616. return -1;
  3617. }
  3618. PyObject *q = PyTuple_GET_ITEM(result, 0);
  3619. PyObject *r = PyTuple_GET_ITEM(result, 1);
  3620. if (!PyLong_Check(q) || !PyLong_Check(r)) {
  3621. Py_DECREF(result);
  3622. PyErr_SetString(PyExc_ValueError,
  3623. "tuple of int is required from int_divmod()");
  3624. return -1;
  3625. }
  3626. if (pdiv != NULL) {
  3627. *pdiv = (PyLongObject *)Py_NewRef(q);
  3628. }
  3629. if (pmod != NULL) {
  3630. *pmod = (PyLongObject *)Py_NewRef(r);
  3631. }
  3632. Py_DECREF(result);
  3633. return 0;
  3634. }
  3635. #endif /* WITH_PYLONG_MODULE */
  3636. /* The / and % operators are now defined in terms of divmod().
  3637. The expression a mod b has the value a - b*floor(a/b).
  3638. The long_divrem function gives the remainder after division of
  3639. |a| by |b|, with the sign of a. This is also expressed
  3640. as a - b*trunc(a/b), if trunc truncates towards zero.
  3641. Some examples:
  3642. a b a rem b a mod b
  3643. 13 10 3 3
  3644. -13 10 -3 7
  3645. 13 -10 3 -7
  3646. -13 -10 -3 -3
  3647. So, to get from rem to mod, we have to add b if a and b
  3648. have different signs. We then subtract one from the 'div'
  3649. part of the outcome to keep the invariant intact. */
  3650. /* Compute
  3651. * *pdiv, *pmod = divmod(v, w)
  3652. * NULL can be passed for pdiv or pmod, in which case that part of
  3653. * the result is simply thrown away. The caller owns a reference to
  3654. * each of these it requests (does not pass NULL for).
  3655. */
  3656. static int
  3657. l_divmod(PyLongObject *v, PyLongObject *w,
  3658. PyLongObject **pdiv, PyLongObject **pmod)
  3659. {
  3660. PyLongObject *div, *mod;
  3661. if (_PyLong_DigitCount(v) == 1 && _PyLong_DigitCount(w) == 1) {
  3662. /* Fast path for single-digit longs */
  3663. div = NULL;
  3664. if (pdiv != NULL) {
  3665. div = (PyLongObject *)fast_floor_div(v, w);
  3666. if (div == NULL) {
  3667. return -1;
  3668. }
  3669. }
  3670. if (pmod != NULL) {
  3671. mod = (PyLongObject *)fast_mod(v, w);
  3672. if (mod == NULL) {
  3673. Py_XDECREF(div);
  3674. return -1;
  3675. }
  3676. *pmod = mod;
  3677. }
  3678. if (pdiv != NULL) {
  3679. /* We only want to set `*pdiv` when `*pmod` is
  3680. set successfully. */
  3681. *pdiv = div;
  3682. }
  3683. return 0;
  3684. }
  3685. #if WITH_PYLONG_MODULE
  3686. Py_ssize_t size_v = _PyLong_DigitCount(v); /* digits in numerator */
  3687. Py_ssize_t size_w = _PyLong_DigitCount(w); /* digits in denominator */
  3688. if (size_w > 300 && (size_v - size_w) > 150) {
  3689. /* Switch to _pylong.int_divmod(). If the quotient is small then
  3690. "schoolbook" division is linear-time so don't use in that case.
  3691. These limits are empirically determined and should be slightly
  3692. conservative so that _pylong is used in cases it is likely
  3693. to be faster. See Tools/scripts/divmod_threshold.py. */
  3694. return pylong_int_divmod(v, w, pdiv, pmod);
  3695. }
  3696. #endif
  3697. if (long_divrem(v, w, &div, &mod) < 0)
  3698. return -1;
  3699. if ((_PyLong_IsNegative(mod) && _PyLong_IsPositive(w)) ||
  3700. (_PyLong_IsPositive(mod) && _PyLong_IsNegative(w))) {
  3701. PyLongObject *temp;
  3702. temp = (PyLongObject *) long_add(mod, w);
  3703. Py_SETREF(mod, temp);
  3704. if (mod == NULL) {
  3705. Py_DECREF(div);
  3706. return -1;
  3707. }
  3708. temp = (PyLongObject *) long_sub(div, (PyLongObject *)_PyLong_GetOne());
  3709. if (temp == NULL) {
  3710. Py_DECREF(mod);
  3711. Py_DECREF(div);
  3712. return -1;
  3713. }
  3714. Py_SETREF(div, temp);
  3715. }
  3716. if (pdiv != NULL)
  3717. *pdiv = div;
  3718. else
  3719. Py_DECREF(div);
  3720. if (pmod != NULL)
  3721. *pmod = mod;
  3722. else
  3723. Py_DECREF(mod);
  3724. return 0;
  3725. }
  3726. /* Compute
  3727. * *pmod = v % w
  3728. * pmod cannot be NULL. The caller owns a reference to pmod.
  3729. */
  3730. static int
  3731. l_mod(PyLongObject *v, PyLongObject *w, PyLongObject **pmod)
  3732. {
  3733. PyLongObject *mod;
  3734. assert(pmod);
  3735. if (_PyLong_DigitCount(v) == 1 && _PyLong_DigitCount(w) == 1) {
  3736. /* Fast path for single-digit longs */
  3737. *pmod = (PyLongObject *)fast_mod(v, w);
  3738. return -(*pmod == NULL);
  3739. }
  3740. if (long_rem(v, w, &mod) < 0)
  3741. return -1;
  3742. if ((_PyLong_IsNegative(mod) && _PyLong_IsPositive(w)) ||
  3743. (_PyLong_IsPositive(mod) && _PyLong_IsNegative(w))) {
  3744. PyLongObject *temp;
  3745. temp = (PyLongObject *) long_add(mod, w);
  3746. Py_SETREF(mod, temp);
  3747. if (mod == NULL)
  3748. return -1;
  3749. }
  3750. *pmod = mod;
  3751. return 0;
  3752. }
  3753. static PyObject *
  3754. long_div(PyObject *a, PyObject *b)
  3755. {
  3756. PyLongObject *div;
  3757. CHECK_BINOP(a, b);
  3758. if (_PyLong_DigitCount((PyLongObject*)a) == 1 && _PyLong_DigitCount((PyLongObject*)b) == 1) {
  3759. return fast_floor_div((PyLongObject*)a, (PyLongObject*)b);
  3760. }
  3761. if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0)
  3762. div = NULL;
  3763. return (PyObject *)div;
  3764. }
  3765. /* PyLong/PyLong -> float, with correctly rounded result. */
  3766. #define MANT_DIG_DIGITS (DBL_MANT_DIG / PyLong_SHIFT)
  3767. #define MANT_DIG_BITS (DBL_MANT_DIG % PyLong_SHIFT)
  3768. static PyObject *
  3769. long_true_divide(PyObject *v, PyObject *w)
  3770. {
  3771. PyLongObject *a, *b, *x;
  3772. Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
  3773. digit mask, low;
  3774. int inexact, negate, a_is_small, b_is_small;
  3775. double dx, result;
  3776. CHECK_BINOP(v, w);
  3777. a = (PyLongObject *)v;
  3778. b = (PyLongObject *)w;
  3779. /*
  3780. Method in a nutshell:
  3781. 0. reduce to case a, b > 0; filter out obvious underflow/overflow
  3782. 1. choose a suitable integer 'shift'
  3783. 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
  3784. 3. adjust x for correct rounding
  3785. 4. convert x to a double dx with the same value
  3786. 5. return ldexp(dx, shift).
  3787. In more detail:
  3788. 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
  3789. returns either 0.0 or -0.0, depending on the sign of b. For a and
  3790. b both nonzero, ignore signs of a and b, and add the sign back in
  3791. at the end. Now write a_bits and b_bits for the bit lengths of a
  3792. and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
  3793. for b). Then
  3794. 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
  3795. So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
  3796. so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
  3797. DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
  3798. the way, we can assume that
  3799. DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
  3800. 1. The integer 'shift' is chosen so that x has the right number of
  3801. bits for a double, plus two or three extra bits that will be used
  3802. in the rounding decisions. Writing a_bits and b_bits for the
  3803. number of significant bits in a and b respectively, a
  3804. straightforward formula for shift is:
  3805. shift = a_bits - b_bits - DBL_MANT_DIG - 2
  3806. This is fine in the usual case, but if a/b is smaller than the
  3807. smallest normal float then it can lead to double rounding on an
  3808. IEEE 754 platform, giving incorrectly rounded results. So we
  3809. adjust the formula slightly. The actual formula used is:
  3810. shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
  3811. 2. The quantity x is computed by first shifting a (left -shift bits
  3812. if shift <= 0, right shift bits if shift > 0) and then dividing by
  3813. b. For both the shift and the division, we keep track of whether
  3814. the result is inexact, in a flag 'inexact'; this information is
  3815. needed at the rounding stage.
  3816. With the choice of shift above, together with our assumption that
  3817. a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
  3818. that x >= 1.
  3819. 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
  3820. this with an exactly representable float of the form
  3821. round(x/2**extra_bits) * 2**(extra_bits+shift).
  3822. For float representability, we need x/2**extra_bits <
  3823. 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
  3824. DBL_MANT_DIG. This translates to the condition:
  3825. extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
  3826. To round, we just modify the bottom digit of x in-place; this can
  3827. end up giving a digit with value > PyLONG_MASK, but that's not a
  3828. problem since digits can hold values up to 2*PyLONG_MASK+1.
  3829. With the original choices for shift above, extra_bits will always
  3830. be 2 or 3. Then rounding under the round-half-to-even rule, we
  3831. round up iff the most significant of the extra bits is 1, and
  3832. either: (a) the computation of x in step 2 had an inexact result,
  3833. or (b) at least one other of the extra bits is 1, or (c) the least
  3834. significant bit of x (above those to be rounded) is 1.
  3835. 4. Conversion to a double is straightforward; all floating-point
  3836. operations involved in the conversion are exact, so there's no
  3837. danger of rounding errors.
  3838. 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
  3839. The result will always be exactly representable as a double, except
  3840. in the case that it overflows. To avoid dependence on the exact
  3841. behaviour of ldexp on overflow, we check for overflow before
  3842. applying ldexp. The result of ldexp is adjusted for sign before
  3843. returning.
  3844. */
  3845. /* Reduce to case where a and b are both positive. */
  3846. a_size = _PyLong_DigitCount(a);
  3847. b_size = _PyLong_DigitCount(b);
  3848. negate = (_PyLong_IsNegative(a)) != (_PyLong_IsNegative(b));
  3849. if (b_size == 0) {
  3850. PyErr_SetString(PyExc_ZeroDivisionError,
  3851. "division by zero");
  3852. goto error;
  3853. }
  3854. if (a_size == 0)
  3855. goto underflow_or_zero;
  3856. /* Fast path for a and b small (exactly representable in a double).
  3857. Relies on floating-point division being correctly rounded; results
  3858. may be subject to double rounding on x86 machines that operate with
  3859. the x87 FPU set to 64-bit precision. */
  3860. a_is_small = a_size <= MANT_DIG_DIGITS ||
  3861. (a_size == MANT_DIG_DIGITS+1 &&
  3862. a->long_value.ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
  3863. b_is_small = b_size <= MANT_DIG_DIGITS ||
  3864. (b_size == MANT_DIG_DIGITS+1 &&
  3865. b->long_value.ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
  3866. if (a_is_small && b_is_small) {
  3867. double da, db;
  3868. da = a->long_value.ob_digit[--a_size];
  3869. while (a_size > 0)
  3870. da = da * PyLong_BASE + a->long_value.ob_digit[--a_size];
  3871. db = b->long_value.ob_digit[--b_size];
  3872. while (b_size > 0)
  3873. db = db * PyLong_BASE + b->long_value.ob_digit[--b_size];
  3874. result = da / db;
  3875. goto success;
  3876. }
  3877. /* Catch obvious cases of underflow and overflow */
  3878. diff = a_size - b_size;
  3879. if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
  3880. /* Extreme overflow */
  3881. goto overflow;
  3882. else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
  3883. /* Extreme underflow */
  3884. goto underflow_or_zero;
  3885. /* Next line is now safe from overflowing a Py_ssize_t */
  3886. diff = diff * PyLong_SHIFT + bit_length_digit(a->long_value.ob_digit[a_size - 1]) -
  3887. bit_length_digit(b->long_value.ob_digit[b_size - 1]);
  3888. /* Now diff = a_bits - b_bits. */
  3889. if (diff > DBL_MAX_EXP)
  3890. goto overflow;
  3891. else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
  3892. goto underflow_or_zero;
  3893. /* Choose value for shift; see comments for step 1 above. */
  3894. shift = Py_MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
  3895. inexact = 0;
  3896. /* x = abs(a * 2**-shift) */
  3897. if (shift <= 0) {
  3898. Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
  3899. digit rem;
  3900. /* x = a << -shift */
  3901. if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
  3902. /* In practice, it's probably impossible to end up
  3903. here. Both a and b would have to be enormous,
  3904. using close to SIZE_T_MAX bytes of memory each. */
  3905. PyErr_SetString(PyExc_OverflowError,
  3906. "intermediate overflow during division");
  3907. goto error;
  3908. }
  3909. x = _PyLong_New(a_size + shift_digits + 1);
  3910. if (x == NULL)
  3911. goto error;
  3912. for (i = 0; i < shift_digits; i++)
  3913. x->long_value.ob_digit[i] = 0;
  3914. rem = v_lshift(x->long_value.ob_digit + shift_digits, a->long_value.ob_digit,
  3915. a_size, -shift % PyLong_SHIFT);
  3916. x->long_value.ob_digit[a_size + shift_digits] = rem;
  3917. }
  3918. else {
  3919. Py_ssize_t shift_digits = shift / PyLong_SHIFT;
  3920. digit rem;
  3921. /* x = a >> shift */
  3922. assert(a_size >= shift_digits);
  3923. x = _PyLong_New(a_size - shift_digits);
  3924. if (x == NULL)
  3925. goto error;
  3926. rem = v_rshift(x->long_value.ob_digit, a->long_value.ob_digit + shift_digits,
  3927. a_size - shift_digits, shift % PyLong_SHIFT);
  3928. /* set inexact if any of the bits shifted out is nonzero */
  3929. if (rem)
  3930. inexact = 1;
  3931. while (!inexact && shift_digits > 0)
  3932. if (a->long_value.ob_digit[--shift_digits])
  3933. inexact = 1;
  3934. }
  3935. long_normalize(x);
  3936. x_size = _PyLong_SignedDigitCount(x);
  3937. /* x //= b. If the remainder is nonzero, set inexact. We own the only
  3938. reference to x, so it's safe to modify it in-place. */
  3939. if (b_size == 1) {
  3940. digit rem = inplace_divrem1(x->long_value.ob_digit, x->long_value.ob_digit, x_size,
  3941. b->long_value.ob_digit[0]);
  3942. long_normalize(x);
  3943. if (rem)
  3944. inexact = 1;
  3945. }
  3946. else {
  3947. PyLongObject *div, *rem;
  3948. div = x_divrem(x, b, &rem);
  3949. Py_SETREF(x, div);
  3950. if (x == NULL)
  3951. goto error;
  3952. if (!_PyLong_IsZero(rem))
  3953. inexact = 1;
  3954. Py_DECREF(rem);
  3955. }
  3956. x_size = _PyLong_DigitCount(x);
  3957. assert(x_size > 0); /* result of division is never zero */
  3958. x_bits = (x_size-1)*PyLong_SHIFT+bit_length_digit(x->long_value.ob_digit[x_size-1]);
  3959. /* The number of extra bits that have to be rounded away. */
  3960. extra_bits = Py_MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
  3961. assert(extra_bits == 2 || extra_bits == 3);
  3962. /* Round by directly modifying the low digit of x. */
  3963. mask = (digit)1 << (extra_bits - 1);
  3964. low = x->long_value.ob_digit[0] | inexact;
  3965. if ((low & mask) && (low & (3U*mask-1U)))
  3966. low += mask;
  3967. x->long_value.ob_digit[0] = low & ~(2U*mask-1U);
  3968. /* Convert x to a double dx; the conversion is exact. */
  3969. dx = x->long_value.ob_digit[--x_size];
  3970. while (x_size > 0)
  3971. dx = dx * PyLong_BASE + x->long_value.ob_digit[--x_size];
  3972. Py_DECREF(x);
  3973. /* Check whether ldexp result will overflow a double. */
  3974. if (shift + x_bits >= DBL_MAX_EXP &&
  3975. (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
  3976. goto overflow;
  3977. result = ldexp(dx, (int)shift);
  3978. success:
  3979. return PyFloat_FromDouble(negate ? -result : result);
  3980. underflow_or_zero:
  3981. return PyFloat_FromDouble(negate ? -0.0 : 0.0);
  3982. overflow:
  3983. PyErr_SetString(PyExc_OverflowError,
  3984. "integer division result too large for a float");
  3985. error:
  3986. return NULL;
  3987. }
  3988. static PyObject *
  3989. long_mod(PyObject *a, PyObject *b)
  3990. {
  3991. PyLongObject *mod;
  3992. CHECK_BINOP(a, b);
  3993. if (l_mod((PyLongObject*)a, (PyLongObject*)b, &mod) < 0)
  3994. mod = NULL;
  3995. return (PyObject *)mod;
  3996. }
  3997. static PyObject *
  3998. long_divmod(PyObject *a, PyObject *b)
  3999. {
  4000. PyLongObject *div, *mod;
  4001. PyObject *z;
  4002. CHECK_BINOP(a, b);
  4003. if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) {
  4004. return NULL;
  4005. }
  4006. z = PyTuple_New(2);
  4007. if (z != NULL) {
  4008. PyTuple_SET_ITEM(z, 0, (PyObject *) div);
  4009. PyTuple_SET_ITEM(z, 1, (PyObject *) mod);
  4010. }
  4011. else {
  4012. Py_DECREF(div);
  4013. Py_DECREF(mod);
  4014. }
  4015. return z;
  4016. }
  4017. /* Compute an inverse to a modulo n, or raise ValueError if a is not
  4018. invertible modulo n. Assumes n is positive. The inverse returned
  4019. is whatever falls out of the extended Euclidean algorithm: it may
  4020. be either positive or negative, but will be smaller than n in
  4021. absolute value.
  4022. Pure Python equivalent for long_invmod:
  4023. def invmod(a, n):
  4024. b, c = 1, 0
  4025. while n:
  4026. q, r = divmod(a, n)
  4027. a, b, c, n = n, c, b - q*c, r
  4028. # at this point a is the gcd of the original inputs
  4029. if a == 1:
  4030. return b
  4031. raise ValueError("Not invertible")
  4032. */
  4033. static PyLongObject *
  4034. long_invmod(PyLongObject *a, PyLongObject *n)
  4035. {
  4036. PyLongObject *b, *c;
  4037. /* Should only ever be called for positive n */
  4038. assert(_PyLong_IsPositive(n));
  4039. b = (PyLongObject *)PyLong_FromLong(1L);
  4040. if (b == NULL) {
  4041. return NULL;
  4042. }
  4043. c = (PyLongObject *)PyLong_FromLong(0L);
  4044. if (c == NULL) {
  4045. Py_DECREF(b);
  4046. return NULL;
  4047. }
  4048. Py_INCREF(a);
  4049. Py_INCREF(n);
  4050. /* references now owned: a, b, c, n */
  4051. while (!_PyLong_IsZero(n)) {
  4052. PyLongObject *q, *r, *s, *t;
  4053. if (l_divmod(a, n, &q, &r) == -1) {
  4054. goto Error;
  4055. }
  4056. Py_SETREF(a, n);
  4057. n = r;
  4058. t = (PyLongObject *)long_mul(q, c);
  4059. Py_DECREF(q);
  4060. if (t == NULL) {
  4061. goto Error;
  4062. }
  4063. s = (PyLongObject *)long_sub(b, t);
  4064. Py_DECREF(t);
  4065. if (s == NULL) {
  4066. goto Error;
  4067. }
  4068. Py_SETREF(b, c);
  4069. c = s;
  4070. }
  4071. /* references now owned: a, b, c, n */
  4072. Py_DECREF(c);
  4073. Py_DECREF(n);
  4074. if (long_compare(a, (PyLongObject *)_PyLong_GetOne())) {
  4075. /* a != 1; we don't have an inverse. */
  4076. Py_DECREF(a);
  4077. Py_DECREF(b);
  4078. PyErr_SetString(PyExc_ValueError,
  4079. "base is not invertible for the given modulus");
  4080. return NULL;
  4081. }
  4082. else {
  4083. /* a == 1; b gives an inverse modulo n */
  4084. Py_DECREF(a);
  4085. return b;
  4086. }
  4087. Error:
  4088. Py_DECREF(a);
  4089. Py_DECREF(b);
  4090. Py_DECREF(c);
  4091. Py_DECREF(n);
  4092. return NULL;
  4093. }
  4094. /* pow(v, w, x) */
  4095. static PyObject *
  4096. long_pow(PyObject *v, PyObject *w, PyObject *x)
  4097. {
  4098. PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
  4099. int negativeOutput = 0; /* if x<0 return negative output */
  4100. PyLongObject *z = NULL; /* accumulated result */
  4101. Py_ssize_t i, j; /* counters */
  4102. PyLongObject *temp = NULL;
  4103. PyLongObject *a2 = NULL; /* may temporarily hold a**2 % c */
  4104. /* k-ary values. If the exponent is large enough, table is
  4105. * precomputed so that table[i] == a**(2*i+1) % c for i in
  4106. * range(EXP_TABLE_LEN).
  4107. * Note: this is uninitialized stack trash: don't pay to set it to known
  4108. * values unless it's needed. Instead ensure that num_table_entries is
  4109. * set to the number of entries actually filled whenever a branch to the
  4110. * Error or Done labels is possible.
  4111. */
  4112. PyLongObject *table[EXP_TABLE_LEN];
  4113. Py_ssize_t num_table_entries = 0;
  4114. /* a, b, c = v, w, x */
  4115. CHECK_BINOP(v, w);
  4116. a = (PyLongObject*)Py_NewRef(v);
  4117. b = (PyLongObject*)Py_NewRef(w);
  4118. if (PyLong_Check(x)) {
  4119. c = (PyLongObject *)Py_NewRef(x);
  4120. }
  4121. else if (x == Py_None)
  4122. c = NULL;
  4123. else {
  4124. Py_DECREF(a);
  4125. Py_DECREF(b);
  4126. Py_RETURN_NOTIMPLEMENTED;
  4127. }
  4128. if (_PyLong_IsNegative(b) && c == NULL) {
  4129. /* if exponent is negative and there's no modulus:
  4130. return a float. This works because we know
  4131. that this calls float_pow() which converts its
  4132. arguments to double. */
  4133. Py_DECREF(a);
  4134. Py_DECREF(b);
  4135. return PyFloat_Type.tp_as_number->nb_power(v, w, x);
  4136. }
  4137. if (c) {
  4138. /* if modulus == 0:
  4139. raise ValueError() */
  4140. if (_PyLong_IsZero(c)) {
  4141. PyErr_SetString(PyExc_ValueError,
  4142. "pow() 3rd argument cannot be 0");
  4143. goto Error;
  4144. }
  4145. /* if modulus < 0:
  4146. negativeOutput = True
  4147. modulus = -modulus */
  4148. if (_PyLong_IsNegative(c)) {
  4149. negativeOutput = 1;
  4150. temp = (PyLongObject *)_PyLong_Copy(c);
  4151. if (temp == NULL)
  4152. goto Error;
  4153. Py_SETREF(c, temp);
  4154. temp = NULL;
  4155. _PyLong_Negate(&c);
  4156. if (c == NULL)
  4157. goto Error;
  4158. }
  4159. /* if modulus == 1:
  4160. return 0 */
  4161. if (_PyLong_IsNonNegativeCompact(c) && (c->long_value.ob_digit[0] == 1)) {
  4162. z = (PyLongObject *)PyLong_FromLong(0L);
  4163. goto Done;
  4164. }
  4165. /* if exponent is negative, negate the exponent and
  4166. replace the base with a modular inverse */
  4167. if (_PyLong_IsNegative(b)) {
  4168. temp = (PyLongObject *)_PyLong_Copy(b);
  4169. if (temp == NULL)
  4170. goto Error;
  4171. Py_SETREF(b, temp);
  4172. temp = NULL;
  4173. _PyLong_Negate(&b);
  4174. if (b == NULL)
  4175. goto Error;
  4176. temp = long_invmod(a, c);
  4177. if (temp == NULL)
  4178. goto Error;
  4179. Py_SETREF(a, temp);
  4180. temp = NULL;
  4181. }
  4182. /* Reduce base by modulus in some cases:
  4183. 1. If base < 0. Forcing the base non-negative makes things easier.
  4184. 2. If base is obviously larger than the modulus. The "small
  4185. exponent" case later can multiply directly by base repeatedly,
  4186. while the "large exponent" case multiplies directly by base 31
  4187. times. It can be unboundedly faster to multiply by
  4188. base % modulus instead.
  4189. We could _always_ do this reduction, but l_mod() isn't cheap,
  4190. so we only do it when it buys something. */
  4191. if (_PyLong_IsNegative(a) || _PyLong_DigitCount(a) > _PyLong_DigitCount(c)) {
  4192. if (l_mod(a, c, &temp) < 0)
  4193. goto Error;
  4194. Py_SETREF(a, temp);
  4195. temp = NULL;
  4196. }
  4197. }
  4198. /* At this point a, b, and c are guaranteed non-negative UNLESS
  4199. c is NULL, in which case a may be negative. */
  4200. z = (PyLongObject *)PyLong_FromLong(1L);
  4201. if (z == NULL)
  4202. goto Error;
  4203. /* Perform a modular reduction, X = X % c, but leave X alone if c
  4204. * is NULL.
  4205. */
  4206. #define REDUCE(X) \
  4207. do { \
  4208. if (c != NULL) { \
  4209. if (l_mod(X, c, &temp) < 0) \
  4210. goto Error; \
  4211. Py_XDECREF(X); \
  4212. X = temp; \
  4213. temp = NULL; \
  4214. } \
  4215. } while(0)
  4216. /* Multiply two values, then reduce the result:
  4217. result = X*Y % c. If c is NULL, skip the mod. */
  4218. #define MULT(X, Y, result) \
  4219. do { \
  4220. temp = (PyLongObject *)long_mul(X, Y); \
  4221. if (temp == NULL) \
  4222. goto Error; \
  4223. Py_XDECREF(result); \
  4224. result = temp; \
  4225. temp = NULL; \
  4226. REDUCE(result); \
  4227. } while(0)
  4228. i = _PyLong_SignedDigitCount(b);
  4229. digit bi = i ? b->long_value.ob_digit[i-1] : 0;
  4230. digit bit;
  4231. if (i <= 1 && bi <= 3) {
  4232. /* aim for minimal overhead */
  4233. if (bi >= 2) {
  4234. MULT(a, a, z);
  4235. if (bi == 3) {
  4236. MULT(z, a, z);
  4237. }
  4238. }
  4239. else if (bi == 1) {
  4240. /* Multiplying by 1 serves two purposes: if `a` is of an int
  4241. * subclass, makes the result an int (e.g., pow(False, 1) returns
  4242. * 0 instead of False), and potentially reduces `a` by the modulus.
  4243. */
  4244. MULT(a, z, z);
  4245. }
  4246. /* else bi is 0, and z==1 is correct */
  4247. }
  4248. else if (i <= HUGE_EXP_CUTOFF / PyLong_SHIFT ) {
  4249. /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
  4250. /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
  4251. /* Find the first significant exponent bit. Search right to left
  4252. * because we're primarily trying to cut overhead for small powers.
  4253. */
  4254. assert(bi); /* else there is no significant bit */
  4255. Py_SETREF(z, (PyLongObject*)Py_NewRef(a));
  4256. for (bit = 2; ; bit <<= 1) {
  4257. if (bit > bi) { /* found the first bit */
  4258. assert((bi & bit) == 0);
  4259. bit >>= 1;
  4260. assert(bi & bit);
  4261. break;
  4262. }
  4263. }
  4264. for (--i, bit >>= 1;;) {
  4265. for (; bit != 0; bit >>= 1) {
  4266. MULT(z, z, z);
  4267. if (bi & bit) {
  4268. MULT(z, a, z);
  4269. }
  4270. }
  4271. if (--i < 0) {
  4272. break;
  4273. }
  4274. bi = b->long_value.ob_digit[i];
  4275. bit = (digit)1 << (PyLong_SHIFT-1);
  4276. }
  4277. }
  4278. else {
  4279. /* Left-to-right k-ary sliding window exponentiation
  4280. * (Handbook of Applied Cryptography (HAC) Algorithm 14.85)
  4281. */
  4282. table[0] = (PyLongObject*)Py_NewRef(a);
  4283. num_table_entries = 1;
  4284. MULT(a, a, a2);
  4285. /* table[i] == a**(2*i + 1) % c */
  4286. for (i = 1; i < EXP_TABLE_LEN; ++i) {
  4287. table[i] = NULL; /* must set to known value for MULT */
  4288. MULT(table[i-1], a2, table[i]);
  4289. ++num_table_entries; /* incremented iff MULT succeeded */
  4290. }
  4291. Py_CLEAR(a2);
  4292. /* Repeatedly extract the next (no more than) EXP_WINDOW_SIZE bits
  4293. * into `pending`, starting with the next 1 bit. The current bit
  4294. * length of `pending` is `blen`.
  4295. */
  4296. int pending = 0, blen = 0;
  4297. #define ABSORB_PENDING do { \
  4298. int ntz = 0; /* number of trailing zeroes in `pending` */ \
  4299. assert(pending && blen); \
  4300. assert(pending >> (blen - 1)); \
  4301. assert(pending >> blen == 0); \
  4302. while ((pending & 1) == 0) { \
  4303. ++ntz; \
  4304. pending >>= 1; \
  4305. } \
  4306. assert(ntz < blen); \
  4307. blen -= ntz; \
  4308. do { \
  4309. MULT(z, z, z); \
  4310. } while (--blen); \
  4311. MULT(z, table[pending >> 1], z); \
  4312. while (ntz-- > 0) \
  4313. MULT(z, z, z); \
  4314. assert(blen == 0); \
  4315. pending = 0; \
  4316. } while(0)
  4317. for (i = _PyLong_SignedDigitCount(b) - 1; i >= 0; --i) {
  4318. const digit bi = b->long_value.ob_digit[i];
  4319. for (j = PyLong_SHIFT - 1; j >= 0; --j) {
  4320. const int bit = (bi >> j) & 1;
  4321. pending = (pending << 1) | bit;
  4322. if (pending) {
  4323. ++blen;
  4324. if (blen == EXP_WINDOW_SIZE)
  4325. ABSORB_PENDING;
  4326. }
  4327. else /* absorb strings of 0 bits */
  4328. MULT(z, z, z);
  4329. }
  4330. }
  4331. if (pending)
  4332. ABSORB_PENDING;
  4333. }
  4334. if (negativeOutput && !_PyLong_IsZero(z)) {
  4335. temp = (PyLongObject *)long_sub(z, c);
  4336. if (temp == NULL)
  4337. goto Error;
  4338. Py_SETREF(z, temp);
  4339. temp = NULL;
  4340. }
  4341. goto Done;
  4342. Error:
  4343. Py_CLEAR(z);
  4344. /* fall through */
  4345. Done:
  4346. for (i = 0; i < num_table_entries; ++i)
  4347. Py_DECREF(table[i]);
  4348. Py_DECREF(a);
  4349. Py_DECREF(b);
  4350. Py_XDECREF(c);
  4351. Py_XDECREF(a2);
  4352. Py_XDECREF(temp);
  4353. return (PyObject *)z;
  4354. }
  4355. static PyObject *
  4356. long_invert(PyLongObject *v)
  4357. {
  4358. /* Implement ~x as -(x+1) */
  4359. PyLongObject *x;
  4360. if (_PyLong_IsCompact(v))
  4361. return _PyLong_FromSTwoDigits(~medium_value(v));
  4362. x = (PyLongObject *) long_add(v, (PyLongObject *)_PyLong_GetOne());
  4363. if (x == NULL)
  4364. return NULL;
  4365. _PyLong_Negate(&x);
  4366. /* No need for maybe_small_long here, since any small longs
  4367. will have been caught in the _PyLong_IsCompact() fast path. */
  4368. return (PyObject *)x;
  4369. }
  4370. static PyObject *
  4371. long_neg(PyLongObject *v)
  4372. {
  4373. PyLongObject *z;
  4374. if (_PyLong_IsCompact(v))
  4375. return _PyLong_FromSTwoDigits(-medium_value(v));
  4376. z = (PyLongObject *)_PyLong_Copy(v);
  4377. if (z != NULL)
  4378. _PyLong_FlipSign(z);
  4379. return (PyObject *)z;
  4380. }
  4381. static PyObject *
  4382. long_abs(PyLongObject *v)
  4383. {
  4384. if (_PyLong_IsNegative(v))
  4385. return long_neg(v);
  4386. else
  4387. return long_long((PyObject *)v);
  4388. }
  4389. static int
  4390. long_bool(PyLongObject *v)
  4391. {
  4392. return !_PyLong_IsZero(v);
  4393. }
  4394. /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
  4395. static int
  4396. divmod_shift(PyObject *shiftby, Py_ssize_t *wordshift, digit *remshift)
  4397. {
  4398. assert(PyLong_Check(shiftby));
  4399. assert(!_PyLong_IsNegative((PyLongObject *)shiftby));
  4400. Py_ssize_t lshiftby = PyLong_AsSsize_t((PyObject *)shiftby);
  4401. if (lshiftby >= 0) {
  4402. *wordshift = lshiftby / PyLong_SHIFT;
  4403. *remshift = lshiftby % PyLong_SHIFT;
  4404. return 0;
  4405. }
  4406. /* PyLong_Check(shiftby) is true and shiftby is not negative, so it must
  4407. be that PyLong_AsSsize_t raised an OverflowError. */
  4408. assert(PyErr_ExceptionMatches(PyExc_OverflowError));
  4409. PyErr_Clear();
  4410. PyLongObject *wordshift_obj = divrem1((PyLongObject *)shiftby, PyLong_SHIFT, remshift);
  4411. if (wordshift_obj == NULL) {
  4412. return -1;
  4413. }
  4414. *wordshift = PyLong_AsSsize_t((PyObject *)wordshift_obj);
  4415. Py_DECREF(wordshift_obj);
  4416. if (*wordshift >= 0 && *wordshift < PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(digit)) {
  4417. return 0;
  4418. }
  4419. PyErr_Clear();
  4420. /* Clip the value. With such large wordshift the right shift
  4421. returns 0 and the left shift raises an error in _PyLong_New(). */
  4422. *wordshift = PY_SSIZE_T_MAX / sizeof(digit);
  4423. *remshift = 0;
  4424. return 0;
  4425. }
  4426. /* Inner function for both long_rshift and _PyLong_Rshift, shifting an
  4427. integer right by PyLong_SHIFT*wordshift + remshift bits.
  4428. wordshift should be nonnegative. */
  4429. static PyObject *
  4430. long_rshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
  4431. {
  4432. PyLongObject *z = NULL;
  4433. Py_ssize_t newsize, hishift, size_a;
  4434. twodigits accum;
  4435. int a_negative;
  4436. /* Total number of bits shifted must be nonnegative. */
  4437. assert(wordshift >= 0);
  4438. assert(remshift < PyLong_SHIFT);
  4439. /* Fast path for small a. */
  4440. if (_PyLong_IsCompact(a)) {
  4441. stwodigits m, x;
  4442. digit shift;
  4443. m = medium_value(a);
  4444. shift = wordshift == 0 ? remshift : PyLong_SHIFT;
  4445. x = m < 0 ? ~(~m >> shift) : m >> shift;
  4446. return _PyLong_FromSTwoDigits(x);
  4447. }
  4448. a_negative = _PyLong_IsNegative(a);
  4449. size_a = _PyLong_DigitCount(a);
  4450. if (a_negative) {
  4451. /* For negative 'a', adjust so that 0 < remshift <= PyLong_SHIFT,
  4452. while keeping PyLong_SHIFT*wordshift + remshift the same. This
  4453. ensures that 'newsize' is computed correctly below. */
  4454. if (remshift == 0) {
  4455. if (wordshift == 0) {
  4456. /* Can only happen if the original shift was 0. */
  4457. return long_long((PyObject *)a);
  4458. }
  4459. remshift = PyLong_SHIFT;
  4460. --wordshift;
  4461. }
  4462. }
  4463. assert(wordshift >= 0);
  4464. newsize = size_a - wordshift;
  4465. if (newsize <= 0) {
  4466. /* Shifting all the bits of 'a' out gives either -1 or 0. */
  4467. return PyLong_FromLong(-a_negative);
  4468. }
  4469. z = _PyLong_New(newsize);
  4470. if (z == NULL) {
  4471. return NULL;
  4472. }
  4473. hishift = PyLong_SHIFT - remshift;
  4474. accum = a->long_value.ob_digit[wordshift];
  4475. if (a_negative) {
  4476. /*
  4477. For a positive integer a and nonnegative shift, we have:
  4478. (-a) >> shift == -((a + 2**shift - 1) >> shift).
  4479. In the addition `a + (2**shift - 1)`, the low `wordshift` digits of
  4480. `2**shift - 1` all have value `PyLong_MASK`, so we get a carry out
  4481. from the bottom `wordshift` digits when at least one of the least
  4482. significant `wordshift` digits of `a` is nonzero. Digit `wordshift`
  4483. of `2**shift - 1` has value `PyLong_MASK >> hishift`.
  4484. */
  4485. _PyLong_SetSignAndDigitCount(z, -1, newsize);
  4486. digit sticky = 0;
  4487. for (Py_ssize_t j = 0; j < wordshift; j++) {
  4488. sticky |= a->long_value.ob_digit[j];
  4489. }
  4490. accum += (PyLong_MASK >> hishift) + (digit)(sticky != 0);
  4491. }
  4492. accum >>= remshift;
  4493. for (Py_ssize_t i = 0, j = wordshift + 1; j < size_a; i++, j++) {
  4494. accum += (twodigits)a->long_value.ob_digit[j] << hishift;
  4495. z->long_value.ob_digit[i] = (digit)(accum & PyLong_MASK);
  4496. accum >>= PyLong_SHIFT;
  4497. }
  4498. assert(accum <= PyLong_MASK);
  4499. z->long_value.ob_digit[newsize - 1] = (digit)accum;
  4500. z = maybe_small_long(long_normalize(z));
  4501. return (PyObject *)z;
  4502. }
  4503. static PyObject *
  4504. long_rshift(PyObject *a, PyObject *b)
  4505. {
  4506. Py_ssize_t wordshift;
  4507. digit remshift;
  4508. CHECK_BINOP(a, b);
  4509. if (_PyLong_IsNegative((PyLongObject *)b)) {
  4510. PyErr_SetString(PyExc_ValueError, "negative shift count");
  4511. return NULL;
  4512. }
  4513. if (_PyLong_IsZero((PyLongObject *)a)) {
  4514. return PyLong_FromLong(0);
  4515. }
  4516. if (divmod_shift(b, &wordshift, &remshift) < 0)
  4517. return NULL;
  4518. return long_rshift1((PyLongObject *)a, wordshift, remshift);
  4519. }
  4520. /* Return a >> shiftby. */
  4521. PyObject *
  4522. _PyLong_Rshift(PyObject *a, size_t shiftby)
  4523. {
  4524. Py_ssize_t wordshift;
  4525. digit remshift;
  4526. assert(PyLong_Check(a));
  4527. if (_PyLong_IsZero((PyLongObject *)a)) {
  4528. return PyLong_FromLong(0);
  4529. }
  4530. wordshift = shiftby / PyLong_SHIFT;
  4531. remshift = shiftby % PyLong_SHIFT;
  4532. return long_rshift1((PyLongObject *)a, wordshift, remshift);
  4533. }
  4534. static PyObject *
  4535. long_lshift1(PyLongObject *a, Py_ssize_t wordshift, digit remshift)
  4536. {
  4537. PyLongObject *z = NULL;
  4538. Py_ssize_t oldsize, newsize, i, j;
  4539. twodigits accum;
  4540. if (wordshift == 0 && _PyLong_IsCompact(a)) {
  4541. stwodigits m = medium_value(a);
  4542. // bypass undefined shift operator behavior
  4543. stwodigits x = m < 0 ? -(-m << remshift) : m << remshift;
  4544. return _PyLong_FromSTwoDigits(x);
  4545. }
  4546. oldsize = _PyLong_DigitCount(a);
  4547. newsize = oldsize + wordshift;
  4548. if (remshift)
  4549. ++newsize;
  4550. z = _PyLong_New(newsize);
  4551. if (z == NULL)
  4552. return NULL;
  4553. if (_PyLong_IsNegative(a)) {
  4554. assert(Py_REFCNT(z) == 1);
  4555. _PyLong_FlipSign(z);
  4556. }
  4557. for (i = 0; i < wordshift; i++)
  4558. z->long_value.ob_digit[i] = 0;
  4559. accum = 0;
  4560. for (j = 0; j < oldsize; i++, j++) {
  4561. accum |= (twodigits)a->long_value.ob_digit[j] << remshift;
  4562. z->long_value.ob_digit[i] = (digit)(accum & PyLong_MASK);
  4563. accum >>= PyLong_SHIFT;
  4564. }
  4565. if (remshift)
  4566. z->long_value.ob_digit[newsize-1] = (digit)accum;
  4567. else
  4568. assert(!accum);
  4569. z = long_normalize(z);
  4570. return (PyObject *) maybe_small_long(z);
  4571. }
  4572. static PyObject *
  4573. long_lshift(PyObject *a, PyObject *b)
  4574. {
  4575. Py_ssize_t wordshift;
  4576. digit remshift;
  4577. CHECK_BINOP(a, b);
  4578. if (_PyLong_IsNegative((PyLongObject *)b)) {
  4579. PyErr_SetString(PyExc_ValueError, "negative shift count");
  4580. return NULL;
  4581. }
  4582. if (_PyLong_IsZero((PyLongObject *)a)) {
  4583. return PyLong_FromLong(0);
  4584. }
  4585. if (divmod_shift(b, &wordshift, &remshift) < 0)
  4586. return NULL;
  4587. return long_lshift1((PyLongObject *)a, wordshift, remshift);
  4588. }
  4589. /* Return a << shiftby. */
  4590. PyObject *
  4591. _PyLong_Lshift(PyObject *a, size_t shiftby)
  4592. {
  4593. Py_ssize_t wordshift;
  4594. digit remshift;
  4595. assert(PyLong_Check(a));
  4596. if (_PyLong_IsZero((PyLongObject *)a)) {
  4597. return PyLong_FromLong(0);
  4598. }
  4599. wordshift = shiftby / PyLong_SHIFT;
  4600. remshift = shiftby % PyLong_SHIFT;
  4601. return long_lshift1((PyLongObject *)a, wordshift, remshift);
  4602. }
  4603. /* Compute two's complement of digit vector a[0:m], writing result to
  4604. z[0:m]. The digit vector a need not be normalized, but should not
  4605. be entirely zero. a and z may point to the same digit vector. */
  4606. static void
  4607. v_complement(digit *z, digit *a, Py_ssize_t m)
  4608. {
  4609. Py_ssize_t i;
  4610. digit carry = 1;
  4611. for (i = 0; i < m; ++i) {
  4612. carry += a[i] ^ PyLong_MASK;
  4613. z[i] = carry & PyLong_MASK;
  4614. carry >>= PyLong_SHIFT;
  4615. }
  4616. assert(carry == 0);
  4617. }
  4618. /* Bitwise and/xor/or operations */
  4619. static PyObject *
  4620. long_bitwise(PyLongObject *a,
  4621. char op, /* '&', '|', '^' */
  4622. PyLongObject *b)
  4623. {
  4624. int nega, negb, negz;
  4625. Py_ssize_t size_a, size_b, size_z, i;
  4626. PyLongObject *z;
  4627. /* Bitwise operations for negative numbers operate as though
  4628. on a two's complement representation. So convert arguments
  4629. from sign-magnitude to two's complement, and convert the
  4630. result back to sign-magnitude at the end. */
  4631. /* If a is negative, replace it by its two's complement. */
  4632. size_a = _PyLong_DigitCount(a);
  4633. nega = _PyLong_IsNegative(a);
  4634. if (nega) {
  4635. z = _PyLong_New(size_a);
  4636. if (z == NULL)
  4637. return NULL;
  4638. v_complement(z->long_value.ob_digit, a->long_value.ob_digit, size_a);
  4639. a = z;
  4640. }
  4641. else
  4642. /* Keep reference count consistent. */
  4643. Py_INCREF(a);
  4644. /* Same for b. */
  4645. size_b = _PyLong_DigitCount(b);
  4646. negb = _PyLong_IsNegative(b);
  4647. if (negb) {
  4648. z = _PyLong_New(size_b);
  4649. if (z == NULL) {
  4650. Py_DECREF(a);
  4651. return NULL;
  4652. }
  4653. v_complement(z->long_value.ob_digit, b->long_value.ob_digit, size_b);
  4654. b = z;
  4655. }
  4656. else
  4657. Py_INCREF(b);
  4658. /* Swap a and b if necessary to ensure size_a >= size_b. */
  4659. if (size_a < size_b) {
  4660. z = a; a = b; b = z;
  4661. size_z = size_a; size_a = size_b; size_b = size_z;
  4662. negz = nega; nega = negb; negb = negz;
  4663. }
  4664. /* JRH: The original logic here was to allocate the result value (z)
  4665. as the longer of the two operands. However, there are some cases
  4666. where the result is guaranteed to be shorter than that: AND of two
  4667. positives, OR of two negatives: use the shorter number. AND with
  4668. mixed signs: use the positive number. OR with mixed signs: use the
  4669. negative number.
  4670. */
  4671. switch (op) {
  4672. case '^':
  4673. negz = nega ^ negb;
  4674. size_z = size_a;
  4675. break;
  4676. case '&':
  4677. negz = nega & negb;
  4678. size_z = negb ? size_a : size_b;
  4679. break;
  4680. case '|':
  4681. negz = nega | negb;
  4682. size_z = negb ? size_b : size_a;
  4683. break;
  4684. default:
  4685. Py_UNREACHABLE();
  4686. }
  4687. /* We allow an extra digit if z is negative, to make sure that
  4688. the final two's complement of z doesn't overflow. */
  4689. z = _PyLong_New(size_z + negz);
  4690. if (z == NULL) {
  4691. Py_DECREF(a);
  4692. Py_DECREF(b);
  4693. return NULL;
  4694. }
  4695. /* Compute digits for overlap of a and b. */
  4696. switch(op) {
  4697. case '&':
  4698. for (i = 0; i < size_b; ++i)
  4699. z->long_value.ob_digit[i] = a->long_value.ob_digit[i] & b->long_value.ob_digit[i];
  4700. break;
  4701. case '|':
  4702. for (i = 0; i < size_b; ++i)
  4703. z->long_value.ob_digit[i] = a->long_value.ob_digit[i] | b->long_value.ob_digit[i];
  4704. break;
  4705. case '^':
  4706. for (i = 0; i < size_b; ++i)
  4707. z->long_value.ob_digit[i] = a->long_value.ob_digit[i] ^ b->long_value.ob_digit[i];
  4708. break;
  4709. default:
  4710. Py_UNREACHABLE();
  4711. }
  4712. /* Copy any remaining digits of a, inverting if necessary. */
  4713. if (op == '^' && negb)
  4714. for (; i < size_z; ++i)
  4715. z->long_value.ob_digit[i] = a->long_value.ob_digit[i] ^ PyLong_MASK;
  4716. else if (i < size_z)
  4717. memcpy(&z->long_value.ob_digit[i], &a->long_value.ob_digit[i],
  4718. (size_z-i)*sizeof(digit));
  4719. /* Complement result if negative. */
  4720. if (negz) {
  4721. _PyLong_FlipSign(z);
  4722. z->long_value.ob_digit[size_z] = PyLong_MASK;
  4723. v_complement(z->long_value.ob_digit, z->long_value.ob_digit, size_z+1);
  4724. }
  4725. Py_DECREF(a);
  4726. Py_DECREF(b);
  4727. return (PyObject *)maybe_small_long(long_normalize(z));
  4728. }
  4729. static PyObject *
  4730. long_and(PyObject *a, PyObject *b)
  4731. {
  4732. CHECK_BINOP(a, b);
  4733. PyLongObject *x = (PyLongObject*)a;
  4734. PyLongObject *y = (PyLongObject*)b;
  4735. if (_PyLong_IsCompact(x) && _PyLong_IsCompact(y)) {
  4736. return _PyLong_FromSTwoDigits(medium_value(x) & medium_value(y));
  4737. }
  4738. return long_bitwise(x, '&', y);
  4739. }
  4740. static PyObject *
  4741. long_xor(PyObject *a, PyObject *b)
  4742. {
  4743. CHECK_BINOP(a, b);
  4744. PyLongObject *x = (PyLongObject*)a;
  4745. PyLongObject *y = (PyLongObject*)b;
  4746. if (_PyLong_IsCompact(x) && _PyLong_IsCompact(y)) {
  4747. return _PyLong_FromSTwoDigits(medium_value(x) ^ medium_value(y));
  4748. }
  4749. return long_bitwise(x, '^', y);
  4750. }
  4751. static PyObject *
  4752. long_or(PyObject *a, PyObject *b)
  4753. {
  4754. CHECK_BINOP(a, b);
  4755. PyLongObject *x = (PyLongObject*)a;
  4756. PyLongObject *y = (PyLongObject*)b;
  4757. if (_PyLong_IsCompact(x) && _PyLong_IsCompact(y)) {
  4758. return _PyLong_FromSTwoDigits(medium_value(x) | medium_value(y));
  4759. }
  4760. return long_bitwise(x, '|', y);
  4761. }
  4762. static PyObject *
  4763. long_long(PyObject *v)
  4764. {
  4765. if (PyLong_CheckExact(v)) {
  4766. return Py_NewRef(v);
  4767. }
  4768. else {
  4769. return _PyLong_Copy((PyLongObject *)v);
  4770. }
  4771. }
  4772. PyObject *
  4773. _PyLong_GCD(PyObject *aarg, PyObject *barg)
  4774. {
  4775. PyLongObject *a, *b, *c = NULL, *d = NULL, *r;
  4776. stwodigits x, y, q, s, t, c_carry, d_carry;
  4777. stwodigits A, B, C, D, T;
  4778. int nbits, k;
  4779. digit *a_digit, *b_digit, *c_digit, *d_digit, *a_end, *b_end;
  4780. a = (PyLongObject *)aarg;
  4781. b = (PyLongObject *)barg;
  4782. if (_PyLong_DigitCount(a) <= 2 && _PyLong_DigitCount(b) <= 2) {
  4783. Py_INCREF(a);
  4784. Py_INCREF(b);
  4785. goto simple;
  4786. }
  4787. /* Initial reduction: make sure that 0 <= b <= a. */
  4788. a = (PyLongObject *)long_abs(a);
  4789. if (a == NULL)
  4790. return NULL;
  4791. b = (PyLongObject *)long_abs(b);
  4792. if (b == NULL) {
  4793. Py_DECREF(a);
  4794. return NULL;
  4795. }
  4796. if (long_compare(a, b) < 0) {
  4797. r = a;
  4798. a = b;
  4799. b = r;
  4800. }
  4801. /* We now own references to a and b */
  4802. Py_ssize_t size_a, size_b, alloc_a, alloc_b;
  4803. alloc_a = _PyLong_DigitCount(a);
  4804. alloc_b = _PyLong_DigitCount(b);
  4805. /* reduce until a fits into 2 digits */
  4806. while ((size_a = _PyLong_DigitCount(a)) > 2) {
  4807. nbits = bit_length_digit(a->long_value.ob_digit[size_a-1]);
  4808. /* extract top 2*PyLong_SHIFT bits of a into x, along with
  4809. corresponding bits of b into y */
  4810. size_b = _PyLong_DigitCount(b);
  4811. assert(size_b <= size_a);
  4812. if (size_b == 0) {
  4813. if (size_a < alloc_a) {
  4814. r = (PyLongObject *)_PyLong_Copy(a);
  4815. Py_DECREF(a);
  4816. }
  4817. else
  4818. r = a;
  4819. Py_DECREF(b);
  4820. Py_XDECREF(c);
  4821. Py_XDECREF(d);
  4822. return (PyObject *)r;
  4823. }
  4824. x = (((twodigits)a->long_value.ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits)) |
  4825. ((twodigits)a->long_value.ob_digit[size_a-2] << (PyLong_SHIFT-nbits)) |
  4826. (a->long_value.ob_digit[size_a-3] >> nbits));
  4827. y = ((size_b >= size_a - 2 ? b->long_value.ob_digit[size_a-3] >> nbits : 0) |
  4828. (size_b >= size_a - 1 ? (twodigits)b->long_value.ob_digit[size_a-2] << (PyLong_SHIFT-nbits) : 0) |
  4829. (size_b >= size_a ? (twodigits)b->long_value.ob_digit[size_a-1] << (2*PyLong_SHIFT-nbits) : 0));
  4830. /* inner loop of Lehmer's algorithm; A, B, C, D never grow
  4831. larger than PyLong_MASK during the algorithm. */
  4832. A = 1; B = 0; C = 0; D = 1;
  4833. for (k=0;; k++) {
  4834. if (y-C == 0)
  4835. break;
  4836. q = (x+(A-1))/(y-C);
  4837. s = B+q*D;
  4838. t = x-q*y;
  4839. if (s > t)
  4840. break;
  4841. x = y; y = t;
  4842. t = A+q*C; A = D; B = C; C = s; D = t;
  4843. }
  4844. if (k == 0) {
  4845. /* no progress; do a Euclidean step */
  4846. if (l_mod(a, b, &r) < 0)
  4847. goto error;
  4848. Py_SETREF(a, b);
  4849. b = r;
  4850. alloc_a = alloc_b;
  4851. alloc_b = _PyLong_DigitCount(b);
  4852. continue;
  4853. }
  4854. /*
  4855. a, b = A*b-B*a, D*a-C*b if k is odd
  4856. a, b = A*a-B*b, D*b-C*a if k is even
  4857. */
  4858. if (k&1) {
  4859. T = -A; A = -B; B = T;
  4860. T = -C; C = -D; D = T;
  4861. }
  4862. if (c != NULL) {
  4863. assert(size_a >= 0);
  4864. _PyLong_SetSignAndDigitCount(c, 1, size_a);
  4865. }
  4866. else if (Py_REFCNT(a) == 1) {
  4867. c = (PyLongObject*)Py_NewRef(a);
  4868. }
  4869. else {
  4870. alloc_a = size_a;
  4871. c = _PyLong_New(size_a);
  4872. if (c == NULL)
  4873. goto error;
  4874. }
  4875. if (d != NULL) {
  4876. assert(size_a >= 0);
  4877. _PyLong_SetSignAndDigitCount(d, 1, size_a);
  4878. }
  4879. else if (Py_REFCNT(b) == 1 && size_a <= alloc_b) {
  4880. d = (PyLongObject*)Py_NewRef(b);
  4881. assert(size_a >= 0);
  4882. _PyLong_SetSignAndDigitCount(d, 1, size_a);
  4883. }
  4884. else {
  4885. alloc_b = size_a;
  4886. d = _PyLong_New(size_a);
  4887. if (d == NULL)
  4888. goto error;
  4889. }
  4890. a_end = a->long_value.ob_digit + size_a;
  4891. b_end = b->long_value.ob_digit + size_b;
  4892. /* compute new a and new b in parallel */
  4893. a_digit = a->long_value.ob_digit;
  4894. b_digit = b->long_value.ob_digit;
  4895. c_digit = c->long_value.ob_digit;
  4896. d_digit = d->long_value.ob_digit;
  4897. c_carry = 0;
  4898. d_carry = 0;
  4899. while (b_digit < b_end) {
  4900. c_carry += (A * *a_digit) - (B * *b_digit);
  4901. d_carry += (D * *b_digit++) - (C * *a_digit++);
  4902. *c_digit++ = (digit)(c_carry & PyLong_MASK);
  4903. *d_digit++ = (digit)(d_carry & PyLong_MASK);
  4904. c_carry >>= PyLong_SHIFT;
  4905. d_carry >>= PyLong_SHIFT;
  4906. }
  4907. while (a_digit < a_end) {
  4908. c_carry += A * *a_digit;
  4909. d_carry -= C * *a_digit++;
  4910. *c_digit++ = (digit)(c_carry & PyLong_MASK);
  4911. *d_digit++ = (digit)(d_carry & PyLong_MASK);
  4912. c_carry >>= PyLong_SHIFT;
  4913. d_carry >>= PyLong_SHIFT;
  4914. }
  4915. assert(c_carry == 0);
  4916. assert(d_carry == 0);
  4917. Py_INCREF(c);
  4918. Py_INCREF(d);
  4919. Py_DECREF(a);
  4920. Py_DECREF(b);
  4921. a = long_normalize(c);
  4922. b = long_normalize(d);
  4923. }
  4924. Py_XDECREF(c);
  4925. Py_XDECREF(d);
  4926. simple:
  4927. assert(Py_REFCNT(a) > 0);
  4928. assert(Py_REFCNT(b) > 0);
  4929. /* Issue #24999: use two shifts instead of ">> 2*PyLong_SHIFT" to avoid
  4930. undefined behaviour when LONG_MAX type is smaller than 60 bits */
  4931. #if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
  4932. /* a fits into a long, so b must too */
  4933. x = PyLong_AsLong((PyObject *)a);
  4934. y = PyLong_AsLong((PyObject *)b);
  4935. #elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
  4936. x = PyLong_AsLongLong((PyObject *)a);
  4937. y = PyLong_AsLongLong((PyObject *)b);
  4938. #else
  4939. # error "_PyLong_GCD"
  4940. #endif
  4941. x = Py_ABS(x);
  4942. y = Py_ABS(y);
  4943. Py_DECREF(a);
  4944. Py_DECREF(b);
  4945. /* usual Euclidean algorithm for longs */
  4946. while (y != 0) {
  4947. t = y;
  4948. y = x % y;
  4949. x = t;
  4950. }
  4951. #if LONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
  4952. return PyLong_FromLong(x);
  4953. #elif LLONG_MAX >> PyLong_SHIFT >> PyLong_SHIFT
  4954. return PyLong_FromLongLong(x);
  4955. #else
  4956. # error "_PyLong_GCD"
  4957. #endif
  4958. error:
  4959. Py_DECREF(a);
  4960. Py_DECREF(b);
  4961. Py_XDECREF(c);
  4962. Py_XDECREF(d);
  4963. return NULL;
  4964. }
  4965. static PyObject *
  4966. long_float(PyObject *v)
  4967. {
  4968. double result;
  4969. result = PyLong_AsDouble(v);
  4970. if (result == -1.0 && PyErr_Occurred())
  4971. return NULL;
  4972. return PyFloat_FromDouble(result);
  4973. }
  4974. static PyObject *
  4975. long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase);
  4976. /*[clinic input]
  4977. @classmethod
  4978. int.__new__ as long_new
  4979. x: object(c_default="NULL") = 0
  4980. /
  4981. base as obase: object(c_default="NULL") = 10
  4982. [clinic start generated code]*/
  4983. static PyObject *
  4984. long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase)
  4985. /*[clinic end generated code: output=e47cfe777ab0f24c input=81c98f418af9eb6f]*/
  4986. {
  4987. Py_ssize_t base;
  4988. if (type != &PyLong_Type)
  4989. return long_subtype_new(type, x, obase); /* Wimp out */
  4990. if (x == NULL) {
  4991. if (obase != NULL) {
  4992. PyErr_SetString(PyExc_TypeError,
  4993. "int() missing string argument");
  4994. return NULL;
  4995. }
  4996. return PyLong_FromLong(0L);
  4997. }
  4998. /* default base and limit, forward to standard implementation */
  4999. if (obase == NULL)
  5000. return PyNumber_Long(x);
  5001. base = PyNumber_AsSsize_t(obase, NULL);
  5002. if (base == -1 && PyErr_Occurred())
  5003. return NULL;
  5004. if ((base != 0 && base < 2) || base > 36) {
  5005. PyErr_SetString(PyExc_ValueError,
  5006. "int() base must be >= 2 and <= 36, or 0");
  5007. return NULL;
  5008. }
  5009. if (PyUnicode_Check(x))
  5010. return PyLong_FromUnicodeObject(x, (int)base);
  5011. else if (PyByteArray_Check(x) || PyBytes_Check(x)) {
  5012. const char *string;
  5013. if (PyByteArray_Check(x))
  5014. string = PyByteArray_AS_STRING(x);
  5015. else
  5016. string = PyBytes_AS_STRING(x);
  5017. return _PyLong_FromBytes(string, Py_SIZE(x), (int)base);
  5018. }
  5019. else {
  5020. PyErr_SetString(PyExc_TypeError,
  5021. "int() can't convert non-string with explicit base");
  5022. return NULL;
  5023. }
  5024. }
  5025. /* Wimpy, slow approach to tp_new calls for subtypes of int:
  5026. first create a regular int from whatever arguments we got,
  5027. then allocate a subtype instance and initialize it from
  5028. the regular int. The regular int is then thrown away.
  5029. */
  5030. static PyObject *
  5031. long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
  5032. {
  5033. PyLongObject *tmp, *newobj;
  5034. Py_ssize_t i, n;
  5035. assert(PyType_IsSubtype(type, &PyLong_Type));
  5036. tmp = (PyLongObject *)long_new_impl(&PyLong_Type, x, obase);
  5037. if (tmp == NULL)
  5038. return NULL;
  5039. assert(PyLong_Check(tmp));
  5040. n = _PyLong_DigitCount(tmp);
  5041. /* Fast operations for single digit integers (including zero)
  5042. * assume that there is always at least one digit present. */
  5043. if (n == 0) {
  5044. n = 1;
  5045. }
  5046. newobj = (PyLongObject *)type->tp_alloc(type, n);
  5047. if (newobj == NULL) {
  5048. Py_DECREF(tmp);
  5049. return NULL;
  5050. }
  5051. assert(PyLong_Check(newobj));
  5052. newobj->long_value.lv_tag = tmp->long_value.lv_tag;
  5053. for (i = 0; i < n; i++) {
  5054. newobj->long_value.ob_digit[i] = tmp->long_value.ob_digit[i];
  5055. }
  5056. Py_DECREF(tmp);
  5057. return (PyObject *)newobj;
  5058. }
  5059. /*[clinic input]
  5060. int.__getnewargs__
  5061. [clinic start generated code]*/
  5062. static PyObject *
  5063. int___getnewargs___impl(PyObject *self)
  5064. /*[clinic end generated code: output=839a49de3f00b61b input=5904770ab1fb8c75]*/
  5065. {
  5066. return Py_BuildValue("(N)", _PyLong_Copy((PyLongObject *)self));
  5067. }
  5068. static PyObject *
  5069. long_get0(PyObject *Py_UNUSED(self), void *Py_UNUSED(context))
  5070. {
  5071. return PyLong_FromLong(0L);
  5072. }
  5073. static PyObject *
  5074. long_get1(PyObject *Py_UNUSED(self), void *Py_UNUSED(ignored))
  5075. {
  5076. return PyLong_FromLong(1L);
  5077. }
  5078. /*[clinic input]
  5079. int.__format__
  5080. format_spec: unicode
  5081. /
  5082. Convert to a string according to format_spec.
  5083. [clinic start generated code]*/
  5084. static PyObject *
  5085. int___format___impl(PyObject *self, PyObject *format_spec)
  5086. /*[clinic end generated code: output=b4929dee9ae18689 input=d5e1254a47e8d1dc]*/
  5087. {
  5088. _PyUnicodeWriter writer;
  5089. int ret;
  5090. _PyUnicodeWriter_Init(&writer);
  5091. ret = _PyLong_FormatAdvancedWriter(
  5092. &writer,
  5093. self,
  5094. format_spec, 0, PyUnicode_GET_LENGTH(format_spec));
  5095. if (ret == -1) {
  5096. _PyUnicodeWriter_Dealloc(&writer);
  5097. return NULL;
  5098. }
  5099. return _PyUnicodeWriter_Finish(&writer);
  5100. }
  5101. /* Return a pair (q, r) such that a = b * q + r, and
  5102. abs(r) <= abs(b)/2, with equality possible only if q is even.
  5103. In other words, q == a / b, rounded to the nearest integer using
  5104. round-half-to-even. */
  5105. PyObject *
  5106. _PyLong_DivmodNear(PyObject *a, PyObject *b)
  5107. {
  5108. PyLongObject *quo = NULL, *rem = NULL;
  5109. PyObject *twice_rem, *result, *temp;
  5110. int quo_is_odd, quo_is_neg;
  5111. Py_ssize_t cmp;
  5112. /* Equivalent Python code:
  5113. def divmod_near(a, b):
  5114. q, r = divmod(a, b)
  5115. # round up if either r / b > 0.5, or r / b == 0.5 and q is odd.
  5116. # The expression r / b > 0.5 is equivalent to 2 * r > b if b is
  5117. # positive, 2 * r < b if b negative.
  5118. greater_than_half = 2*r > b if b > 0 else 2*r < b
  5119. exactly_half = 2*r == b
  5120. if greater_than_half or exactly_half and q % 2 == 1:
  5121. q += 1
  5122. r -= b
  5123. return q, r
  5124. */
  5125. if (!PyLong_Check(a) || !PyLong_Check(b)) {
  5126. PyErr_SetString(PyExc_TypeError,
  5127. "non-integer arguments in division");
  5128. return NULL;
  5129. }
  5130. /* Do a and b have different signs? If so, quotient is negative. */
  5131. quo_is_neg = (_PyLong_IsNegative((PyLongObject *)a)) != (_PyLong_IsNegative((PyLongObject *)b));
  5132. if (long_divrem((PyLongObject*)a, (PyLongObject*)b, &quo, &rem) < 0)
  5133. goto error;
  5134. /* compare twice the remainder with the divisor, to see
  5135. if we need to adjust the quotient and remainder */
  5136. PyObject *one = _PyLong_GetOne(); // borrowed reference
  5137. twice_rem = long_lshift((PyObject *)rem, one);
  5138. if (twice_rem == NULL)
  5139. goto error;
  5140. if (quo_is_neg) {
  5141. temp = long_neg((PyLongObject*)twice_rem);
  5142. Py_SETREF(twice_rem, temp);
  5143. if (twice_rem == NULL)
  5144. goto error;
  5145. }
  5146. cmp = long_compare((PyLongObject *)twice_rem, (PyLongObject *)b);
  5147. Py_DECREF(twice_rem);
  5148. quo_is_odd = (quo->long_value.ob_digit[0] & 1) != 0;
  5149. if ((_PyLong_IsNegative((PyLongObject *)b) ? cmp < 0 : cmp > 0) || (cmp == 0 && quo_is_odd)) {
  5150. /* fix up quotient */
  5151. if (quo_is_neg)
  5152. temp = long_sub(quo, (PyLongObject *)one);
  5153. else
  5154. temp = long_add(quo, (PyLongObject *)one);
  5155. Py_SETREF(quo, (PyLongObject *)temp);
  5156. if (quo == NULL)
  5157. goto error;
  5158. /* and remainder */
  5159. if (quo_is_neg)
  5160. temp = long_add(rem, (PyLongObject *)b);
  5161. else
  5162. temp = long_sub(rem, (PyLongObject *)b);
  5163. Py_SETREF(rem, (PyLongObject *)temp);
  5164. if (rem == NULL)
  5165. goto error;
  5166. }
  5167. result = PyTuple_New(2);
  5168. if (result == NULL)
  5169. goto error;
  5170. /* PyTuple_SET_ITEM steals references */
  5171. PyTuple_SET_ITEM(result, 0, (PyObject *)quo);
  5172. PyTuple_SET_ITEM(result, 1, (PyObject *)rem);
  5173. return result;
  5174. error:
  5175. Py_XDECREF(quo);
  5176. Py_XDECREF(rem);
  5177. return NULL;
  5178. }
  5179. /*[clinic input]
  5180. int.__round__
  5181. ndigits as o_ndigits: object = NULL
  5182. /
  5183. Rounding an Integral returns itself.
  5184. Rounding with an ndigits argument also returns an integer.
  5185. [clinic start generated code]*/
  5186. static PyObject *
  5187. int___round___impl(PyObject *self, PyObject *o_ndigits)
  5188. /*[clinic end generated code: output=954fda6b18875998 input=1614cf23ec9e18c3]*/
  5189. {
  5190. PyObject *temp, *result, *ndigits;
  5191. /* To round an integer m to the nearest 10**n (n positive), we make use of
  5192. * the divmod_near operation, defined by:
  5193. *
  5194. * divmod_near(a, b) = (q, r)
  5195. *
  5196. * where q is the nearest integer to the quotient a / b (the
  5197. * nearest even integer in the case of a tie) and r == a - q * b.
  5198. * Hence q * b = a - r is the nearest multiple of b to a,
  5199. * preferring even multiples in the case of a tie.
  5200. *
  5201. * So the nearest multiple of 10**n to m is:
  5202. *
  5203. * m - divmod_near(m, 10**n)[1].
  5204. */
  5205. if (o_ndigits == NULL)
  5206. return long_long(self);
  5207. ndigits = _PyNumber_Index(o_ndigits);
  5208. if (ndigits == NULL)
  5209. return NULL;
  5210. /* if ndigits >= 0 then no rounding is necessary; return self unchanged */
  5211. if (!_PyLong_IsNegative((PyLongObject *)ndigits)) {
  5212. Py_DECREF(ndigits);
  5213. return long_long(self);
  5214. }
  5215. /* result = self - divmod_near(self, 10 ** -ndigits)[1] */
  5216. temp = long_neg((PyLongObject*)ndigits);
  5217. Py_SETREF(ndigits, temp);
  5218. if (ndigits == NULL)
  5219. return NULL;
  5220. result = PyLong_FromLong(10L);
  5221. if (result == NULL) {
  5222. Py_DECREF(ndigits);
  5223. return NULL;
  5224. }
  5225. temp = long_pow(result, ndigits, Py_None);
  5226. Py_DECREF(ndigits);
  5227. Py_SETREF(result, temp);
  5228. if (result == NULL)
  5229. return NULL;
  5230. temp = _PyLong_DivmodNear(self, result);
  5231. Py_SETREF(result, temp);
  5232. if (result == NULL)
  5233. return NULL;
  5234. temp = long_sub((PyLongObject *)self,
  5235. (PyLongObject *)PyTuple_GET_ITEM(result, 1));
  5236. Py_SETREF(result, temp);
  5237. return result;
  5238. }
  5239. /*[clinic input]
  5240. int.__sizeof__ -> Py_ssize_t
  5241. Returns size in memory, in bytes.
  5242. [clinic start generated code]*/
  5243. static Py_ssize_t
  5244. int___sizeof___impl(PyObject *self)
  5245. /*[clinic end generated code: output=3303f008eaa6a0a5 input=9b51620c76fc4507]*/
  5246. {
  5247. /* using Py_MAX(..., 1) because we always allocate space for at least
  5248. one digit, even though the integer zero has a digit count of 0 */
  5249. Py_ssize_t ndigits = Py_MAX(_PyLong_DigitCount((PyLongObject *)self), 1);
  5250. return Py_TYPE(self)->tp_basicsize + Py_TYPE(self)->tp_itemsize * ndigits;
  5251. }
  5252. /*[clinic input]
  5253. int.bit_length
  5254. Number of bits necessary to represent self in binary.
  5255. >>> bin(37)
  5256. '0b100101'
  5257. >>> (37).bit_length()
  5258. 6
  5259. [clinic start generated code]*/
  5260. static PyObject *
  5261. int_bit_length_impl(PyObject *self)
  5262. /*[clinic end generated code: output=fc1977c9353d6a59 input=e4eb7a587e849a32]*/
  5263. {
  5264. PyLongObject *result, *x, *y;
  5265. Py_ssize_t ndigits;
  5266. int msd_bits;
  5267. digit msd;
  5268. assert(self != NULL);
  5269. assert(PyLong_Check(self));
  5270. ndigits = _PyLong_DigitCount((PyLongObject *)self);
  5271. if (ndigits == 0)
  5272. return PyLong_FromLong(0);
  5273. msd = ((PyLongObject *)self)->long_value.ob_digit[ndigits-1];
  5274. msd_bits = bit_length_digit(msd);
  5275. if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
  5276. return PyLong_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
  5277. /* expression above may overflow; use Python integers instead */
  5278. result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
  5279. if (result == NULL)
  5280. return NULL;
  5281. x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
  5282. if (x == NULL)
  5283. goto error;
  5284. y = (PyLongObject *)long_mul(result, x);
  5285. Py_DECREF(x);
  5286. if (y == NULL)
  5287. goto error;
  5288. Py_SETREF(result, y);
  5289. x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
  5290. if (x == NULL)
  5291. goto error;
  5292. y = (PyLongObject *)long_add(result, x);
  5293. Py_DECREF(x);
  5294. if (y == NULL)
  5295. goto error;
  5296. Py_SETREF(result, y);
  5297. return (PyObject *)result;
  5298. error:
  5299. Py_DECREF(result);
  5300. return NULL;
  5301. }
  5302. static int
  5303. popcount_digit(digit d)
  5304. {
  5305. // digit can be larger than uint32_t, but only PyLong_SHIFT bits
  5306. // of it will be ever used.
  5307. static_assert(PyLong_SHIFT <= 32, "digit is larger than uint32_t");
  5308. return _Py_popcount32((uint32_t)d);
  5309. }
  5310. /*[clinic input]
  5311. int.bit_count
  5312. Number of ones in the binary representation of the absolute value of self.
  5313. Also known as the population count.
  5314. >>> bin(13)
  5315. '0b1101'
  5316. >>> (13).bit_count()
  5317. 3
  5318. [clinic start generated code]*/
  5319. static PyObject *
  5320. int_bit_count_impl(PyObject *self)
  5321. /*[clinic end generated code: output=2e571970daf1e5c3 input=7e0adef8e8ccdf2e]*/
  5322. {
  5323. assert(self != NULL);
  5324. assert(PyLong_Check(self));
  5325. PyLongObject *z = (PyLongObject *)self;
  5326. Py_ssize_t ndigits = _PyLong_DigitCount(z);
  5327. Py_ssize_t bit_count = 0;
  5328. /* Each digit has up to PyLong_SHIFT ones, so the accumulated bit count
  5329. from the first PY_SSIZE_T_MAX/PyLong_SHIFT digits can't overflow a
  5330. Py_ssize_t. */
  5331. Py_ssize_t ndigits_fast = Py_MIN(ndigits, PY_SSIZE_T_MAX/PyLong_SHIFT);
  5332. for (Py_ssize_t i = 0; i < ndigits_fast; i++) {
  5333. bit_count += popcount_digit(z->long_value.ob_digit[i]);
  5334. }
  5335. PyObject *result = PyLong_FromSsize_t(bit_count);
  5336. if (result == NULL) {
  5337. return NULL;
  5338. }
  5339. /* Use Python integers if bit_count would overflow. */
  5340. for (Py_ssize_t i = ndigits_fast; i < ndigits; i++) {
  5341. PyObject *x = PyLong_FromLong(popcount_digit(z->long_value.ob_digit[i]));
  5342. if (x == NULL) {
  5343. goto error;
  5344. }
  5345. PyObject *y = long_add((PyLongObject *)result, (PyLongObject *)x);
  5346. Py_DECREF(x);
  5347. if (y == NULL) {
  5348. goto error;
  5349. }
  5350. Py_SETREF(result, y);
  5351. }
  5352. return result;
  5353. error:
  5354. Py_DECREF(result);
  5355. return NULL;
  5356. }
  5357. /*[clinic input]
  5358. int.as_integer_ratio
  5359. Return a pair of integers, whose ratio is equal to the original int.
  5360. The ratio is in lowest terms and has a positive denominator.
  5361. >>> (10).as_integer_ratio()
  5362. (10, 1)
  5363. >>> (-10).as_integer_ratio()
  5364. (-10, 1)
  5365. >>> (0).as_integer_ratio()
  5366. (0, 1)
  5367. [clinic start generated code]*/
  5368. static PyObject *
  5369. int_as_integer_ratio_impl(PyObject *self)
  5370. /*[clinic end generated code: output=e60803ae1cc8621a input=384ff1766634bec2]*/
  5371. {
  5372. PyObject *ratio_tuple;
  5373. PyObject *numerator = long_long(self);
  5374. if (numerator == NULL) {
  5375. return NULL;
  5376. }
  5377. ratio_tuple = PyTuple_Pack(2, numerator, _PyLong_GetOne());
  5378. Py_DECREF(numerator);
  5379. return ratio_tuple;
  5380. }
  5381. /*[clinic input]
  5382. int.to_bytes
  5383. length: Py_ssize_t = 1
  5384. Length of bytes object to use. An OverflowError is raised if the
  5385. integer is not representable with the given number of bytes. Default
  5386. is length 1.
  5387. byteorder: unicode(c_default="NULL") = "big"
  5388. The byte order used to represent the integer. If byteorder is 'big',
  5389. the most significant byte is at the beginning of the byte array. If
  5390. byteorder is 'little', the most significant byte is at the end of the
  5391. byte array. To request the native byte order of the host system, use
  5392. `sys.byteorder' as the byte order value. Default is to use 'big'.
  5393. *
  5394. signed as is_signed: bool = False
  5395. Determines whether two's complement is used to represent the integer.
  5396. If signed is False and a negative integer is given, an OverflowError
  5397. is raised.
  5398. Return an array of bytes representing an integer.
  5399. [clinic start generated code]*/
  5400. static PyObject *
  5401. int_to_bytes_impl(PyObject *self, Py_ssize_t length, PyObject *byteorder,
  5402. int is_signed)
  5403. /*[clinic end generated code: output=89c801df114050a3 input=d42ecfb545039d71]*/
  5404. {
  5405. int little_endian;
  5406. PyObject *bytes;
  5407. if (byteorder == NULL)
  5408. little_endian = 0;
  5409. else if (_PyUnicode_Equal(byteorder, &_Py_ID(little)))
  5410. little_endian = 1;
  5411. else if (_PyUnicode_Equal(byteorder, &_Py_ID(big)))
  5412. little_endian = 0;
  5413. else {
  5414. PyErr_SetString(PyExc_ValueError,
  5415. "byteorder must be either 'little' or 'big'");
  5416. return NULL;
  5417. }
  5418. if (length < 0) {
  5419. PyErr_SetString(PyExc_ValueError,
  5420. "length argument must be non-negative");
  5421. return NULL;
  5422. }
  5423. bytes = PyBytes_FromStringAndSize(NULL, length);
  5424. if (bytes == NULL)
  5425. return NULL;
  5426. if (_PyLong_AsByteArray((PyLongObject *)self,
  5427. (unsigned char *)PyBytes_AS_STRING(bytes),
  5428. length, little_endian, is_signed) < 0) {
  5429. Py_DECREF(bytes);
  5430. return NULL;
  5431. }
  5432. return bytes;
  5433. }
  5434. /*[clinic input]
  5435. @classmethod
  5436. int.from_bytes
  5437. bytes as bytes_obj: object
  5438. Holds the array of bytes to convert. The argument must either
  5439. support the buffer protocol or be an iterable object producing bytes.
  5440. Bytes and bytearray are examples of built-in objects that support the
  5441. buffer protocol.
  5442. byteorder: unicode(c_default="NULL") = "big"
  5443. The byte order used to represent the integer. If byteorder is 'big',
  5444. the most significant byte is at the beginning of the byte array. If
  5445. byteorder is 'little', the most significant byte is at the end of the
  5446. byte array. To request the native byte order of the host system, use
  5447. `sys.byteorder' as the byte order value. Default is to use 'big'.
  5448. *
  5449. signed as is_signed: bool = False
  5450. Indicates whether two's complement is used to represent the integer.
  5451. Return the integer represented by the given array of bytes.
  5452. [clinic start generated code]*/
  5453. static PyObject *
  5454. int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
  5455. PyObject *byteorder, int is_signed)
  5456. /*[clinic end generated code: output=efc5d68e31f9314f input=33326dccdd655553]*/
  5457. {
  5458. int little_endian;
  5459. PyObject *long_obj, *bytes;
  5460. if (byteorder == NULL)
  5461. little_endian = 0;
  5462. else if (_PyUnicode_Equal(byteorder, &_Py_ID(little)))
  5463. little_endian = 1;
  5464. else if (_PyUnicode_Equal(byteorder, &_Py_ID(big)))
  5465. little_endian = 0;
  5466. else {
  5467. PyErr_SetString(PyExc_ValueError,
  5468. "byteorder must be either 'little' or 'big'");
  5469. return NULL;
  5470. }
  5471. bytes = PyObject_Bytes(bytes_obj);
  5472. if (bytes == NULL)
  5473. return NULL;
  5474. long_obj = _PyLong_FromByteArray(
  5475. (unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
  5476. little_endian, is_signed);
  5477. Py_DECREF(bytes);
  5478. if (long_obj != NULL && type != &PyLong_Type) {
  5479. Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
  5480. }
  5481. return long_obj;
  5482. }
  5483. static PyObject *
  5484. long_long_meth(PyObject *self, PyObject *Py_UNUSED(ignored))
  5485. {
  5486. return long_long(self);
  5487. }
  5488. /*[clinic input]
  5489. int.is_integer
  5490. Returns True. Exists for duck type compatibility with float.is_integer.
  5491. [clinic start generated code]*/
  5492. static PyObject *
  5493. int_is_integer_impl(PyObject *self)
  5494. /*[clinic end generated code: output=90f8e794ce5430ef input=7e41c4d4416e05f2]*/
  5495. {
  5496. Py_RETURN_TRUE;
  5497. }
  5498. static PyMethodDef long_methods[] = {
  5499. {"conjugate", long_long_meth, METH_NOARGS,
  5500. "Returns self, the complex conjugate of any int."},
  5501. INT_BIT_LENGTH_METHODDEF
  5502. INT_BIT_COUNT_METHODDEF
  5503. INT_TO_BYTES_METHODDEF
  5504. INT_FROM_BYTES_METHODDEF
  5505. INT_AS_INTEGER_RATIO_METHODDEF
  5506. {"__trunc__", long_long_meth, METH_NOARGS,
  5507. "Truncating an Integral returns itself."},
  5508. {"__floor__", long_long_meth, METH_NOARGS,
  5509. "Flooring an Integral returns itself."},
  5510. {"__ceil__", long_long_meth, METH_NOARGS,
  5511. "Ceiling of an Integral returns itself."},
  5512. INT___ROUND___METHODDEF
  5513. INT___GETNEWARGS___METHODDEF
  5514. INT___FORMAT___METHODDEF
  5515. INT___SIZEOF___METHODDEF
  5516. INT_IS_INTEGER_METHODDEF
  5517. {NULL, NULL} /* sentinel */
  5518. };
  5519. static PyGetSetDef long_getset[] = {
  5520. {"real",
  5521. (getter)long_long_meth, (setter)NULL,
  5522. "the real part of a complex number",
  5523. NULL},
  5524. {"imag",
  5525. long_get0, (setter)NULL,
  5526. "the imaginary part of a complex number",
  5527. NULL},
  5528. {"numerator",
  5529. (getter)long_long_meth, (setter)NULL,
  5530. "the numerator of a rational number in lowest terms",
  5531. NULL},
  5532. {"denominator",
  5533. long_get1, (setter)NULL,
  5534. "the denominator of a rational number in lowest terms",
  5535. NULL},
  5536. {NULL} /* Sentinel */
  5537. };
  5538. PyDoc_STRVAR(long_doc,
  5539. "int([x]) -> integer\n\
  5540. int(x, base=10) -> integer\n\
  5541. \n\
  5542. Convert a number or string to an integer, or return 0 if no arguments\n\
  5543. are given. If x is a number, return x.__int__(). For floating point\n\
  5544. numbers, this truncates towards zero.\n\
  5545. \n\
  5546. If x is not a number or if base is given, then x must be a string,\n\
  5547. bytes, or bytearray instance representing an integer literal in the\n\
  5548. given base. The literal can be preceded by '+' or '-' and be surrounded\n\
  5549. by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\n\
  5550. Base 0 means to interpret the base from the string as an integer literal.\n\
  5551. >>> int('0b100', base=0)\n\
  5552. 4");
  5553. static PyNumberMethods long_as_number = {
  5554. (binaryfunc)long_add, /*nb_add*/
  5555. (binaryfunc)long_sub, /*nb_subtract*/
  5556. (binaryfunc)long_mul, /*nb_multiply*/
  5557. long_mod, /*nb_remainder*/
  5558. long_divmod, /*nb_divmod*/
  5559. long_pow, /*nb_power*/
  5560. (unaryfunc)long_neg, /*nb_negative*/
  5561. long_long, /*tp_positive*/
  5562. (unaryfunc)long_abs, /*tp_absolute*/
  5563. (inquiry)long_bool, /*tp_bool*/
  5564. (unaryfunc)long_invert, /*nb_invert*/
  5565. long_lshift, /*nb_lshift*/
  5566. long_rshift, /*nb_rshift*/
  5567. long_and, /*nb_and*/
  5568. long_xor, /*nb_xor*/
  5569. long_or, /*nb_or*/
  5570. long_long, /*nb_int*/
  5571. 0, /*nb_reserved*/
  5572. long_float, /*nb_float*/
  5573. 0, /* nb_inplace_add */
  5574. 0, /* nb_inplace_subtract */
  5575. 0, /* nb_inplace_multiply */
  5576. 0, /* nb_inplace_remainder */
  5577. 0, /* nb_inplace_power */
  5578. 0, /* nb_inplace_lshift */
  5579. 0, /* nb_inplace_rshift */
  5580. 0, /* nb_inplace_and */
  5581. 0, /* nb_inplace_xor */
  5582. 0, /* nb_inplace_or */
  5583. long_div, /* nb_floor_divide */
  5584. long_true_divide, /* nb_true_divide */
  5585. 0, /* nb_inplace_floor_divide */
  5586. 0, /* nb_inplace_true_divide */
  5587. long_long, /* nb_index */
  5588. };
  5589. PyTypeObject PyLong_Type = {
  5590. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  5591. "int", /* tp_name */
  5592. offsetof(PyLongObject, long_value.ob_digit), /* tp_basicsize */
  5593. sizeof(digit), /* tp_itemsize */
  5594. long_dealloc, /* tp_dealloc */
  5595. 0, /* tp_vectorcall_offset */
  5596. 0, /* tp_getattr */
  5597. 0, /* tp_setattr */
  5598. 0, /* tp_as_async */
  5599. long_to_decimal_string, /* tp_repr */
  5600. &long_as_number, /* tp_as_number */
  5601. 0, /* tp_as_sequence */
  5602. 0, /* tp_as_mapping */
  5603. (hashfunc)long_hash, /* tp_hash */
  5604. 0, /* tp_call */
  5605. 0, /* tp_str */
  5606. PyObject_GenericGetAttr, /* tp_getattro */
  5607. 0, /* tp_setattro */
  5608. 0, /* tp_as_buffer */
  5609. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  5610. Py_TPFLAGS_LONG_SUBCLASS |
  5611. _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
  5612. long_doc, /* tp_doc */
  5613. 0, /* tp_traverse */
  5614. 0, /* tp_clear */
  5615. long_richcompare, /* tp_richcompare */
  5616. 0, /* tp_weaklistoffset */
  5617. 0, /* tp_iter */
  5618. 0, /* tp_iternext */
  5619. long_methods, /* tp_methods */
  5620. 0, /* tp_members */
  5621. long_getset, /* tp_getset */
  5622. 0, /* tp_base */
  5623. 0, /* tp_dict */
  5624. 0, /* tp_descr_get */
  5625. 0, /* tp_descr_set */
  5626. 0, /* tp_dictoffset */
  5627. 0, /* tp_init */
  5628. 0, /* tp_alloc */
  5629. long_new, /* tp_new */
  5630. PyObject_Free, /* tp_free */
  5631. };
  5632. static PyTypeObject Int_InfoType;
  5633. PyDoc_STRVAR(int_info__doc__,
  5634. "sys.int_info\n\
  5635. \n\
  5636. A named tuple that holds information about Python's\n\
  5637. internal representation of integers. The attributes are read only.");
  5638. static PyStructSequence_Field int_info_fields[] = {
  5639. {"bits_per_digit", "size of a digit in bits"},
  5640. {"sizeof_digit", "size in bytes of the C type used to represent a digit"},
  5641. {"default_max_str_digits", "maximum string conversion digits limitation"},
  5642. {"str_digits_check_threshold", "minimum positive value for int_max_str_digits"},
  5643. {NULL, NULL}
  5644. };
  5645. static PyStructSequence_Desc int_info_desc = {
  5646. "sys.int_info", /* name */
  5647. int_info__doc__, /* doc */
  5648. int_info_fields, /* fields */
  5649. 4 /* number of fields */
  5650. };
  5651. PyObject *
  5652. PyLong_GetInfo(void)
  5653. {
  5654. PyObject* int_info;
  5655. int field = 0;
  5656. int_info = PyStructSequence_New(&Int_InfoType);
  5657. if (int_info == NULL)
  5658. return NULL;
  5659. PyStructSequence_SET_ITEM(int_info, field++,
  5660. PyLong_FromLong(PyLong_SHIFT));
  5661. PyStructSequence_SET_ITEM(int_info, field++,
  5662. PyLong_FromLong(sizeof(digit)));
  5663. /*
  5664. * The following two fields were added after investigating uses of
  5665. * sys.int_info in the wild: Exceedingly rarely used. The ONLY use found was
  5666. * numba using sys.int_info.bits_per_digit as attribute access rather than
  5667. * sequence unpacking. Cython and sympy also refer to sys.int_info but only
  5668. * as info for debugging. No concern about adding these in a backport.
  5669. */
  5670. PyStructSequence_SET_ITEM(int_info, field++,
  5671. PyLong_FromLong(_PY_LONG_DEFAULT_MAX_STR_DIGITS));
  5672. PyStructSequence_SET_ITEM(int_info, field++,
  5673. PyLong_FromLong(_PY_LONG_MAX_STR_DIGITS_THRESHOLD));
  5674. if (PyErr_Occurred()) {
  5675. Py_CLEAR(int_info);
  5676. return NULL;
  5677. }
  5678. return int_info;
  5679. }
  5680. /* runtime lifecycle */
  5681. PyStatus
  5682. _PyLong_InitTypes(PyInterpreterState *interp)
  5683. {
  5684. /* initialize int_info */
  5685. if (_PyStructSequence_InitBuiltin(interp, &Int_InfoType,
  5686. &int_info_desc) < 0)
  5687. {
  5688. return _PyStatus_ERR("can't init int info type");
  5689. }
  5690. return _PyStatus_OK();
  5691. }
  5692. void
  5693. _PyLong_FiniTypes(PyInterpreterState *interp)
  5694. {
  5695. _PyStructSequence_FiniBuiltin(interp, &Int_InfoType);
  5696. }
  5697. #undef PyUnstable_Long_IsCompact
  5698. int
  5699. PyUnstable_Long_IsCompact(const PyLongObject* op) {
  5700. return _PyLong_IsCompact(op);
  5701. }
  5702. #undef PyUnstable_Long_CompactValue
  5703. Py_ssize_t
  5704. PyUnstable_Long_CompactValue(const PyLongObject* op) {
  5705. return _PyLong_CompactValue(op);
  5706. }