longobject.c 199 KB

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