_decimal.c 173 KB

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