_decimal.c 176 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056
  1. /*
  2. * Copyright (c) 2008-2012 Stefan Krah. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
  16. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  21. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  22. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  23. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  24. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  25. * SUCH DAMAGE.
  26. */
  27. #ifndef Py_BUILD_CORE_BUILTIN
  28. # define Py_BUILD_CORE_MODULE 1
  29. #endif
  30. #include <Python.h>
  31. #include "pycore_long.h" // _PyLong_IsZero()
  32. #include "pycore_pystate.h" // _PyThreadState_GET()
  33. #include "complexobject.h"
  34. #include "mpdecimal.h"
  35. #include <stdlib.h>
  36. #include "docstrings.h"
  37. #if !defined(MPD_VERSION_HEX) || MPD_VERSION_HEX < 0x02050000
  38. #error "libmpdec version >= 2.5.0 required"
  39. #endif
  40. /*
  41. * Type sizes with assertions in mpdecimal.h and pyport.h:
  42. * sizeof(size_t) == sizeof(Py_ssize_t)
  43. * sizeof(size_t) == sizeof(mpd_uint_t) == sizeof(mpd_ssize_t)
  44. */
  45. #ifdef TEST_COVERAGE
  46. #undef Py_LOCAL_INLINE
  47. #define Py_LOCAL_INLINE Py_LOCAL
  48. #endif
  49. #define MPD_Float_operation MPD_Not_implemented
  50. #define BOUNDS_CHECK(x, MIN, MAX) x = (x < MIN || MAX < x) ? MAX : x
  51. #if defined(__GNUC__) && !defined(__INTEL_COMPILER)
  52. #define UNUSED __attribute__((unused))
  53. #else
  54. #define UNUSED
  55. #endif
  56. /* _Py_DEC_MINALLOC >= MPD_MINALLOC */
  57. #define _Py_DEC_MINALLOC 4
  58. typedef struct {
  59. PyObject_HEAD
  60. Py_hash_t hash;
  61. mpd_t dec;
  62. mpd_uint_t data[_Py_DEC_MINALLOC];
  63. } PyDecObject;
  64. typedef struct {
  65. PyObject_HEAD
  66. uint32_t *flags;
  67. } PyDecSignalDictObject;
  68. typedef struct {
  69. PyObject_HEAD
  70. mpd_context_t ctx;
  71. PyObject *traps;
  72. PyObject *flags;
  73. int capitals;
  74. PyThreadState *tstate;
  75. } PyDecContextObject;
  76. typedef struct {
  77. PyObject_HEAD
  78. PyObject *local;
  79. PyObject *global;
  80. } PyDecContextManagerObject;
  81. #undef MPD
  82. #undef CTX
  83. static PyTypeObject PyDec_Type;
  84. static PyTypeObject *PyDecSignalDict_Type;
  85. static PyTypeObject PyDecContext_Type;
  86. static PyTypeObject PyDecContextManager_Type;
  87. #define PyDec_CheckExact(v) Py_IS_TYPE(v, &PyDec_Type)
  88. #define PyDec_Check(v) PyObject_TypeCheck(v, &PyDec_Type)
  89. #define PyDecSignalDict_Check(v) Py_IS_TYPE(v, PyDecSignalDict_Type)
  90. #define PyDecContext_Check(v) PyObject_TypeCheck(v, &PyDecContext_Type)
  91. #define MPD(v) (&((PyDecObject *)v)->dec)
  92. #define SdFlagAddr(v) (((PyDecSignalDictObject *)v)->flags)
  93. #define SdFlags(v) (*((PyDecSignalDictObject *)v)->flags)
  94. #define CTX(v) (&((PyDecContextObject *)v)->ctx)
  95. #define CtxCaps(v) (((PyDecContextObject *)v)->capitals)
  96. Py_LOCAL_INLINE(PyObject *)
  97. incr_true(void)
  98. {
  99. return Py_NewRef(Py_True);
  100. }
  101. Py_LOCAL_INLINE(PyObject *)
  102. incr_false(void)
  103. {
  104. return Py_NewRef(Py_False);
  105. }
  106. #ifndef WITH_DECIMAL_CONTEXTVAR
  107. /* Key for thread state dictionary */
  108. static PyObject *tls_context_key = NULL;
  109. /* Invariant: NULL or the most recently accessed thread local context */
  110. static PyDecContextObject *cached_context = NULL;
  111. #else
  112. static PyObject *current_context_var = NULL;
  113. #endif
  114. /* Template for creating new thread contexts, calling Context() without
  115. * arguments and initializing the module_context on first access. */
  116. static PyObject *default_context_template = NULL;
  117. /* Basic and extended context templates */
  118. static PyObject *basic_context_template = NULL;
  119. static PyObject *extended_context_template = NULL;
  120. /* Error codes for functions that return signals or conditions */
  121. #define DEC_INVALID_SIGNALS (MPD_Max_status+1U)
  122. #define DEC_ERR_OCCURRED (DEC_INVALID_SIGNALS<<1)
  123. #define DEC_ERRORS (DEC_INVALID_SIGNALS|DEC_ERR_OCCURRED)
  124. typedef struct {
  125. const char *name; /* condition or signal name */
  126. const char *fqname; /* fully qualified name */
  127. uint32_t flag; /* libmpdec flag */
  128. PyObject *ex; /* corresponding exception */
  129. } DecCondMap;
  130. /* Top level Exception; inherits from ArithmeticError */
  131. static PyObject *DecimalException = NULL;
  132. /* Exceptions that correspond to IEEE signals */
  133. #define SUBNORMAL 5
  134. #define INEXACT 6
  135. #define ROUNDED 7
  136. #define SIGNAL_MAP_LEN 9
  137. static DecCondMap signal_map[] = {
  138. {"InvalidOperation", "decimal.InvalidOperation", MPD_IEEE_Invalid_operation, NULL},
  139. {"FloatOperation", "decimal.FloatOperation", MPD_Float_operation, NULL},
  140. {"DivisionByZero", "decimal.DivisionByZero", MPD_Division_by_zero, NULL},
  141. {"Overflow", "decimal.Overflow", MPD_Overflow, NULL},
  142. {"Underflow", "decimal.Underflow", MPD_Underflow, NULL},
  143. {"Subnormal", "decimal.Subnormal", MPD_Subnormal, NULL},
  144. {"Inexact", "decimal.Inexact", MPD_Inexact, NULL},
  145. {"Rounded", "decimal.Rounded", MPD_Rounded, NULL},
  146. {"Clamped", "decimal.Clamped", MPD_Clamped, NULL},
  147. {NULL}
  148. };
  149. /* Exceptions that inherit from InvalidOperation */
  150. static DecCondMap cond_map[] = {
  151. {"InvalidOperation", "decimal.InvalidOperation", MPD_Invalid_operation, NULL},
  152. {"ConversionSyntax", "decimal.ConversionSyntax", MPD_Conversion_syntax, NULL},
  153. {"DivisionImpossible", "decimal.DivisionImpossible", MPD_Division_impossible, NULL},
  154. {"DivisionUndefined", "decimal.DivisionUndefined", MPD_Division_undefined, NULL},
  155. {"InvalidContext", "decimal.InvalidContext", MPD_Invalid_context, NULL},
  156. #ifdef EXTRA_FUNCTIONALITY
  157. {"MallocError", "decimal.MallocError", MPD_Malloc_error, NULL},
  158. #endif
  159. {NULL}
  160. };
  161. static const char *dec_signal_string[MPD_NUM_FLAGS] = {
  162. "Clamped",
  163. "InvalidOperation",
  164. "DivisionByZero",
  165. "InvalidOperation",
  166. "InvalidOperation",
  167. "InvalidOperation",
  168. "Inexact",
  169. "InvalidOperation",
  170. "InvalidOperation",
  171. "InvalidOperation",
  172. "FloatOperation",
  173. "Overflow",
  174. "Rounded",
  175. "Subnormal",
  176. "Underflow",
  177. };
  178. #ifdef EXTRA_FUNCTIONALITY
  179. #define _PY_DEC_ROUND_GUARD MPD_ROUND_GUARD
  180. #else
  181. #define _PY_DEC_ROUND_GUARD (MPD_ROUND_GUARD-1)
  182. #endif
  183. static PyObject *round_map[_PY_DEC_ROUND_GUARD];
  184. static const char *invalid_rounding_err =
  185. "valid values for rounding are:\n\
  186. [ROUND_CEILING, ROUND_FLOOR, ROUND_UP, ROUND_DOWN,\n\
  187. ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN,\n\
  188. ROUND_05UP]";
  189. static const char *invalid_signals_err =
  190. "valid values for signals are:\n\
  191. [InvalidOperation, FloatOperation, DivisionByZero,\n\
  192. Overflow, Underflow, Subnormal, Inexact, Rounded,\n\
  193. Clamped]";
  194. #ifdef EXTRA_FUNCTIONALITY
  195. static const char *invalid_flags_err =
  196. "valid values for _flags or _traps are:\n\
  197. signals:\n\
  198. [DecIEEEInvalidOperation, DecFloatOperation, DecDivisionByZero,\n\
  199. DecOverflow, DecUnderflow, DecSubnormal, DecInexact, DecRounded,\n\
  200. DecClamped]\n\
  201. conditions which trigger DecIEEEInvalidOperation:\n\
  202. [DecInvalidOperation, DecConversionSyntax, DecDivisionImpossible,\n\
  203. DecDivisionUndefined, DecFpuError, DecInvalidContext, DecMallocError]";
  204. #endif
  205. static int
  206. value_error_int(const char *mesg)
  207. {
  208. PyErr_SetString(PyExc_ValueError, mesg);
  209. return -1;
  210. }
  211. static PyObject *
  212. value_error_ptr(const char *mesg)
  213. {
  214. PyErr_SetString(PyExc_ValueError, mesg);
  215. return NULL;
  216. }
  217. static int
  218. type_error_int(const char *mesg)
  219. {
  220. PyErr_SetString(PyExc_TypeError, mesg);
  221. return -1;
  222. }
  223. static int
  224. runtime_error_int(const char *mesg)
  225. {
  226. PyErr_SetString(PyExc_RuntimeError, mesg);
  227. return -1;
  228. }
  229. #define INTERNAL_ERROR_INT(funcname) \
  230. return runtime_error_int("internal error in " funcname)
  231. static PyObject *
  232. runtime_error_ptr(const char *mesg)
  233. {
  234. PyErr_SetString(PyExc_RuntimeError, mesg);
  235. return NULL;
  236. }
  237. #define INTERNAL_ERROR_PTR(funcname) \
  238. return runtime_error_ptr("internal error in " funcname)
  239. static void
  240. dec_traphandler(mpd_context_t *ctx UNUSED) /* GCOV_NOT_REACHED */
  241. { /* GCOV_NOT_REACHED */
  242. return; /* GCOV_NOT_REACHED */
  243. }
  244. static PyObject *
  245. flags_as_exception(uint32_t flags)
  246. {
  247. DecCondMap *cm;
  248. for (cm = signal_map; cm->name != NULL; cm++) {
  249. if (flags&cm->flag) {
  250. return cm->ex;
  251. }
  252. }
  253. INTERNAL_ERROR_PTR("flags_as_exception"); /* GCOV_NOT_REACHED */
  254. }
  255. Py_LOCAL_INLINE(uint32_t)
  256. exception_as_flag(PyObject *ex)
  257. {
  258. DecCondMap *cm;
  259. for (cm = signal_map; cm->name != NULL; cm++) {
  260. if (cm->ex == ex) {
  261. return cm->flag;
  262. }
  263. }
  264. PyErr_SetString(PyExc_KeyError, invalid_signals_err);
  265. return DEC_INVALID_SIGNALS;
  266. }
  267. static PyObject *
  268. flags_as_list(uint32_t flags)
  269. {
  270. PyObject *list;
  271. DecCondMap *cm;
  272. list = PyList_New(0);
  273. if (list == NULL) {
  274. return NULL;
  275. }
  276. for (cm = cond_map; cm->name != NULL; cm++) {
  277. if (flags&cm->flag) {
  278. if (PyList_Append(list, cm->ex) < 0) {
  279. goto error;
  280. }
  281. }
  282. }
  283. for (cm = signal_map+1; cm->name != NULL; cm++) {
  284. if (flags&cm->flag) {
  285. if (PyList_Append(list, cm->ex) < 0) {
  286. goto error;
  287. }
  288. }
  289. }
  290. return list;
  291. error:
  292. Py_DECREF(list);
  293. return NULL;
  294. }
  295. static PyObject *
  296. signals_as_list(uint32_t flags)
  297. {
  298. PyObject *list;
  299. DecCondMap *cm;
  300. list = PyList_New(0);
  301. if (list == NULL) {
  302. return NULL;
  303. }
  304. for (cm = signal_map; cm->name != NULL; cm++) {
  305. if (flags&cm->flag) {
  306. if (PyList_Append(list, cm->ex) < 0) {
  307. Py_DECREF(list);
  308. return NULL;
  309. }
  310. }
  311. }
  312. return list;
  313. }
  314. static uint32_t
  315. list_as_flags(PyObject *list)
  316. {
  317. PyObject *item;
  318. uint32_t flags, x;
  319. Py_ssize_t n, j;
  320. assert(PyList_Check(list));
  321. n = PyList_Size(list);
  322. flags = 0;
  323. for (j = 0; j < n; j++) {
  324. item = PyList_GetItem(list, j);
  325. x = exception_as_flag(item);
  326. if (x & DEC_ERRORS) {
  327. return x;
  328. }
  329. flags |= x;
  330. }
  331. return flags;
  332. }
  333. static PyObject *
  334. flags_as_dict(uint32_t flags)
  335. {
  336. DecCondMap *cm;
  337. PyObject *dict;
  338. dict = PyDict_New();
  339. if (dict == NULL) {
  340. return NULL;
  341. }
  342. for (cm = signal_map; cm->name != NULL; cm++) {
  343. PyObject *b = flags&cm->flag ? Py_True : Py_False;
  344. if (PyDict_SetItem(dict, cm->ex, b) < 0) {
  345. Py_DECREF(dict);
  346. return NULL;
  347. }
  348. }
  349. return dict;
  350. }
  351. static uint32_t
  352. dict_as_flags(PyObject *val)
  353. {
  354. PyObject *b;
  355. DecCondMap *cm;
  356. uint32_t flags = 0;
  357. int x;
  358. if (!PyDict_Check(val)) {
  359. PyErr_SetString(PyExc_TypeError,
  360. "argument must be a signal dict");
  361. return DEC_INVALID_SIGNALS;
  362. }
  363. if (PyDict_Size(val) != SIGNAL_MAP_LEN) {
  364. PyErr_SetString(PyExc_KeyError,
  365. "invalid signal dict");
  366. return DEC_INVALID_SIGNALS;
  367. }
  368. for (cm = signal_map; cm->name != NULL; cm++) {
  369. b = PyDict_GetItemWithError(val, cm->ex);
  370. if (b == NULL) {
  371. if (PyErr_Occurred()) {
  372. return DEC_ERR_OCCURRED;
  373. }
  374. PyErr_SetString(PyExc_KeyError,
  375. "invalid signal dict");
  376. return DEC_INVALID_SIGNALS;
  377. }
  378. x = PyObject_IsTrue(b);
  379. if (x < 0) {
  380. return DEC_ERR_OCCURRED;
  381. }
  382. if (x == 1) {
  383. flags |= cm->flag;
  384. }
  385. }
  386. return flags;
  387. }
  388. #ifdef EXTRA_FUNCTIONALITY
  389. static uint32_t
  390. long_as_flags(PyObject *v)
  391. {
  392. long x;
  393. x = PyLong_AsLong(v);
  394. if (x == -1 && PyErr_Occurred()) {
  395. return DEC_ERR_OCCURRED;
  396. }
  397. if (x < 0 || x > (long)MPD_Max_status) {
  398. PyErr_SetString(PyExc_TypeError, invalid_flags_err);
  399. return DEC_INVALID_SIGNALS;
  400. }
  401. return x;
  402. }
  403. #endif
  404. static int
  405. dec_addstatus(PyObject *context, uint32_t status)
  406. {
  407. mpd_context_t *ctx = CTX(context);
  408. ctx->status |= status;
  409. if (status & (ctx->traps|MPD_Malloc_error)) {
  410. PyObject *ex, *siglist;
  411. if (status & MPD_Malloc_error) {
  412. PyErr_NoMemory();
  413. return 1;
  414. }
  415. ex = flags_as_exception(ctx->traps&status);
  416. if (ex == NULL) {
  417. return 1; /* GCOV_NOT_REACHED */
  418. }
  419. siglist = flags_as_list(ctx->traps&status);
  420. if (siglist == NULL) {
  421. return 1;
  422. }
  423. PyErr_SetObject(ex, siglist);
  424. Py_DECREF(siglist);
  425. return 1;
  426. }
  427. return 0;
  428. }
  429. static int
  430. getround(PyObject *v)
  431. {
  432. int i;
  433. if (PyUnicode_Check(v)) {
  434. for (i = 0; i < _PY_DEC_ROUND_GUARD; i++) {
  435. if (v == round_map[i]) {
  436. return i;
  437. }
  438. }
  439. for (i = 0; i < _PY_DEC_ROUND_GUARD; i++) {
  440. if (PyUnicode_Compare(v, round_map[i]) == 0) {
  441. return i;
  442. }
  443. }
  444. }
  445. return type_error_int(invalid_rounding_err);
  446. }
  447. /******************************************************************************/
  448. /* SignalDict Object */
  449. /******************************************************************************/
  450. /* The SignalDict is a MutableMapping that provides access to the
  451. mpd_context_t flags, which reside in the context object. When a
  452. new context is created, context.traps and context.flags are
  453. initialized to new SignalDicts. Once a SignalDict is tied to
  454. a context, it cannot be deleted. */
  455. static const char *INVALID_SIGNALDICT_ERROR_MSG = "invalid signal dict";
  456. static int
  457. signaldict_init(PyObject *self, PyObject *args UNUSED, PyObject *kwds UNUSED)
  458. {
  459. SdFlagAddr(self) = NULL;
  460. return 0;
  461. }
  462. static Py_ssize_t
  463. signaldict_len(PyObject *self)
  464. {
  465. if (SdFlagAddr(self) == NULL) {
  466. return value_error_int(INVALID_SIGNALDICT_ERROR_MSG);
  467. }
  468. return SIGNAL_MAP_LEN;
  469. }
  470. static PyObject *SignalTuple;
  471. static PyObject *
  472. signaldict_iter(PyObject *self UNUSED)
  473. {
  474. if (SdFlagAddr(self) == NULL) {
  475. return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG);
  476. }
  477. return PyTuple_Type.tp_iter(SignalTuple);
  478. }
  479. static PyObject *
  480. signaldict_getitem(PyObject *self, PyObject *key)
  481. {
  482. uint32_t flag;
  483. if (SdFlagAddr(self) == NULL) {
  484. return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG);
  485. }
  486. flag = exception_as_flag(key);
  487. if (flag & DEC_ERRORS) {
  488. return NULL;
  489. }
  490. return SdFlags(self)&flag ? incr_true() : incr_false();
  491. }
  492. static int
  493. signaldict_setitem(PyObject *self, PyObject *key, PyObject *value)
  494. {
  495. uint32_t flag;
  496. int x;
  497. if (SdFlagAddr(self) == NULL) {
  498. return value_error_int(INVALID_SIGNALDICT_ERROR_MSG);
  499. }
  500. if (value == NULL) {
  501. return value_error_int("signal keys cannot be deleted");
  502. }
  503. flag = exception_as_flag(key);
  504. if (flag & DEC_ERRORS) {
  505. return -1;
  506. }
  507. x = PyObject_IsTrue(value);
  508. if (x < 0) {
  509. return -1;
  510. }
  511. if (x == 1) {
  512. SdFlags(self) |= flag;
  513. }
  514. else {
  515. SdFlags(self) &= ~flag;
  516. }
  517. return 0;
  518. }
  519. static PyObject *
  520. signaldict_repr(PyObject *self)
  521. {
  522. DecCondMap *cm;
  523. const char *n[SIGNAL_MAP_LEN]; /* name */
  524. const char *b[SIGNAL_MAP_LEN]; /* bool */
  525. int i;
  526. if (SdFlagAddr(self) == NULL) {
  527. return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG);
  528. }
  529. assert(SIGNAL_MAP_LEN == 9);
  530. for (cm=signal_map, i=0; cm->name != NULL; cm++, i++) {
  531. n[i] = cm->fqname;
  532. b[i] = SdFlags(self)&cm->flag ? "True" : "False";
  533. }
  534. return PyUnicode_FromFormat(
  535. "{<class '%s'>:%s, <class '%s'>:%s, <class '%s'>:%s, "
  536. "<class '%s'>:%s, <class '%s'>:%s, <class '%s'>:%s, "
  537. "<class '%s'>:%s, <class '%s'>:%s, <class '%s'>:%s}",
  538. n[0], b[0], n[1], b[1], n[2], b[2],
  539. n[3], b[3], n[4], b[4], n[5], b[5],
  540. n[6], b[6], n[7], b[7], n[8], b[8]);
  541. }
  542. static PyObject *
  543. signaldict_richcompare(PyObject *v, PyObject *w, int op)
  544. {
  545. PyObject *res = Py_NotImplemented;
  546. assert(PyDecSignalDict_Check(v));
  547. if ((SdFlagAddr(v) == NULL) || (SdFlagAddr(w) == NULL)) {
  548. return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG);
  549. }
  550. if (op == Py_EQ || op == Py_NE) {
  551. if (PyDecSignalDict_Check(w)) {
  552. res = (SdFlags(v)==SdFlags(w)) ^ (op==Py_NE) ? Py_True : Py_False;
  553. }
  554. else if (PyDict_Check(w)) {
  555. uint32_t flags = dict_as_flags(w);
  556. if (flags & DEC_ERRORS) {
  557. if (flags & DEC_INVALID_SIGNALS) {
  558. /* non-comparable: Py_NotImplemented */
  559. PyErr_Clear();
  560. }
  561. else {
  562. return NULL;
  563. }
  564. }
  565. else {
  566. res = (SdFlags(v)==flags) ^ (op==Py_NE) ? Py_True : Py_False;
  567. }
  568. }
  569. }
  570. return Py_NewRef(res);
  571. }
  572. static PyObject *
  573. signaldict_copy(PyObject *self, PyObject *args UNUSED)
  574. {
  575. if (SdFlagAddr(self) == NULL) {
  576. return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG);
  577. }
  578. return flags_as_dict(SdFlags(self));
  579. }
  580. static PyMappingMethods signaldict_as_mapping = {
  581. (lenfunc)signaldict_len, /* mp_length */
  582. (binaryfunc)signaldict_getitem, /* mp_subscript */
  583. (objobjargproc)signaldict_setitem /* mp_ass_subscript */
  584. };
  585. static PyMethodDef signaldict_methods[] = {
  586. { "copy", (PyCFunction)signaldict_copy, METH_NOARGS, NULL},
  587. {NULL, NULL}
  588. };
  589. static PyTypeObject PyDecSignalDictMixin_Type =
  590. {
  591. PyVarObject_HEAD_INIT(0, 0)
  592. "decimal.SignalDictMixin", /* tp_name */
  593. sizeof(PyDecSignalDictObject), /* tp_basicsize */
  594. 0, /* tp_itemsize */
  595. 0, /* tp_dealloc */
  596. 0, /* tp_vectorcall_offset */
  597. (getattrfunc) 0, /* tp_getattr */
  598. (setattrfunc) 0, /* tp_setattr */
  599. 0, /* tp_as_async */
  600. (reprfunc) signaldict_repr, /* tp_repr */
  601. 0, /* tp_as_number */
  602. 0, /* tp_as_sequence */
  603. &signaldict_as_mapping, /* tp_as_mapping */
  604. PyObject_HashNotImplemented, /* tp_hash */
  605. 0, /* tp_call */
  606. (reprfunc) 0, /* tp_str */
  607. PyObject_GenericGetAttr, /* tp_getattro */
  608. (setattrofunc) 0, /* tp_setattro */
  609. (PyBufferProcs *) 0, /* tp_as_buffer */
  610. Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
  611. 0, /* tp_doc */
  612. 0, /* tp_traverse */
  613. 0, /* tp_clear */
  614. signaldict_richcompare, /* tp_richcompare */
  615. 0, /* tp_weaklistoffset */
  616. (getiterfunc)signaldict_iter, /* tp_iter */
  617. 0, /* tp_iternext */
  618. signaldict_methods, /* tp_methods */
  619. 0, /* tp_members */
  620. 0, /* tp_getset */
  621. 0, /* tp_base */
  622. 0, /* tp_dict */
  623. 0, /* tp_descr_get */
  624. 0, /* tp_descr_set */
  625. 0, /* tp_dictoffset */
  626. (initproc)signaldict_init, /* tp_init */
  627. 0, /* tp_alloc */
  628. PyType_GenericNew, /* tp_new */
  629. };
  630. /******************************************************************************/
  631. /* Context Object, Part 1 */
  632. /******************************************************************************/
  633. #define Dec_CONTEXT_GET_SSIZE(mem) \
  634. static PyObject * \
  635. context_get##mem(PyObject *self, void *closure UNUSED) \
  636. { \
  637. return PyLong_FromSsize_t(mpd_get##mem(CTX(self))); \
  638. }
  639. #define Dec_CONTEXT_GET_ULONG(mem) \
  640. static PyObject * \
  641. context_get##mem(PyObject *self, void *closure UNUSED) \
  642. { \
  643. return PyLong_FromUnsignedLong(mpd_get##mem(CTX(self))); \
  644. }
  645. Dec_CONTEXT_GET_SSIZE(prec)
  646. Dec_CONTEXT_GET_SSIZE(emax)
  647. Dec_CONTEXT_GET_SSIZE(emin)
  648. Dec_CONTEXT_GET_SSIZE(clamp)
  649. #ifdef EXTRA_FUNCTIONALITY
  650. Dec_CONTEXT_GET_ULONG(traps)
  651. Dec_CONTEXT_GET_ULONG(status)
  652. #endif
  653. static PyObject *
  654. context_getround(PyObject *self, void *closure UNUSED)
  655. {
  656. int i = mpd_getround(CTX(self));
  657. return Py_NewRef(round_map[i]);
  658. }
  659. static PyObject *
  660. context_getcapitals(PyObject *self, void *closure UNUSED)
  661. {
  662. return PyLong_FromLong(CtxCaps(self));
  663. }
  664. #ifdef EXTRA_FUNCTIONALITY
  665. static PyObject *
  666. context_getallcr(PyObject *self, void *closure UNUSED)
  667. {
  668. return PyLong_FromLong(mpd_getcr(CTX(self)));
  669. }
  670. #endif
  671. static PyObject *
  672. context_getetiny(PyObject *self, PyObject *dummy UNUSED)
  673. {
  674. return PyLong_FromSsize_t(mpd_etiny(CTX(self)));
  675. }
  676. static PyObject *
  677. context_getetop(PyObject *self, PyObject *dummy UNUSED)
  678. {
  679. return PyLong_FromSsize_t(mpd_etop(CTX(self)));
  680. }
  681. static int
  682. context_setprec(PyObject *self, PyObject *value, void *closure UNUSED)
  683. {
  684. mpd_context_t *ctx;
  685. mpd_ssize_t x;
  686. x = PyLong_AsSsize_t(value);
  687. if (x == -1 && PyErr_Occurred()) {
  688. return -1;
  689. }
  690. ctx = CTX(self);
  691. if (!mpd_qsetprec(ctx, x)) {
  692. return value_error_int(
  693. "valid range for prec is [1, MAX_PREC]");
  694. }
  695. return 0;
  696. }
  697. static int
  698. context_setemin(PyObject *self, PyObject *value, void *closure UNUSED)
  699. {
  700. mpd_context_t *ctx;
  701. mpd_ssize_t x;
  702. x = PyLong_AsSsize_t(value);
  703. if (x == -1 && PyErr_Occurred()) {
  704. return -1;
  705. }
  706. ctx = CTX(self);
  707. if (!mpd_qsetemin(ctx, x)) {
  708. return value_error_int(
  709. "valid range for Emin is [MIN_EMIN, 0]");
  710. }
  711. return 0;
  712. }
  713. static int
  714. context_setemax(PyObject *self, PyObject *value, void *closure UNUSED)
  715. {
  716. mpd_context_t *ctx;
  717. mpd_ssize_t x;
  718. x = PyLong_AsSsize_t(value);
  719. if (x == -1 && PyErr_Occurred()) {
  720. return -1;
  721. }
  722. ctx = CTX(self);
  723. if (!mpd_qsetemax(ctx, x)) {
  724. return value_error_int(
  725. "valid range for Emax is [0, MAX_EMAX]");
  726. }
  727. return 0;
  728. }
  729. #ifdef CONFIG_32
  730. static PyObject *
  731. context_unsafe_setprec(PyObject *self, PyObject *value)
  732. {
  733. mpd_context_t *ctx = CTX(self);
  734. mpd_ssize_t x;
  735. x = PyLong_AsSsize_t(value);
  736. if (x == -1 && PyErr_Occurred()) {
  737. return NULL;
  738. }
  739. if (x < 1 || x > 1070000000L) {
  740. return value_error_ptr(
  741. "valid range for unsafe prec is [1, 1070000000]");
  742. }
  743. ctx->prec = x;
  744. Py_RETURN_NONE;
  745. }
  746. static PyObject *
  747. context_unsafe_setemin(PyObject *self, PyObject *value)
  748. {
  749. mpd_context_t *ctx = CTX(self);
  750. mpd_ssize_t x;
  751. x = PyLong_AsSsize_t(value);
  752. if (x == -1 && PyErr_Occurred()) {
  753. return NULL;
  754. }
  755. if (x < -1070000000L || x > 0) {
  756. return value_error_ptr(
  757. "valid range for unsafe emin is [-1070000000, 0]");
  758. }
  759. ctx->emin = x;
  760. Py_RETURN_NONE;
  761. }
  762. static PyObject *
  763. context_unsafe_setemax(PyObject *self, PyObject *value)
  764. {
  765. mpd_context_t *ctx = CTX(self);
  766. mpd_ssize_t x;
  767. x = PyLong_AsSsize_t(value);
  768. if (x == -1 && PyErr_Occurred()) {
  769. return NULL;
  770. }
  771. if (x < 0 || x > 1070000000L) {
  772. return value_error_ptr(
  773. "valid range for unsafe emax is [0, 1070000000]");
  774. }
  775. ctx->emax = x;
  776. Py_RETURN_NONE;
  777. }
  778. #endif
  779. static int
  780. context_setround(PyObject *self, PyObject *value, void *closure UNUSED)
  781. {
  782. mpd_context_t *ctx;
  783. int x;
  784. x = getround(value);
  785. if (x == -1) {
  786. return -1;
  787. }
  788. ctx = CTX(self);
  789. if (!mpd_qsetround(ctx, x)) {
  790. INTERNAL_ERROR_INT("context_setround"); /* GCOV_NOT_REACHED */
  791. }
  792. return 0;
  793. }
  794. static int
  795. context_setcapitals(PyObject *self, PyObject *value, void *closure UNUSED)
  796. {
  797. mpd_ssize_t x;
  798. x = PyLong_AsSsize_t(value);
  799. if (x == -1 && PyErr_Occurred()) {
  800. return -1;
  801. }
  802. if (x != 0 && x != 1) {
  803. return value_error_int(
  804. "valid values for capitals are 0 or 1");
  805. }
  806. CtxCaps(self) = (int)x;
  807. return 0;
  808. }
  809. #ifdef EXTRA_FUNCTIONALITY
  810. static int
  811. context_settraps(PyObject *self, PyObject *value, void *closure UNUSED)
  812. {
  813. mpd_context_t *ctx;
  814. uint32_t flags;
  815. flags = long_as_flags(value);
  816. if (flags & DEC_ERRORS) {
  817. return -1;
  818. }
  819. ctx = CTX(self);
  820. if (!mpd_qsettraps(ctx, flags)) {
  821. INTERNAL_ERROR_INT("context_settraps");
  822. }
  823. return 0;
  824. }
  825. #endif
  826. static int
  827. context_settraps_list(PyObject *self, PyObject *value)
  828. {
  829. mpd_context_t *ctx;
  830. uint32_t flags;
  831. flags = list_as_flags(value);
  832. if (flags & DEC_ERRORS) {
  833. return -1;
  834. }
  835. ctx = CTX(self);
  836. if (!mpd_qsettraps(ctx, flags)) {
  837. INTERNAL_ERROR_INT("context_settraps_list");
  838. }
  839. return 0;
  840. }
  841. static int
  842. context_settraps_dict(PyObject *self, PyObject *value)
  843. {
  844. mpd_context_t *ctx;
  845. uint32_t flags;
  846. if (PyDecSignalDict_Check(value)) {
  847. flags = SdFlags(value);
  848. }
  849. else {
  850. flags = dict_as_flags(value);
  851. if (flags & DEC_ERRORS) {
  852. return -1;
  853. }
  854. }
  855. ctx = CTX(self);
  856. if (!mpd_qsettraps(ctx, flags)) {
  857. INTERNAL_ERROR_INT("context_settraps_dict");
  858. }
  859. return 0;
  860. }
  861. #ifdef EXTRA_FUNCTIONALITY
  862. static int
  863. context_setstatus(PyObject *self, PyObject *value, void *closure UNUSED)
  864. {
  865. mpd_context_t *ctx;
  866. uint32_t flags;
  867. flags = long_as_flags(value);
  868. if (flags & DEC_ERRORS) {
  869. return -1;
  870. }
  871. ctx = CTX(self);
  872. if (!mpd_qsetstatus(ctx, flags)) {
  873. INTERNAL_ERROR_INT("context_setstatus");
  874. }
  875. return 0;
  876. }
  877. #endif
  878. static int
  879. context_setstatus_list(PyObject *self, PyObject *value)
  880. {
  881. mpd_context_t *ctx;
  882. uint32_t flags;
  883. flags = list_as_flags(value);
  884. if (flags & DEC_ERRORS) {
  885. return -1;
  886. }
  887. ctx = CTX(self);
  888. if (!mpd_qsetstatus(ctx, flags)) {
  889. INTERNAL_ERROR_INT("context_setstatus_list");
  890. }
  891. return 0;
  892. }
  893. static int
  894. context_setstatus_dict(PyObject *self, PyObject *value)
  895. {
  896. mpd_context_t *ctx;
  897. uint32_t flags;
  898. if (PyDecSignalDict_Check(value)) {
  899. flags = SdFlags(value);
  900. }
  901. else {
  902. flags = dict_as_flags(value);
  903. if (flags & DEC_ERRORS) {
  904. return -1;
  905. }
  906. }
  907. ctx = CTX(self);
  908. if (!mpd_qsetstatus(ctx, flags)) {
  909. INTERNAL_ERROR_INT("context_setstatus_dict");
  910. }
  911. return 0;
  912. }
  913. static int
  914. context_setclamp(PyObject *self, PyObject *value, void *closure UNUSED)
  915. {
  916. mpd_context_t *ctx;
  917. mpd_ssize_t x;
  918. x = PyLong_AsSsize_t(value);
  919. if (x == -1 && PyErr_Occurred()) {
  920. return -1;
  921. }
  922. BOUNDS_CHECK(x, INT_MIN, INT_MAX);
  923. ctx = CTX(self);
  924. if (!mpd_qsetclamp(ctx, (int)x)) {
  925. return value_error_int("valid values for clamp are 0 or 1");
  926. }
  927. return 0;
  928. }
  929. #ifdef EXTRA_FUNCTIONALITY
  930. static int
  931. context_setallcr(PyObject *self, PyObject *value, void *closure UNUSED)
  932. {
  933. mpd_context_t *ctx;
  934. mpd_ssize_t x;
  935. x = PyLong_AsSsize_t(value);
  936. if (x == -1 && PyErr_Occurred()) {
  937. return -1;
  938. }
  939. BOUNDS_CHECK(x, INT_MIN, INT_MAX);
  940. ctx = CTX(self);
  941. if (!mpd_qsetcr(ctx, (int)x)) {
  942. return value_error_int("valid values for _allcr are 0 or 1");
  943. }
  944. return 0;
  945. }
  946. #endif
  947. static PyObject *
  948. context_getattr(PyObject *self, PyObject *name)
  949. {
  950. PyObject *retval;
  951. if (PyUnicode_Check(name)) {
  952. if (PyUnicode_CompareWithASCIIString(name, "traps") == 0) {
  953. retval = ((PyDecContextObject *)self)->traps;
  954. return Py_NewRef(retval);
  955. }
  956. if (PyUnicode_CompareWithASCIIString(name, "flags") == 0) {
  957. retval = ((PyDecContextObject *)self)->flags;
  958. return Py_NewRef(retval);
  959. }
  960. }
  961. return PyObject_GenericGetAttr(self, name);
  962. }
  963. static int
  964. context_setattr(PyObject *self, PyObject *name, PyObject *value)
  965. {
  966. if (value == NULL) {
  967. PyErr_SetString(PyExc_AttributeError,
  968. "context attributes cannot be deleted");
  969. return -1;
  970. }
  971. if (PyUnicode_Check(name)) {
  972. if (PyUnicode_CompareWithASCIIString(name, "traps") == 0) {
  973. return context_settraps_dict(self, value);
  974. }
  975. if (PyUnicode_CompareWithASCIIString(name, "flags") == 0) {
  976. return context_setstatus_dict(self, value);
  977. }
  978. }
  979. return PyObject_GenericSetAttr(self, name, value);
  980. }
  981. static int
  982. context_setattrs(PyObject *self, PyObject *prec, PyObject *rounding,
  983. PyObject *emin, PyObject *emax, PyObject *capitals,
  984. PyObject *clamp, PyObject *status, PyObject *traps) {
  985. int ret;
  986. if (prec != Py_None && context_setprec(self, prec, NULL) < 0) {
  987. return -1;
  988. }
  989. if (rounding != Py_None && context_setround(self, rounding, NULL) < 0) {
  990. return -1;
  991. }
  992. if (emin != Py_None && context_setemin(self, emin, NULL) < 0) {
  993. return -1;
  994. }
  995. if (emax != Py_None && context_setemax(self, emax, NULL) < 0) {
  996. return -1;
  997. }
  998. if (capitals != Py_None && context_setcapitals(self, capitals, NULL) < 0) {
  999. return -1;
  1000. }
  1001. if (clamp != Py_None && context_setclamp(self, clamp, NULL) < 0) {
  1002. return -1;
  1003. }
  1004. if (traps != Py_None) {
  1005. if (PyList_Check(traps)) {
  1006. ret = context_settraps_list(self, traps);
  1007. }
  1008. #ifdef EXTRA_FUNCTIONALITY
  1009. else if (PyLong_Check(traps)) {
  1010. ret = context_settraps(self, traps, NULL);
  1011. }
  1012. #endif
  1013. else {
  1014. ret = context_settraps_dict(self, traps);
  1015. }
  1016. if (ret < 0) {
  1017. return ret;
  1018. }
  1019. }
  1020. if (status != Py_None) {
  1021. if (PyList_Check(status)) {
  1022. ret = context_setstatus_list(self, status);
  1023. }
  1024. #ifdef EXTRA_FUNCTIONALITY
  1025. else if (PyLong_Check(status)) {
  1026. ret = context_setstatus(self, status, NULL);
  1027. }
  1028. #endif
  1029. else {
  1030. ret = context_setstatus_dict(self, status);
  1031. }
  1032. if (ret < 0) {
  1033. return ret;
  1034. }
  1035. }
  1036. return 0;
  1037. }
  1038. static PyObject *
  1039. context_clear_traps(PyObject *self, PyObject *dummy UNUSED)
  1040. {
  1041. CTX(self)->traps = 0;
  1042. Py_RETURN_NONE;
  1043. }
  1044. static PyObject *
  1045. context_clear_flags(PyObject *self, PyObject *dummy UNUSED)
  1046. {
  1047. CTX(self)->status = 0;
  1048. Py_RETURN_NONE;
  1049. }
  1050. #define DEC_DFLT_EMAX 999999
  1051. #define DEC_DFLT_EMIN -999999
  1052. static mpd_context_t dflt_ctx = {
  1053. 28, DEC_DFLT_EMAX, DEC_DFLT_EMIN,
  1054. MPD_IEEE_Invalid_operation|MPD_Division_by_zero|MPD_Overflow,
  1055. 0, 0, MPD_ROUND_HALF_EVEN, 0, 1
  1056. };
  1057. static PyObject *
  1058. context_new(PyTypeObject *type, PyObject *args UNUSED, PyObject *kwds UNUSED)
  1059. {
  1060. PyDecContextObject *self = NULL;
  1061. mpd_context_t *ctx;
  1062. if (type == &PyDecContext_Type) {
  1063. self = PyObject_New(PyDecContextObject, &PyDecContext_Type);
  1064. }
  1065. else {
  1066. self = (PyDecContextObject *)type->tp_alloc(type, 0);
  1067. }
  1068. if (self == NULL) {
  1069. return NULL;
  1070. }
  1071. self->traps = PyObject_CallObject((PyObject *)PyDecSignalDict_Type, NULL);
  1072. if (self->traps == NULL) {
  1073. self->flags = NULL;
  1074. Py_DECREF(self);
  1075. return NULL;
  1076. }
  1077. self->flags = PyObject_CallObject((PyObject *)PyDecSignalDict_Type, NULL);
  1078. if (self->flags == NULL) {
  1079. Py_DECREF(self);
  1080. return NULL;
  1081. }
  1082. ctx = CTX(self);
  1083. if (default_context_template) {
  1084. *ctx = *CTX(default_context_template);
  1085. }
  1086. else {
  1087. *ctx = dflt_ctx;
  1088. }
  1089. SdFlagAddr(self->traps) = &ctx->traps;
  1090. SdFlagAddr(self->flags) = &ctx->status;
  1091. CtxCaps(self) = 1;
  1092. self->tstate = NULL;
  1093. return (PyObject *)self;
  1094. }
  1095. static void
  1096. context_dealloc(PyDecContextObject *self)
  1097. {
  1098. #ifndef WITH_DECIMAL_CONTEXTVAR
  1099. if (self == cached_context) {
  1100. cached_context = NULL;
  1101. }
  1102. #endif
  1103. Py_XDECREF(self->traps);
  1104. Py_XDECREF(self->flags);
  1105. Py_TYPE(self)->tp_free(self);
  1106. }
  1107. static int
  1108. context_init(PyObject *self, PyObject *args, PyObject *kwds)
  1109. {
  1110. static char *kwlist[] = {
  1111. "prec", "rounding", "Emin", "Emax", "capitals", "clamp",
  1112. "flags", "traps", NULL
  1113. };
  1114. PyObject *prec = Py_None;
  1115. PyObject *rounding = Py_None;
  1116. PyObject *emin = Py_None;
  1117. PyObject *emax = Py_None;
  1118. PyObject *capitals = Py_None;
  1119. PyObject *clamp = Py_None;
  1120. PyObject *status = Py_None;
  1121. PyObject *traps = Py_None;
  1122. assert(PyTuple_Check(args));
  1123. if (!PyArg_ParseTupleAndKeywords(
  1124. args, kwds,
  1125. "|OOOOOOOO", kwlist,
  1126. &prec, &rounding, &emin, &emax, &capitals, &clamp, &status, &traps
  1127. )) {
  1128. return -1;
  1129. }
  1130. return context_setattrs(
  1131. self, prec, rounding,
  1132. emin, emax, capitals,
  1133. clamp, status, traps
  1134. );
  1135. }
  1136. static PyObject *
  1137. context_repr(PyDecContextObject *self)
  1138. {
  1139. mpd_context_t *ctx;
  1140. char flags[MPD_MAX_SIGNAL_LIST];
  1141. char traps[MPD_MAX_SIGNAL_LIST];
  1142. int n, mem;
  1143. assert(PyDecContext_Check(self));
  1144. ctx = CTX(self);
  1145. mem = MPD_MAX_SIGNAL_LIST;
  1146. n = mpd_lsnprint_signals(flags, mem, ctx->status, dec_signal_string);
  1147. if (n < 0 || n >= mem) {
  1148. INTERNAL_ERROR_PTR("context_repr");
  1149. }
  1150. n = mpd_lsnprint_signals(traps, mem, ctx->traps, dec_signal_string);
  1151. if (n < 0 || n >= mem) {
  1152. INTERNAL_ERROR_PTR("context_repr");
  1153. }
  1154. return PyUnicode_FromFormat(
  1155. "Context(prec=%zd, rounding=%s, Emin=%zd, Emax=%zd, "
  1156. "capitals=%d, clamp=%d, flags=%s, traps=%s)",
  1157. ctx->prec, mpd_round_string[ctx->round], ctx->emin, ctx->emax,
  1158. self->capitals, ctx->clamp, flags, traps);
  1159. }
  1160. static void
  1161. init_basic_context(PyObject *v)
  1162. {
  1163. mpd_context_t ctx = dflt_ctx;
  1164. ctx.prec = 9;
  1165. ctx.traps |= (MPD_Underflow|MPD_Clamped);
  1166. ctx.round = MPD_ROUND_HALF_UP;
  1167. *CTX(v) = ctx;
  1168. CtxCaps(v) = 1;
  1169. }
  1170. static void
  1171. init_extended_context(PyObject *v)
  1172. {
  1173. mpd_context_t ctx = dflt_ctx;
  1174. ctx.prec = 9;
  1175. ctx.traps = 0;
  1176. *CTX(v) = ctx;
  1177. CtxCaps(v) = 1;
  1178. }
  1179. #ifdef EXTRA_FUNCTIONALITY
  1180. /* Factory function for creating IEEE interchange format contexts */
  1181. static PyObject *
  1182. ieee_context(PyObject *dummy UNUSED, PyObject *v)
  1183. {
  1184. PyObject *context;
  1185. mpd_ssize_t bits;
  1186. mpd_context_t ctx;
  1187. bits = PyLong_AsSsize_t(v);
  1188. if (bits == -1 && PyErr_Occurred()) {
  1189. return NULL;
  1190. }
  1191. if (bits <= 0 || bits > INT_MAX) {
  1192. goto error;
  1193. }
  1194. if (mpd_ieee_context(&ctx, (int)bits) < 0) {
  1195. goto error;
  1196. }
  1197. context = PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL);
  1198. if (context == NULL) {
  1199. return NULL;
  1200. }
  1201. *CTX(context) = ctx;
  1202. return context;
  1203. error:
  1204. PyErr_Format(PyExc_ValueError,
  1205. "argument must be a multiple of 32, with a maximum of %d",
  1206. MPD_IEEE_CONTEXT_MAX_BITS);
  1207. return NULL;
  1208. }
  1209. #endif
  1210. static PyObject *
  1211. context_copy(PyObject *self, PyObject *args UNUSED)
  1212. {
  1213. PyObject *copy;
  1214. copy = PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL);
  1215. if (copy == NULL) {
  1216. return NULL;
  1217. }
  1218. *CTX(copy) = *CTX(self);
  1219. CTX(copy)->newtrap = 0;
  1220. CtxCaps(copy) = CtxCaps(self);
  1221. return copy;
  1222. }
  1223. static PyObject *
  1224. context_reduce(PyObject *self, PyObject *args UNUSED)
  1225. {
  1226. PyObject *flags;
  1227. PyObject *traps;
  1228. PyObject *ret;
  1229. mpd_context_t *ctx;
  1230. ctx = CTX(self);
  1231. flags = signals_as_list(ctx->status);
  1232. if (flags == NULL) {
  1233. return NULL;
  1234. }
  1235. traps = signals_as_list(ctx->traps);
  1236. if (traps == NULL) {
  1237. Py_DECREF(flags);
  1238. return NULL;
  1239. }
  1240. ret = Py_BuildValue(
  1241. "O(nsnniiOO)",
  1242. Py_TYPE(self),
  1243. ctx->prec, mpd_round_string[ctx->round], ctx->emin, ctx->emax,
  1244. CtxCaps(self), ctx->clamp, flags, traps
  1245. );
  1246. Py_DECREF(flags);
  1247. Py_DECREF(traps);
  1248. return ret;
  1249. }
  1250. static PyGetSetDef context_getsets [] =
  1251. {
  1252. { "prec", (getter)context_getprec, (setter)context_setprec, NULL, NULL},
  1253. { "Emax", (getter)context_getemax, (setter)context_setemax, NULL, NULL},
  1254. { "Emin", (getter)context_getemin, (setter)context_setemin, NULL, NULL},
  1255. { "rounding", (getter)context_getround, (setter)context_setround, NULL, NULL},
  1256. { "capitals", (getter)context_getcapitals, (setter)context_setcapitals, NULL, NULL},
  1257. { "clamp", (getter)context_getclamp, (setter)context_setclamp, NULL, NULL},
  1258. #ifdef EXTRA_FUNCTIONALITY
  1259. { "_allcr", (getter)context_getallcr, (setter)context_setallcr, NULL, NULL},
  1260. { "_traps", (getter)context_gettraps, (setter)context_settraps, NULL, NULL},
  1261. { "_flags", (getter)context_getstatus, (setter)context_setstatus, NULL, NULL},
  1262. #endif
  1263. {NULL}
  1264. };
  1265. #define CONTEXT_CHECK(obj) \
  1266. if (!PyDecContext_Check(obj)) { \
  1267. PyErr_SetString(PyExc_TypeError, \
  1268. "argument must be a context"); \
  1269. return NULL; \
  1270. }
  1271. #define CONTEXT_CHECK_VA(obj) \
  1272. if (obj == Py_None) { \
  1273. CURRENT_CONTEXT(obj); \
  1274. } \
  1275. else if (!PyDecContext_Check(obj)) { \
  1276. PyErr_SetString(PyExc_TypeError, \
  1277. "optional argument must be a context"); \
  1278. return NULL; \
  1279. }
  1280. /******************************************************************************/
  1281. /* Global, thread local and temporary contexts */
  1282. /******************************************************************************/
  1283. /*
  1284. * Thread local storage currently has a speed penalty of about 4%.
  1285. * All functions that map Python's arithmetic operators to mpdecimal
  1286. * functions have to look up the current context for each and every
  1287. * operation.
  1288. */
  1289. #ifndef WITH_DECIMAL_CONTEXTVAR
  1290. /* Get the context from the thread state dictionary. */
  1291. static PyObject *
  1292. current_context_from_dict(void)
  1293. {
  1294. PyThreadState *tstate = _PyThreadState_GET();
  1295. #ifdef Py_DEBUG
  1296. // The caller must hold the GIL
  1297. _Py_EnsureTstateNotNULL(tstate);
  1298. #endif
  1299. PyObject *dict = _PyThreadState_GetDict(tstate);
  1300. if (dict == NULL) {
  1301. PyErr_SetString(PyExc_RuntimeError,
  1302. "cannot get thread state");
  1303. return NULL;
  1304. }
  1305. PyObject *tl_context = PyDict_GetItemWithError(dict, tls_context_key);
  1306. if (tl_context != NULL) {
  1307. /* We already have a thread local context. */
  1308. CONTEXT_CHECK(tl_context);
  1309. }
  1310. else {
  1311. if (PyErr_Occurred()) {
  1312. return NULL;
  1313. }
  1314. /* Set up a new thread local context. */
  1315. tl_context = context_copy(default_context_template, NULL);
  1316. if (tl_context == NULL) {
  1317. return NULL;
  1318. }
  1319. CTX(tl_context)->status = 0;
  1320. if (PyDict_SetItem(dict, tls_context_key, tl_context) < 0) {
  1321. Py_DECREF(tl_context);
  1322. return NULL;
  1323. }
  1324. Py_DECREF(tl_context);
  1325. }
  1326. /* Cache the context of the current thread, assuming that it
  1327. * will be accessed several times before a thread switch. */
  1328. cached_context = (PyDecContextObject *)tl_context;
  1329. cached_context->tstate = tstate;
  1330. /* Borrowed reference with refcount==1 */
  1331. return tl_context;
  1332. }
  1333. /* Return borrowed reference to thread local context. */
  1334. static PyObject *
  1335. current_context(void)
  1336. {
  1337. PyThreadState *tstate = _PyThreadState_GET();
  1338. if (cached_context && cached_context->tstate == tstate) {
  1339. return (PyObject *)cached_context;
  1340. }
  1341. return current_context_from_dict();
  1342. }
  1343. /* ctxobj := borrowed reference to the current context */
  1344. #define CURRENT_CONTEXT(ctxobj) \
  1345. ctxobj = current_context(); \
  1346. if (ctxobj == NULL) { \
  1347. return NULL; \
  1348. }
  1349. /* Return a new reference to the current context */
  1350. static PyObject *
  1351. PyDec_GetCurrentContext(PyObject *self UNUSED, PyObject *args UNUSED)
  1352. {
  1353. PyObject *context;
  1354. context = current_context();
  1355. if (context == NULL) {
  1356. return NULL;
  1357. }
  1358. return Py_NewRef(context);
  1359. }
  1360. /* Set the thread local context to a new context, decrement old reference */
  1361. static PyObject *
  1362. PyDec_SetCurrentContext(PyObject *self UNUSED, PyObject *v)
  1363. {
  1364. PyObject *dict;
  1365. CONTEXT_CHECK(v);
  1366. dict = PyThreadState_GetDict();
  1367. if (dict == NULL) {
  1368. PyErr_SetString(PyExc_RuntimeError,
  1369. "cannot get thread state");
  1370. return NULL;
  1371. }
  1372. /* If the new context is one of the templates, make a copy.
  1373. * This is the current behavior of decimal.py. */
  1374. if (v == default_context_template ||
  1375. v == basic_context_template ||
  1376. v == extended_context_template) {
  1377. v = context_copy(v, NULL);
  1378. if (v == NULL) {
  1379. return NULL;
  1380. }
  1381. CTX(v)->status = 0;
  1382. }
  1383. else {
  1384. Py_INCREF(v);
  1385. }
  1386. cached_context = NULL;
  1387. if (PyDict_SetItem(dict, tls_context_key, v) < 0) {
  1388. Py_DECREF(v);
  1389. return NULL;
  1390. }
  1391. Py_DECREF(v);
  1392. Py_RETURN_NONE;
  1393. }
  1394. #else
  1395. static PyObject *
  1396. init_current_context(void)
  1397. {
  1398. PyObject *tl_context = context_copy(default_context_template, NULL);
  1399. if (tl_context == NULL) {
  1400. return NULL;
  1401. }
  1402. CTX(tl_context)->status = 0;
  1403. PyObject *tok = PyContextVar_Set(current_context_var, tl_context);
  1404. if (tok == NULL) {
  1405. Py_DECREF(tl_context);
  1406. return NULL;
  1407. }
  1408. Py_DECREF(tok);
  1409. return tl_context;
  1410. }
  1411. static inline PyObject *
  1412. current_context(void)
  1413. {
  1414. PyObject *tl_context;
  1415. if (PyContextVar_Get(current_context_var, NULL, &tl_context) < 0) {
  1416. return NULL;
  1417. }
  1418. if (tl_context != NULL) {
  1419. return tl_context;
  1420. }
  1421. return init_current_context();
  1422. }
  1423. /* ctxobj := borrowed reference to the current context */
  1424. #define CURRENT_CONTEXT(ctxobj) \
  1425. ctxobj = current_context(); \
  1426. if (ctxobj == NULL) { \
  1427. return NULL; \
  1428. } \
  1429. Py_DECREF(ctxobj);
  1430. /* Return a new reference to the current context */
  1431. static PyObject *
  1432. PyDec_GetCurrentContext(PyObject *self UNUSED, PyObject *args UNUSED)
  1433. {
  1434. return current_context();
  1435. }
  1436. /* Set the thread local context to a new context, decrement old reference */
  1437. static PyObject *
  1438. PyDec_SetCurrentContext(PyObject *self UNUSED, PyObject *v)
  1439. {
  1440. CONTEXT_CHECK(v);
  1441. /* If the new context is one of the templates, make a copy.
  1442. * This is the current behavior of decimal.py. */
  1443. if (v == default_context_template ||
  1444. v == basic_context_template ||
  1445. v == extended_context_template) {
  1446. v = context_copy(v, NULL);
  1447. if (v == NULL) {
  1448. return NULL;
  1449. }
  1450. CTX(v)->status = 0;
  1451. }
  1452. else {
  1453. Py_INCREF(v);
  1454. }
  1455. PyObject *tok = PyContextVar_Set(current_context_var, v);
  1456. Py_DECREF(v);
  1457. if (tok == NULL) {
  1458. return NULL;
  1459. }
  1460. Py_DECREF(tok);
  1461. Py_RETURN_NONE;
  1462. }
  1463. #endif
  1464. /* Context manager object for the 'with' statement. The manager
  1465. * owns one reference to the global (outer) context and one
  1466. * to the local (inner) context. */
  1467. static PyObject *
  1468. ctxmanager_new(PyTypeObject *type UNUSED, PyObject *args, PyObject *kwds)
  1469. {
  1470. static char *kwlist[] = {
  1471. "ctx", "prec", "rounding",
  1472. "Emin", "Emax", "capitals",
  1473. "clamp", "flags", "traps",
  1474. NULL
  1475. };
  1476. PyDecContextManagerObject *self;
  1477. PyObject *local = Py_None;
  1478. PyObject *global;
  1479. PyObject *prec = Py_None;
  1480. PyObject *rounding = Py_None;
  1481. PyObject *Emin = Py_None;
  1482. PyObject *Emax = Py_None;
  1483. PyObject *capitals = Py_None;
  1484. PyObject *clamp = Py_None;
  1485. PyObject *flags = Py_None;
  1486. PyObject *traps = Py_None;
  1487. CURRENT_CONTEXT(global);
  1488. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOOOOOOO", kwlist, &local,
  1489. &prec, &rounding, &Emin, &Emax, &capitals, &clamp, &flags, &traps)) {
  1490. return NULL;
  1491. }
  1492. if (local == Py_None) {
  1493. local = global;
  1494. }
  1495. else if (!PyDecContext_Check(local)) {
  1496. PyErr_SetString(PyExc_TypeError,
  1497. "optional argument must be a context");
  1498. return NULL;
  1499. }
  1500. self = PyObject_New(PyDecContextManagerObject,
  1501. &PyDecContextManager_Type);
  1502. if (self == NULL) {
  1503. return NULL;
  1504. }
  1505. self->local = context_copy(local, NULL);
  1506. if (self->local == NULL) {
  1507. self->global = NULL;
  1508. Py_DECREF(self);
  1509. return NULL;
  1510. }
  1511. self->global = Py_NewRef(global);
  1512. int ret = context_setattrs(
  1513. self->local, prec, rounding,
  1514. Emin, Emax, capitals,
  1515. clamp, flags, traps
  1516. );
  1517. if (ret < 0) {
  1518. Py_DECREF(self);
  1519. return NULL;
  1520. }
  1521. return (PyObject *)self;
  1522. }
  1523. static void
  1524. ctxmanager_dealloc(PyDecContextManagerObject *self)
  1525. {
  1526. Py_XDECREF(self->local);
  1527. Py_XDECREF(self->global);
  1528. PyObject_Free(self);
  1529. }
  1530. static PyObject *
  1531. ctxmanager_set_local(PyDecContextManagerObject *self, PyObject *args UNUSED)
  1532. {
  1533. PyObject *ret;
  1534. ret = PyDec_SetCurrentContext(NULL, self->local);
  1535. if (ret == NULL) {
  1536. return NULL;
  1537. }
  1538. Py_DECREF(ret);
  1539. return Py_NewRef(self->local);
  1540. }
  1541. static PyObject *
  1542. ctxmanager_restore_global(PyDecContextManagerObject *self,
  1543. PyObject *args UNUSED)
  1544. {
  1545. PyObject *ret;
  1546. ret = PyDec_SetCurrentContext(NULL, self->global);
  1547. if (ret == NULL) {
  1548. return NULL;
  1549. }
  1550. Py_DECREF(ret);
  1551. Py_RETURN_NONE;
  1552. }
  1553. static PyMethodDef ctxmanager_methods[] = {
  1554. {"__enter__", (PyCFunction)ctxmanager_set_local, METH_NOARGS, NULL},
  1555. {"__exit__", (PyCFunction)ctxmanager_restore_global, METH_VARARGS, NULL},
  1556. {NULL, NULL}
  1557. };
  1558. static PyTypeObject PyDecContextManager_Type =
  1559. {
  1560. PyVarObject_HEAD_INIT(NULL, 0)
  1561. "decimal.ContextManager", /* tp_name */
  1562. sizeof(PyDecContextManagerObject), /* tp_basicsize */
  1563. 0, /* tp_itemsize */
  1564. (destructor) ctxmanager_dealloc, /* tp_dealloc */
  1565. 0, /* tp_vectorcall_offset */
  1566. (getattrfunc) 0, /* tp_getattr */
  1567. (setattrfunc) 0, /* tp_setattr */
  1568. 0, /* tp_as_async */
  1569. (reprfunc) 0, /* tp_repr */
  1570. 0, /* tp_as_number */
  1571. 0, /* tp_as_sequence */
  1572. 0, /* tp_as_mapping */
  1573. 0, /* tp_hash */
  1574. 0, /* tp_call */
  1575. 0, /* tp_str */
  1576. (getattrofunc) PyObject_GenericGetAttr, /* tp_getattro */
  1577. (setattrofunc) 0, /* tp_setattro */
  1578. (PyBufferProcs *) 0, /* tp_as_buffer */
  1579. Py_TPFLAGS_DEFAULT, /* tp_flags */
  1580. 0, /* tp_doc */
  1581. 0, /* tp_traverse */
  1582. 0, /* tp_clear */
  1583. 0, /* tp_richcompare */
  1584. 0, /* tp_weaklistoffset */
  1585. 0, /* tp_iter */
  1586. 0, /* tp_iternext */
  1587. ctxmanager_methods, /* tp_methods */
  1588. };
  1589. /******************************************************************************/
  1590. /* New Decimal Object */
  1591. /******************************************************************************/
  1592. static PyObject *
  1593. PyDecType_New(PyTypeObject *type)
  1594. {
  1595. PyDecObject *dec;
  1596. if (type == &PyDec_Type) {
  1597. dec = PyObject_New(PyDecObject, &PyDec_Type);
  1598. }
  1599. else {
  1600. dec = (PyDecObject *)type->tp_alloc(type, 0);
  1601. }
  1602. if (dec == NULL) {
  1603. return NULL;
  1604. }
  1605. dec->hash = -1;
  1606. MPD(dec)->flags = MPD_STATIC|MPD_STATIC_DATA;
  1607. MPD(dec)->exp = 0;
  1608. MPD(dec)->digits = 0;
  1609. MPD(dec)->len = 0;
  1610. MPD(dec)->alloc = _Py_DEC_MINALLOC;
  1611. MPD(dec)->data = dec->data;
  1612. return (PyObject *)dec;
  1613. }
  1614. #define dec_alloc() PyDecType_New(&PyDec_Type)
  1615. static void
  1616. dec_dealloc(PyObject *dec)
  1617. {
  1618. mpd_del(MPD(dec));
  1619. Py_TYPE(dec)->tp_free(dec);
  1620. }
  1621. /******************************************************************************/
  1622. /* Conversions to Decimal */
  1623. /******************************************************************************/
  1624. Py_LOCAL_INLINE(int)
  1625. is_space(int kind, const void *data, Py_ssize_t pos)
  1626. {
  1627. Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
  1628. return Py_UNICODE_ISSPACE(ch);
  1629. }
  1630. /* Return the ASCII representation of a numeric Unicode string. The numeric
  1631. string may contain ascii characters in the range [1, 127], any Unicode
  1632. space and any unicode digit. If strip_ws is true, leading and trailing
  1633. whitespace is stripped. If ignore_underscores is true, underscores are
  1634. ignored.
  1635. Return NULL if malloc fails and an empty string if invalid characters
  1636. are found. */
  1637. static char *
  1638. numeric_as_ascii(PyObject *u, int strip_ws, int ignore_underscores)
  1639. {
  1640. int kind;
  1641. const void *data;
  1642. Py_UCS4 ch;
  1643. char *res, *cp;
  1644. Py_ssize_t j, len;
  1645. int d;
  1646. if (PyUnicode_READY(u) == -1) {
  1647. return NULL;
  1648. }
  1649. kind = PyUnicode_KIND(u);
  1650. data = PyUnicode_DATA(u);
  1651. len = PyUnicode_GET_LENGTH(u);
  1652. cp = res = PyMem_Malloc(len+1);
  1653. if (res == NULL) {
  1654. PyErr_NoMemory();
  1655. return NULL;
  1656. }
  1657. j = 0;
  1658. if (strip_ws) {
  1659. while (len > 0 && is_space(kind, data, len-1)) {
  1660. len--;
  1661. }
  1662. while (j < len && is_space(kind, data, j)) {
  1663. j++;
  1664. }
  1665. }
  1666. for (; j < len; j++) {
  1667. ch = PyUnicode_READ(kind, data, j);
  1668. if (ignore_underscores && ch == '_') {
  1669. continue;
  1670. }
  1671. if (0 < ch && ch <= 127) {
  1672. *cp++ = ch;
  1673. continue;
  1674. }
  1675. if (Py_UNICODE_ISSPACE(ch)) {
  1676. *cp++ = ' ';
  1677. continue;
  1678. }
  1679. d = Py_UNICODE_TODECIMAL(ch);
  1680. if (d < 0) {
  1681. /* empty string triggers ConversionSyntax */
  1682. *res = '\0';
  1683. return res;
  1684. }
  1685. *cp++ = '0' + d;
  1686. }
  1687. *cp = '\0';
  1688. return res;
  1689. }
  1690. /* Return a new PyDecObject or a subtype from a C string. Use the context
  1691. during conversion. */
  1692. static PyObject *
  1693. PyDecType_FromCString(PyTypeObject *type, const char *s,
  1694. PyObject *context)
  1695. {
  1696. PyObject *dec;
  1697. uint32_t status = 0;
  1698. dec = PyDecType_New(type);
  1699. if (dec == NULL) {
  1700. return NULL;
  1701. }
  1702. mpd_qset_string(MPD(dec), s, CTX(context), &status);
  1703. if (dec_addstatus(context, status)) {
  1704. Py_DECREF(dec);
  1705. return NULL;
  1706. }
  1707. return dec;
  1708. }
  1709. /* Return a new PyDecObject or a subtype from a C string. Attempt exact
  1710. conversion. If the operand cannot be converted exactly, set
  1711. InvalidOperation. */
  1712. static PyObject *
  1713. PyDecType_FromCStringExact(PyTypeObject *type, const char *s,
  1714. PyObject *context)
  1715. {
  1716. PyObject *dec;
  1717. uint32_t status = 0;
  1718. mpd_context_t maxctx;
  1719. dec = PyDecType_New(type);
  1720. if (dec == NULL) {
  1721. return NULL;
  1722. }
  1723. mpd_maxcontext(&maxctx);
  1724. mpd_qset_string(MPD(dec), s, &maxctx, &status);
  1725. if (status & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) {
  1726. /* we want exact results */
  1727. mpd_seterror(MPD(dec), MPD_Invalid_operation, &status);
  1728. }
  1729. status &= MPD_Errors;
  1730. if (dec_addstatus(context, status)) {
  1731. Py_DECREF(dec);
  1732. return NULL;
  1733. }
  1734. return dec;
  1735. }
  1736. /* Return a new PyDecObject or a subtype from a PyUnicodeObject. */
  1737. static PyObject *
  1738. PyDecType_FromUnicode(PyTypeObject *type, PyObject *u,
  1739. PyObject *context)
  1740. {
  1741. PyObject *dec;
  1742. char *s;
  1743. s = numeric_as_ascii(u, 0, 0);
  1744. if (s == NULL) {
  1745. return NULL;
  1746. }
  1747. dec = PyDecType_FromCString(type, s, context);
  1748. PyMem_Free(s);
  1749. return dec;
  1750. }
  1751. /* Return a new PyDecObject or a subtype from a PyUnicodeObject. Attempt exact
  1752. * conversion. If the conversion is not exact, fail with InvalidOperation.
  1753. * Allow leading and trailing whitespace in the input operand. */
  1754. static PyObject *
  1755. PyDecType_FromUnicodeExactWS(PyTypeObject *type, PyObject *u,
  1756. PyObject *context)
  1757. {
  1758. PyObject *dec;
  1759. char *s;
  1760. s = numeric_as_ascii(u, 1, 1);
  1761. if (s == NULL) {
  1762. return NULL;
  1763. }
  1764. dec = PyDecType_FromCStringExact(type, s, context);
  1765. PyMem_Free(s);
  1766. return dec;
  1767. }
  1768. /* Set PyDecObject from triple without any error checking. */
  1769. Py_LOCAL_INLINE(void)
  1770. _dec_settriple(PyObject *dec, uint8_t sign, uint32_t v, mpd_ssize_t exp)
  1771. {
  1772. #ifdef CONFIG_64
  1773. MPD(dec)->data[0] = v;
  1774. MPD(dec)->len = 1;
  1775. #else
  1776. uint32_t q, r;
  1777. q = v / MPD_RADIX;
  1778. r = v - q * MPD_RADIX;
  1779. MPD(dec)->data[1] = q;
  1780. MPD(dec)->data[0] = r;
  1781. MPD(dec)->len = q ? 2 : 1;
  1782. #endif
  1783. mpd_set_flags(MPD(dec), sign);
  1784. MPD(dec)->exp = exp;
  1785. mpd_setdigits(MPD(dec));
  1786. }
  1787. /* Return a new PyDecObject from an mpd_ssize_t. */
  1788. static PyObject *
  1789. PyDecType_FromSsize(PyTypeObject *type, mpd_ssize_t v, PyObject *context)
  1790. {
  1791. PyObject *dec;
  1792. uint32_t status = 0;
  1793. dec = PyDecType_New(type);
  1794. if (dec == NULL) {
  1795. return NULL;
  1796. }
  1797. mpd_qset_ssize(MPD(dec), v, CTX(context), &status);
  1798. if (dec_addstatus(context, status)) {
  1799. Py_DECREF(dec);
  1800. return NULL;
  1801. }
  1802. return dec;
  1803. }
  1804. /* Return a new PyDecObject from an mpd_ssize_t. Conversion is exact. */
  1805. static PyObject *
  1806. PyDecType_FromSsizeExact(PyTypeObject *type, mpd_ssize_t v, PyObject *context)
  1807. {
  1808. PyObject *dec;
  1809. uint32_t status = 0;
  1810. mpd_context_t maxctx;
  1811. dec = PyDecType_New(type);
  1812. if (dec == NULL) {
  1813. return NULL;
  1814. }
  1815. mpd_maxcontext(&maxctx);
  1816. mpd_qset_ssize(MPD(dec), v, &maxctx, &status);
  1817. if (dec_addstatus(context, status)) {
  1818. Py_DECREF(dec);
  1819. return NULL;
  1820. }
  1821. return dec;
  1822. }
  1823. /* Convert from a PyLongObject. The context is not modified; flags set
  1824. during conversion are accumulated in the status parameter. */
  1825. static PyObject *
  1826. dec_from_long(PyTypeObject *type, PyObject *v,
  1827. const mpd_context_t *ctx, uint32_t *status)
  1828. {
  1829. PyObject *dec;
  1830. PyLongObject *l = (PyLongObject *)v;
  1831. dec = PyDecType_New(type);
  1832. if (dec == NULL) {
  1833. return NULL;
  1834. }
  1835. if (_PyLong_IsZero(l)) {
  1836. _dec_settriple(dec, MPD_POS, 0, 0);
  1837. return dec;
  1838. }
  1839. uint8_t sign = _PyLong_IsNegative(l) ? MPD_NEG : MPD_POS;
  1840. if (_PyLong_IsCompact(l)) {
  1841. _dec_settriple(dec, sign, l->long_value.ob_digit[0], 0);
  1842. mpd_qfinalize(MPD(dec), ctx, status);
  1843. return dec;
  1844. }
  1845. size_t len = _PyLong_DigitCount(l);
  1846. #if PYLONG_BITS_IN_DIGIT == 30
  1847. mpd_qimport_u32(MPD(dec), l->long_value.ob_digit, len, sign, PyLong_BASE,
  1848. ctx, status);
  1849. #elif PYLONG_BITS_IN_DIGIT == 15
  1850. mpd_qimport_u16(MPD(dec), l->long_value.ob_digit, len, sign, PyLong_BASE,
  1851. ctx, status);
  1852. #else
  1853. #error "PYLONG_BITS_IN_DIGIT should be 15 or 30"
  1854. #endif
  1855. return dec;
  1856. }
  1857. /* Return a new PyDecObject from a PyLongObject. Use the context for
  1858. conversion. */
  1859. static PyObject *
  1860. PyDecType_FromLong(PyTypeObject *type, PyObject *v, PyObject *context)
  1861. {
  1862. PyObject *dec;
  1863. uint32_t status = 0;
  1864. if (!PyLong_Check(v)) {
  1865. PyErr_SetString(PyExc_TypeError, "argument must be an integer");
  1866. return NULL;
  1867. }
  1868. dec = dec_from_long(type, v, CTX(context), &status);
  1869. if (dec == NULL) {
  1870. return NULL;
  1871. }
  1872. if (dec_addstatus(context, status)) {
  1873. Py_DECREF(dec);
  1874. return NULL;
  1875. }
  1876. return dec;
  1877. }
  1878. /* Return a new PyDecObject from a PyLongObject. Use a maximum context
  1879. for conversion. If the conversion is not exact, set InvalidOperation. */
  1880. static PyObject *
  1881. PyDecType_FromLongExact(PyTypeObject *type, PyObject *v,
  1882. PyObject *context)
  1883. {
  1884. PyObject *dec;
  1885. uint32_t status = 0;
  1886. mpd_context_t maxctx;
  1887. if (!PyLong_Check(v)) {
  1888. PyErr_SetString(PyExc_TypeError, "argument must be an integer");
  1889. return NULL;
  1890. }
  1891. mpd_maxcontext(&maxctx);
  1892. dec = dec_from_long(type, v, &maxctx, &status);
  1893. if (dec == NULL) {
  1894. return NULL;
  1895. }
  1896. if (status & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) {
  1897. /* we want exact results */
  1898. mpd_seterror(MPD(dec), MPD_Invalid_operation, &status);
  1899. }
  1900. status &= MPD_Errors;
  1901. if (dec_addstatus(context, status)) {
  1902. Py_DECREF(dec);
  1903. return NULL;
  1904. }
  1905. return dec;
  1906. }
  1907. /* External C-API functions */
  1908. static binaryfunc _py_long_multiply;
  1909. static binaryfunc _py_long_floor_divide;
  1910. static ternaryfunc _py_long_power;
  1911. static unaryfunc _py_float_abs;
  1912. static PyCFunction _py_long_bit_length;
  1913. static PyCFunction _py_float_as_integer_ratio;
  1914. /* Return a PyDecObject or a subtype from a PyFloatObject.
  1915. Conversion is exact. */
  1916. static PyObject *
  1917. PyDecType_FromFloatExact(PyTypeObject *type, PyObject *v,
  1918. PyObject *context)
  1919. {
  1920. PyObject *dec, *tmp;
  1921. PyObject *n, *d, *n_d;
  1922. mpd_ssize_t k;
  1923. double x;
  1924. int sign;
  1925. mpd_t *d1, *d2;
  1926. uint32_t status = 0;
  1927. mpd_context_t maxctx;
  1928. assert(PyType_IsSubtype(type, &PyDec_Type));
  1929. if (PyLong_Check(v)) {
  1930. return PyDecType_FromLongExact(type, v, context);
  1931. }
  1932. if (!PyFloat_Check(v)) {
  1933. PyErr_SetString(PyExc_TypeError,
  1934. "argument must be int or float");
  1935. return NULL;
  1936. }
  1937. x = PyFloat_AsDouble(v);
  1938. if (x == -1.0 && PyErr_Occurred()) {
  1939. return NULL;
  1940. }
  1941. sign = (copysign(1.0, x) == 1.0) ? 0 : 1;
  1942. if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) {
  1943. dec = PyDecType_New(type);
  1944. if (dec == NULL) {
  1945. return NULL;
  1946. }
  1947. if (Py_IS_NAN(x)) {
  1948. /* decimal.py calls repr(float(+-nan)),
  1949. * which always gives a positive result. */
  1950. mpd_setspecial(MPD(dec), MPD_POS, MPD_NAN);
  1951. }
  1952. else {
  1953. mpd_setspecial(MPD(dec), sign, MPD_INF);
  1954. }
  1955. return dec;
  1956. }
  1957. /* absolute value of the float */
  1958. tmp = _py_float_abs(v);
  1959. if (tmp == NULL) {
  1960. return NULL;
  1961. }
  1962. /* float as integer ratio: numerator/denominator */
  1963. n_d = _py_float_as_integer_ratio(tmp, NULL);
  1964. Py_DECREF(tmp);
  1965. if (n_d == NULL) {
  1966. return NULL;
  1967. }
  1968. n = PyTuple_GET_ITEM(n_d, 0);
  1969. d = PyTuple_GET_ITEM(n_d, 1);
  1970. tmp = _py_long_bit_length(d, NULL);
  1971. if (tmp == NULL) {
  1972. Py_DECREF(n_d);
  1973. return NULL;
  1974. }
  1975. k = PyLong_AsSsize_t(tmp);
  1976. Py_DECREF(tmp);
  1977. if (k == -1 && PyErr_Occurred()) {
  1978. Py_DECREF(n_d);
  1979. return NULL;
  1980. }
  1981. k--;
  1982. dec = PyDecType_FromLongExact(type, n, context);
  1983. Py_DECREF(n_d);
  1984. if (dec == NULL) {
  1985. return NULL;
  1986. }
  1987. d1 = mpd_qnew();
  1988. if (d1 == NULL) {
  1989. Py_DECREF(dec);
  1990. PyErr_NoMemory();
  1991. return NULL;
  1992. }
  1993. d2 = mpd_qnew();
  1994. if (d2 == NULL) {
  1995. mpd_del(d1);
  1996. Py_DECREF(dec);
  1997. PyErr_NoMemory();
  1998. return NULL;
  1999. }
  2000. mpd_maxcontext(&maxctx);
  2001. mpd_qset_uint(d1, 5, &maxctx, &status);
  2002. mpd_qset_ssize(d2, k, &maxctx, &status);
  2003. mpd_qpow(d1, d1, d2, &maxctx, &status);
  2004. if (dec_addstatus(context, status)) {
  2005. mpd_del(d1);
  2006. mpd_del(d2);
  2007. Py_DECREF(dec);
  2008. return NULL;
  2009. }
  2010. /* result = n * 5**k */
  2011. mpd_qmul(MPD(dec), MPD(dec), d1, &maxctx, &status);
  2012. mpd_del(d1);
  2013. mpd_del(d2);
  2014. if (dec_addstatus(context, status)) {
  2015. Py_DECREF(dec);
  2016. return NULL;
  2017. }
  2018. /* result = +- n * 5**k * 10**-k */
  2019. mpd_set_sign(MPD(dec), sign);
  2020. MPD(dec)->exp = -k;
  2021. return dec;
  2022. }
  2023. static PyObject *
  2024. PyDecType_FromFloat(PyTypeObject *type, PyObject *v,
  2025. PyObject *context)
  2026. {
  2027. PyObject *dec;
  2028. uint32_t status = 0;
  2029. dec = PyDecType_FromFloatExact(type, v, context);
  2030. if (dec == NULL) {
  2031. return NULL;
  2032. }
  2033. mpd_qfinalize(MPD(dec), CTX(context), &status);
  2034. if (dec_addstatus(context, status)) {
  2035. Py_DECREF(dec);
  2036. return NULL;
  2037. }
  2038. return dec;
  2039. }
  2040. /* Return a new PyDecObject or a subtype from a Decimal. */
  2041. static PyObject *
  2042. PyDecType_FromDecimalExact(PyTypeObject *type, PyObject *v, PyObject *context)
  2043. {
  2044. PyObject *dec;
  2045. uint32_t status = 0;
  2046. if (type == &PyDec_Type && PyDec_CheckExact(v)) {
  2047. return Py_NewRef(v);
  2048. }
  2049. dec = PyDecType_New(type);
  2050. if (dec == NULL) {
  2051. return NULL;
  2052. }
  2053. mpd_qcopy(MPD(dec), MPD(v), &status);
  2054. if (dec_addstatus(context, status)) {
  2055. Py_DECREF(dec);
  2056. return NULL;
  2057. }
  2058. return dec;
  2059. }
  2060. static PyObject *
  2061. sequence_as_tuple(PyObject *v, PyObject *ex, const char *mesg)
  2062. {
  2063. if (PyTuple_Check(v)) {
  2064. return Py_NewRef(v);
  2065. }
  2066. if (PyList_Check(v)) {
  2067. return PyList_AsTuple(v);
  2068. }
  2069. PyErr_SetString(ex, mesg);
  2070. return NULL;
  2071. }
  2072. /* Return a new C string representation of a DecimalTuple. */
  2073. static char *
  2074. dectuple_as_str(PyObject *dectuple)
  2075. {
  2076. PyObject *digits = NULL, *tmp;
  2077. char *decstring = NULL;
  2078. char sign_special[6];
  2079. char *cp;
  2080. long sign, l;
  2081. mpd_ssize_t exp = 0;
  2082. Py_ssize_t i, mem, tsize;
  2083. int is_infinite = 0;
  2084. int n;
  2085. assert(PyTuple_Check(dectuple));
  2086. if (PyTuple_Size(dectuple) != 3) {
  2087. PyErr_SetString(PyExc_ValueError,
  2088. "argument must be a sequence of length 3");
  2089. goto error;
  2090. }
  2091. /* sign */
  2092. tmp = PyTuple_GET_ITEM(dectuple, 0);
  2093. if (!PyLong_Check(tmp)) {
  2094. PyErr_SetString(PyExc_ValueError,
  2095. "sign must be an integer with the value 0 or 1");
  2096. goto error;
  2097. }
  2098. sign = PyLong_AsLong(tmp);
  2099. if (sign == -1 && PyErr_Occurred()) {
  2100. goto error;
  2101. }
  2102. if (sign != 0 && sign != 1) {
  2103. PyErr_SetString(PyExc_ValueError,
  2104. "sign must be an integer with the value 0 or 1");
  2105. goto error;
  2106. }
  2107. sign_special[0] = sign ? '-' : '+';
  2108. sign_special[1] = '\0';
  2109. /* exponent or encoding for a special number */
  2110. tmp = PyTuple_GET_ITEM(dectuple, 2);
  2111. if (PyUnicode_Check(tmp)) {
  2112. /* special */
  2113. if (PyUnicode_CompareWithASCIIString(tmp, "F") == 0) {
  2114. strcat(sign_special, "Inf");
  2115. is_infinite = 1;
  2116. }
  2117. else if (PyUnicode_CompareWithASCIIString(tmp, "n") == 0) {
  2118. strcat(sign_special, "NaN");
  2119. }
  2120. else if (PyUnicode_CompareWithASCIIString(tmp, "N") == 0) {
  2121. strcat(sign_special, "sNaN");
  2122. }
  2123. else {
  2124. PyErr_SetString(PyExc_ValueError,
  2125. "string argument in the third position "
  2126. "must be 'F', 'n' or 'N'");
  2127. goto error;
  2128. }
  2129. }
  2130. else {
  2131. /* exponent */
  2132. if (!PyLong_Check(tmp)) {
  2133. PyErr_SetString(PyExc_ValueError,
  2134. "exponent must be an integer");
  2135. goto error;
  2136. }
  2137. exp = PyLong_AsSsize_t(tmp);
  2138. if (exp == -1 && PyErr_Occurred()) {
  2139. goto error;
  2140. }
  2141. }
  2142. /* coefficient */
  2143. digits = sequence_as_tuple(PyTuple_GET_ITEM(dectuple, 1), PyExc_ValueError,
  2144. "coefficient must be a tuple of digits");
  2145. if (digits == NULL) {
  2146. goto error;
  2147. }
  2148. tsize = PyTuple_Size(digits);
  2149. /* [sign][coeffdigits+1][E][-][expdigits+1]['\0'] */
  2150. mem = 1 + tsize + 3 + MPD_EXPDIGITS + 2;
  2151. cp = decstring = PyMem_Malloc(mem);
  2152. if (decstring == NULL) {
  2153. PyErr_NoMemory();
  2154. goto error;
  2155. }
  2156. n = snprintf(cp, mem, "%s", sign_special);
  2157. if (n < 0 || n >= mem) {
  2158. PyErr_SetString(PyExc_RuntimeError,
  2159. "internal error in dec_sequence_as_str");
  2160. goto error;
  2161. }
  2162. cp += n;
  2163. if (tsize == 0 && sign_special[1] == '\0') {
  2164. /* empty tuple: zero coefficient, except for special numbers */
  2165. *cp++ = '0';
  2166. }
  2167. for (i = 0; i < tsize; i++) {
  2168. tmp = PyTuple_GET_ITEM(digits, i);
  2169. if (!PyLong_Check(tmp)) {
  2170. PyErr_SetString(PyExc_ValueError,
  2171. "coefficient must be a tuple of digits");
  2172. goto error;
  2173. }
  2174. l = PyLong_AsLong(tmp);
  2175. if (l == -1 && PyErr_Occurred()) {
  2176. goto error;
  2177. }
  2178. if (l < 0 || l > 9) {
  2179. PyErr_SetString(PyExc_ValueError,
  2180. "coefficient must be a tuple of digits");
  2181. goto error;
  2182. }
  2183. if (is_infinite) {
  2184. /* accept but ignore any well-formed coefficient for compatibility
  2185. with decimal.py */
  2186. continue;
  2187. }
  2188. *cp++ = (char)l + '0';
  2189. }
  2190. *cp = '\0';
  2191. if (sign_special[1] == '\0') {
  2192. /* not a special number */
  2193. *cp++ = 'E';
  2194. n = snprintf(cp, MPD_EXPDIGITS+2, "%" PRI_mpd_ssize_t, exp);
  2195. if (n < 0 || n >= MPD_EXPDIGITS+2) {
  2196. PyErr_SetString(PyExc_RuntimeError,
  2197. "internal error in dec_sequence_as_str");
  2198. goto error;
  2199. }
  2200. }
  2201. Py_XDECREF(digits);
  2202. return decstring;
  2203. error:
  2204. Py_XDECREF(digits);
  2205. if (decstring) PyMem_Free(decstring);
  2206. return NULL;
  2207. }
  2208. /* Currently accepts tuples and lists. */
  2209. static PyObject *
  2210. PyDecType_FromSequence(PyTypeObject *type, PyObject *v,
  2211. PyObject *context)
  2212. {
  2213. PyObject *dectuple;
  2214. PyObject *dec;
  2215. char *s;
  2216. dectuple = sequence_as_tuple(v, PyExc_TypeError,
  2217. "argument must be a tuple or list");
  2218. if (dectuple == NULL) {
  2219. return NULL;
  2220. }
  2221. s = dectuple_as_str(dectuple);
  2222. Py_DECREF(dectuple);
  2223. if (s == NULL) {
  2224. return NULL;
  2225. }
  2226. dec = PyDecType_FromCString(type, s, context);
  2227. PyMem_Free(s);
  2228. return dec;
  2229. }
  2230. /* Currently accepts tuples and lists. */
  2231. static PyObject *
  2232. PyDecType_FromSequenceExact(PyTypeObject *type, PyObject *v,
  2233. PyObject *context)
  2234. {
  2235. PyObject *dectuple;
  2236. PyObject *dec;
  2237. char *s;
  2238. dectuple = sequence_as_tuple(v, PyExc_TypeError,
  2239. "argument must be a tuple or list");
  2240. if (dectuple == NULL) {
  2241. return NULL;
  2242. }
  2243. s = dectuple_as_str(dectuple);
  2244. Py_DECREF(dectuple);
  2245. if (s == NULL) {
  2246. return NULL;
  2247. }
  2248. dec = PyDecType_FromCStringExact(type, s, context);
  2249. PyMem_Free(s);
  2250. return dec;
  2251. }
  2252. #define PyDec_FromCString(str, context) \
  2253. PyDecType_FromCString(&PyDec_Type, str, context)
  2254. #define PyDec_FromCStringExact(str, context) \
  2255. PyDecType_FromCStringExact(&PyDec_Type, str, context)
  2256. #define PyDec_FromUnicode(unicode, context) \
  2257. PyDecType_FromUnicode(&PyDec_Type, unicode, context)
  2258. #define PyDec_FromUnicodeExact(unicode, context) \
  2259. PyDecType_FromUnicodeExact(&PyDec_Type, unicode, context)
  2260. #define PyDec_FromUnicodeExactWS(unicode, context) \
  2261. PyDecType_FromUnicodeExactWS(&PyDec_Type, unicode, context)
  2262. #define PyDec_FromSsize(v, context) \
  2263. PyDecType_FromSsize(&PyDec_Type, v, context)
  2264. #define PyDec_FromSsizeExact(v, context) \
  2265. PyDecType_FromSsizeExact(&PyDec_Type, v, context)
  2266. #define PyDec_FromLong(pylong, context) \
  2267. PyDecType_FromLong(&PyDec_Type, pylong, context)
  2268. #define PyDec_FromLongExact(pylong, context) \
  2269. PyDecType_FromLongExact(&PyDec_Type, pylong, context)
  2270. #define PyDec_FromFloat(pyfloat, context) \
  2271. PyDecType_FromFloat(&PyDec_Type, pyfloat, context)
  2272. #define PyDec_FromFloatExact(pyfloat, context) \
  2273. PyDecType_FromFloatExact(&PyDec_Type, pyfloat, context)
  2274. #define PyDec_FromSequence(sequence, context) \
  2275. PyDecType_FromSequence(&PyDec_Type, sequence, context)
  2276. #define PyDec_FromSequenceExact(sequence, context) \
  2277. PyDecType_FromSequenceExact(&PyDec_Type, sequence, context)
  2278. /* class method */
  2279. static PyObject *
  2280. dec_from_float(PyObject *type, PyObject *pyfloat)
  2281. {
  2282. PyObject *context;
  2283. PyObject *result;
  2284. CURRENT_CONTEXT(context);
  2285. result = PyDecType_FromFloatExact(&PyDec_Type, pyfloat, context);
  2286. if (type != (PyObject *)&PyDec_Type && result != NULL) {
  2287. Py_SETREF(result, PyObject_CallFunctionObjArgs(type, result, NULL));
  2288. }
  2289. return result;
  2290. }
  2291. /* create_decimal_from_float */
  2292. static PyObject *
  2293. ctx_from_float(PyObject *context, PyObject *v)
  2294. {
  2295. return PyDec_FromFloat(v, context);
  2296. }
  2297. /* Apply the context to the input operand. Return a new PyDecObject. */
  2298. static PyObject *
  2299. dec_apply(PyObject *v, PyObject *context)
  2300. {
  2301. PyObject *result;
  2302. uint32_t status = 0;
  2303. result = dec_alloc();
  2304. if (result == NULL) {
  2305. return NULL;
  2306. }
  2307. mpd_qcopy(MPD(result), MPD(v), &status);
  2308. if (dec_addstatus(context, status)) {
  2309. Py_DECREF(result);
  2310. return NULL;
  2311. }
  2312. mpd_qfinalize(MPD(result), CTX(context), &status);
  2313. if (dec_addstatus(context, status)) {
  2314. Py_DECREF(result);
  2315. return NULL;
  2316. }
  2317. return result;
  2318. }
  2319. /* 'v' can have any type accepted by the Decimal constructor. Attempt
  2320. an exact conversion. If the result does not meet the restrictions
  2321. for an mpd_t, fail with InvalidOperation. */
  2322. static PyObject *
  2323. PyDecType_FromObjectExact(PyTypeObject *type, PyObject *v, PyObject *context)
  2324. {
  2325. if (v == NULL) {
  2326. return PyDecType_FromSsizeExact(type, 0, context);
  2327. }
  2328. else if (PyDec_Check(v)) {
  2329. return PyDecType_FromDecimalExact(type, v, context);
  2330. }
  2331. else if (PyUnicode_Check(v)) {
  2332. return PyDecType_FromUnicodeExactWS(type, v, context);
  2333. }
  2334. else if (PyLong_Check(v)) {
  2335. return PyDecType_FromLongExact(type, v, context);
  2336. }
  2337. else if (PyTuple_Check(v) || PyList_Check(v)) {
  2338. return PyDecType_FromSequenceExact(type, v, context);
  2339. }
  2340. else if (PyFloat_Check(v)) {
  2341. if (dec_addstatus(context, MPD_Float_operation)) {
  2342. return NULL;
  2343. }
  2344. return PyDecType_FromFloatExact(type, v, context);
  2345. }
  2346. else {
  2347. PyErr_Format(PyExc_TypeError,
  2348. "conversion from %s to Decimal is not supported",
  2349. Py_TYPE(v)->tp_name);
  2350. return NULL;
  2351. }
  2352. }
  2353. /* The context is used during conversion. This function is the
  2354. equivalent of context.create_decimal(). */
  2355. static PyObject *
  2356. PyDec_FromObject(PyObject *v, PyObject *context)
  2357. {
  2358. if (v == NULL) {
  2359. return PyDec_FromSsize(0, context);
  2360. }
  2361. else if (PyDec_Check(v)) {
  2362. mpd_context_t *ctx = CTX(context);
  2363. if (mpd_isnan(MPD(v)) &&
  2364. MPD(v)->digits > ctx->prec - ctx->clamp) {
  2365. /* Special case: too many NaN payload digits */
  2366. PyObject *result;
  2367. if (dec_addstatus(context, MPD_Conversion_syntax)) {
  2368. return NULL;
  2369. }
  2370. result = dec_alloc();
  2371. if (result == NULL) {
  2372. return NULL;
  2373. }
  2374. mpd_setspecial(MPD(result), MPD_POS, MPD_NAN);
  2375. return result;
  2376. }
  2377. return dec_apply(v, context);
  2378. }
  2379. else if (PyUnicode_Check(v)) {
  2380. return PyDec_FromUnicode(v, context);
  2381. }
  2382. else if (PyLong_Check(v)) {
  2383. return PyDec_FromLong(v, context);
  2384. }
  2385. else if (PyTuple_Check(v) || PyList_Check(v)) {
  2386. return PyDec_FromSequence(v, context);
  2387. }
  2388. else if (PyFloat_Check(v)) {
  2389. if (dec_addstatus(context, MPD_Float_operation)) {
  2390. return NULL;
  2391. }
  2392. return PyDec_FromFloat(v, context);
  2393. }
  2394. else {
  2395. PyErr_Format(PyExc_TypeError,
  2396. "conversion from %s to Decimal is not supported",
  2397. Py_TYPE(v)->tp_name);
  2398. return NULL;
  2399. }
  2400. }
  2401. static PyObject *
  2402. dec_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2403. {
  2404. static char *kwlist[] = {"value", "context", NULL};
  2405. PyObject *v = NULL;
  2406. PyObject *context = Py_None;
  2407. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwlist,
  2408. &v, &context)) {
  2409. return NULL;
  2410. }
  2411. CONTEXT_CHECK_VA(context);
  2412. return PyDecType_FromObjectExact(type, v, context);
  2413. }
  2414. static PyObject *
  2415. ctx_create_decimal(PyObject *context, PyObject *args)
  2416. {
  2417. PyObject *v = NULL;
  2418. if (!PyArg_ParseTuple(args, "|O", &v)) {
  2419. return NULL;
  2420. }
  2421. return PyDec_FromObject(v, context);
  2422. }
  2423. /******************************************************************************/
  2424. /* Implicit conversions to Decimal */
  2425. /******************************************************************************/
  2426. /* Try to convert PyObject v to a new PyDecObject conv. If the conversion
  2427. fails, set conv to NULL (exception is set). If the conversion is not
  2428. implemented, set conv to Py_NotImplemented. */
  2429. #define NOT_IMPL 0
  2430. #define TYPE_ERR 1
  2431. Py_LOCAL_INLINE(int)
  2432. convert_op(int type_err, PyObject **conv, PyObject *v, PyObject *context)
  2433. {
  2434. if (PyDec_Check(v)) {
  2435. *conv = Py_NewRef(v);
  2436. return 1;
  2437. }
  2438. if (PyLong_Check(v)) {
  2439. *conv = PyDec_FromLongExact(v, context);
  2440. if (*conv == NULL) {
  2441. return 0;
  2442. }
  2443. return 1;
  2444. }
  2445. if (type_err) {
  2446. PyErr_Format(PyExc_TypeError,
  2447. "conversion from %s to Decimal is not supported",
  2448. Py_TYPE(v)->tp_name);
  2449. }
  2450. else {
  2451. *conv = Py_NewRef(Py_NotImplemented);
  2452. }
  2453. return 0;
  2454. }
  2455. /* Return NotImplemented for unsupported types. */
  2456. #define CONVERT_OP(a, v, context) \
  2457. if (!convert_op(NOT_IMPL, a, v, context)) { \
  2458. return *(a); \
  2459. }
  2460. #define CONVERT_BINOP(a, b, v, w, context) \
  2461. if (!convert_op(NOT_IMPL, a, v, context)) { \
  2462. return *(a); \
  2463. } \
  2464. if (!convert_op(NOT_IMPL, b, w, context)) { \
  2465. Py_DECREF(*(a)); \
  2466. return *(b); \
  2467. }
  2468. #define CONVERT_TERNOP(a, b, c, v, w, x, context) \
  2469. if (!convert_op(NOT_IMPL, a, v, context)) { \
  2470. return *(a); \
  2471. } \
  2472. if (!convert_op(NOT_IMPL, b, w, context)) { \
  2473. Py_DECREF(*(a)); \
  2474. return *(b); \
  2475. } \
  2476. if (!convert_op(NOT_IMPL, c, x, context)) { \
  2477. Py_DECREF(*(a)); \
  2478. Py_DECREF(*(b)); \
  2479. return *(c); \
  2480. }
  2481. /* Raise TypeError for unsupported types. */
  2482. #define CONVERT_OP_RAISE(a, v, context) \
  2483. if (!convert_op(TYPE_ERR, a, v, context)) { \
  2484. return NULL; \
  2485. }
  2486. #define CONVERT_BINOP_RAISE(a, b, v, w, context) \
  2487. if (!convert_op(TYPE_ERR, a, v, context)) { \
  2488. return NULL; \
  2489. } \
  2490. if (!convert_op(TYPE_ERR, b, w, context)) { \
  2491. Py_DECREF(*(a)); \
  2492. return NULL; \
  2493. }
  2494. #define CONVERT_TERNOP_RAISE(a, b, c, v, w, x, context) \
  2495. if (!convert_op(TYPE_ERR, a, v, context)) { \
  2496. return NULL; \
  2497. } \
  2498. if (!convert_op(TYPE_ERR, b, w, context)) { \
  2499. Py_DECREF(*(a)); \
  2500. return NULL; \
  2501. } \
  2502. if (!convert_op(TYPE_ERR, c, x, context)) { \
  2503. Py_DECREF(*(a)); \
  2504. Py_DECREF(*(b)); \
  2505. return NULL; \
  2506. }
  2507. /******************************************************************************/
  2508. /* Implicit conversions to Decimal for comparison */
  2509. /******************************************************************************/
  2510. /* Convert rationals for comparison */
  2511. static PyObject *Rational = NULL;
  2512. static PyObject *
  2513. multiply_by_denominator(PyObject *v, PyObject *r, PyObject *context)
  2514. {
  2515. PyObject *result;
  2516. PyObject *tmp = NULL;
  2517. PyObject *denom = NULL;
  2518. uint32_t status = 0;
  2519. mpd_context_t maxctx;
  2520. mpd_ssize_t exp;
  2521. mpd_t *vv;
  2522. /* v is not special, r is a rational */
  2523. tmp = PyObject_GetAttrString(r, "denominator");
  2524. if (tmp == NULL) {
  2525. return NULL;
  2526. }
  2527. denom = PyDec_FromLongExact(tmp, context);
  2528. Py_DECREF(tmp);
  2529. if (denom == NULL) {
  2530. return NULL;
  2531. }
  2532. vv = mpd_qncopy(MPD(v));
  2533. if (vv == NULL) {
  2534. Py_DECREF(denom);
  2535. PyErr_NoMemory();
  2536. return NULL;
  2537. }
  2538. result = dec_alloc();
  2539. if (result == NULL) {
  2540. Py_DECREF(denom);
  2541. mpd_del(vv);
  2542. return NULL;
  2543. }
  2544. mpd_maxcontext(&maxctx);
  2545. /* Prevent Overflow in the following multiplication. The result of
  2546. the multiplication is only used in mpd_qcmp, which can handle
  2547. values that are technically out of bounds, like (for 32-bit)
  2548. 99999999999999999999...99999999e+425000000. */
  2549. exp = vv->exp;
  2550. vv->exp = 0;
  2551. mpd_qmul(MPD(result), vv, MPD(denom), &maxctx, &status);
  2552. MPD(result)->exp = exp;
  2553. Py_DECREF(denom);
  2554. mpd_del(vv);
  2555. /* If any status has been accumulated during the multiplication,
  2556. the result is invalid. This is very unlikely, since even the
  2557. 32-bit version supports 425000000 digits. */
  2558. if (status) {
  2559. PyErr_SetString(PyExc_ValueError,
  2560. "exact conversion for comparison failed");
  2561. Py_DECREF(result);
  2562. return NULL;
  2563. }
  2564. return result;
  2565. }
  2566. static PyObject *
  2567. numerator_as_decimal(PyObject *r, PyObject *context)
  2568. {
  2569. PyObject *tmp, *num;
  2570. tmp = PyObject_GetAttrString(r, "numerator");
  2571. if (tmp == NULL) {
  2572. return NULL;
  2573. }
  2574. num = PyDec_FromLongExact(tmp, context);
  2575. Py_DECREF(tmp);
  2576. return num;
  2577. }
  2578. /* Convert v and w for comparison. v is a Decimal. If w is a Rational, both
  2579. v and w have to be transformed. Return 1 for success, with new references
  2580. to the converted objects in vcmp and wcmp. Return 0 for failure. In that
  2581. case wcmp is either NULL or Py_NotImplemented (new reference) and vcmp
  2582. is undefined. */
  2583. static int
  2584. convert_op_cmp(PyObject **vcmp, PyObject **wcmp, PyObject *v, PyObject *w,
  2585. int op, PyObject *context)
  2586. {
  2587. mpd_context_t *ctx = CTX(context);
  2588. *vcmp = v;
  2589. if (PyDec_Check(w)) {
  2590. *wcmp = Py_NewRef(w);
  2591. }
  2592. else if (PyLong_Check(w)) {
  2593. *wcmp = PyDec_FromLongExact(w, context);
  2594. }
  2595. else if (PyFloat_Check(w)) {
  2596. if (op != Py_EQ && op != Py_NE &&
  2597. dec_addstatus(context, MPD_Float_operation)) {
  2598. *wcmp = NULL;
  2599. }
  2600. else {
  2601. ctx->status |= MPD_Float_operation;
  2602. *wcmp = PyDec_FromFloatExact(w, context);
  2603. }
  2604. }
  2605. else if (PyComplex_Check(w) && (op == Py_EQ || op == Py_NE)) {
  2606. Py_complex c = PyComplex_AsCComplex(w);
  2607. if (c.real == -1.0 && PyErr_Occurred()) {
  2608. *wcmp = NULL;
  2609. }
  2610. else if (c.imag == 0.0) {
  2611. PyObject *tmp = PyFloat_FromDouble(c.real);
  2612. if (tmp == NULL) {
  2613. *wcmp = NULL;
  2614. }
  2615. else {
  2616. ctx->status |= MPD_Float_operation;
  2617. *wcmp = PyDec_FromFloatExact(tmp, context);
  2618. Py_DECREF(tmp);
  2619. }
  2620. }
  2621. else {
  2622. *wcmp = Py_NewRef(Py_NotImplemented);
  2623. }
  2624. }
  2625. else {
  2626. int is_rational = PyObject_IsInstance(w, Rational);
  2627. if (is_rational < 0) {
  2628. *wcmp = NULL;
  2629. }
  2630. else if (is_rational > 0) {
  2631. *wcmp = numerator_as_decimal(w, context);
  2632. if (*wcmp && !mpd_isspecial(MPD(v))) {
  2633. *vcmp = multiply_by_denominator(v, w, context);
  2634. if (*vcmp == NULL) {
  2635. Py_CLEAR(*wcmp);
  2636. }
  2637. }
  2638. }
  2639. else {
  2640. *wcmp = Py_NewRef(Py_NotImplemented);
  2641. }
  2642. }
  2643. if (*wcmp == NULL || *wcmp == Py_NotImplemented) {
  2644. return 0;
  2645. }
  2646. if (*vcmp == v) {
  2647. Py_INCREF(v);
  2648. }
  2649. return 1;
  2650. }
  2651. #define CONVERT_BINOP_CMP(vcmp, wcmp, v, w, op, ctx) \
  2652. if (!convert_op_cmp(vcmp, wcmp, v, w, op, ctx)) { \
  2653. return *(wcmp); \
  2654. } \
  2655. /******************************************************************************/
  2656. /* Conversions from decimal */
  2657. /******************************************************************************/
  2658. static PyObject *
  2659. unicode_fromascii(const char *s, Py_ssize_t size)
  2660. {
  2661. PyObject *res;
  2662. res = PyUnicode_New(size, 127);
  2663. if (res == NULL) {
  2664. return NULL;
  2665. }
  2666. memcpy(PyUnicode_1BYTE_DATA(res), s, size);
  2667. return res;
  2668. }
  2669. /* PyDecObject as a string. The default module context is only used for
  2670. the value of 'capitals'. */
  2671. static PyObject *
  2672. dec_str(PyObject *dec)
  2673. {
  2674. PyObject *res, *context;
  2675. mpd_ssize_t size;
  2676. char *cp;
  2677. CURRENT_CONTEXT(context);
  2678. size = mpd_to_sci_size(&cp, MPD(dec), CtxCaps(context));
  2679. if (size < 0) {
  2680. PyErr_NoMemory();
  2681. return NULL;
  2682. }
  2683. res = unicode_fromascii(cp, size);
  2684. mpd_free(cp);
  2685. return res;
  2686. }
  2687. /* Representation of a PyDecObject. */
  2688. static PyObject *
  2689. dec_repr(PyObject *dec)
  2690. {
  2691. PyObject *res, *context;
  2692. char *cp;
  2693. CURRENT_CONTEXT(context);
  2694. cp = mpd_to_sci(MPD(dec), CtxCaps(context));
  2695. if (cp == NULL) {
  2696. PyErr_NoMemory();
  2697. return NULL;
  2698. }
  2699. res = PyUnicode_FromFormat("Decimal('%s')", cp);
  2700. mpd_free(cp);
  2701. return res;
  2702. }
  2703. /* Return a duplicate of src, copy embedded null characters. */
  2704. static char *
  2705. dec_strdup(const char *src, Py_ssize_t size)
  2706. {
  2707. char *dest = PyMem_Malloc(size+1);
  2708. if (dest == NULL) {
  2709. PyErr_NoMemory();
  2710. return NULL;
  2711. }
  2712. memcpy(dest, src, size);
  2713. dest[size] = '\0';
  2714. return dest;
  2715. }
  2716. static void
  2717. dec_replace_fillchar(char *dest)
  2718. {
  2719. while (*dest != '\0') {
  2720. if (*dest == '\xff') *dest = '\0';
  2721. dest++;
  2722. }
  2723. }
  2724. /* Convert decimal_point or thousands_sep, which may be multibyte or in
  2725. the range [128, 255], to a UTF8 string. */
  2726. static PyObject *
  2727. dotsep_as_utf8(const char *s)
  2728. {
  2729. PyObject *utf8;
  2730. PyObject *tmp;
  2731. wchar_t buf[2];
  2732. size_t n;
  2733. n = mbstowcs(buf, s, 2);
  2734. if (n != 1) { /* Issue #7442 */
  2735. PyErr_SetString(PyExc_ValueError,
  2736. "invalid decimal point or unsupported "
  2737. "combination of LC_CTYPE and LC_NUMERIC");
  2738. return NULL;
  2739. }
  2740. tmp = PyUnicode_FromWideChar(buf, n);
  2741. if (tmp == NULL) {
  2742. return NULL;
  2743. }
  2744. utf8 = PyUnicode_AsUTF8String(tmp);
  2745. Py_DECREF(tmp);
  2746. return utf8;
  2747. }
  2748. /* copy of libmpdec _mpd_round() */
  2749. static void
  2750. _mpd_round(mpd_t *result, const mpd_t *a, mpd_ssize_t prec,
  2751. const mpd_context_t *ctx, uint32_t *status)
  2752. {
  2753. mpd_ssize_t exp = a->exp + a->digits - prec;
  2754. if (prec <= 0) {
  2755. mpd_seterror(result, MPD_Invalid_operation, status);
  2756. return;
  2757. }
  2758. if (mpd_isspecial(a) || mpd_iszero(a)) {
  2759. mpd_qcopy(result, a, status);
  2760. return;
  2761. }
  2762. mpd_qrescale_fmt(result, a, exp, ctx, status);
  2763. if (result->digits > prec) {
  2764. mpd_qrescale_fmt(result, result, exp+1, ctx, status);
  2765. }
  2766. }
  2767. /* Locate negative zero "z" option within a UTF-8 format spec string.
  2768. * Returns pointer to "z", else NULL.
  2769. * The portion of the spec we're working with is [[fill]align][sign][z] */
  2770. static const char *
  2771. format_spec_z_search(char const *fmt, Py_ssize_t size) {
  2772. char const *pos = fmt;
  2773. char const *fmt_end = fmt + size;
  2774. /* skip over [[fill]align] (fill may be multi-byte character) */
  2775. pos += 1;
  2776. while (pos < fmt_end && *pos & 0x80) {
  2777. pos += 1;
  2778. }
  2779. if (pos < fmt_end && strchr("<>=^", *pos) != NULL) {
  2780. pos += 1;
  2781. } else {
  2782. /* fill not present-- skip over [align] */
  2783. pos = fmt;
  2784. if (pos < fmt_end && strchr("<>=^", *pos) != NULL) {
  2785. pos += 1;
  2786. }
  2787. }
  2788. /* skip over [sign] */
  2789. if (pos < fmt_end && strchr("+- ", *pos) != NULL) {
  2790. pos += 1;
  2791. }
  2792. return pos < fmt_end && *pos == 'z' ? pos : NULL;
  2793. }
  2794. static int
  2795. dict_get_item_string(PyObject *dict, const char *key, PyObject **valueobj, const char **valuestr)
  2796. {
  2797. *valueobj = NULL;
  2798. PyObject *keyobj = PyUnicode_FromString(key);
  2799. if (keyobj == NULL) {
  2800. return -1;
  2801. }
  2802. PyObject *value = PyDict_GetItemWithError(dict, keyobj);
  2803. Py_DECREF(keyobj);
  2804. if (value == NULL) {
  2805. if (PyErr_Occurred()) {
  2806. return -1;
  2807. }
  2808. return 0;
  2809. }
  2810. value = PyUnicode_AsUTF8String(value);
  2811. if (value == NULL) {
  2812. return -1;
  2813. }
  2814. *valueobj = value;
  2815. *valuestr = PyBytes_AS_STRING(value);
  2816. return 0;
  2817. }
  2818. /* Formatted representation of a PyDecObject. */
  2819. static PyObject *
  2820. dec_format(PyObject *dec, PyObject *args)
  2821. {
  2822. PyObject *result = NULL;
  2823. PyObject *override = NULL;
  2824. PyObject *dot = NULL;
  2825. PyObject *sep = NULL;
  2826. PyObject *grouping = NULL;
  2827. PyObject *fmtarg;
  2828. PyObject *context;
  2829. mpd_spec_t spec;
  2830. char const *fmt;
  2831. char *fmt_copy = NULL;
  2832. char *decstring = NULL;
  2833. uint32_t status = 0;
  2834. int replace_fillchar = 0;
  2835. int no_neg_0 = 0;
  2836. Py_ssize_t size;
  2837. mpd_t *mpd = MPD(dec);
  2838. mpd_uint_t dt[MPD_MINALLOC_MAX];
  2839. mpd_t tmp = {MPD_STATIC|MPD_STATIC_DATA,0,0,0,MPD_MINALLOC_MAX,dt};
  2840. CURRENT_CONTEXT(context);
  2841. if (!PyArg_ParseTuple(args, "O|O", &fmtarg, &override)) {
  2842. return NULL;
  2843. }
  2844. if (PyUnicode_Check(fmtarg)) {
  2845. fmt = PyUnicode_AsUTF8AndSize(fmtarg, &size);
  2846. if (fmt == NULL) {
  2847. return NULL;
  2848. }
  2849. /* NOTE: If https://github.com/python/cpython/pull/29438 lands, the
  2850. * format string manipulation below can be eliminated by enhancing
  2851. * the forked mpd_parse_fmt_str(). */
  2852. if (size > 0 && fmt[0] == '\0') {
  2853. /* NUL fill character: must be replaced with a valid UTF-8 char
  2854. before calling mpd_parse_fmt_str(). */
  2855. replace_fillchar = 1;
  2856. fmt = fmt_copy = dec_strdup(fmt, size);
  2857. if (fmt_copy == NULL) {
  2858. return NULL;
  2859. }
  2860. fmt_copy[0] = '_';
  2861. }
  2862. /* Strip 'z' option, which isn't understood by mpd_parse_fmt_str().
  2863. * NOTE: fmt is always null terminated by PyUnicode_AsUTF8AndSize() */
  2864. char const *z_position = format_spec_z_search(fmt, size);
  2865. if (z_position != NULL) {
  2866. no_neg_0 = 1;
  2867. size_t z_index = z_position - fmt;
  2868. if (fmt_copy == NULL) {
  2869. fmt = fmt_copy = dec_strdup(fmt, size);
  2870. if (fmt_copy == NULL) {
  2871. return NULL;
  2872. }
  2873. }
  2874. /* Shift characters (including null terminator) left,
  2875. overwriting the 'z' option. */
  2876. memmove(fmt_copy + z_index, fmt_copy + z_index + 1, size - z_index);
  2877. size -= 1;
  2878. }
  2879. }
  2880. else {
  2881. PyErr_SetString(PyExc_TypeError,
  2882. "format arg must be str");
  2883. return NULL;
  2884. }
  2885. if (!mpd_parse_fmt_str(&spec, fmt, CtxCaps(context))) {
  2886. PyErr_SetString(PyExc_ValueError,
  2887. "invalid format string");
  2888. goto finish;
  2889. }
  2890. if (replace_fillchar) {
  2891. /* In order to avoid clobbering parts of UTF-8 thousands separators or
  2892. decimal points when the substitution is reversed later, the actual
  2893. placeholder must be an invalid UTF-8 byte. */
  2894. spec.fill[0] = '\xff';
  2895. spec.fill[1] = '\0';
  2896. }
  2897. if (override) {
  2898. /* Values for decimal_point, thousands_sep and grouping can
  2899. be explicitly specified in the override dict. These values
  2900. take precedence over the values obtained from localeconv()
  2901. in mpd_parse_fmt_str(). The feature is not documented and
  2902. is only used in test_decimal. */
  2903. if (!PyDict_Check(override)) {
  2904. PyErr_SetString(PyExc_TypeError,
  2905. "optional argument must be a dict");
  2906. goto finish;
  2907. }
  2908. if (dict_get_item_string(override, "decimal_point", &dot, &spec.dot) ||
  2909. dict_get_item_string(override, "thousands_sep", &sep, &spec.sep) ||
  2910. dict_get_item_string(override, "grouping", &grouping, &spec.grouping))
  2911. {
  2912. goto finish;
  2913. }
  2914. if (mpd_validate_lconv(&spec) < 0) {
  2915. PyErr_SetString(PyExc_ValueError,
  2916. "invalid override dict");
  2917. goto finish;
  2918. }
  2919. }
  2920. else {
  2921. size_t n = strlen(spec.dot);
  2922. if (n > 1 || (n == 1 && !isascii((unsigned char)spec.dot[0]))) {
  2923. /* fix locale dependent non-ascii characters */
  2924. dot = dotsep_as_utf8(spec.dot);
  2925. if (dot == NULL) {
  2926. goto finish;
  2927. }
  2928. spec.dot = PyBytes_AS_STRING(dot);
  2929. }
  2930. n = strlen(spec.sep);
  2931. if (n > 1 || (n == 1 && !isascii((unsigned char)spec.sep[0]))) {
  2932. /* fix locale dependent non-ascii characters */
  2933. sep = dotsep_as_utf8(spec.sep);
  2934. if (sep == NULL) {
  2935. goto finish;
  2936. }
  2937. spec.sep = PyBytes_AS_STRING(sep);
  2938. }
  2939. }
  2940. if (no_neg_0 && mpd_isnegative(mpd) && !mpd_isspecial(mpd)) {
  2941. /* Round into a temporary (carefully mirroring the rounding
  2942. of mpd_qformat_spec()), and check if the result is negative zero.
  2943. If so, clear the sign and format the resulting positive zero. */
  2944. mpd_ssize_t prec;
  2945. mpd_qcopy(&tmp, mpd, &status);
  2946. if (spec.prec >= 0) {
  2947. switch (spec.type) {
  2948. case 'f':
  2949. mpd_qrescale(&tmp, &tmp, -spec.prec, CTX(context), &status);
  2950. break;
  2951. case '%':
  2952. tmp.exp += 2;
  2953. mpd_qrescale(&tmp, &tmp, -spec.prec, CTX(context), &status);
  2954. break;
  2955. case 'g':
  2956. prec = (spec.prec == 0) ? 1 : spec.prec;
  2957. if (tmp.digits > prec) {
  2958. _mpd_round(&tmp, &tmp, prec, CTX(context), &status);
  2959. }
  2960. break;
  2961. case 'e':
  2962. if (!mpd_iszero(&tmp)) {
  2963. _mpd_round(&tmp, &tmp, spec.prec+1, CTX(context), &status);
  2964. }
  2965. break;
  2966. }
  2967. }
  2968. if (status & MPD_Errors) {
  2969. PyErr_SetString(PyExc_ValueError, "unexpected error when rounding");
  2970. goto finish;
  2971. }
  2972. if (mpd_iszero(&tmp)) {
  2973. mpd_set_positive(&tmp);
  2974. mpd = &tmp;
  2975. }
  2976. }
  2977. decstring = mpd_qformat_spec(mpd, &spec, CTX(context), &status);
  2978. if (decstring == NULL) {
  2979. if (status & MPD_Malloc_error) {
  2980. PyErr_NoMemory();
  2981. }
  2982. else {
  2983. PyErr_SetString(PyExc_ValueError,
  2984. "format specification exceeds internal limits of _decimal");
  2985. }
  2986. goto finish;
  2987. }
  2988. size = strlen(decstring);
  2989. if (replace_fillchar) {
  2990. dec_replace_fillchar(decstring);
  2991. }
  2992. result = PyUnicode_DecodeUTF8(decstring, size, NULL);
  2993. finish:
  2994. Py_XDECREF(grouping);
  2995. Py_XDECREF(sep);
  2996. Py_XDECREF(dot);
  2997. if (fmt_copy) PyMem_Free(fmt_copy);
  2998. if (decstring) mpd_free(decstring);
  2999. return result;
  3000. }
  3001. /* Return a PyLongObject from a PyDecObject, using the specified rounding
  3002. * mode. The context precision is not observed. */
  3003. static PyObject *
  3004. dec_as_long(PyObject *dec, PyObject *context, int round)
  3005. {
  3006. PyLongObject *pylong;
  3007. digit *ob_digit;
  3008. size_t n;
  3009. mpd_t *x;
  3010. mpd_context_t workctx;
  3011. uint32_t status = 0;
  3012. if (mpd_isspecial(MPD(dec))) {
  3013. if (mpd_isnan(MPD(dec))) {
  3014. PyErr_SetString(PyExc_ValueError,
  3015. "cannot convert NaN to integer");
  3016. }
  3017. else {
  3018. PyErr_SetString(PyExc_OverflowError,
  3019. "cannot convert Infinity to integer");
  3020. }
  3021. return NULL;
  3022. }
  3023. x = mpd_qnew();
  3024. if (x == NULL) {
  3025. PyErr_NoMemory();
  3026. return NULL;
  3027. }
  3028. workctx = *CTX(context);
  3029. workctx.round = round;
  3030. mpd_qround_to_int(x, MPD(dec), &workctx, &status);
  3031. if (dec_addstatus(context, status)) {
  3032. mpd_del(x);
  3033. return NULL;
  3034. }
  3035. status = 0;
  3036. ob_digit = NULL;
  3037. #if PYLONG_BITS_IN_DIGIT == 30
  3038. n = mpd_qexport_u32(&ob_digit, 0, PyLong_BASE, x, &status);
  3039. #elif PYLONG_BITS_IN_DIGIT == 15
  3040. n = mpd_qexport_u16(&ob_digit, 0, PyLong_BASE, x, &status);
  3041. #else
  3042. #error "PYLONG_BITS_IN_DIGIT should be 15 or 30"
  3043. #endif
  3044. if (n == SIZE_MAX) {
  3045. PyErr_NoMemory();
  3046. mpd_del(x);
  3047. return NULL;
  3048. }
  3049. if (n == 1) {
  3050. sdigit val = mpd_arith_sign(x) * ob_digit[0];
  3051. mpd_free(ob_digit);
  3052. mpd_del(x);
  3053. return PyLong_FromLong(val);
  3054. }
  3055. assert(n > 0);
  3056. assert(!mpd_iszero(x));
  3057. pylong = _PyLong_FromDigits(mpd_isnegative(x), n, ob_digit);
  3058. mpd_free(ob_digit);
  3059. mpd_del(x);
  3060. return (PyObject *) pylong;
  3061. }
  3062. /* Convert a Decimal to its exact integer ratio representation. */
  3063. static PyObject *
  3064. dec_as_integer_ratio(PyObject *self, PyObject *args UNUSED)
  3065. {
  3066. PyObject *numerator = NULL;
  3067. PyObject *denominator = NULL;
  3068. PyObject *exponent = NULL;
  3069. PyObject *result = NULL;
  3070. PyObject *tmp;
  3071. mpd_ssize_t exp;
  3072. PyObject *context;
  3073. uint32_t status = 0;
  3074. if (mpd_isspecial(MPD(self))) {
  3075. if (mpd_isnan(MPD(self))) {
  3076. PyErr_SetString(PyExc_ValueError,
  3077. "cannot convert NaN to integer ratio");
  3078. }
  3079. else {
  3080. PyErr_SetString(PyExc_OverflowError,
  3081. "cannot convert Infinity to integer ratio");
  3082. }
  3083. return NULL;
  3084. }
  3085. CURRENT_CONTEXT(context);
  3086. tmp = dec_alloc();
  3087. if (tmp == NULL) {
  3088. return NULL;
  3089. }
  3090. if (!mpd_qcopy(MPD(tmp), MPD(self), &status)) {
  3091. Py_DECREF(tmp);
  3092. PyErr_NoMemory();
  3093. return NULL;
  3094. }
  3095. exp = mpd_iszero(MPD(tmp)) ? 0 : MPD(tmp)->exp;
  3096. MPD(tmp)->exp = 0;
  3097. /* context and rounding are unused here: the conversion is exact */
  3098. numerator = dec_as_long(tmp, context, MPD_ROUND_FLOOR);
  3099. Py_DECREF(tmp);
  3100. if (numerator == NULL) {
  3101. goto error;
  3102. }
  3103. exponent = PyLong_FromSsize_t(exp < 0 ? -exp : exp);
  3104. if (exponent == NULL) {
  3105. goto error;
  3106. }
  3107. tmp = PyLong_FromLong(10);
  3108. if (tmp == NULL) {
  3109. goto error;
  3110. }
  3111. Py_SETREF(exponent, _py_long_power(tmp, exponent, Py_None));
  3112. Py_DECREF(tmp);
  3113. if (exponent == NULL) {
  3114. goto error;
  3115. }
  3116. if (exp >= 0) {
  3117. Py_SETREF(numerator, _py_long_multiply(numerator, exponent));
  3118. if (numerator == NULL) {
  3119. goto error;
  3120. }
  3121. denominator = PyLong_FromLong(1);
  3122. if (denominator == NULL) {
  3123. goto error;
  3124. }
  3125. }
  3126. else {
  3127. denominator = exponent;
  3128. exponent = NULL;
  3129. tmp = _PyLong_GCD(numerator, denominator);
  3130. if (tmp == NULL) {
  3131. goto error;
  3132. }
  3133. Py_SETREF(numerator, _py_long_floor_divide(numerator, tmp));
  3134. if (numerator == NULL) {
  3135. Py_DECREF(tmp);
  3136. goto error;
  3137. }
  3138. Py_SETREF(denominator, _py_long_floor_divide(denominator, tmp));
  3139. Py_DECREF(tmp);
  3140. if (denominator == NULL) {
  3141. goto error;
  3142. }
  3143. }
  3144. result = PyTuple_Pack(2, numerator, denominator);
  3145. error:
  3146. Py_XDECREF(exponent);
  3147. Py_XDECREF(denominator);
  3148. Py_XDECREF(numerator);
  3149. return result;
  3150. }
  3151. static PyObject *
  3152. PyDec_ToIntegralValue(PyObject *dec, PyObject *args, PyObject *kwds)
  3153. {
  3154. static char *kwlist[] = {"rounding", "context", NULL};
  3155. PyObject *result;
  3156. PyObject *rounding = Py_None;
  3157. PyObject *context = Py_None;
  3158. uint32_t status = 0;
  3159. mpd_context_t workctx;
  3160. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwlist,
  3161. &rounding, &context)) {
  3162. return NULL;
  3163. }
  3164. CONTEXT_CHECK_VA(context);
  3165. workctx = *CTX(context);
  3166. if (rounding != Py_None) {
  3167. int round = getround(rounding);
  3168. if (round < 0) {
  3169. return NULL;
  3170. }
  3171. if (!mpd_qsetround(&workctx, round)) {
  3172. INTERNAL_ERROR_PTR("PyDec_ToIntegralValue"); /* GCOV_NOT_REACHED */
  3173. }
  3174. }
  3175. result = dec_alloc();
  3176. if (result == NULL) {
  3177. return NULL;
  3178. }
  3179. mpd_qround_to_int(MPD(result), MPD(dec), &workctx, &status);
  3180. if (dec_addstatus(context, status)) {
  3181. Py_DECREF(result);
  3182. return NULL;
  3183. }
  3184. return result;
  3185. }
  3186. static PyObject *
  3187. PyDec_ToIntegralExact(PyObject *dec, PyObject *args, PyObject *kwds)
  3188. {
  3189. static char *kwlist[] = {"rounding", "context", NULL};
  3190. PyObject *result;
  3191. PyObject *rounding = Py_None;
  3192. PyObject *context = Py_None;
  3193. uint32_t status = 0;
  3194. mpd_context_t workctx;
  3195. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwlist,
  3196. &rounding, &context)) {
  3197. return NULL;
  3198. }
  3199. CONTEXT_CHECK_VA(context);
  3200. workctx = *CTX(context);
  3201. if (rounding != Py_None) {
  3202. int round = getround(rounding);
  3203. if (round < 0) {
  3204. return NULL;
  3205. }
  3206. if (!mpd_qsetround(&workctx, round)) {
  3207. INTERNAL_ERROR_PTR("PyDec_ToIntegralExact"); /* GCOV_NOT_REACHED */
  3208. }
  3209. }
  3210. result = dec_alloc();
  3211. if (result == NULL) {
  3212. return NULL;
  3213. }
  3214. mpd_qround_to_intx(MPD(result), MPD(dec), &workctx, &status);
  3215. if (dec_addstatus(context, status)) {
  3216. Py_DECREF(result);
  3217. return NULL;
  3218. }
  3219. return result;
  3220. }
  3221. static PyObject *
  3222. PyDec_AsFloat(PyObject *dec)
  3223. {
  3224. PyObject *f, *s;
  3225. if (mpd_isnan(MPD(dec))) {
  3226. if (mpd_issnan(MPD(dec))) {
  3227. PyErr_SetString(PyExc_ValueError,
  3228. "cannot convert signaling NaN to float");
  3229. return NULL;
  3230. }
  3231. if (mpd_isnegative(MPD(dec))) {
  3232. s = PyUnicode_FromString("-nan");
  3233. }
  3234. else {
  3235. s = PyUnicode_FromString("nan");
  3236. }
  3237. }
  3238. else {
  3239. s = dec_str(dec);
  3240. }
  3241. if (s == NULL) {
  3242. return NULL;
  3243. }
  3244. f = PyFloat_FromString(s);
  3245. Py_DECREF(s);
  3246. return f;
  3247. }
  3248. static PyObject *
  3249. PyDec_Round(PyObject *dec, PyObject *args)
  3250. {
  3251. PyObject *result;
  3252. PyObject *x = NULL;
  3253. uint32_t status = 0;
  3254. PyObject *context;
  3255. CURRENT_CONTEXT(context);
  3256. if (!PyArg_ParseTuple(args, "|O", &x)) {
  3257. return NULL;
  3258. }
  3259. if (x) {
  3260. mpd_uint_t dq[1] = {1};
  3261. mpd_t q = {MPD_STATIC|MPD_CONST_DATA,0,1,1,1,dq};
  3262. mpd_ssize_t y;
  3263. if (!PyLong_Check(x)) {
  3264. PyErr_SetString(PyExc_TypeError,
  3265. "optional arg must be an integer");
  3266. return NULL;
  3267. }
  3268. y = PyLong_AsSsize_t(x);
  3269. if (y == -1 && PyErr_Occurred()) {
  3270. return NULL;
  3271. }
  3272. result = dec_alloc();
  3273. if (result == NULL) {
  3274. return NULL;
  3275. }
  3276. q.exp = (y == MPD_SSIZE_MIN) ? MPD_SSIZE_MAX : -y;
  3277. mpd_qquantize(MPD(result), MPD(dec), &q, CTX(context), &status);
  3278. if (dec_addstatus(context, status)) {
  3279. Py_DECREF(result);
  3280. return NULL;
  3281. }
  3282. return result;
  3283. }
  3284. else {
  3285. return dec_as_long(dec, context, MPD_ROUND_HALF_EVEN);
  3286. }
  3287. }
  3288. static PyTypeObject *DecimalTuple = NULL;
  3289. /* Return the DecimalTuple representation of a PyDecObject. */
  3290. static PyObject *
  3291. PyDec_AsTuple(PyObject *dec, PyObject *dummy UNUSED)
  3292. {
  3293. PyObject *result = NULL;
  3294. PyObject *sign = NULL;
  3295. PyObject *coeff = NULL;
  3296. PyObject *expt = NULL;
  3297. PyObject *tmp = NULL;
  3298. mpd_t *x = NULL;
  3299. char *intstring = NULL;
  3300. Py_ssize_t intlen, i;
  3301. x = mpd_qncopy(MPD(dec));
  3302. if (x == NULL) {
  3303. PyErr_NoMemory();
  3304. goto out;
  3305. }
  3306. sign = PyLong_FromUnsignedLong(mpd_sign(MPD(dec)));
  3307. if (sign == NULL) {
  3308. goto out;
  3309. }
  3310. if (mpd_isinfinite(x)) {
  3311. expt = PyUnicode_FromString("F");
  3312. if (expt == NULL) {
  3313. goto out;
  3314. }
  3315. /* decimal.py has non-compliant infinity payloads. */
  3316. coeff = Py_BuildValue("(i)", 0);
  3317. if (coeff == NULL) {
  3318. goto out;
  3319. }
  3320. }
  3321. else {
  3322. if (mpd_isnan(x)) {
  3323. expt = PyUnicode_FromString(mpd_isqnan(x)?"n":"N");
  3324. }
  3325. else {
  3326. expt = PyLong_FromSsize_t(MPD(dec)->exp);
  3327. }
  3328. if (expt == NULL) {
  3329. goto out;
  3330. }
  3331. /* coefficient is defined */
  3332. if (x->len > 0) {
  3333. /* make an integer */
  3334. x->exp = 0;
  3335. /* clear NaN and sign */
  3336. mpd_clear_flags(x);
  3337. intstring = mpd_to_sci(x, 1);
  3338. if (intstring == NULL) {
  3339. PyErr_NoMemory();
  3340. goto out;
  3341. }
  3342. intlen = strlen(intstring);
  3343. coeff = PyTuple_New(intlen);
  3344. if (coeff == NULL) {
  3345. goto out;
  3346. }
  3347. for (i = 0; i < intlen; i++) {
  3348. tmp = PyLong_FromLong(intstring[i]-'0');
  3349. if (tmp == NULL) {
  3350. goto out;
  3351. }
  3352. PyTuple_SET_ITEM(coeff, i, tmp);
  3353. }
  3354. }
  3355. else {
  3356. coeff = PyTuple_New(0);
  3357. if (coeff == NULL) {
  3358. goto out;
  3359. }
  3360. }
  3361. }
  3362. result = PyObject_CallFunctionObjArgs((PyObject *)DecimalTuple,
  3363. sign, coeff, expt, NULL);
  3364. out:
  3365. if (x) mpd_del(x);
  3366. if (intstring) mpd_free(intstring);
  3367. Py_XDECREF(sign);
  3368. Py_XDECREF(coeff);
  3369. Py_XDECREF(expt);
  3370. return result;
  3371. }
  3372. /******************************************************************************/
  3373. /* Macros for converting mpdecimal functions to Decimal methods */
  3374. /******************************************************************************/
  3375. /* Unary number method that uses the default module context. */
  3376. #define Dec_UnaryNumberMethod(MPDFUNC) \
  3377. static PyObject * \
  3378. nm_##MPDFUNC(PyObject *self) \
  3379. { \
  3380. PyObject *result; \
  3381. PyObject *context; \
  3382. uint32_t status = 0; \
  3383. \
  3384. CURRENT_CONTEXT(context); \
  3385. if ((result = dec_alloc()) == NULL) { \
  3386. return NULL; \
  3387. } \
  3388. \
  3389. MPDFUNC(MPD(result), MPD(self), CTX(context), &status); \
  3390. if (dec_addstatus(context, status)) { \
  3391. Py_DECREF(result); \
  3392. return NULL; \
  3393. } \
  3394. \
  3395. return result; \
  3396. }
  3397. /* Binary number method that uses default module context. */
  3398. #define Dec_BinaryNumberMethod(MPDFUNC) \
  3399. static PyObject * \
  3400. nm_##MPDFUNC(PyObject *self, PyObject *other) \
  3401. { \
  3402. PyObject *a, *b; \
  3403. PyObject *result; \
  3404. PyObject *context; \
  3405. uint32_t status = 0; \
  3406. \
  3407. CURRENT_CONTEXT(context) ; \
  3408. CONVERT_BINOP(&a, &b, self, other, context); \
  3409. \
  3410. if ((result = dec_alloc()) == NULL) { \
  3411. Py_DECREF(a); \
  3412. Py_DECREF(b); \
  3413. return NULL; \
  3414. } \
  3415. \
  3416. MPDFUNC(MPD(result), MPD(a), MPD(b), CTX(context), &status); \
  3417. Py_DECREF(a); \
  3418. Py_DECREF(b); \
  3419. if (dec_addstatus(context, status)) { \
  3420. Py_DECREF(result); \
  3421. return NULL; \
  3422. } \
  3423. \
  3424. return result; \
  3425. }
  3426. /* Boolean function without a context arg. */
  3427. #define Dec_BoolFunc(MPDFUNC) \
  3428. static PyObject * \
  3429. dec_##MPDFUNC(PyObject *self, PyObject *dummy UNUSED) \
  3430. { \
  3431. return MPDFUNC(MPD(self)) ? incr_true() : incr_false(); \
  3432. }
  3433. /* Boolean function with an optional context arg. */
  3434. #define Dec_BoolFuncVA(MPDFUNC) \
  3435. static PyObject * \
  3436. dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
  3437. { \
  3438. static char *kwlist[] = {"context", NULL}; \
  3439. PyObject *context = Py_None; \
  3440. \
  3441. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist, \
  3442. &context)) { \
  3443. return NULL; \
  3444. } \
  3445. CONTEXT_CHECK_VA(context); \
  3446. \
  3447. return MPDFUNC(MPD(self), CTX(context)) ? incr_true() : incr_false(); \
  3448. }
  3449. /* Unary function with an optional context arg. */
  3450. #define Dec_UnaryFuncVA(MPDFUNC) \
  3451. static PyObject * \
  3452. dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
  3453. { \
  3454. static char *kwlist[] = {"context", NULL}; \
  3455. PyObject *result; \
  3456. PyObject *context = Py_None; \
  3457. uint32_t status = 0; \
  3458. \
  3459. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist, \
  3460. &context)) { \
  3461. return NULL; \
  3462. } \
  3463. CONTEXT_CHECK_VA(context); \
  3464. \
  3465. if ((result = dec_alloc()) == NULL) { \
  3466. return NULL; \
  3467. } \
  3468. \
  3469. MPDFUNC(MPD(result), MPD(self), CTX(context), &status); \
  3470. if (dec_addstatus(context, status)) { \
  3471. Py_DECREF(result); \
  3472. return NULL; \
  3473. } \
  3474. \
  3475. return result; \
  3476. }
  3477. /* Binary function with an optional context arg. */
  3478. #define Dec_BinaryFuncVA(MPDFUNC) \
  3479. static PyObject * \
  3480. dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
  3481. { \
  3482. static char *kwlist[] = {"other", "context", NULL}; \
  3483. PyObject *other; \
  3484. PyObject *a, *b; \
  3485. PyObject *result; \
  3486. PyObject *context = Py_None; \
  3487. uint32_t status = 0; \
  3488. \
  3489. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist, \
  3490. &other, &context)) { \
  3491. return NULL; \
  3492. } \
  3493. CONTEXT_CHECK_VA(context); \
  3494. CONVERT_BINOP_RAISE(&a, &b, self, other, context); \
  3495. \
  3496. if ((result = dec_alloc()) == NULL) { \
  3497. Py_DECREF(a); \
  3498. Py_DECREF(b); \
  3499. return NULL; \
  3500. } \
  3501. \
  3502. MPDFUNC(MPD(result), MPD(a), MPD(b), CTX(context), &status); \
  3503. Py_DECREF(a); \
  3504. Py_DECREF(b); \
  3505. if (dec_addstatus(context, status)) { \
  3506. Py_DECREF(result); \
  3507. return NULL; \
  3508. } \
  3509. \
  3510. return result; \
  3511. }
  3512. /* Binary function with an optional context arg. Actual MPDFUNC does
  3513. NOT take a context. The context is used to record InvalidOperation
  3514. if the second operand cannot be converted exactly. */
  3515. #define Dec_BinaryFuncVA_NO_CTX(MPDFUNC) \
  3516. static PyObject * \
  3517. dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
  3518. { \
  3519. static char *kwlist[] = {"other", "context", NULL}; \
  3520. PyObject *context = Py_None; \
  3521. PyObject *other; \
  3522. PyObject *a, *b; \
  3523. PyObject *result; \
  3524. \
  3525. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist, \
  3526. &other, &context)) { \
  3527. return NULL; \
  3528. } \
  3529. CONTEXT_CHECK_VA(context); \
  3530. CONVERT_BINOP_RAISE(&a, &b, self, other, context); \
  3531. \
  3532. if ((result = dec_alloc()) == NULL) { \
  3533. Py_DECREF(a); \
  3534. Py_DECREF(b); \
  3535. return NULL; \
  3536. } \
  3537. \
  3538. MPDFUNC(MPD(result), MPD(a), MPD(b)); \
  3539. Py_DECREF(a); \
  3540. Py_DECREF(b); \
  3541. \
  3542. return result; \
  3543. }
  3544. /* Ternary function with an optional context arg. */
  3545. #define Dec_TernaryFuncVA(MPDFUNC) \
  3546. static PyObject * \
  3547. dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
  3548. { \
  3549. static char *kwlist[] = {"other", "third", "context", NULL}; \
  3550. PyObject *other, *third; \
  3551. PyObject *a, *b, *c; \
  3552. PyObject *result; \
  3553. PyObject *context = Py_None; \
  3554. uint32_t status = 0; \
  3555. \
  3556. if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O", kwlist, \
  3557. &other, &third, &context)) { \
  3558. return NULL; \
  3559. } \
  3560. CONTEXT_CHECK_VA(context); \
  3561. CONVERT_TERNOP_RAISE(&a, &b, &c, self, other, third, context); \
  3562. \
  3563. if ((result = dec_alloc()) == NULL) { \
  3564. Py_DECREF(a); \
  3565. Py_DECREF(b); \
  3566. Py_DECREF(c); \
  3567. return NULL; \
  3568. } \
  3569. \
  3570. MPDFUNC(MPD(result), MPD(a), MPD(b), MPD(c), CTX(context), &status); \
  3571. Py_DECREF(a); \
  3572. Py_DECREF(b); \
  3573. Py_DECREF(c); \
  3574. if (dec_addstatus(context, status)) { \
  3575. Py_DECREF(result); \
  3576. return NULL; \
  3577. } \
  3578. \
  3579. return result; \
  3580. }
  3581. /**********************************************/
  3582. /* Number methods */
  3583. /**********************************************/
  3584. Dec_UnaryNumberMethod(mpd_qminus)
  3585. Dec_UnaryNumberMethod(mpd_qplus)
  3586. Dec_UnaryNumberMethod(mpd_qabs)
  3587. Dec_BinaryNumberMethod(mpd_qadd)
  3588. Dec_BinaryNumberMethod(mpd_qsub)
  3589. Dec_BinaryNumberMethod(mpd_qmul)
  3590. Dec_BinaryNumberMethod(mpd_qdiv)
  3591. Dec_BinaryNumberMethod(mpd_qrem)
  3592. Dec_BinaryNumberMethod(mpd_qdivint)
  3593. static PyObject *
  3594. nm_dec_as_long(PyObject *dec)
  3595. {
  3596. PyObject *context;
  3597. CURRENT_CONTEXT(context);
  3598. return dec_as_long(dec, context, MPD_ROUND_DOWN);
  3599. }
  3600. static int
  3601. nm_nonzero(PyObject *v)
  3602. {
  3603. return !mpd_iszero(MPD(v));
  3604. }
  3605. static PyObject *
  3606. nm_mpd_qdivmod(PyObject *v, PyObject *w)
  3607. {
  3608. PyObject *a, *b;
  3609. PyObject *q, *r;
  3610. PyObject *context;
  3611. uint32_t status = 0;
  3612. PyObject *ret;
  3613. CURRENT_CONTEXT(context);
  3614. CONVERT_BINOP(&a, &b, v, w, context);
  3615. q = dec_alloc();
  3616. if (q == NULL) {
  3617. Py_DECREF(a);
  3618. Py_DECREF(b);
  3619. return NULL;
  3620. }
  3621. r = dec_alloc();
  3622. if (r == NULL) {
  3623. Py_DECREF(a);
  3624. Py_DECREF(b);
  3625. Py_DECREF(q);
  3626. return NULL;
  3627. }
  3628. mpd_qdivmod(MPD(q), MPD(r), MPD(a), MPD(b), CTX(context), &status);
  3629. Py_DECREF(a);
  3630. Py_DECREF(b);
  3631. if (dec_addstatus(context, status)) {
  3632. Py_DECREF(r);
  3633. Py_DECREF(q);
  3634. return NULL;
  3635. }
  3636. ret = Py_BuildValue("(OO)", q, r);
  3637. Py_DECREF(r);
  3638. Py_DECREF(q);
  3639. return ret;
  3640. }
  3641. static PyObject *
  3642. nm_mpd_qpow(PyObject *base, PyObject *exp, PyObject *mod)
  3643. {
  3644. PyObject *a, *b, *c = NULL;
  3645. PyObject *result;
  3646. PyObject *context;
  3647. uint32_t status = 0;
  3648. CURRENT_CONTEXT(context);
  3649. CONVERT_BINOP(&a, &b, base, exp, context);
  3650. if (mod != Py_None) {
  3651. if (!convert_op(NOT_IMPL, &c, mod, context)) {
  3652. Py_DECREF(a);
  3653. Py_DECREF(b);
  3654. return c;
  3655. }
  3656. }
  3657. result = dec_alloc();
  3658. if (result == NULL) {
  3659. Py_DECREF(a);
  3660. Py_DECREF(b);
  3661. Py_XDECREF(c);
  3662. return NULL;
  3663. }
  3664. if (c == NULL) {
  3665. mpd_qpow(MPD(result), MPD(a), MPD(b),
  3666. CTX(context), &status);
  3667. }
  3668. else {
  3669. mpd_qpowmod(MPD(result), MPD(a), MPD(b), MPD(c),
  3670. CTX(context), &status);
  3671. Py_DECREF(c);
  3672. }
  3673. Py_DECREF(a);
  3674. Py_DECREF(b);
  3675. if (dec_addstatus(context, status)) {
  3676. Py_DECREF(result);
  3677. return NULL;
  3678. }
  3679. return result;
  3680. }
  3681. /******************************************************************************/
  3682. /* Decimal Methods */
  3683. /******************************************************************************/
  3684. /* Unary arithmetic functions, optional context arg */
  3685. Dec_UnaryFuncVA(mpd_qexp)
  3686. Dec_UnaryFuncVA(mpd_qln)
  3687. Dec_UnaryFuncVA(mpd_qlog10)
  3688. Dec_UnaryFuncVA(mpd_qnext_minus)
  3689. Dec_UnaryFuncVA(mpd_qnext_plus)
  3690. Dec_UnaryFuncVA(mpd_qreduce)
  3691. Dec_UnaryFuncVA(mpd_qsqrt)
  3692. /* Binary arithmetic functions, optional context arg */
  3693. Dec_BinaryFuncVA(mpd_qcompare)
  3694. Dec_BinaryFuncVA(mpd_qcompare_signal)
  3695. Dec_BinaryFuncVA(mpd_qmax)
  3696. Dec_BinaryFuncVA(mpd_qmax_mag)
  3697. Dec_BinaryFuncVA(mpd_qmin)
  3698. Dec_BinaryFuncVA(mpd_qmin_mag)
  3699. Dec_BinaryFuncVA(mpd_qnext_toward)
  3700. Dec_BinaryFuncVA(mpd_qrem_near)
  3701. /* Ternary arithmetic functions, optional context arg */
  3702. Dec_TernaryFuncVA(mpd_qfma)
  3703. /* Boolean functions, no context arg */
  3704. Dec_BoolFunc(mpd_iscanonical)
  3705. Dec_BoolFunc(mpd_isfinite)
  3706. Dec_BoolFunc(mpd_isinfinite)
  3707. Dec_BoolFunc(mpd_isnan)
  3708. Dec_BoolFunc(mpd_isqnan)
  3709. Dec_BoolFunc(mpd_issnan)
  3710. Dec_BoolFunc(mpd_issigned)
  3711. Dec_BoolFunc(mpd_iszero)
  3712. /* Boolean functions, optional context arg */
  3713. Dec_BoolFuncVA(mpd_isnormal)
  3714. Dec_BoolFuncVA(mpd_issubnormal)
  3715. /* Unary functions, no context arg */
  3716. static PyObject *
  3717. dec_mpd_adjexp(PyObject *self, PyObject *dummy UNUSED)
  3718. {
  3719. mpd_ssize_t retval;
  3720. if (mpd_isspecial(MPD(self))) {
  3721. retval = 0;
  3722. }
  3723. else {
  3724. retval = mpd_adjexp(MPD(self));
  3725. }
  3726. return PyLong_FromSsize_t(retval);
  3727. }
  3728. static PyObject *
  3729. dec_canonical(PyObject *self, PyObject *dummy UNUSED)
  3730. {
  3731. return Py_NewRef(self);
  3732. }
  3733. static PyObject *
  3734. dec_conjugate(PyObject *self, PyObject *dummy UNUSED)
  3735. {
  3736. return Py_NewRef(self);
  3737. }
  3738. static PyObject *
  3739. dec_mpd_radix(PyObject *self UNUSED, PyObject *dummy UNUSED)
  3740. {
  3741. PyObject *result;
  3742. result = dec_alloc();
  3743. if (result == NULL) {
  3744. return NULL;
  3745. }
  3746. _dec_settriple(result, MPD_POS, 10, 0);
  3747. return result;
  3748. }
  3749. static PyObject *
  3750. dec_mpd_qcopy_abs(PyObject *self, PyObject *dummy UNUSED)
  3751. {
  3752. PyObject *result;
  3753. uint32_t status = 0;
  3754. if ((result = dec_alloc()) == NULL) {
  3755. return NULL;
  3756. }
  3757. mpd_qcopy_abs(MPD(result), MPD(self), &status);
  3758. if (status & MPD_Malloc_error) {
  3759. Py_DECREF(result);
  3760. PyErr_NoMemory();
  3761. return NULL;
  3762. }
  3763. return result;
  3764. }
  3765. static PyObject *
  3766. dec_mpd_qcopy_negate(PyObject *self, PyObject *dummy UNUSED)
  3767. {
  3768. PyObject *result;
  3769. uint32_t status = 0;
  3770. if ((result = dec_alloc()) == NULL) {
  3771. return NULL;
  3772. }
  3773. mpd_qcopy_negate(MPD(result), MPD(self), &status);
  3774. if (status & MPD_Malloc_error) {
  3775. Py_DECREF(result);
  3776. PyErr_NoMemory();
  3777. return NULL;
  3778. }
  3779. return result;
  3780. }
  3781. /* Unary functions, optional context arg */
  3782. Dec_UnaryFuncVA(mpd_qinvert)
  3783. Dec_UnaryFuncVA(mpd_qlogb)
  3784. static PyObject *
  3785. dec_mpd_class(PyObject *self, PyObject *args, PyObject *kwds)
  3786. {
  3787. static char *kwlist[] = {"context", NULL};
  3788. PyObject *context = Py_None;
  3789. const char *cp;
  3790. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist,
  3791. &context)) {
  3792. return NULL;
  3793. }
  3794. CONTEXT_CHECK_VA(context);
  3795. cp = mpd_class(MPD(self), CTX(context));
  3796. return PyUnicode_FromString(cp);
  3797. }
  3798. static PyObject *
  3799. dec_mpd_to_eng(PyObject *self, PyObject *args, PyObject *kwds)
  3800. {
  3801. static char *kwlist[] = {"context", NULL};
  3802. PyObject *result;
  3803. PyObject *context = Py_None;
  3804. mpd_ssize_t size;
  3805. char *s;
  3806. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist,
  3807. &context)) {
  3808. return NULL;
  3809. }
  3810. CONTEXT_CHECK_VA(context);
  3811. size = mpd_to_eng_size(&s, MPD(self), CtxCaps(context));
  3812. if (size < 0) {
  3813. PyErr_NoMemory();
  3814. return NULL;
  3815. }
  3816. result = unicode_fromascii(s, size);
  3817. mpd_free(s);
  3818. return result;
  3819. }
  3820. /* Binary functions, optional context arg for conversion errors */
  3821. Dec_BinaryFuncVA_NO_CTX(mpd_compare_total)
  3822. Dec_BinaryFuncVA_NO_CTX(mpd_compare_total_mag)
  3823. static PyObject *
  3824. dec_mpd_qcopy_sign(PyObject *self, PyObject *args, PyObject *kwds)
  3825. {
  3826. static char *kwlist[] = {"other", "context", NULL};
  3827. PyObject *other;
  3828. PyObject *a, *b;
  3829. PyObject *result;
  3830. PyObject *context = Py_None;
  3831. uint32_t status = 0;
  3832. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist,
  3833. &other, &context)) {
  3834. return NULL;
  3835. }
  3836. CONTEXT_CHECK_VA(context);
  3837. CONVERT_BINOP_RAISE(&a, &b, self, other, context);
  3838. result = dec_alloc();
  3839. if (result == NULL) {
  3840. Py_DECREF(a);
  3841. Py_DECREF(b);
  3842. return NULL;
  3843. }
  3844. mpd_qcopy_sign(MPD(result), MPD(a), MPD(b), &status);
  3845. Py_DECREF(a);
  3846. Py_DECREF(b);
  3847. if (dec_addstatus(context, status)) {
  3848. Py_DECREF(result);
  3849. return NULL;
  3850. }
  3851. return result;
  3852. }
  3853. static PyObject *
  3854. dec_mpd_same_quantum(PyObject *self, PyObject *args, PyObject *kwds)
  3855. {
  3856. static char *kwlist[] = {"other", "context", NULL};
  3857. PyObject *other;
  3858. PyObject *a, *b;
  3859. PyObject *result;
  3860. PyObject *context = Py_None;
  3861. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist,
  3862. &other, &context)) {
  3863. return NULL;
  3864. }
  3865. CONTEXT_CHECK_VA(context);
  3866. CONVERT_BINOP_RAISE(&a, &b, self, other, context);
  3867. result = mpd_same_quantum(MPD(a), MPD(b)) ? incr_true() : incr_false();
  3868. Py_DECREF(a);
  3869. Py_DECREF(b);
  3870. return result;
  3871. }
  3872. /* Binary functions, optional context arg */
  3873. Dec_BinaryFuncVA(mpd_qand)
  3874. Dec_BinaryFuncVA(mpd_qor)
  3875. Dec_BinaryFuncVA(mpd_qxor)
  3876. Dec_BinaryFuncVA(mpd_qrotate)
  3877. Dec_BinaryFuncVA(mpd_qscaleb)
  3878. Dec_BinaryFuncVA(mpd_qshift)
  3879. static PyObject *
  3880. dec_mpd_qquantize(PyObject *v, PyObject *args, PyObject *kwds)
  3881. {
  3882. static char *kwlist[] = {"exp", "rounding", "context", NULL};
  3883. PyObject *rounding = Py_None;
  3884. PyObject *context = Py_None;
  3885. PyObject *w, *a, *b;
  3886. PyObject *result;
  3887. uint32_t status = 0;
  3888. mpd_context_t workctx;
  3889. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO", kwlist,
  3890. &w, &rounding, &context)) {
  3891. return NULL;
  3892. }
  3893. CONTEXT_CHECK_VA(context);
  3894. workctx = *CTX(context);
  3895. if (rounding != Py_None) {
  3896. int round = getround(rounding);
  3897. if (round < 0) {
  3898. return NULL;
  3899. }
  3900. if (!mpd_qsetround(&workctx, round)) {
  3901. INTERNAL_ERROR_PTR("dec_mpd_qquantize"); /* GCOV_NOT_REACHED */
  3902. }
  3903. }
  3904. CONVERT_BINOP_RAISE(&a, &b, v, w, context);
  3905. result = dec_alloc();
  3906. if (result == NULL) {
  3907. Py_DECREF(a);
  3908. Py_DECREF(b);
  3909. return NULL;
  3910. }
  3911. mpd_qquantize(MPD(result), MPD(a), MPD(b), &workctx, &status);
  3912. Py_DECREF(a);
  3913. Py_DECREF(b);
  3914. if (dec_addstatus(context, status)) {
  3915. Py_DECREF(result);
  3916. return NULL;
  3917. }
  3918. return result;
  3919. }
  3920. /* Special methods */
  3921. static PyObject *
  3922. dec_richcompare(PyObject *v, PyObject *w, int op)
  3923. {
  3924. PyObject *a;
  3925. PyObject *b;
  3926. PyObject *context;
  3927. uint32_t status = 0;
  3928. int a_issnan, b_issnan;
  3929. int r;
  3930. assert(PyDec_Check(v));
  3931. CURRENT_CONTEXT(context);
  3932. CONVERT_BINOP_CMP(&a, &b, v, w, op, context);
  3933. a_issnan = mpd_issnan(MPD(a));
  3934. b_issnan = mpd_issnan(MPD(b));
  3935. r = mpd_qcmp(MPD(a), MPD(b), &status);
  3936. Py_DECREF(a);
  3937. Py_DECREF(b);
  3938. if (r == INT_MAX) {
  3939. /* sNaNs or op={le,ge,lt,gt} always signal. */
  3940. if (a_issnan || b_issnan || (op != Py_EQ && op != Py_NE)) {
  3941. if (dec_addstatus(context, status)) {
  3942. return NULL;
  3943. }
  3944. }
  3945. /* qNaN comparison with op={eq,ne} or comparison
  3946. * with InvalidOperation disabled. */
  3947. return (op == Py_NE) ? incr_true() : incr_false();
  3948. }
  3949. switch (op) {
  3950. case Py_EQ:
  3951. r = (r == 0);
  3952. break;
  3953. case Py_NE:
  3954. r = (r != 0);
  3955. break;
  3956. case Py_LE:
  3957. r = (r <= 0);
  3958. break;
  3959. case Py_GE:
  3960. r = (r >= 0);
  3961. break;
  3962. case Py_LT:
  3963. r = (r == -1);
  3964. break;
  3965. case Py_GT:
  3966. r = (r == 1);
  3967. break;
  3968. }
  3969. return PyBool_FromLong(r);
  3970. }
  3971. /* __ceil__ */
  3972. static PyObject *
  3973. dec_ceil(PyObject *self, PyObject *dummy UNUSED)
  3974. {
  3975. PyObject *context;
  3976. CURRENT_CONTEXT(context);
  3977. return dec_as_long(self, context, MPD_ROUND_CEILING);
  3978. }
  3979. /* __complex__ */
  3980. static PyObject *
  3981. dec_complex(PyObject *self, PyObject *dummy UNUSED)
  3982. {
  3983. PyObject *f;
  3984. double x;
  3985. f = PyDec_AsFloat(self);
  3986. if (f == NULL) {
  3987. return NULL;
  3988. }
  3989. x = PyFloat_AsDouble(f);
  3990. Py_DECREF(f);
  3991. if (x == -1.0 && PyErr_Occurred()) {
  3992. return NULL;
  3993. }
  3994. return PyComplex_FromDoubles(x, 0);
  3995. }
  3996. /* __copy__ and __deepcopy__ */
  3997. static PyObject *
  3998. dec_copy(PyObject *self, PyObject *dummy UNUSED)
  3999. {
  4000. return Py_NewRef(self);
  4001. }
  4002. /* __floor__ */
  4003. static PyObject *
  4004. dec_floor(PyObject *self, PyObject *dummy UNUSED)
  4005. {
  4006. PyObject *context;
  4007. CURRENT_CONTEXT(context);
  4008. return dec_as_long(self, context, MPD_ROUND_FLOOR);
  4009. }
  4010. /* Always uses the module context */
  4011. static Py_hash_t
  4012. _dec_hash(PyDecObject *v)
  4013. {
  4014. #if defined(CONFIG_64) && _PyHASH_BITS == 61
  4015. /* 2**61 - 1 */
  4016. mpd_uint_t p_data[1] = {2305843009213693951ULL};
  4017. mpd_t p = {MPD_POS|MPD_STATIC|MPD_CONST_DATA, 0, 19, 1, 1, p_data};
  4018. /* Inverse of 10 modulo p */
  4019. mpd_uint_t inv10_p_data[1] = {2075258708292324556ULL};
  4020. mpd_t inv10_p = {MPD_POS|MPD_STATIC|MPD_CONST_DATA,
  4021. 0, 19, 1, 1, inv10_p_data};
  4022. #elif defined(CONFIG_32) && _PyHASH_BITS == 31
  4023. /* 2**31 - 1 */
  4024. mpd_uint_t p_data[2] = {147483647UL, 2};
  4025. mpd_t p = {MPD_POS|MPD_STATIC|MPD_CONST_DATA, 0, 10, 2, 2, p_data};
  4026. /* Inverse of 10 modulo p */
  4027. mpd_uint_t inv10_p_data[2] = {503238553UL, 1};
  4028. mpd_t inv10_p = {MPD_POS|MPD_STATIC|MPD_CONST_DATA,
  4029. 0, 10, 2, 2, inv10_p_data};
  4030. #else
  4031. #error "No valid combination of CONFIG_64, CONFIG_32 and _PyHASH_BITS"
  4032. #endif
  4033. const Py_hash_t py_hash_inf = 314159;
  4034. mpd_uint_t ten_data[1] = {10};
  4035. mpd_t ten = {MPD_POS|MPD_STATIC|MPD_CONST_DATA,
  4036. 0, 2, 1, 1, ten_data};
  4037. Py_hash_t result;
  4038. mpd_t *exp_hash = NULL;
  4039. mpd_t *tmp = NULL;
  4040. mpd_ssize_t exp;
  4041. uint32_t status = 0;
  4042. mpd_context_t maxctx;
  4043. if (mpd_isspecial(MPD(v))) {
  4044. if (mpd_issnan(MPD(v))) {
  4045. PyErr_SetString(PyExc_TypeError,
  4046. "Cannot hash a signaling NaN value");
  4047. return -1;
  4048. }
  4049. else if (mpd_isnan(MPD(v))) {
  4050. return _Py_HashPointer(v);
  4051. }
  4052. else {
  4053. return py_hash_inf * mpd_arith_sign(MPD(v));
  4054. }
  4055. }
  4056. mpd_maxcontext(&maxctx);
  4057. exp_hash = mpd_qnew();
  4058. if (exp_hash == NULL) {
  4059. goto malloc_error;
  4060. }
  4061. tmp = mpd_qnew();
  4062. if (tmp == NULL) {
  4063. goto malloc_error;
  4064. }
  4065. /*
  4066. * exp(v): exponent of v
  4067. * int(v): coefficient of v
  4068. */
  4069. exp = MPD(v)->exp;
  4070. if (exp >= 0) {
  4071. /* 10**exp(v) % p */
  4072. mpd_qsset_ssize(tmp, exp, &maxctx, &status);
  4073. mpd_qpowmod(exp_hash, &ten, tmp, &p, &maxctx, &status);
  4074. }
  4075. else {
  4076. /* inv10_p**(-exp(v)) % p */
  4077. mpd_qsset_ssize(tmp, -exp, &maxctx, &status);
  4078. mpd_qpowmod(exp_hash, &inv10_p, tmp, &p, &maxctx, &status);
  4079. }
  4080. /* hash = (int(v) * exp_hash) % p */
  4081. if (!mpd_qcopy(tmp, MPD(v), &status)) {
  4082. goto malloc_error;
  4083. }
  4084. tmp->exp = 0;
  4085. mpd_set_positive(tmp);
  4086. maxctx.prec = MPD_MAX_PREC + 21;
  4087. maxctx.emax = MPD_MAX_EMAX + 21;
  4088. maxctx.emin = MPD_MIN_EMIN - 21;
  4089. mpd_qmul(tmp, tmp, exp_hash, &maxctx, &status);
  4090. mpd_qrem(tmp, tmp, &p, &maxctx, &status);
  4091. result = mpd_qget_ssize(tmp, &status);
  4092. result = mpd_ispositive(MPD(v)) ? result : -result;
  4093. result = (result == -1) ? -2 : result;
  4094. if (status != 0) {
  4095. if (status & MPD_Malloc_error) {
  4096. goto malloc_error;
  4097. }
  4098. else {
  4099. PyErr_SetString(PyExc_RuntimeError, /* GCOV_NOT_REACHED */
  4100. "dec_hash: internal error: please report"); /* GCOV_NOT_REACHED */
  4101. }
  4102. result = -1; /* GCOV_NOT_REACHED */
  4103. }
  4104. finish:
  4105. if (exp_hash) mpd_del(exp_hash);
  4106. if (tmp) mpd_del(tmp);
  4107. return result;
  4108. malloc_error:
  4109. PyErr_NoMemory();
  4110. result = -1;
  4111. goto finish;
  4112. }
  4113. static Py_hash_t
  4114. dec_hash(PyDecObject *self)
  4115. {
  4116. if (self->hash == -1) {
  4117. self->hash = _dec_hash(self);
  4118. }
  4119. return self->hash;
  4120. }
  4121. /* __reduce__ */
  4122. static PyObject *
  4123. dec_reduce(PyObject *self, PyObject *dummy UNUSED)
  4124. {
  4125. PyObject *result, *str;
  4126. str = dec_str(self);
  4127. if (str == NULL) {
  4128. return NULL;
  4129. }
  4130. result = Py_BuildValue("O(O)", Py_TYPE(self), str);
  4131. Py_DECREF(str);
  4132. return result;
  4133. }
  4134. /* __sizeof__ */
  4135. static PyObject *
  4136. dec_sizeof(PyObject *v, PyObject *dummy UNUSED)
  4137. {
  4138. size_t res = _PyObject_SIZE(Py_TYPE(v));
  4139. if (mpd_isdynamic_data(MPD(v))) {
  4140. res += (size_t)MPD(v)->alloc * sizeof(mpd_uint_t);
  4141. }
  4142. return PyLong_FromSize_t(res);
  4143. }
  4144. /* __trunc__ */
  4145. static PyObject *
  4146. dec_trunc(PyObject *self, PyObject *dummy UNUSED)
  4147. {
  4148. PyObject *context;
  4149. CURRENT_CONTEXT(context);
  4150. return dec_as_long(self, context, MPD_ROUND_DOWN);
  4151. }
  4152. /* real and imag */
  4153. static PyObject *
  4154. dec_real(PyObject *self, void *closure UNUSED)
  4155. {
  4156. return Py_NewRef(self);
  4157. }
  4158. static PyObject *
  4159. dec_imag(PyObject *self UNUSED, void *closure UNUSED)
  4160. {
  4161. PyObject *result;
  4162. result = dec_alloc();
  4163. if (result == NULL) {
  4164. return NULL;
  4165. }
  4166. _dec_settriple(result, MPD_POS, 0, 0);
  4167. return result;
  4168. }
  4169. static PyGetSetDef dec_getsets [] =
  4170. {
  4171. { "real", (getter)dec_real, NULL, NULL, NULL},
  4172. { "imag", (getter)dec_imag, NULL, NULL, NULL},
  4173. {NULL}
  4174. };
  4175. static PyNumberMethods dec_number_methods =
  4176. {
  4177. (binaryfunc) nm_mpd_qadd,
  4178. (binaryfunc) nm_mpd_qsub,
  4179. (binaryfunc) nm_mpd_qmul,
  4180. (binaryfunc) nm_mpd_qrem,
  4181. (binaryfunc) nm_mpd_qdivmod,
  4182. (ternaryfunc) nm_mpd_qpow,
  4183. (unaryfunc) nm_mpd_qminus,
  4184. (unaryfunc) nm_mpd_qplus,
  4185. (unaryfunc) nm_mpd_qabs,
  4186. (inquiry) nm_nonzero,
  4187. (unaryfunc) 0, /* no bit-complement */
  4188. (binaryfunc) 0, /* no shiftl */
  4189. (binaryfunc) 0, /* no shiftr */
  4190. (binaryfunc) 0, /* no bit-and */
  4191. (binaryfunc) 0, /* no bit-xor */
  4192. (binaryfunc) 0, /* no bit-ior */
  4193. (unaryfunc) nm_dec_as_long,
  4194. 0, /* nb_reserved */
  4195. (unaryfunc) PyDec_AsFloat,
  4196. 0, /* binaryfunc nb_inplace_add; */
  4197. 0, /* binaryfunc nb_inplace_subtract; */
  4198. 0, /* binaryfunc nb_inplace_multiply; */
  4199. 0, /* binaryfunc nb_inplace_remainder; */
  4200. 0, /* ternaryfunc nb_inplace_power; */
  4201. 0, /* binaryfunc nb_inplace_lshift; */
  4202. 0, /* binaryfunc nb_inplace_rshift; */
  4203. 0, /* binaryfunc nb_inplace_and; */
  4204. 0, /* binaryfunc nb_inplace_xor; */
  4205. 0, /* binaryfunc nb_inplace_or; */
  4206. (binaryfunc) nm_mpd_qdivint, /* binaryfunc nb_floor_divide; */
  4207. (binaryfunc) nm_mpd_qdiv, /* binaryfunc nb_true_divide; */
  4208. 0, /* binaryfunc nb_inplace_floor_divide; */
  4209. 0, /* binaryfunc nb_inplace_true_divide; */
  4210. };
  4211. static PyMethodDef dec_methods [] =
  4212. {
  4213. /* Unary arithmetic functions, optional context arg */
  4214. { "exp", _PyCFunction_CAST(dec_mpd_qexp), METH_VARARGS|METH_KEYWORDS, doc_exp },
  4215. { "ln", _PyCFunction_CAST(dec_mpd_qln), METH_VARARGS|METH_KEYWORDS, doc_ln },
  4216. { "log10", _PyCFunction_CAST(dec_mpd_qlog10), METH_VARARGS|METH_KEYWORDS, doc_log10 },
  4217. { "next_minus", _PyCFunction_CAST(dec_mpd_qnext_minus), METH_VARARGS|METH_KEYWORDS, doc_next_minus },
  4218. { "next_plus", _PyCFunction_CAST(dec_mpd_qnext_plus), METH_VARARGS|METH_KEYWORDS, doc_next_plus },
  4219. { "normalize", _PyCFunction_CAST(dec_mpd_qreduce), METH_VARARGS|METH_KEYWORDS, doc_normalize },
  4220. { "to_integral", _PyCFunction_CAST(PyDec_ToIntegralValue), METH_VARARGS|METH_KEYWORDS, doc_to_integral },
  4221. { "to_integral_exact", _PyCFunction_CAST(PyDec_ToIntegralExact), METH_VARARGS|METH_KEYWORDS, doc_to_integral_exact },
  4222. { "to_integral_value", _PyCFunction_CAST(PyDec_ToIntegralValue), METH_VARARGS|METH_KEYWORDS, doc_to_integral_value },
  4223. { "sqrt", _PyCFunction_CAST(dec_mpd_qsqrt), METH_VARARGS|METH_KEYWORDS, doc_sqrt },
  4224. /* Binary arithmetic functions, optional context arg */
  4225. { "compare", _PyCFunction_CAST(dec_mpd_qcompare), METH_VARARGS|METH_KEYWORDS, doc_compare },
  4226. { "compare_signal", _PyCFunction_CAST(dec_mpd_qcompare_signal), METH_VARARGS|METH_KEYWORDS, doc_compare_signal },
  4227. { "max", _PyCFunction_CAST(dec_mpd_qmax), METH_VARARGS|METH_KEYWORDS, doc_max },
  4228. { "max_mag", _PyCFunction_CAST(dec_mpd_qmax_mag), METH_VARARGS|METH_KEYWORDS, doc_max_mag },
  4229. { "min", _PyCFunction_CAST(dec_mpd_qmin), METH_VARARGS|METH_KEYWORDS, doc_min },
  4230. { "min_mag", _PyCFunction_CAST(dec_mpd_qmin_mag), METH_VARARGS|METH_KEYWORDS, doc_min_mag },
  4231. { "next_toward", _PyCFunction_CAST(dec_mpd_qnext_toward), METH_VARARGS|METH_KEYWORDS, doc_next_toward },
  4232. { "quantize", _PyCFunction_CAST(dec_mpd_qquantize), METH_VARARGS|METH_KEYWORDS, doc_quantize },
  4233. { "remainder_near", _PyCFunction_CAST(dec_mpd_qrem_near), METH_VARARGS|METH_KEYWORDS, doc_remainder_near },
  4234. /* Ternary arithmetic functions, optional context arg */
  4235. { "fma", _PyCFunction_CAST(dec_mpd_qfma), METH_VARARGS|METH_KEYWORDS, doc_fma },
  4236. /* Boolean functions, no context arg */
  4237. { "is_canonical", dec_mpd_iscanonical, METH_NOARGS, doc_is_canonical },
  4238. { "is_finite", dec_mpd_isfinite, METH_NOARGS, doc_is_finite },
  4239. { "is_infinite", dec_mpd_isinfinite, METH_NOARGS, doc_is_infinite },
  4240. { "is_nan", dec_mpd_isnan, METH_NOARGS, doc_is_nan },
  4241. { "is_qnan", dec_mpd_isqnan, METH_NOARGS, doc_is_qnan },
  4242. { "is_snan", dec_mpd_issnan, METH_NOARGS, doc_is_snan },
  4243. { "is_signed", dec_mpd_issigned, METH_NOARGS, doc_is_signed },
  4244. { "is_zero", dec_mpd_iszero, METH_NOARGS, doc_is_zero },
  4245. /* Boolean functions, optional context arg */
  4246. { "is_normal", _PyCFunction_CAST(dec_mpd_isnormal), METH_VARARGS|METH_KEYWORDS, doc_is_normal },
  4247. { "is_subnormal", _PyCFunction_CAST(dec_mpd_issubnormal), METH_VARARGS|METH_KEYWORDS, doc_is_subnormal },
  4248. /* Unary functions, no context arg */
  4249. { "adjusted", dec_mpd_adjexp, METH_NOARGS, doc_adjusted },
  4250. { "canonical", dec_canonical, METH_NOARGS, doc_canonical },
  4251. { "conjugate", dec_conjugate, METH_NOARGS, doc_conjugate },
  4252. { "radix", dec_mpd_radix, METH_NOARGS, doc_radix },
  4253. /* Unary functions, optional context arg for conversion errors */
  4254. { "copy_abs", dec_mpd_qcopy_abs, METH_NOARGS, doc_copy_abs },
  4255. { "copy_negate", dec_mpd_qcopy_negate, METH_NOARGS, doc_copy_negate },
  4256. /* Unary functions, optional context arg */
  4257. { "logb", _PyCFunction_CAST(dec_mpd_qlogb), METH_VARARGS|METH_KEYWORDS, doc_logb },
  4258. { "logical_invert", _PyCFunction_CAST(dec_mpd_qinvert), METH_VARARGS|METH_KEYWORDS, doc_logical_invert },
  4259. { "number_class", _PyCFunction_CAST(dec_mpd_class), METH_VARARGS|METH_KEYWORDS, doc_number_class },
  4260. { "to_eng_string", _PyCFunction_CAST(dec_mpd_to_eng), METH_VARARGS|METH_KEYWORDS, doc_to_eng_string },
  4261. /* Binary functions, optional context arg for conversion errors */
  4262. { "compare_total", _PyCFunction_CAST(dec_mpd_compare_total), METH_VARARGS|METH_KEYWORDS, doc_compare_total },
  4263. { "compare_total_mag", _PyCFunction_CAST(dec_mpd_compare_total_mag), METH_VARARGS|METH_KEYWORDS, doc_compare_total_mag },
  4264. { "copy_sign", _PyCFunction_CAST(dec_mpd_qcopy_sign), METH_VARARGS|METH_KEYWORDS, doc_copy_sign },
  4265. { "same_quantum", _PyCFunction_CAST(dec_mpd_same_quantum), METH_VARARGS|METH_KEYWORDS, doc_same_quantum },
  4266. /* Binary functions, optional context arg */
  4267. { "logical_and", _PyCFunction_CAST(dec_mpd_qand), METH_VARARGS|METH_KEYWORDS, doc_logical_and },
  4268. { "logical_or", _PyCFunction_CAST(dec_mpd_qor), METH_VARARGS|METH_KEYWORDS, doc_logical_or },
  4269. { "logical_xor", _PyCFunction_CAST(dec_mpd_qxor), METH_VARARGS|METH_KEYWORDS, doc_logical_xor },
  4270. { "rotate", _PyCFunction_CAST(dec_mpd_qrotate), METH_VARARGS|METH_KEYWORDS, doc_rotate },
  4271. { "scaleb", _PyCFunction_CAST(dec_mpd_qscaleb), METH_VARARGS|METH_KEYWORDS, doc_scaleb },
  4272. { "shift", _PyCFunction_CAST(dec_mpd_qshift), METH_VARARGS|METH_KEYWORDS, doc_shift },
  4273. /* Miscellaneous */
  4274. { "from_float", dec_from_float, METH_O|METH_CLASS, doc_from_float },
  4275. { "as_tuple", PyDec_AsTuple, METH_NOARGS, doc_as_tuple },
  4276. { "as_integer_ratio", dec_as_integer_ratio, METH_NOARGS, doc_as_integer_ratio },
  4277. /* Special methods */
  4278. { "__copy__", dec_copy, METH_NOARGS, NULL },
  4279. { "__deepcopy__", dec_copy, METH_O, NULL },
  4280. { "__format__", dec_format, METH_VARARGS, NULL },
  4281. { "__reduce__", dec_reduce, METH_NOARGS, NULL },
  4282. { "__round__", PyDec_Round, METH_VARARGS, NULL },
  4283. { "__ceil__", dec_ceil, METH_NOARGS, NULL },
  4284. { "__floor__", dec_floor, METH_NOARGS, NULL },
  4285. { "__trunc__", dec_trunc, METH_NOARGS, NULL },
  4286. { "__complex__", dec_complex, METH_NOARGS, NULL },
  4287. { "__sizeof__", dec_sizeof, METH_NOARGS, NULL },
  4288. { NULL, NULL, 1 }
  4289. };
  4290. static PyTypeObject PyDec_Type =
  4291. {
  4292. PyVarObject_HEAD_INIT(NULL, 0)
  4293. "decimal.Decimal", /* tp_name */
  4294. sizeof(PyDecObject), /* tp_basicsize */
  4295. 0, /* tp_itemsize */
  4296. (destructor) dec_dealloc, /* tp_dealloc */
  4297. 0, /* tp_vectorcall_offset */
  4298. (getattrfunc) 0, /* tp_getattr */
  4299. (setattrfunc) 0, /* tp_setattr */
  4300. 0, /* tp_as_async */
  4301. (reprfunc) dec_repr, /* tp_repr */
  4302. &dec_number_methods, /* tp_as_number */
  4303. 0, /* tp_as_sequence */
  4304. 0, /* tp_as_mapping */
  4305. (hashfunc) dec_hash, /* tp_hash */
  4306. 0, /* tp_call */
  4307. (reprfunc) dec_str, /* tp_str */
  4308. (getattrofunc) PyObject_GenericGetAttr, /* tp_getattro */
  4309. (setattrofunc) 0, /* tp_setattro */
  4310. (PyBufferProcs *) 0, /* tp_as_buffer */
  4311. (Py_TPFLAGS_DEFAULT|
  4312. Py_TPFLAGS_BASETYPE), /* tp_flags */
  4313. doc_decimal, /* tp_doc */
  4314. 0, /* tp_traverse */
  4315. 0, /* tp_clear */
  4316. dec_richcompare, /* tp_richcompare */
  4317. 0, /* tp_weaklistoffset */
  4318. 0, /* tp_iter */
  4319. 0, /* tp_iternext */
  4320. dec_methods, /* tp_methods */
  4321. 0, /* tp_members */
  4322. dec_getsets, /* tp_getset */
  4323. 0, /* tp_base */
  4324. 0, /* tp_dict */
  4325. 0, /* tp_descr_get */
  4326. 0, /* tp_descr_set */
  4327. 0, /* tp_dictoffset */
  4328. 0, /* tp_init */
  4329. 0, /* tp_alloc */
  4330. dec_new, /* tp_new */
  4331. PyObject_Del, /* tp_free */
  4332. };
  4333. /******************************************************************************/
  4334. /* Context Object, Part 2 */
  4335. /******************************************************************************/
  4336. /************************************************************************/
  4337. /* Macros for converting mpdecimal functions to Context methods */
  4338. /************************************************************************/
  4339. /* Boolean context method. */
  4340. #define DecCtx_BoolFunc(MPDFUNC) \
  4341. static PyObject * \
  4342. ctx_##MPDFUNC(PyObject *context, PyObject *v) \
  4343. { \
  4344. PyObject *ret; \
  4345. PyObject *a; \
  4346. \
  4347. CONVERT_OP_RAISE(&a, v, context); \
  4348. \
  4349. ret = MPDFUNC(MPD(a), CTX(context)) ? incr_true() : incr_false(); \
  4350. Py_DECREF(a); \
  4351. return ret; \
  4352. }
  4353. /* Boolean context method. MPDFUNC does NOT use a context. */
  4354. #define DecCtx_BoolFunc_NO_CTX(MPDFUNC) \
  4355. static PyObject * \
  4356. ctx_##MPDFUNC(PyObject *context, PyObject *v) \
  4357. { \
  4358. PyObject *ret; \
  4359. PyObject *a; \
  4360. \
  4361. CONVERT_OP_RAISE(&a, v, context); \
  4362. \
  4363. ret = MPDFUNC(MPD(a)) ? incr_true() : incr_false(); \
  4364. Py_DECREF(a); \
  4365. return ret; \
  4366. }
  4367. /* Unary context method. */
  4368. #define DecCtx_UnaryFunc(MPDFUNC) \
  4369. static PyObject * \
  4370. ctx_##MPDFUNC(PyObject *context, PyObject *v) \
  4371. { \
  4372. PyObject *result, *a; \
  4373. uint32_t status = 0; \
  4374. \
  4375. CONVERT_OP_RAISE(&a, v, context); \
  4376. \
  4377. if ((result = dec_alloc()) == NULL) { \
  4378. Py_DECREF(a); \
  4379. return NULL; \
  4380. } \
  4381. \
  4382. MPDFUNC(MPD(result), MPD(a), CTX(context), &status); \
  4383. Py_DECREF(a); \
  4384. if (dec_addstatus(context, status)) { \
  4385. Py_DECREF(result); \
  4386. return NULL; \
  4387. } \
  4388. \
  4389. return result; \
  4390. }
  4391. /* Binary context method. */
  4392. #define DecCtx_BinaryFunc(MPDFUNC) \
  4393. static PyObject * \
  4394. ctx_##MPDFUNC(PyObject *context, PyObject *args) \
  4395. { \
  4396. PyObject *v, *w; \
  4397. PyObject *a, *b; \
  4398. PyObject *result; \
  4399. uint32_t status = 0; \
  4400. \
  4401. if (!PyArg_ParseTuple(args, "OO", &v, &w)) { \
  4402. return NULL; \
  4403. } \
  4404. \
  4405. CONVERT_BINOP_RAISE(&a, &b, v, w, context); \
  4406. \
  4407. if ((result = dec_alloc()) == NULL) { \
  4408. Py_DECREF(a); \
  4409. Py_DECREF(b); \
  4410. return NULL; \
  4411. } \
  4412. \
  4413. MPDFUNC(MPD(result), MPD(a), MPD(b), CTX(context), &status); \
  4414. Py_DECREF(a); \
  4415. Py_DECREF(b); \
  4416. if (dec_addstatus(context, status)) { \
  4417. Py_DECREF(result); \
  4418. return NULL; \
  4419. } \
  4420. \
  4421. return result; \
  4422. }
  4423. /*
  4424. * Binary context method. The context is only used for conversion.
  4425. * The actual MPDFUNC does NOT take a context arg.
  4426. */
  4427. #define DecCtx_BinaryFunc_NO_CTX(MPDFUNC) \
  4428. static PyObject * \
  4429. ctx_##MPDFUNC(PyObject *context, PyObject *args) \
  4430. { \
  4431. PyObject *v, *w; \
  4432. PyObject *a, *b; \
  4433. PyObject *result; \
  4434. \
  4435. if (!PyArg_ParseTuple(args, "OO", &v, &w)) { \
  4436. return NULL; \
  4437. } \
  4438. \
  4439. CONVERT_BINOP_RAISE(&a, &b, v, w, context); \
  4440. \
  4441. if ((result = dec_alloc()) == NULL) { \
  4442. Py_DECREF(a); \
  4443. Py_DECREF(b); \
  4444. return NULL; \
  4445. } \
  4446. \
  4447. MPDFUNC(MPD(result), MPD(a), MPD(b)); \
  4448. Py_DECREF(a); \
  4449. Py_DECREF(b); \
  4450. \
  4451. return result; \
  4452. }
  4453. /* Ternary context method. */
  4454. #define DecCtx_TernaryFunc(MPDFUNC) \
  4455. static PyObject * \
  4456. ctx_##MPDFUNC(PyObject *context, PyObject *args) \
  4457. { \
  4458. PyObject *v, *w, *x; \
  4459. PyObject *a, *b, *c; \
  4460. PyObject *result; \
  4461. uint32_t status = 0; \
  4462. \
  4463. if (!PyArg_ParseTuple(args, "OOO", &v, &w, &x)) { \
  4464. return NULL; \
  4465. } \
  4466. \
  4467. CONVERT_TERNOP_RAISE(&a, &b, &c, v, w, x, context); \
  4468. \
  4469. if ((result = dec_alloc()) == NULL) { \
  4470. Py_DECREF(a); \
  4471. Py_DECREF(b); \
  4472. Py_DECREF(c); \
  4473. return NULL; \
  4474. } \
  4475. \
  4476. MPDFUNC(MPD(result), MPD(a), MPD(b), MPD(c), CTX(context), &status); \
  4477. Py_DECREF(a); \
  4478. Py_DECREF(b); \
  4479. Py_DECREF(c); \
  4480. if (dec_addstatus(context, status)) { \
  4481. Py_DECREF(result); \
  4482. return NULL; \
  4483. } \
  4484. \
  4485. return result; \
  4486. }
  4487. /* Unary arithmetic functions */
  4488. DecCtx_UnaryFunc(mpd_qabs)
  4489. DecCtx_UnaryFunc(mpd_qexp)
  4490. DecCtx_UnaryFunc(mpd_qln)
  4491. DecCtx_UnaryFunc(mpd_qlog10)
  4492. DecCtx_UnaryFunc(mpd_qminus)
  4493. DecCtx_UnaryFunc(mpd_qnext_minus)
  4494. DecCtx_UnaryFunc(mpd_qnext_plus)
  4495. DecCtx_UnaryFunc(mpd_qplus)
  4496. DecCtx_UnaryFunc(mpd_qreduce)
  4497. DecCtx_UnaryFunc(mpd_qround_to_int)
  4498. DecCtx_UnaryFunc(mpd_qround_to_intx)
  4499. DecCtx_UnaryFunc(mpd_qsqrt)
  4500. /* Binary arithmetic functions */
  4501. DecCtx_BinaryFunc(mpd_qadd)
  4502. DecCtx_BinaryFunc(mpd_qcompare)
  4503. DecCtx_BinaryFunc(mpd_qcompare_signal)
  4504. DecCtx_BinaryFunc(mpd_qdiv)
  4505. DecCtx_BinaryFunc(mpd_qdivint)
  4506. DecCtx_BinaryFunc(mpd_qmax)
  4507. DecCtx_BinaryFunc(mpd_qmax_mag)
  4508. DecCtx_BinaryFunc(mpd_qmin)
  4509. DecCtx_BinaryFunc(mpd_qmin_mag)
  4510. DecCtx_BinaryFunc(mpd_qmul)
  4511. DecCtx_BinaryFunc(mpd_qnext_toward)
  4512. DecCtx_BinaryFunc(mpd_qquantize)
  4513. DecCtx_BinaryFunc(mpd_qrem)
  4514. DecCtx_BinaryFunc(mpd_qrem_near)
  4515. DecCtx_BinaryFunc(mpd_qsub)
  4516. static PyObject *
  4517. ctx_mpd_qdivmod(PyObject *context, PyObject *args)
  4518. {
  4519. PyObject *v, *w;
  4520. PyObject *a, *b;
  4521. PyObject *q, *r;
  4522. uint32_t status = 0;
  4523. PyObject *ret;
  4524. if (!PyArg_ParseTuple(args, "OO", &v, &w)) {
  4525. return NULL;
  4526. }
  4527. CONVERT_BINOP_RAISE(&a, &b, v, w, context);
  4528. q = dec_alloc();
  4529. if (q == NULL) {
  4530. Py_DECREF(a);
  4531. Py_DECREF(b);
  4532. return NULL;
  4533. }
  4534. r = dec_alloc();
  4535. if (r == NULL) {
  4536. Py_DECREF(a);
  4537. Py_DECREF(b);
  4538. Py_DECREF(q);
  4539. return NULL;
  4540. }
  4541. mpd_qdivmod(MPD(q), MPD(r), MPD(a), MPD(b), CTX(context), &status);
  4542. Py_DECREF(a);
  4543. Py_DECREF(b);
  4544. if (dec_addstatus(context, status)) {
  4545. Py_DECREF(r);
  4546. Py_DECREF(q);
  4547. return NULL;
  4548. }
  4549. ret = Py_BuildValue("(OO)", q, r);
  4550. Py_DECREF(r);
  4551. Py_DECREF(q);
  4552. return ret;
  4553. }
  4554. /* Binary or ternary arithmetic functions */
  4555. static PyObject *
  4556. ctx_mpd_qpow(PyObject *context, PyObject *args, PyObject *kwds)
  4557. {
  4558. static char *kwlist[] = {"a", "b", "modulo", NULL};
  4559. PyObject *base, *exp, *mod = Py_None;
  4560. PyObject *a, *b, *c = NULL;
  4561. PyObject *result;
  4562. uint32_t status = 0;
  4563. if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O", kwlist,
  4564. &base, &exp, &mod)) {
  4565. return NULL;
  4566. }
  4567. CONVERT_BINOP_RAISE(&a, &b, base, exp, context);
  4568. if (mod != Py_None) {
  4569. if (!convert_op(TYPE_ERR, &c, mod, context)) {
  4570. Py_DECREF(a);
  4571. Py_DECREF(b);
  4572. return c;
  4573. }
  4574. }
  4575. result = dec_alloc();
  4576. if (result == NULL) {
  4577. Py_DECREF(a);
  4578. Py_DECREF(b);
  4579. Py_XDECREF(c);
  4580. return NULL;
  4581. }
  4582. if (c == NULL) {
  4583. mpd_qpow(MPD(result), MPD(a), MPD(b),
  4584. CTX(context), &status);
  4585. }
  4586. else {
  4587. mpd_qpowmod(MPD(result), MPD(a), MPD(b), MPD(c),
  4588. CTX(context), &status);
  4589. Py_DECREF(c);
  4590. }
  4591. Py_DECREF(a);
  4592. Py_DECREF(b);
  4593. if (dec_addstatus(context, status)) {
  4594. Py_DECREF(result);
  4595. return NULL;
  4596. }
  4597. return result;
  4598. }
  4599. /* Ternary arithmetic functions */
  4600. DecCtx_TernaryFunc(mpd_qfma)
  4601. /* No argument */
  4602. static PyObject *
  4603. ctx_mpd_radix(PyObject *context, PyObject *dummy)
  4604. {
  4605. return dec_mpd_radix(context, dummy);
  4606. }
  4607. /* Boolean functions: single decimal argument */
  4608. DecCtx_BoolFunc(mpd_isnormal)
  4609. DecCtx_BoolFunc(mpd_issubnormal)
  4610. DecCtx_BoolFunc_NO_CTX(mpd_isfinite)
  4611. DecCtx_BoolFunc_NO_CTX(mpd_isinfinite)
  4612. DecCtx_BoolFunc_NO_CTX(mpd_isnan)
  4613. DecCtx_BoolFunc_NO_CTX(mpd_isqnan)
  4614. DecCtx_BoolFunc_NO_CTX(mpd_issigned)
  4615. DecCtx_BoolFunc_NO_CTX(mpd_issnan)
  4616. DecCtx_BoolFunc_NO_CTX(mpd_iszero)
  4617. static PyObject *
  4618. ctx_iscanonical(PyObject *context UNUSED, PyObject *v)
  4619. {
  4620. if (!PyDec_Check(v)) {
  4621. PyErr_SetString(PyExc_TypeError,
  4622. "argument must be a Decimal");
  4623. return NULL;
  4624. }
  4625. return mpd_iscanonical(MPD(v)) ? incr_true() : incr_false();
  4626. }
  4627. /* Functions with a single decimal argument */
  4628. static PyObject *
  4629. PyDecContext_Apply(PyObject *context, PyObject *v)
  4630. {
  4631. PyObject *result, *a;
  4632. CONVERT_OP_RAISE(&a, v, context);
  4633. result = dec_apply(a, context);
  4634. Py_DECREF(a);
  4635. return result;
  4636. }
  4637. static PyObject *
  4638. ctx_canonical(PyObject *context UNUSED, PyObject *v)
  4639. {
  4640. if (!PyDec_Check(v)) {
  4641. PyErr_SetString(PyExc_TypeError,
  4642. "argument must be a Decimal");
  4643. return NULL;
  4644. }
  4645. return Py_NewRef(v);
  4646. }
  4647. static PyObject *
  4648. ctx_mpd_qcopy_abs(PyObject *context, PyObject *v)
  4649. {
  4650. PyObject *result, *a;
  4651. uint32_t status = 0;
  4652. CONVERT_OP_RAISE(&a, v, context);
  4653. result = dec_alloc();
  4654. if (result == NULL) {
  4655. Py_DECREF(a);
  4656. return NULL;
  4657. }
  4658. mpd_qcopy_abs(MPD(result), MPD(a), &status);
  4659. Py_DECREF(a);
  4660. if (dec_addstatus(context, status)) {
  4661. Py_DECREF(result);
  4662. return NULL;
  4663. }
  4664. return result;
  4665. }
  4666. static PyObject *
  4667. ctx_copy_decimal(PyObject *context, PyObject *v)
  4668. {
  4669. PyObject *result;
  4670. CONVERT_OP_RAISE(&result, v, context);
  4671. return result;
  4672. }
  4673. static PyObject *
  4674. ctx_mpd_qcopy_negate(PyObject *context, PyObject *v)
  4675. {
  4676. PyObject *result, *a;
  4677. uint32_t status = 0;
  4678. CONVERT_OP_RAISE(&a, v, context);
  4679. result = dec_alloc();
  4680. if (result == NULL) {
  4681. Py_DECREF(a);
  4682. return NULL;
  4683. }
  4684. mpd_qcopy_negate(MPD(result), MPD(a), &status);
  4685. Py_DECREF(a);
  4686. if (dec_addstatus(context, status)) {
  4687. Py_DECREF(result);
  4688. return NULL;
  4689. }
  4690. return result;
  4691. }
  4692. DecCtx_UnaryFunc(mpd_qlogb)
  4693. DecCtx_UnaryFunc(mpd_qinvert)
  4694. static PyObject *
  4695. ctx_mpd_class(PyObject *context, PyObject *v)
  4696. {
  4697. PyObject *a;
  4698. const char *cp;
  4699. CONVERT_OP_RAISE(&a, v, context);
  4700. cp = mpd_class(MPD(a), CTX(context));
  4701. Py_DECREF(a);
  4702. return PyUnicode_FromString(cp);
  4703. }
  4704. static PyObject *
  4705. ctx_mpd_to_sci(PyObject *context, PyObject *v)
  4706. {
  4707. PyObject *result;
  4708. PyObject *a;
  4709. mpd_ssize_t size;
  4710. char *s;
  4711. CONVERT_OP_RAISE(&a, v, context);
  4712. size = mpd_to_sci_size(&s, MPD(a), CtxCaps(context));
  4713. Py_DECREF(a);
  4714. if (size < 0) {
  4715. PyErr_NoMemory();
  4716. return NULL;
  4717. }
  4718. result = unicode_fromascii(s, size);
  4719. mpd_free(s);
  4720. return result;
  4721. }
  4722. static PyObject *
  4723. ctx_mpd_to_eng(PyObject *context, PyObject *v)
  4724. {
  4725. PyObject *result;
  4726. PyObject *a;
  4727. mpd_ssize_t size;
  4728. char *s;
  4729. CONVERT_OP_RAISE(&a, v, context);
  4730. size = mpd_to_eng_size(&s, MPD(a), CtxCaps(context));
  4731. Py_DECREF(a);
  4732. if (size < 0) {
  4733. PyErr_NoMemory();
  4734. return NULL;
  4735. }
  4736. result = unicode_fromascii(s, size);
  4737. mpd_free(s);
  4738. return result;
  4739. }
  4740. /* Functions with two decimal arguments */
  4741. DecCtx_BinaryFunc_NO_CTX(mpd_compare_total)
  4742. DecCtx_BinaryFunc_NO_CTX(mpd_compare_total_mag)
  4743. static PyObject *
  4744. ctx_mpd_qcopy_sign(PyObject *context, PyObject *args)
  4745. {
  4746. PyObject *v, *w;
  4747. PyObject *a, *b;
  4748. PyObject *result;
  4749. uint32_t status = 0;
  4750. if (!PyArg_ParseTuple(args, "OO", &v, &w)) {
  4751. return NULL;
  4752. }
  4753. CONVERT_BINOP_RAISE(&a, &b, v, w, context);
  4754. result = dec_alloc();
  4755. if (result == NULL) {
  4756. Py_DECREF(a);
  4757. Py_DECREF(b);
  4758. return NULL;
  4759. }
  4760. mpd_qcopy_sign(MPD(result), MPD(a), MPD(b), &status);
  4761. Py_DECREF(a);
  4762. Py_DECREF(b);
  4763. if (dec_addstatus(context, status)) {
  4764. Py_DECREF(result);
  4765. return NULL;
  4766. }
  4767. return result;
  4768. }
  4769. DecCtx_BinaryFunc(mpd_qand)
  4770. DecCtx_BinaryFunc(mpd_qor)
  4771. DecCtx_BinaryFunc(mpd_qxor)
  4772. DecCtx_BinaryFunc(mpd_qrotate)
  4773. DecCtx_BinaryFunc(mpd_qscaleb)
  4774. DecCtx_BinaryFunc(mpd_qshift)
  4775. static PyObject *
  4776. ctx_mpd_same_quantum(PyObject *context, PyObject *args)
  4777. {
  4778. PyObject *v, *w;
  4779. PyObject *a, *b;
  4780. PyObject *result;
  4781. if (!PyArg_ParseTuple(args, "OO", &v, &w)) {
  4782. return NULL;
  4783. }
  4784. CONVERT_BINOP_RAISE(&a, &b, v, w, context);
  4785. result = mpd_same_quantum(MPD(a), MPD(b)) ? incr_true() : incr_false();
  4786. Py_DECREF(a);
  4787. Py_DECREF(b);
  4788. return result;
  4789. }
  4790. static PyMethodDef context_methods [] =
  4791. {
  4792. /* Unary arithmetic functions */
  4793. { "abs", ctx_mpd_qabs, METH_O, doc_ctx_abs },
  4794. { "exp", ctx_mpd_qexp, METH_O, doc_ctx_exp },
  4795. { "ln", ctx_mpd_qln, METH_O, doc_ctx_ln },
  4796. { "log10", ctx_mpd_qlog10, METH_O, doc_ctx_log10 },
  4797. { "minus", ctx_mpd_qminus, METH_O, doc_ctx_minus },
  4798. { "next_minus", ctx_mpd_qnext_minus, METH_O, doc_ctx_next_minus },
  4799. { "next_plus", ctx_mpd_qnext_plus, METH_O, doc_ctx_next_plus },
  4800. { "normalize", ctx_mpd_qreduce, METH_O, doc_ctx_normalize },
  4801. { "plus", ctx_mpd_qplus, METH_O, doc_ctx_plus },
  4802. { "to_integral", ctx_mpd_qround_to_int, METH_O, doc_ctx_to_integral },
  4803. { "to_integral_exact", ctx_mpd_qround_to_intx, METH_O, doc_ctx_to_integral_exact },
  4804. { "to_integral_value", ctx_mpd_qround_to_int, METH_O, doc_ctx_to_integral_value },
  4805. { "sqrt", ctx_mpd_qsqrt, METH_O, doc_ctx_sqrt },
  4806. /* Binary arithmetic functions */
  4807. { "add", ctx_mpd_qadd, METH_VARARGS, doc_ctx_add },
  4808. { "compare", ctx_mpd_qcompare, METH_VARARGS, doc_ctx_compare },
  4809. { "compare_signal", ctx_mpd_qcompare_signal, METH_VARARGS, doc_ctx_compare_signal },
  4810. { "divide", ctx_mpd_qdiv, METH_VARARGS, doc_ctx_divide },
  4811. { "divide_int", ctx_mpd_qdivint, METH_VARARGS, doc_ctx_divide_int },
  4812. { "divmod", ctx_mpd_qdivmod, METH_VARARGS, doc_ctx_divmod },
  4813. { "max", ctx_mpd_qmax, METH_VARARGS, doc_ctx_max },
  4814. { "max_mag", ctx_mpd_qmax_mag, METH_VARARGS, doc_ctx_max_mag },
  4815. { "min", ctx_mpd_qmin, METH_VARARGS, doc_ctx_min },
  4816. { "min_mag", ctx_mpd_qmin_mag, METH_VARARGS, doc_ctx_min_mag },
  4817. { "multiply", ctx_mpd_qmul, METH_VARARGS, doc_ctx_multiply },
  4818. { "next_toward", ctx_mpd_qnext_toward, METH_VARARGS, doc_ctx_next_toward },
  4819. { "quantize", ctx_mpd_qquantize, METH_VARARGS, doc_ctx_quantize },
  4820. { "remainder", ctx_mpd_qrem, METH_VARARGS, doc_ctx_remainder },
  4821. { "remainder_near", ctx_mpd_qrem_near, METH_VARARGS, doc_ctx_remainder_near },
  4822. { "subtract", ctx_mpd_qsub, METH_VARARGS, doc_ctx_subtract },
  4823. /* Binary or ternary arithmetic functions */
  4824. { "power", _PyCFunction_CAST(ctx_mpd_qpow), METH_VARARGS|METH_KEYWORDS, doc_ctx_power },
  4825. /* Ternary arithmetic functions */
  4826. { "fma", ctx_mpd_qfma, METH_VARARGS, doc_ctx_fma },
  4827. /* No argument */
  4828. { "Etiny", context_getetiny, METH_NOARGS, doc_ctx_Etiny },
  4829. { "Etop", context_getetop, METH_NOARGS, doc_ctx_Etop },
  4830. { "radix", ctx_mpd_radix, METH_NOARGS, doc_ctx_radix },
  4831. /* Boolean functions */
  4832. { "is_canonical", ctx_iscanonical, METH_O, doc_ctx_is_canonical },
  4833. { "is_finite", ctx_mpd_isfinite, METH_O, doc_ctx_is_finite },
  4834. { "is_infinite", ctx_mpd_isinfinite, METH_O, doc_ctx_is_infinite },
  4835. { "is_nan", ctx_mpd_isnan, METH_O, doc_ctx_is_nan },
  4836. { "is_normal", ctx_mpd_isnormal, METH_O, doc_ctx_is_normal },
  4837. { "is_qnan", ctx_mpd_isqnan, METH_O, doc_ctx_is_qnan },
  4838. { "is_signed", ctx_mpd_issigned, METH_O, doc_ctx_is_signed },
  4839. { "is_snan", ctx_mpd_issnan, METH_O, doc_ctx_is_snan },
  4840. { "is_subnormal", ctx_mpd_issubnormal, METH_O, doc_ctx_is_subnormal },
  4841. { "is_zero", ctx_mpd_iszero, METH_O, doc_ctx_is_zero },
  4842. /* Functions with a single decimal argument */
  4843. { "_apply", PyDecContext_Apply, METH_O, NULL }, /* alias for apply */
  4844. #ifdef EXTRA_FUNCTIONALITY
  4845. { "apply", PyDecContext_Apply, METH_O, doc_ctx_apply },
  4846. #endif
  4847. { "canonical", ctx_canonical, METH_O, doc_ctx_canonical },
  4848. { "copy_abs", ctx_mpd_qcopy_abs, METH_O, doc_ctx_copy_abs },
  4849. { "copy_decimal", ctx_copy_decimal, METH_O, doc_ctx_copy_decimal },
  4850. { "copy_negate", ctx_mpd_qcopy_negate, METH_O, doc_ctx_copy_negate },
  4851. { "logb", ctx_mpd_qlogb, METH_O, doc_ctx_logb },
  4852. { "logical_invert", ctx_mpd_qinvert, METH_O, doc_ctx_logical_invert },
  4853. { "number_class", ctx_mpd_class, METH_O, doc_ctx_number_class },
  4854. { "to_sci_string", ctx_mpd_to_sci, METH_O, doc_ctx_to_sci_string },
  4855. { "to_eng_string", ctx_mpd_to_eng, METH_O, doc_ctx_to_eng_string },
  4856. /* Functions with two decimal arguments */
  4857. { "compare_total", ctx_mpd_compare_total, METH_VARARGS, doc_ctx_compare_total },
  4858. { "compare_total_mag", ctx_mpd_compare_total_mag, METH_VARARGS, doc_ctx_compare_total_mag },
  4859. { "copy_sign", ctx_mpd_qcopy_sign, METH_VARARGS, doc_ctx_copy_sign },
  4860. { "logical_and", ctx_mpd_qand, METH_VARARGS, doc_ctx_logical_and },
  4861. { "logical_or", ctx_mpd_qor, METH_VARARGS, doc_ctx_logical_or },
  4862. { "logical_xor", ctx_mpd_qxor, METH_VARARGS, doc_ctx_logical_xor },
  4863. { "rotate", ctx_mpd_qrotate, METH_VARARGS, doc_ctx_rotate },
  4864. { "same_quantum", ctx_mpd_same_quantum, METH_VARARGS, doc_ctx_same_quantum },
  4865. { "scaleb", ctx_mpd_qscaleb, METH_VARARGS, doc_ctx_scaleb },
  4866. { "shift", ctx_mpd_qshift, METH_VARARGS, doc_ctx_shift },
  4867. /* Set context values */
  4868. { "clear_flags", context_clear_flags, METH_NOARGS, doc_ctx_clear_flags },
  4869. { "clear_traps", context_clear_traps, METH_NOARGS, doc_ctx_clear_traps },
  4870. #ifdef CONFIG_32
  4871. /* Unsafe set functions with relaxed range checks */
  4872. { "_unsafe_setprec", context_unsafe_setprec, METH_O, NULL },
  4873. { "_unsafe_setemin", context_unsafe_setemin, METH_O, NULL },
  4874. { "_unsafe_setemax", context_unsafe_setemax, METH_O, NULL },
  4875. #endif
  4876. /* Miscellaneous */
  4877. { "__copy__", (PyCFunction)context_copy, METH_NOARGS, NULL },
  4878. { "__reduce__", context_reduce, METH_NOARGS, NULL },
  4879. { "copy", (PyCFunction)context_copy, METH_NOARGS, doc_ctx_copy },
  4880. { "create_decimal", ctx_create_decimal, METH_VARARGS, doc_ctx_create_decimal },
  4881. { "create_decimal_from_float", ctx_from_float, METH_O, doc_ctx_create_decimal_from_float },
  4882. { NULL, NULL, 1 }
  4883. };
  4884. static PyTypeObject PyDecContext_Type =
  4885. {
  4886. PyVarObject_HEAD_INIT(NULL, 0)
  4887. "decimal.Context", /* tp_name */
  4888. sizeof(PyDecContextObject), /* tp_basicsize */
  4889. 0, /* tp_itemsize */
  4890. (destructor) context_dealloc, /* tp_dealloc */
  4891. 0, /* tp_vectorcall_offset */
  4892. (getattrfunc) 0, /* tp_getattr */
  4893. (setattrfunc) 0, /* tp_setattr */
  4894. 0, /* tp_as_async */
  4895. (reprfunc) context_repr, /* tp_repr */
  4896. 0, /* tp_as_number */
  4897. 0, /* tp_as_sequence */
  4898. 0, /* tp_as_mapping */
  4899. (hashfunc) 0, /* tp_hash */
  4900. 0, /* tp_call */
  4901. 0, /* tp_str */
  4902. (getattrofunc) context_getattr, /* tp_getattro */
  4903. (setattrofunc) context_setattr, /* tp_setattro */
  4904. (PyBufferProcs *) 0, /* tp_as_buffer */
  4905. Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
  4906. doc_context, /* tp_doc */
  4907. 0, /* tp_traverse */
  4908. 0, /* tp_clear */
  4909. 0, /* tp_richcompare */
  4910. 0, /* tp_weaklistoffset */
  4911. 0, /* tp_iter */
  4912. 0, /* tp_iternext */
  4913. context_methods, /* tp_methods */
  4914. 0, /* tp_members */
  4915. context_getsets, /* tp_getset */
  4916. 0, /* tp_base */
  4917. 0, /* tp_dict */
  4918. 0, /* tp_descr_get */
  4919. 0, /* tp_descr_set */
  4920. 0, /* tp_dictoffset */
  4921. context_init, /* tp_init */
  4922. 0, /* tp_alloc */
  4923. context_new, /* tp_new */
  4924. PyObject_Del, /* tp_free */
  4925. };
  4926. static PyMethodDef _decimal_methods [] =
  4927. {
  4928. { "getcontext", (PyCFunction)PyDec_GetCurrentContext, METH_NOARGS, doc_getcontext},
  4929. { "setcontext", (PyCFunction)PyDec_SetCurrentContext, METH_O, doc_setcontext},
  4930. { "localcontext", _PyCFunction_CAST(ctxmanager_new), METH_VARARGS|METH_KEYWORDS, doc_localcontext},
  4931. #ifdef EXTRA_FUNCTIONALITY
  4932. { "IEEEContext", (PyCFunction)ieee_context, METH_O, doc_ieee_context},
  4933. #endif
  4934. { NULL, NULL, 1, NULL }
  4935. };
  4936. static struct PyModuleDef _decimal_module = {
  4937. PyModuleDef_HEAD_INIT,
  4938. "decimal",
  4939. doc__decimal,
  4940. -1,
  4941. _decimal_methods,
  4942. NULL,
  4943. NULL,
  4944. NULL,
  4945. NULL
  4946. };
  4947. struct ssize_constmap { const char *name; mpd_ssize_t val; };
  4948. static struct ssize_constmap ssize_constants [] = {
  4949. {"MAX_PREC", MPD_MAX_PREC},
  4950. {"MAX_EMAX", MPD_MAX_EMAX},
  4951. {"MIN_EMIN", MPD_MIN_EMIN},
  4952. {"MIN_ETINY", MPD_MIN_ETINY},
  4953. {NULL}
  4954. };
  4955. struct int_constmap { const char *name; int val; };
  4956. static struct int_constmap int_constants [] = {
  4957. /* int constants */
  4958. #ifdef EXTRA_FUNCTIONALITY
  4959. {"DECIMAL32", MPD_DECIMAL32},
  4960. {"DECIMAL64", MPD_DECIMAL64},
  4961. {"DECIMAL128", MPD_DECIMAL128},
  4962. {"IEEE_CONTEXT_MAX_BITS", MPD_IEEE_CONTEXT_MAX_BITS},
  4963. /* int condition flags */
  4964. {"DecClamped", MPD_Clamped},
  4965. {"DecConversionSyntax", MPD_Conversion_syntax},
  4966. {"DecDivisionByZero", MPD_Division_by_zero},
  4967. {"DecDivisionImpossible", MPD_Division_impossible},
  4968. {"DecDivisionUndefined", MPD_Division_undefined},
  4969. {"DecFpuError", MPD_Fpu_error},
  4970. {"DecInexact", MPD_Inexact},
  4971. {"DecInvalidContext", MPD_Invalid_context},
  4972. {"DecInvalidOperation", MPD_Invalid_operation},
  4973. {"DecIEEEInvalidOperation", MPD_IEEE_Invalid_operation},
  4974. {"DecMallocError", MPD_Malloc_error},
  4975. {"DecFloatOperation", MPD_Float_operation},
  4976. {"DecOverflow", MPD_Overflow},
  4977. {"DecRounded", MPD_Rounded},
  4978. {"DecSubnormal", MPD_Subnormal},
  4979. {"DecUnderflow", MPD_Underflow},
  4980. {"DecErrors", MPD_Errors},
  4981. {"DecTraps", MPD_Traps},
  4982. #endif
  4983. {NULL}
  4984. };
  4985. #define CHECK_INT(expr) \
  4986. do { if ((expr) < 0) goto error; } while (0)
  4987. #define ASSIGN_PTR(result, expr) \
  4988. do { result = (expr); if (result == NULL) goto error; } while (0)
  4989. #define CHECK_PTR(expr) \
  4990. do { if ((expr) == NULL) goto error; } while (0)
  4991. static PyCFunction
  4992. cfunc_noargs(PyTypeObject *t, const char *name)
  4993. {
  4994. struct PyMethodDef *m;
  4995. if (t->tp_methods == NULL) {
  4996. goto error;
  4997. }
  4998. for (m = t->tp_methods; m->ml_name != NULL; m++) {
  4999. if (strcmp(name, m->ml_name) == 0) {
  5000. if (!(m->ml_flags & METH_NOARGS)) {
  5001. goto error;
  5002. }
  5003. return m->ml_meth;
  5004. }
  5005. }
  5006. error:
  5007. PyErr_Format(PyExc_RuntimeError,
  5008. "internal error: could not find method %s", name);
  5009. return NULL;
  5010. }
  5011. PyMODINIT_FUNC
  5012. PyInit__decimal(void)
  5013. {
  5014. PyObject *m = NULL;
  5015. PyObject *numbers = NULL;
  5016. PyObject *Number = NULL;
  5017. PyObject *collections = NULL;
  5018. PyObject *collections_abc = NULL;
  5019. PyObject *MutableMapping = NULL;
  5020. PyObject *obj = NULL;
  5021. DecCondMap *cm;
  5022. struct ssize_constmap *ssize_cm;
  5023. struct int_constmap *int_cm;
  5024. int i;
  5025. /* Init libmpdec */
  5026. mpd_traphandler = dec_traphandler;
  5027. mpd_mallocfunc = PyMem_Malloc;
  5028. mpd_reallocfunc = PyMem_Realloc;
  5029. mpd_callocfunc = mpd_callocfunc_em;
  5030. mpd_free = PyMem_Free;
  5031. mpd_setminalloc(_Py_DEC_MINALLOC);
  5032. /* Init external C-API functions */
  5033. _py_long_multiply = PyLong_Type.tp_as_number->nb_multiply;
  5034. _py_long_floor_divide = PyLong_Type.tp_as_number->nb_floor_divide;
  5035. _py_long_power = PyLong_Type.tp_as_number->nb_power;
  5036. _py_float_abs = PyFloat_Type.tp_as_number->nb_absolute;
  5037. ASSIGN_PTR(_py_float_as_integer_ratio, cfunc_noargs(&PyFloat_Type,
  5038. "as_integer_ratio"));
  5039. ASSIGN_PTR(_py_long_bit_length, cfunc_noargs(&PyLong_Type, "bit_length"));
  5040. /* Init types */
  5041. PyDec_Type.tp_base = &PyBaseObject_Type;
  5042. PyDecContext_Type.tp_base = &PyBaseObject_Type;
  5043. PyDecContextManager_Type.tp_base = &PyBaseObject_Type;
  5044. PyDecSignalDictMixin_Type.tp_base = &PyBaseObject_Type;
  5045. CHECK_INT(PyType_Ready(&PyDec_Type));
  5046. CHECK_INT(PyType_Ready(&PyDecContext_Type));
  5047. CHECK_INT(PyType_Ready(&PyDecSignalDictMixin_Type));
  5048. CHECK_INT(PyType_Ready(&PyDecContextManager_Type));
  5049. ASSIGN_PTR(obj, PyUnicode_FromString("decimal"));
  5050. CHECK_INT(PyDict_SetItemString(PyDec_Type.tp_dict, "__module__", obj));
  5051. CHECK_INT(PyDict_SetItemString(PyDecContext_Type.tp_dict,
  5052. "__module__", obj));
  5053. Py_CLEAR(obj);
  5054. /* Numeric abstract base classes */
  5055. ASSIGN_PTR(numbers, PyImport_ImportModule("numbers"));
  5056. ASSIGN_PTR(Number, PyObject_GetAttrString(numbers, "Number"));
  5057. /* Register Decimal with the Number abstract base class */
  5058. ASSIGN_PTR(obj, PyObject_CallMethod(Number, "register", "(O)",
  5059. (PyObject *)&PyDec_Type));
  5060. Py_CLEAR(obj);
  5061. /* Rational is a global variable used for fraction comparisons. */
  5062. ASSIGN_PTR(Rational, PyObject_GetAttrString(numbers, "Rational"));
  5063. /* Done with numbers, Number */
  5064. Py_CLEAR(numbers);
  5065. Py_CLEAR(Number);
  5066. /* DecimalTuple */
  5067. ASSIGN_PTR(collections, PyImport_ImportModule("collections"));
  5068. ASSIGN_PTR(DecimalTuple, (PyTypeObject *)PyObject_CallMethod(collections,
  5069. "namedtuple", "(ss)", "DecimalTuple",
  5070. "sign digits exponent"));
  5071. ASSIGN_PTR(obj, PyUnicode_FromString("decimal"));
  5072. CHECK_INT(PyDict_SetItemString(DecimalTuple->tp_dict, "__module__", obj));
  5073. Py_CLEAR(obj);
  5074. /* MutableMapping */
  5075. ASSIGN_PTR(collections_abc, PyImport_ImportModule("collections.abc"));
  5076. ASSIGN_PTR(MutableMapping, PyObject_GetAttrString(collections_abc,
  5077. "MutableMapping"));
  5078. /* Create SignalDict type */
  5079. ASSIGN_PTR(PyDecSignalDict_Type,
  5080. (PyTypeObject *)PyObject_CallFunction(
  5081. (PyObject *)&PyType_Type, "s(OO){}",
  5082. "SignalDict", &PyDecSignalDictMixin_Type,
  5083. MutableMapping));
  5084. /* Done with collections, MutableMapping */
  5085. Py_CLEAR(collections);
  5086. Py_CLEAR(collections_abc);
  5087. Py_CLEAR(MutableMapping);
  5088. /* Create the module */
  5089. ASSIGN_PTR(m, PyModule_Create(&_decimal_module));
  5090. /* Add types to the module */
  5091. CHECK_INT(PyModule_AddObjectRef(m, "Decimal", (PyObject *)&PyDec_Type));
  5092. CHECK_INT(PyModule_AddObjectRef(m, "Context", (PyObject *)&PyDecContext_Type));
  5093. CHECK_INT(PyModule_AddObjectRef(m, "DecimalTuple", (PyObject *)DecimalTuple));
  5094. /* Create top level exception */
  5095. ASSIGN_PTR(DecimalException, PyErr_NewException(
  5096. "decimal.DecimalException",
  5097. PyExc_ArithmeticError, NULL));
  5098. CHECK_INT(PyModule_AddObjectRef(m, "DecimalException", DecimalException));
  5099. /* Create signal tuple */
  5100. ASSIGN_PTR(SignalTuple, PyTuple_New(SIGNAL_MAP_LEN));
  5101. /* Add exceptions that correspond to IEEE signals */
  5102. for (i = SIGNAL_MAP_LEN-1; i >= 0; i--) {
  5103. PyObject *base;
  5104. cm = signal_map + i;
  5105. switch (cm->flag) {
  5106. case MPD_Float_operation:
  5107. base = PyTuple_Pack(2, DecimalException, PyExc_TypeError);
  5108. break;
  5109. case MPD_Division_by_zero:
  5110. base = PyTuple_Pack(2, DecimalException, PyExc_ZeroDivisionError);
  5111. break;
  5112. case MPD_Overflow:
  5113. base = PyTuple_Pack(2, signal_map[INEXACT].ex,
  5114. signal_map[ROUNDED].ex);
  5115. break;
  5116. case MPD_Underflow:
  5117. base = PyTuple_Pack(3, signal_map[INEXACT].ex,
  5118. signal_map[ROUNDED].ex,
  5119. signal_map[SUBNORMAL].ex);
  5120. break;
  5121. default:
  5122. base = PyTuple_Pack(1, DecimalException);
  5123. break;
  5124. }
  5125. if (base == NULL) {
  5126. goto error; /* GCOV_NOT_REACHED */
  5127. }
  5128. ASSIGN_PTR(cm->ex, PyErr_NewException(cm->fqname, base, NULL));
  5129. Py_DECREF(base);
  5130. /* add to module */
  5131. CHECK_INT(PyModule_AddObjectRef(m, cm->name, cm->ex));
  5132. /* add to signal tuple */
  5133. PyTuple_SET_ITEM(SignalTuple, i, Py_NewRef(cm->ex));
  5134. }
  5135. /*
  5136. * Unfortunately, InvalidOperation is a signal that comprises
  5137. * several conditions, including InvalidOperation! Naming the
  5138. * signal IEEEInvalidOperation would prevent the confusion.
  5139. */
  5140. cond_map[0].ex = signal_map[0].ex;
  5141. /* Add remaining exceptions, inherit from InvalidOperation */
  5142. for (cm = cond_map+1; cm->name != NULL; cm++) {
  5143. PyObject *base;
  5144. if (cm->flag == MPD_Division_undefined) {
  5145. base = PyTuple_Pack(2, signal_map[0].ex, PyExc_ZeroDivisionError);
  5146. }
  5147. else {
  5148. base = PyTuple_Pack(1, signal_map[0].ex);
  5149. }
  5150. if (base == NULL) {
  5151. goto error; /* GCOV_NOT_REACHED */
  5152. }
  5153. ASSIGN_PTR(cm->ex, PyErr_NewException(cm->fqname, base, NULL));
  5154. Py_DECREF(base);
  5155. CHECK_INT(PyModule_AddObjectRef(m, cm->name, cm->ex));
  5156. }
  5157. /* Init default context template first */
  5158. ASSIGN_PTR(default_context_template,
  5159. PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL));
  5160. CHECK_INT(PyModule_AddObjectRef(m, "DefaultContext",
  5161. default_context_template));
  5162. #ifndef WITH_DECIMAL_CONTEXTVAR
  5163. ASSIGN_PTR(tls_context_key, PyUnicode_FromString("___DECIMAL_CTX__"));
  5164. CHECK_INT(PyModule_AddObjectRef(m, "HAVE_CONTEXTVAR", Py_False));
  5165. #else
  5166. ASSIGN_PTR(current_context_var, PyContextVar_New("decimal_context", NULL));
  5167. CHECK_INT(PyModule_AddObjectRef(m, "HAVE_CONTEXTVAR", Py_True));
  5168. #endif
  5169. CHECK_INT(PyModule_AddObjectRef(m, "HAVE_THREADS", Py_True));
  5170. /* Init basic context template */
  5171. ASSIGN_PTR(basic_context_template,
  5172. PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL));
  5173. init_basic_context(basic_context_template);
  5174. CHECK_INT(PyModule_AddObjectRef(m, "BasicContext",
  5175. basic_context_template));
  5176. /* Init extended context template */
  5177. ASSIGN_PTR(extended_context_template,
  5178. PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL));
  5179. init_extended_context(extended_context_template);
  5180. CHECK_INT(PyModule_AddObjectRef(m, "ExtendedContext",
  5181. extended_context_template));
  5182. /* Init mpd_ssize_t constants */
  5183. for (ssize_cm = ssize_constants; ssize_cm->name != NULL; ssize_cm++) {
  5184. ASSIGN_PTR(obj, PyLong_FromSsize_t(ssize_cm->val));
  5185. CHECK_INT(PyModule_AddObject(m, ssize_cm->name, obj));
  5186. obj = NULL;
  5187. }
  5188. /* Init int constants */
  5189. for (int_cm = int_constants; int_cm->name != NULL; int_cm++) {
  5190. CHECK_INT(PyModule_AddIntConstant(m, int_cm->name,
  5191. int_cm->val));
  5192. }
  5193. /* Init string constants */
  5194. for (i = 0; i < _PY_DEC_ROUND_GUARD; i++) {
  5195. ASSIGN_PTR(round_map[i], PyUnicode_InternFromString(mpd_round_string[i]));
  5196. CHECK_INT(PyModule_AddObjectRef(m, mpd_round_string[i], round_map[i]));
  5197. }
  5198. /* Add specification version number */
  5199. CHECK_INT(PyModule_AddStringConstant(m, "__version__", "1.70"));
  5200. CHECK_INT(PyModule_AddStringConstant(m, "__libmpdec_version__", mpd_version()));
  5201. return m;
  5202. error:
  5203. Py_CLEAR(obj); /* GCOV_NOT_REACHED */
  5204. Py_CLEAR(numbers); /* GCOV_NOT_REACHED */
  5205. Py_CLEAR(Number); /* GCOV_NOT_REACHED */
  5206. Py_CLEAR(Rational); /* GCOV_NOT_REACHED */
  5207. Py_CLEAR(collections); /* GCOV_NOT_REACHED */
  5208. Py_CLEAR(collections_abc); /* GCOV_NOT_REACHED */
  5209. Py_CLEAR(MutableMapping); /* GCOV_NOT_REACHED */
  5210. Py_CLEAR(SignalTuple); /* GCOV_NOT_REACHED */
  5211. Py_CLEAR(DecimalTuple); /* GCOV_NOT_REACHED */
  5212. Py_CLEAR(default_context_template); /* GCOV_NOT_REACHED */
  5213. #ifndef WITH_DECIMAL_CONTEXTVAR
  5214. Py_CLEAR(tls_context_key); /* GCOV_NOT_REACHED */
  5215. #else
  5216. Py_CLEAR(current_context_var); /* GCOV_NOT_REACHED */
  5217. #endif
  5218. Py_CLEAR(basic_context_template); /* GCOV_NOT_REACHED */
  5219. Py_CLEAR(extended_context_template); /* GCOV_NOT_REACHED */
  5220. Py_CLEAR(m); /* GCOV_NOT_REACHED */
  5221. return NULL; /* GCOV_NOT_REACHED */
  5222. }