longobject.c 200 KB

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