decNumber.cpp 396 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190
  1. // © 2016 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. /* ------------------------------------------------------------------ */
  4. /* Decimal Number arithmetic module */
  5. /* ------------------------------------------------------------------ */
  6. /* Copyright (c) IBM Corporation, 2000-2014. All rights reserved. */
  7. /* */
  8. /* This software is made available under the terms of the */
  9. /* ICU License -- ICU 1.8.1 and later. */
  10. /* */
  11. /* The description and User's Guide ("The decNumber C Library") for */
  12. /* this software is called decNumber.pdf. This document is */
  13. /* available, together with arithmetic and format specifications, */
  14. /* testcases, and Web links, on the General Decimal Arithmetic page. */
  15. /* */
  16. /* Please send comments, suggestions, and corrections to the author: */
  17. /* mfc@uk.ibm.com */
  18. /* Mike Cowlishaw, IBM Fellow */
  19. /* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */
  20. /* ------------------------------------------------------------------ */
  21. /* Modified version, for use from within ICU.
  22. * Renamed public functions, to avoid an unwanted export of the
  23. * standard names from the ICU library.
  24. *
  25. * Use ICU's uprv_malloc() and uprv_free()
  26. *
  27. * Revert comment syntax to plain C
  28. *
  29. * Remove a few compiler warnings.
  30. */
  31. /* This module comprises the routines for arbitrary-precision General */
  32. /* Decimal Arithmetic as defined in the specification which may be */
  33. /* found on the General Decimal Arithmetic pages. It implements both */
  34. /* the full ('extended') arithmetic and the simpler ('subset') */
  35. /* arithmetic. */
  36. /* */
  37. /* Usage notes: */
  38. /* */
  39. /* 1. This code is ANSI C89 except: */
  40. /* */
  41. /* a) C99 line comments (double forward slash) are used. (Most C */
  42. /* compilers accept these. If yours does not, a simple script */
  43. /* can be used to convert them to ANSI C comments.) */
  44. /* */
  45. /* b) Types from C99 stdint.h are used. If you do not have this */
  46. /* header file, see the User's Guide section of the decNumber */
  47. /* documentation; this lists the necessary definitions. */
  48. /* */
  49. /* c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and */
  50. /* uint64_t types may be used. To avoid these, set DECUSE64=0 */
  51. /* and DECDPUN<=4 (see documentation). */
  52. /* */
  53. /* The code also conforms to C99 restrictions; in particular, */
  54. /* strict aliasing rules are observed. */
  55. /* */
  56. /* 2. The decNumber format which this library uses is optimized for */
  57. /* efficient processing of relatively short numbers; in particular */
  58. /* it allows the use of fixed sized structures and minimizes copy */
  59. /* and move operations. It does, however, support arbitrary */
  60. /* precision (up to 999,999,999 digits) and arbitrary exponent */
  61. /* range (Emax in the range 0 through 999,999,999 and Emin in the */
  62. /* range -999,999,999 through 0). Mathematical functions (for */
  63. /* example decNumberExp) as identified below are restricted more */
  64. /* tightly: digits, emax, and -emin in the context must be <= */
  65. /* DEC_MAX_MATH (999999), and their operand(s) must be within */
  66. /* these bounds. */
  67. /* */
  68. /* 3. Logical functions are further restricted; their operands must */
  69. /* be finite, positive, have an exponent of zero, and all digits */
  70. /* must be either 0 or 1. The result will only contain digits */
  71. /* which are 0 or 1 (and will have exponent=0 and a sign of 0). */
  72. /* */
  73. /* 4. Operands to operator functions are never modified unless they */
  74. /* are also specified to be the result number (which is always */
  75. /* permitted). Other than that case, operands must not overlap. */
  76. /* */
  77. /* 5. Error handling: the type of the error is ORed into the status */
  78. /* flags in the current context (decContext structure). The */
  79. /* SIGFPE signal is then raised if the corresponding trap-enabler */
  80. /* flag in the decContext is set (is 1). */
  81. /* */
  82. /* It is the responsibility of the caller to clear the status */
  83. /* flags as required. */
  84. /* */
  85. /* The result of any routine which returns a number will always */
  86. /* be a valid number (which may be a special value, such as an */
  87. /* Infinity or NaN). */
  88. /* */
  89. /* 6. The decNumber format is not an exchangeable concrete */
  90. /* representation as it comprises fields which may be machine- */
  91. /* dependent (packed or unpacked, or special length, for example). */
  92. /* Canonical conversions to and from strings are provided; other */
  93. /* conversions are available in separate modules. */
  94. /* */
  95. /* 7. Normally, input operands are assumed to be valid. Set DECCHECK */
  96. /* to 1 for extended operand checking (including nullptr operands). */
  97. /* Results are undefined if a badly-formed structure (or a nullptr */
  98. /* pointer to a structure) is provided, though with DECCHECK */
  99. /* enabled the operator routines are protected against exceptions. */
  100. /* (Except if the result pointer is nullptr, which is unrecoverable.) */
  101. /* */
  102. /* However, the routines will never cause exceptions if they are */
  103. /* given well-formed operands, even if the value of the operands */
  104. /* is inappropriate for the operation and DECCHECK is not set. */
  105. /* (Except for SIGFPE, as and where documented.) */
  106. /* */
  107. /* 8. Subset arithmetic is available only if DECSUBSET is set to 1. */
  108. /* ------------------------------------------------------------------ */
  109. /* Implementation notes for maintenance of this module: */
  110. /* */
  111. /* 1. Storage leak protection: Routines which use malloc are not */
  112. /* permitted to use return for fastpath or error exits (i.e., */
  113. /* they follow strict structured programming conventions). */
  114. /* Instead they have a do{}while(0); construct surrounding the */
  115. /* code which is protected -- break may be used to exit this. */
  116. /* Other routines can safely use the return statement inline. */
  117. /* */
  118. /* Storage leak accounting can be enabled using DECALLOC. */
  119. /* */
  120. /* 2. All loops use the for(;;) construct. Any do construct does */
  121. /* not loop; it is for allocation protection as just described. */
  122. /* */
  123. /* 3. Setting status in the context must always be the very last */
  124. /* action in a routine, as non-0 status may raise a trap and hence */
  125. /* the call to set status may not return (if the handler uses long */
  126. /* jump). Therefore all cleanup must be done first. In general, */
  127. /* to achieve this status is accumulated and is only applied just */
  128. /* before return by calling decContextSetStatus (via decStatus). */
  129. /* */
  130. /* Routines which allocate storage cannot, in general, use the */
  131. /* 'top level' routines which could cause a non-returning */
  132. /* transfer of control. The decXxxxOp routines are safe (do not */
  133. /* call decStatus even if traps are set in the context) and should */
  134. /* be used instead (they are also a little faster). */
  135. /* */
  136. /* 4. Exponent checking is minimized by allowing the exponent to */
  137. /* grow outside its limits during calculations, provided that */
  138. /* the decFinalize function is called later. Multiplication and */
  139. /* division, and intermediate calculations in exponentiation, */
  140. /* require more careful checks because of the risk of 31-bit */
  141. /* overflow (the most negative valid exponent is -1999999997, for */
  142. /* a 999999999-digit number with adjusted exponent of -999999999). */
  143. /* */
  144. /* 5. Rounding is deferred until finalization of results, with any */
  145. /* 'off to the right' data being represented as a single digit */
  146. /* residue (in the range -1 through 9). This avoids any double- */
  147. /* rounding when more than one shortening takes place (for */
  148. /* example, when a result is subnormal). */
  149. /* */
  150. /* 6. The digits count is allowed to rise to a multiple of DECDPUN */
  151. /* during many operations, so whole Units are handled and exact */
  152. /* accounting of digits is not needed. The correct digits value */
  153. /* is found by decGetDigits, which accounts for leading zeros. */
  154. /* This must be called before any rounding if the number of digits */
  155. /* is not known exactly. */
  156. /* */
  157. /* 7. The multiply-by-reciprocal 'trick' is used for partitioning */
  158. /* numbers up to four digits, using appropriate constants. This */
  159. /* is not useful for longer numbers because overflow of 32 bits */
  160. /* would lead to 4 multiplies, which is almost as expensive as */
  161. /* a divide (unless a floating-point or 64-bit multiply is */
  162. /* assumed to be available). */
  163. /* */
  164. /* 8. Unusual abbreviations that may be used in the commentary: */
  165. /* lhs -- left hand side (operand, of an operation) */
  166. /* lsd -- least significant digit (of coefficient) */
  167. /* lsu -- least significant Unit (of coefficient) */
  168. /* msd -- most significant digit (of coefficient) */
  169. /* msi -- most significant item (in an array) */
  170. /* msu -- most significant Unit (of coefficient) */
  171. /* rhs -- right hand side (operand, of an operation) */
  172. /* +ve -- positive */
  173. /* -ve -- negative */
  174. /* ** -- raise to the power */
  175. /* ------------------------------------------------------------------ */
  176. #include <stdlib.h> /* for malloc, free, etc. */
  177. /* #include <stdio.h> */ /* for printf [if needed] */
  178. #include <string.h> /* for strcpy */
  179. #include <ctype.h> /* for lower */
  180. #include "cmemory.h" /* for uprv_malloc, etc., in ICU */
  181. #include "decNumber.h" /* base number library */
  182. #include "decNumberLocal.h" /* decNumber local types, etc. */
  183. #include "uassert.h"
  184. /* Constants */
  185. /* Public lookup table used by the D2U macro */
  186. static const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
  187. #define DECVERB 1 /* set to 1 for verbose DECCHECK */
  188. #define powers DECPOWERS /* old internal name */
  189. /* Local constants */
  190. #define DIVIDE 0x80 /* Divide operators */
  191. #define REMAINDER 0x40 /* .. */
  192. #define DIVIDEINT 0x20 /* .. */
  193. #define REMNEAR 0x10 /* .. */
  194. #define COMPARE 0x01 /* Compare operators */
  195. #define COMPMAX 0x02 /* .. */
  196. #define COMPMIN 0x03 /* .. */
  197. #define COMPTOTAL 0x04 /* .. */
  198. #define COMPNAN 0x05 /* .. [NaN processing] */
  199. #define COMPSIG 0x06 /* .. [signaling COMPARE] */
  200. #define COMPMAXMAG 0x07 /* .. */
  201. #define COMPMINMAG 0x08 /* .. */
  202. #define DEC_sNaN 0x40000000 /* local status: sNaN signal */
  203. #define BADINT (Int)0x80000000 /* most-negative Int; error indicator */
  204. /* Next two indicate an integer >= 10**6, and its parity (bottom bit) */
  205. #define BIGEVEN (Int)0x80000002
  206. #define BIGODD (Int)0x80000003
  207. static const Unit uarrone[1]={1}; /* Unit array of 1, used for incrementing */
  208. /* ------------------------------------------------------------------ */
  209. /* round-for-reround digits */
  210. /* ------------------------------------------------------------------ */
  211. #if 0
  212. static const uByte DECSTICKYTAB[10]={1,1,2,3,4,6,6,7,8,9}; /* used if sticky */
  213. #endif
  214. /* ------------------------------------------------------------------ */
  215. /* Powers of ten (powers[n]==10**n, 0<=n<=9) */
  216. /* ------------------------------------------------------------------ */
  217. static const uInt DECPOWERS[10]={1, 10, 100, 1000, 10000, 100000, 1000000,
  218. 10000000, 100000000, 1000000000};
  219. /* Granularity-dependent code */
  220. #if DECDPUN<=4
  221. #define eInt Int /* extended integer */
  222. #define ueInt uInt /* unsigned extended integer */
  223. /* Constant multipliers for divide-by-power-of five using reciprocal */
  224. /* multiply, after removing powers of 2 by shifting, and final shift */
  225. /* of 17 [we only need up to **4] */
  226. static const uInt multies[]={131073, 26215, 5243, 1049, 210};
  227. /* QUOT10 -- macro to return the quotient of unit u divided by 10**n */
  228. #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
  229. #else
  230. /* For DECDPUN>4 non-ANSI-89 64-bit types are needed. */
  231. #if !DECUSE64
  232. #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
  233. #endif
  234. #define eInt Long /* extended integer */
  235. #define ueInt uLong /* unsigned extended integer */
  236. #endif
  237. /* Local routines */
  238. static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
  239. decContext *, uByte, uInt *);
  240. static Flag decBiStr(const char *, const char *, const char *);
  241. static uInt decCheckMath(const decNumber *, decContext *, uInt *);
  242. static void decApplyRound(decNumber *, decContext *, Int, uInt *);
  243. static Int decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
  244. static decNumber * decCompareOp(decNumber *, const decNumber *,
  245. const decNumber *, decContext *,
  246. Flag, uInt *);
  247. static void decCopyFit(decNumber *, const decNumber *, decContext *,
  248. Int *, uInt *);
  249. static decNumber * decDecap(decNumber *, Int);
  250. static decNumber * decDivideOp(decNumber *, const decNumber *,
  251. const decNumber *, decContext *, Flag, uInt *);
  252. static decNumber * decExpOp(decNumber *, const decNumber *,
  253. decContext *, uInt *);
  254. static void decFinalize(decNumber *, decContext *, Int *, uInt *);
  255. static Int decGetDigits(Unit *, Int);
  256. static Int decGetInt(const decNumber *);
  257. static decNumber * decLnOp(decNumber *, const decNumber *,
  258. decContext *, uInt *);
  259. static decNumber * decMultiplyOp(decNumber *, const decNumber *,
  260. const decNumber *, decContext *,
  261. uInt *);
  262. static decNumber * decNaNs(decNumber *, const decNumber *,
  263. const decNumber *, decContext *, uInt *);
  264. static decNumber * decQuantizeOp(decNumber *, const decNumber *,
  265. const decNumber *, decContext *, Flag,
  266. uInt *);
  267. static void decReverse(Unit *, Unit *);
  268. static void decSetCoeff(decNumber *, decContext *, const Unit *,
  269. Int, Int *, uInt *);
  270. static void decSetMaxValue(decNumber *, decContext *);
  271. static void decSetOverflow(decNumber *, decContext *, uInt *);
  272. static void decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
  273. static Int decShiftToLeast(Unit *, Int, Int);
  274. static Int decShiftToMost(Unit *, Int, Int);
  275. static void decStatus(decNumber *, uInt, decContext *);
  276. static void decToString(const decNumber *, char[], Flag);
  277. static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);
  278. static Int decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
  279. Unit *, Int);
  280. static Int decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
  281. #if !DECSUBSET
  282. /* decFinish == decFinalize when no subset arithmetic needed */
  283. #define decFinish(a,b,c,d) decFinalize(a,b,c,d)
  284. #else
  285. static void decFinish(decNumber *, decContext *, Int *, uInt *);
  286. static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
  287. #endif
  288. /* Local macros */
  289. /* masked special-values bits */
  290. #define SPECIALARG (rhs->bits & DECSPECIAL)
  291. #define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
  292. /* For use in ICU */
  293. #define malloc(a) uprv_malloc(a)
  294. #define free(a) uprv_free(a)
  295. /* Diagnostic macros, etc. */
  296. #if DECALLOC
  297. /* Handle malloc/free accounting. If enabled, our accountable routines */
  298. /* are used; otherwise the code just goes straight to the system malloc */
  299. /* and free routines. */
  300. #define malloc(a) decMalloc(a)
  301. #define free(a) decFree(a)
  302. #define DECFENCE 0x5a /* corruption detector */
  303. /* 'Our' malloc and free: */
  304. static void *decMalloc(size_t);
  305. static void decFree(void *);
  306. uInt decAllocBytes=0; /* count of bytes allocated */
  307. /* Note that DECALLOC code only checks for storage buffer overflow. */
  308. /* To check for memory leaks, the decAllocBytes variable must be */
  309. /* checked to be 0 at appropriate times (e.g., after the test */
  310. /* harness completes a set of tests). This checking may be unreliable */
  311. /* if the testing is done in a multi-thread environment. */
  312. #endif
  313. #if DECCHECK
  314. /* Optional checking routines. Enabling these means that decNumber */
  315. /* and decContext operands to operator routines are checked for */
  316. /* correctness. This roughly doubles the execution time of the */
  317. /* fastest routines (and adds 600+ bytes), so should not normally be */
  318. /* used in 'production'. */
  319. /* decCheckInexact is used to check that inexact results have a full */
  320. /* complement of digits (where appropriate -- this is not the case */
  321. /* for Quantize, for example) */
  322. #define DECUNRESU ((decNumber *)(void *)0xffffffff)
  323. #define DECUNUSED ((const decNumber *)(void *)0xffffffff)
  324. #define DECUNCONT ((decContext *)(void *)(0xffffffff))
  325. static Flag decCheckOperands(decNumber *, const decNumber *,
  326. const decNumber *, decContext *);
  327. static Flag decCheckNumber(const decNumber *);
  328. static void decCheckInexact(const decNumber *, decContext *);
  329. #endif
  330. #if DECTRACE || DECCHECK
  331. /* Optional trace/debugging routines (may or may not be used) */
  332. void decNumberShow(const decNumber *); /* displays the components of a number */
  333. static void decDumpAr(char, const Unit *, Int);
  334. #endif
  335. /* ================================================================== */
  336. /* Conversions */
  337. /* ================================================================== */
  338. /* ------------------------------------------------------------------ */
  339. /* from-int32 -- conversion from Int or uInt */
  340. /* */
  341. /* dn is the decNumber to receive the integer */
  342. /* in or uin is the integer to be converted */
  343. /* returns dn */
  344. /* */
  345. /* No error is possible. */
  346. /* ------------------------------------------------------------------ */
  347. U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromInt32(decNumber *dn, Int in) {
  348. uInt unsig;
  349. if (in>=0) unsig=in;
  350. else { /* negative (possibly BADINT) */
  351. if (in==BADINT) unsig=(uInt)1073741824*2; /* special case */
  352. else unsig=-in; /* invert */
  353. }
  354. /* in is now positive */
  355. uprv_decNumberFromUInt32(dn, unsig);
  356. if (in<0) dn->bits=DECNEG; /* sign needed */
  357. return dn;
  358. } /* decNumberFromInt32 */
  359. U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromUInt32(decNumber *dn, uInt uin) {
  360. Unit *up; /* work pointer */
  361. uprv_decNumberZero(dn); /* clean */
  362. if (uin==0) return dn; /* [or decGetDigits bad call] */
  363. for (up=dn->lsu; uin>0; up++) {
  364. *up=(Unit)(uin%(DECDPUNMAX+1));
  365. uin=uin/(DECDPUNMAX+1);
  366. }
  367. dn->digits=decGetDigits(dn->lsu, static_cast<int32_t>(up - dn->lsu));
  368. return dn;
  369. } /* decNumberFromUInt32 */
  370. /* ------------------------------------------------------------------ */
  371. /* to-int32 -- conversion to Int or uInt */
  372. /* */
  373. /* dn is the decNumber to convert */
  374. /* set is the context for reporting errors */
  375. /* returns the converted decNumber, or 0 if Invalid is set */
  376. /* */
  377. /* Invalid is set if the decNumber does not have exponent==0 or if */
  378. /* it is a NaN, Infinite, or out-of-range. */
  379. /* ------------------------------------------------------------------ */
  380. U_CAPI Int U_EXPORT2 uprv_decNumberToInt32(const decNumber *dn, decContext *set) {
  381. #if DECCHECK
  382. if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
  383. #endif
  384. /* special or too many digits, or bad exponent */
  385. if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; /* bad */
  386. else { /* is a finite integer with 10 or fewer digits */
  387. Int d; /* work */
  388. const Unit *up; /* .. */
  389. uInt hi=0, lo; /* .. */
  390. up=dn->lsu; /* -> lsu */
  391. lo=*up; /* get 1 to 9 digits */
  392. #if DECDPUN>1 /* split to higher */
  393. hi=lo/10;
  394. lo=lo%10;
  395. #endif
  396. up++;
  397. /* collect remaining Units, if any, into hi */
  398. for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
  399. /* now low has the lsd, hi the remainder */
  400. if (hi>214748364 || (hi==214748364 && lo>7)) { /* out of range? */
  401. /* most-negative is a reprieve */
  402. if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
  403. /* bad -- drop through */
  404. }
  405. else { /* in-range always */
  406. Int i=X10(hi)+lo;
  407. if (dn->bits&DECNEG) return -i;
  408. return i;
  409. }
  410. } /* integer */
  411. uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
  412. return 0;
  413. } /* decNumberToInt32 */
  414. U_CAPI uInt U_EXPORT2 uprv_decNumberToUInt32(const decNumber *dn, decContext *set) {
  415. #if DECCHECK
  416. if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
  417. #endif
  418. /* special or too many digits, or bad exponent, or negative (<0) */
  419. if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
  420. || (dn->bits&DECNEG && !ISZERO(dn))); /* bad */
  421. else { /* is a finite integer with 10 or fewer digits */
  422. Int d; /* work */
  423. const Unit *up; /* .. */
  424. uInt hi=0, lo; /* .. */
  425. up=dn->lsu; /* -> lsu */
  426. lo=*up; /* get 1 to 9 digits */
  427. #if DECDPUN>1 /* split to higher */
  428. hi=lo/10;
  429. lo=lo%10;
  430. #endif
  431. up++;
  432. /* collect remaining Units, if any, into hi */
  433. for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
  434. /* now low has the lsd, hi the remainder */
  435. if (hi>429496729 || (hi==429496729 && lo>5)) ; /* no reprieve possible */
  436. else return X10(hi)+lo;
  437. } /* integer */
  438. uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
  439. return 0;
  440. } /* decNumberToUInt32 */
  441. /* ------------------------------------------------------------------ */
  442. /* to-scientific-string -- conversion to numeric string */
  443. /* to-engineering-string -- conversion to numeric string */
  444. /* */
  445. /* decNumberToString(dn, string); */
  446. /* decNumberToEngString(dn, string); */
  447. /* */
  448. /* dn is the decNumber to convert */
  449. /* string is the string where the result will be laid out */
  450. /* */
  451. /* string must be at least dn->digits+14 characters long */
  452. /* */
  453. /* No error is possible, and no status can be set. */
  454. /* ------------------------------------------------------------------ */
  455. U_CAPI char * U_EXPORT2 uprv_decNumberToString(const decNumber *dn, char *string){
  456. decToString(dn, string, 0);
  457. return string;
  458. } /* DecNumberToString */
  459. U_CAPI char * U_EXPORT2 uprv_decNumberToEngString(const decNumber *dn, char *string){
  460. decToString(dn, string, 1);
  461. return string;
  462. } /* DecNumberToEngString */
  463. /* ------------------------------------------------------------------ */
  464. /* to-number -- conversion from numeric string */
  465. /* */
  466. /* decNumberFromString -- convert string to decNumber */
  467. /* dn -- the number structure to fill */
  468. /* chars[] -- the string to convert ('\0' terminated) */
  469. /* set -- the context used for processing any error, */
  470. /* determining the maximum precision available */
  471. /* (set.digits), determining the maximum and minimum */
  472. /* exponent (set.emax and set.emin), determining if */
  473. /* extended values are allowed, and checking the */
  474. /* rounding mode if overflow occurs or rounding is */
  475. /* needed. */
  476. /* */
  477. /* The length of the coefficient and the size of the exponent are */
  478. /* checked by this routine, so the correct error (Underflow or */
  479. /* Overflow) can be reported or rounding applied, as necessary. */
  480. /* */
  481. /* If bad syntax is detected, the result will be a quiet NaN. */
  482. /* ------------------------------------------------------------------ */
  483. U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromString(decNumber *dn, const char chars[],
  484. decContext *set) {
  485. Int exponent=0; /* working exponent [assume 0] */
  486. uByte bits=0; /* working flags [assume +ve] */
  487. Unit *res; /* where result will be built */
  488. Unit resbuff[SD2U(DECBUFFER+9)];/* local buffer in case need temporary */
  489. /* [+9 allows for ln() constants] */
  490. Unit *allocres=nullptr; /* -> allocated result, iff allocated */
  491. Int d=0; /* count of digits found in decimal part */
  492. const char *dotchar=nullptr; /* where dot was found */
  493. const char *cfirst=chars; /* -> first character of decimal part */
  494. const char *last=nullptr; /* -> last digit of decimal part */
  495. const char *c; /* work */
  496. Unit *up; /* .. */
  497. #if DECDPUN>1
  498. Int cut, out; /* .. */
  499. #endif
  500. Int residue; /* rounding residue */
  501. uInt status=0; /* error code */
  502. #if DECCHECK
  503. if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
  504. return uprv_decNumberZero(dn);
  505. #endif
  506. do { /* status & malloc protection */
  507. for (c=chars;; c++) { /* -> input character */
  508. if (*c>='0' && *c<='9') { /* test for Arabic digit */
  509. last=c;
  510. d++; /* count of real digits */
  511. continue; /* still in decimal part */
  512. }
  513. if (*c=='.' && dotchar==nullptr) { /* first '.' */
  514. dotchar=c; /* record offset into decimal part */
  515. if (c==cfirst) cfirst++; /* first digit must follow */
  516. continue;}
  517. if (c==chars) { /* first in string... */
  518. if (*c=='-') { /* valid - sign */
  519. cfirst++;
  520. bits=DECNEG;
  521. continue;}
  522. if (*c=='+') { /* valid + sign */
  523. cfirst++;
  524. continue;}
  525. }
  526. /* *c is not a digit, or a valid +, -, or '.' */
  527. break;
  528. } /* c */
  529. if (last==nullptr) { /* no digits yet */
  530. status=DEC_Conversion_syntax;/* assume the worst */
  531. if (*c=='\0') break; /* and no more to come... */
  532. #if DECSUBSET
  533. /* if subset then infinities and NaNs are not allowed */
  534. if (!set->extended) break; /* hopeless */
  535. #endif
  536. /* Infinities and NaNs are possible, here */
  537. if (dotchar!=nullptr) break; /* .. unless had a dot */
  538. uprv_decNumberZero(dn); /* be optimistic */
  539. if (decBiStr(c, "infinity", "INFINITY")
  540. || decBiStr(c, "inf", "INF")) {
  541. dn->bits=bits | DECINF;
  542. status=0; /* is OK */
  543. break; /* all done */
  544. }
  545. /* a NaN expected */
  546. /* 2003.09.10 NaNs are now permitted to have a sign */
  547. dn->bits=bits | DECNAN; /* assume simple NaN */
  548. if (*c=='s' || *c=='S') { /* looks like an sNaN */
  549. c++;
  550. dn->bits=bits | DECSNAN;
  551. }
  552. if (*c!='n' && *c!='N') break; /* check caseless "NaN" */
  553. c++;
  554. if (*c!='a' && *c!='A') break; /* .. */
  555. c++;
  556. if (*c!='n' && *c!='N') break; /* .. */
  557. c++;
  558. /* now either nothing, or nnnn payload, expected */
  559. /* -> start of integer and skip leading 0s [including plain 0] */
  560. for (cfirst=c; *cfirst=='0';) cfirst++;
  561. if (*cfirst=='\0') { /* "NaN" or "sNaN", maybe with all 0s */
  562. status=0; /* it's good */
  563. break; /* .. */
  564. }
  565. /* something other than 0s; setup last and d as usual [no dots] */
  566. for (c=cfirst;; c++, d++) {
  567. if (*c<'0' || *c>'9') break; /* test for Arabic digit */
  568. last=c;
  569. }
  570. if (*c!='\0') break; /* not all digits */
  571. if (d>set->digits-1) {
  572. /* [NB: payload in a decNumber can be full length unless */
  573. /* clamped, in which case can only be digits-1] */
  574. if (set->clamp) break;
  575. if (d>set->digits) break;
  576. } /* too many digits? */
  577. /* good; drop through to convert the integer to coefficient */
  578. status=0; /* syntax is OK */
  579. bits=dn->bits; /* for copy-back */
  580. } /* last==nullptr */
  581. else if (*c!='\0') { /* more to process... */
  582. /* had some digits; exponent is only valid sequence now */
  583. Flag nege; /* 1=negative exponent */
  584. const char *firstexp; /* -> first significant exponent digit */
  585. status=DEC_Conversion_syntax;/* assume the worst */
  586. if (*c!='e' && *c!='E') break;
  587. /* Found 'e' or 'E' -- now process explicit exponent */
  588. /* 1998.07.11: sign no longer required */
  589. nege=0;
  590. c++; /* to (possible) sign */
  591. if (*c=='-') {nege=1; c++;}
  592. else if (*c=='+') c++;
  593. if (*c=='\0') break;
  594. for (; *c=='0' && *(c+1)!='\0';) c++; /* strip insignificant zeros */
  595. firstexp=c; /* save exponent digit place */
  596. uInt uexponent = 0; /* Avoid undefined behavior on signed int overflow */
  597. for (; ;c++) {
  598. if (*c<'0' || *c>'9') break; /* not a digit */
  599. uexponent=X10(uexponent)+(uInt)*c-(uInt)'0';
  600. } /* c */
  601. exponent = (Int)uexponent;
  602. /* if not now on a '\0', *c must not be a digit */
  603. if (*c!='\0') break;
  604. /* (this next test must be after the syntax checks) */
  605. /* if it was too long the exponent may have wrapped, so check */
  606. /* carefully and set it to a certain overflow if wrap possible */
  607. if (c>=firstexp+9+1) {
  608. if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
  609. /* [up to 1999999999 is OK, for example 1E-1000000998] */
  610. }
  611. if (nege) exponent=-exponent; /* was negative */
  612. status=0; /* is OK */
  613. } /* stuff after digits */
  614. /* Here when whole string has been inspected; syntax is good */
  615. /* cfirst->first digit (never dot), last->last digit (ditto) */
  616. /* strip leading zeros/dot [leave final 0 if all 0's] */
  617. if (*cfirst=='0') { /* [cfirst has stepped over .] */
  618. for (c=cfirst; c<last; c++, cfirst++) {
  619. if (*c=='.') continue; /* ignore dots */
  620. if (*c!='0') break; /* non-zero found */
  621. d--; /* 0 stripped */
  622. } /* c */
  623. #if DECSUBSET
  624. /* make a rapid exit for easy zeros if !extended */
  625. if (*cfirst=='0' && !set->extended) {
  626. uprv_decNumberZero(dn); /* clean result */
  627. break; /* [could be return] */
  628. }
  629. #endif
  630. } /* at least one leading 0 */
  631. /* Handle decimal point... */
  632. if (dotchar!=nullptr && dotchar<last) /* non-trailing '.' found? */
  633. exponent -= static_cast<int32_t>(last-dotchar); /* adjust exponent */
  634. /* [we can now ignore the .] */
  635. /* OK, the digits string is good. Assemble in the decNumber, or in */
  636. /* a temporary units array if rounding is needed */
  637. if (d<=set->digits) res=dn->lsu; /* fits into supplied decNumber */
  638. else { /* rounding needed */
  639. Int needbytes=D2U(d)*sizeof(Unit);/* bytes needed */
  640. res=resbuff; /* assume use local buffer */
  641. if (needbytes>(Int)sizeof(resbuff)) { /* too big for local */
  642. allocres=(Unit *)malloc(needbytes);
  643. if (allocres==nullptr) {status|=DEC_Insufficient_storage; break;}
  644. res=allocres;
  645. }
  646. }
  647. /* res now -> number lsu, buffer, or allocated storage for Unit array */
  648. /* Place the coefficient into the selected Unit array */
  649. /* [this is often 70% of the cost of this function when DECDPUN>1] */
  650. #if DECDPUN>1
  651. out=0; /* accumulator */
  652. up=res+D2U(d)-1; /* -> msu */
  653. cut=d-(up-res)*DECDPUN; /* digits in top unit */
  654. for (c=cfirst;; c++) { /* along the digits */
  655. if (*c=='.') continue; /* ignore '.' [don't decrement cut] */
  656. out=X10(out)+(Int)*c-(Int)'0';
  657. if (c==last) break; /* done [never get to trailing '.'] */
  658. cut--;
  659. if (cut>0) continue; /* more for this unit */
  660. *up=(Unit)out; /* write unit */
  661. up--; /* prepare for unit below.. */
  662. cut=DECDPUN; /* .. */
  663. out=0; /* .. */
  664. } /* c */
  665. *up=(Unit)out; /* write lsu */
  666. #else
  667. /* DECDPUN==1 */
  668. up=res; /* -> lsu */
  669. for (c=last; c>=cfirst; c--) { /* over each character, from least */
  670. if (*c=='.') continue; /* ignore . [don't step up] */
  671. *up=(Unit)((Int)*c-(Int)'0');
  672. up++;
  673. } /* c */
  674. #endif
  675. dn->bits=bits;
  676. dn->exponent=exponent;
  677. dn->digits=d;
  678. /* if not in number (too long) shorten into the number */
  679. if (d>set->digits) {
  680. residue=0;
  681. decSetCoeff(dn, set, res, d, &residue, &status);
  682. /* always check for overflow or subnormal and round as needed */
  683. decFinalize(dn, set, &residue, &status);
  684. }
  685. else { /* no rounding, but may still have overflow or subnormal */
  686. /* [these tests are just for performance; finalize repeats them] */
  687. if ((dn->exponent-1<set->emin-dn->digits)
  688. || (dn->exponent-1>set->emax-set->digits)) {
  689. residue=0;
  690. decFinalize(dn, set, &residue, &status);
  691. }
  692. }
  693. /* decNumberShow(dn); */
  694. } while(0); /* [for break] */
  695. if (allocres!=nullptr) free(allocres); /* drop any storage used */
  696. if (status!=0) decStatus(dn, status, set);
  697. return dn;
  698. } /* decNumberFromString */
  699. /* ================================================================== */
  700. /* Operators */
  701. /* ================================================================== */
  702. /* ------------------------------------------------------------------ */
  703. /* decNumberAbs -- absolute value operator */
  704. /* */
  705. /* This computes C = abs(A) */
  706. /* */
  707. /* res is C, the result. C may be A */
  708. /* rhs is A */
  709. /* set is the context */
  710. /* */
  711. /* See also decNumberCopyAbs for a quiet bitwise version of this. */
  712. /* C must have space for set->digits digits. */
  713. /* ------------------------------------------------------------------ */
  714. /* This has the same effect as decNumberPlus unless A is negative, */
  715. /* in which case it has the same effect as decNumberMinus. */
  716. /* ------------------------------------------------------------------ */
  717. U_CAPI decNumber * U_EXPORT2 uprv_decNumberAbs(decNumber *res, const decNumber *rhs,
  718. decContext *set) {
  719. decNumber dzero; /* for 0 */
  720. uInt status=0; /* accumulator */
  721. #if DECCHECK
  722. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  723. #endif
  724. uprv_decNumberZero(&dzero); /* set 0 */
  725. dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
  726. decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
  727. if (status!=0) decStatus(res, status, set);
  728. #if DECCHECK
  729. decCheckInexact(res, set);
  730. #endif
  731. return res;
  732. } /* decNumberAbs */
  733. /* ------------------------------------------------------------------ */
  734. /* decNumberAdd -- add two Numbers */
  735. /* */
  736. /* This computes C = A + B */
  737. /* */
  738. /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
  739. /* lhs is A */
  740. /* rhs is B */
  741. /* set is the context */
  742. /* */
  743. /* C must have space for set->digits digits. */
  744. /* ------------------------------------------------------------------ */
  745. /* This just calls the routine shared with Subtract */
  746. U_CAPI decNumber * U_EXPORT2 uprv_decNumberAdd(decNumber *res, const decNumber *lhs,
  747. const decNumber *rhs, decContext *set) {
  748. uInt status=0; /* accumulator */
  749. decAddOp(res, lhs, rhs, set, 0, &status);
  750. if (status!=0) decStatus(res, status, set);
  751. #if DECCHECK
  752. decCheckInexact(res, set);
  753. #endif
  754. return res;
  755. } /* decNumberAdd */
  756. /* ------------------------------------------------------------------ */
  757. /* decNumberAnd -- AND two Numbers, digitwise */
  758. /* */
  759. /* This computes C = A & B */
  760. /* */
  761. /* res is C, the result. C may be A and/or B (e.g., X=X&X) */
  762. /* lhs is A */
  763. /* rhs is B */
  764. /* set is the context (used for result length and error report) */
  765. /* */
  766. /* C must have space for set->digits digits. */
  767. /* */
  768. /* Logical function restrictions apply (see above); a NaN is */
  769. /* returned with Invalid_operation if a restriction is violated. */
  770. /* ------------------------------------------------------------------ */
  771. U_CAPI decNumber * U_EXPORT2 uprv_decNumberAnd(decNumber *res, const decNumber *lhs,
  772. const decNumber *rhs, decContext *set) {
  773. const Unit *ua, *ub; /* -> operands */
  774. const Unit *msua, *msub; /* -> operand msus */
  775. Unit *uc, *msuc; /* -> result and its msu */
  776. Int msudigs; /* digits in res msu */
  777. #if DECCHECK
  778. if (decCheckOperands(res, lhs, rhs, set)) return res;
  779. #endif
  780. if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
  781. || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
  782. decStatus(res, DEC_Invalid_operation, set);
  783. return res;
  784. }
  785. /* operands are valid */
  786. ua=lhs->lsu; /* bottom-up */
  787. ub=rhs->lsu; /* .. */
  788. uc=res->lsu; /* .. */
  789. msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
  790. msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
  791. msuc=uc+D2U(set->digits)-1; /* -> msu of result */
  792. msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
  793. for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
  794. Unit a, b; /* extract units */
  795. if (ua>msua) a=0;
  796. else a=*ua;
  797. if (ub>msub) b=0;
  798. else b=*ub;
  799. *uc=0; /* can now write back */
  800. if (a|b) { /* maybe 1 bits to examine */
  801. Int i, j;
  802. *uc=0; /* can now write back */
  803. /* This loop could be unrolled and/or use BIN2BCD tables */
  804. for (i=0; i<DECDPUN; i++) {
  805. if (a&b&1) *uc=*uc+(Unit)powers[i]; /* effect AND */
  806. j=a%10;
  807. a=a/10;
  808. j|=b%10;
  809. b=b/10;
  810. if (j>1) {
  811. decStatus(res, DEC_Invalid_operation, set);
  812. return res;
  813. }
  814. if (uc==msuc && i==msudigs-1) break; /* just did final digit */
  815. } /* each digit */
  816. } /* both OK */
  817. } /* each unit */
  818. /* [here uc-1 is the msu of the result] */
  819. res->digits=decGetDigits(res->lsu, static_cast<int32_t>(uc - res->lsu));
  820. res->exponent=0; /* integer */
  821. res->bits=0; /* sign=0 */
  822. return res; /* [no status to set] */
  823. } /* decNumberAnd */
  824. /* ------------------------------------------------------------------ */
  825. /* decNumberCompare -- compare two Numbers */
  826. /* */
  827. /* This computes C = A ? B */
  828. /* */
  829. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  830. /* lhs is A */
  831. /* rhs is B */
  832. /* set is the context */
  833. /* */
  834. /* C must have space for one digit (or NaN). */
  835. /* ------------------------------------------------------------------ */
  836. U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompare(decNumber *res, const decNumber *lhs,
  837. const decNumber *rhs, decContext *set) {
  838. uInt status=0; /* accumulator */
  839. decCompareOp(res, lhs, rhs, set, COMPARE, &status);
  840. if (status!=0) decStatus(res, status, set);
  841. return res;
  842. } /* decNumberCompare */
  843. /* ------------------------------------------------------------------ */
  844. /* decNumberCompareSignal -- compare, signalling on all NaNs */
  845. /* */
  846. /* This computes C = A ? B */
  847. /* */
  848. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  849. /* lhs is A */
  850. /* rhs is B */
  851. /* set is the context */
  852. /* */
  853. /* C must have space for one digit (or NaN). */
  854. /* ------------------------------------------------------------------ */
  855. U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareSignal(decNumber *res, const decNumber *lhs,
  856. const decNumber *rhs, decContext *set) {
  857. uInt status=0; /* accumulator */
  858. decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
  859. if (status!=0) decStatus(res, status, set);
  860. return res;
  861. } /* decNumberCompareSignal */
  862. /* ------------------------------------------------------------------ */
  863. /* decNumberCompareTotal -- compare two Numbers, using total ordering */
  864. /* */
  865. /* This computes C = A ? B, under total ordering */
  866. /* */
  867. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  868. /* lhs is A */
  869. /* rhs is B */
  870. /* set is the context */
  871. /* */
  872. /* C must have space for one digit; the result will always be one of */
  873. /* -1, 0, or 1. */
  874. /* ------------------------------------------------------------------ */
  875. U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotal(decNumber *res, const decNumber *lhs,
  876. const decNumber *rhs, decContext *set) {
  877. uInt status=0; /* accumulator */
  878. decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
  879. if (status!=0) decStatus(res, status, set);
  880. return res;
  881. } /* decNumberCompareTotal */
  882. /* ------------------------------------------------------------------ */
  883. /* decNumberCompareTotalMag -- compare, total ordering of magnitudes */
  884. /* */
  885. /* This computes C = |A| ? |B|, under total ordering */
  886. /* */
  887. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  888. /* lhs is A */
  889. /* rhs is B */
  890. /* set is the context */
  891. /* */
  892. /* C must have space for one digit; the result will always be one of */
  893. /* -1, 0, or 1. */
  894. /* ------------------------------------------------------------------ */
  895. U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
  896. const decNumber *rhs, decContext *set) {
  897. uInt status=0; /* accumulator */
  898. uInt needbytes; /* for space calculations */
  899. decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0 */
  900. decNumber *allocbufa=nullptr; /* -> allocated bufa, iff allocated */
  901. decNumber bufb[D2N(DECBUFFER+1)];
  902. decNumber *allocbufb=nullptr; /* -> allocated bufb, iff allocated */
  903. decNumber *a, *b; /* temporary pointers */
  904. #if DECCHECK
  905. if (decCheckOperands(res, lhs, rhs, set)) return res;
  906. #endif
  907. do { /* protect allocated storage */
  908. /* if either is negative, take a copy and absolute */
  909. if (decNumberIsNegative(lhs)) { /* lhs<0 */
  910. a=bufa;
  911. needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
  912. if (needbytes>sizeof(bufa)) { /* need malloc space */
  913. allocbufa=(decNumber *)malloc(needbytes);
  914. if (allocbufa==nullptr) { /* hopeless -- abandon */
  915. status|=DEC_Insufficient_storage;
  916. break;}
  917. a=allocbufa; /* use the allocated space */
  918. }
  919. uprv_decNumberCopy(a, lhs); /* copy content */
  920. a->bits&=~DECNEG; /* .. and clear the sign */
  921. lhs=a; /* use copy from here on */
  922. }
  923. if (decNumberIsNegative(rhs)) { /* rhs<0 */
  924. b=bufb;
  925. needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
  926. if (needbytes>sizeof(bufb)) { /* need malloc space */
  927. allocbufb=(decNumber *)malloc(needbytes);
  928. if (allocbufb==nullptr) { /* hopeless -- abandon */
  929. status|=DEC_Insufficient_storage;
  930. break;}
  931. b=allocbufb; /* use the allocated space */
  932. }
  933. uprv_decNumberCopy(b, rhs); /* copy content */
  934. b->bits&=~DECNEG; /* .. and clear the sign */
  935. rhs=b; /* use copy from here on */
  936. }
  937. decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
  938. } while(0); /* end protected */
  939. if (allocbufa!=nullptr) free(allocbufa); /* drop any storage used */
  940. if (allocbufb!=nullptr) free(allocbufb); /* .. */
  941. if (status!=0) decStatus(res, status, set);
  942. return res;
  943. } /* decNumberCompareTotalMag */
  944. /* ------------------------------------------------------------------ */
  945. /* decNumberDivide -- divide one number by another */
  946. /* */
  947. /* This computes C = A / B */
  948. /* */
  949. /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
  950. /* lhs is A */
  951. /* rhs is B */
  952. /* set is the context */
  953. /* */
  954. /* C must have space for set->digits digits. */
  955. /* ------------------------------------------------------------------ */
  956. U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivide(decNumber *res, const decNumber *lhs,
  957. const decNumber *rhs, decContext *set) {
  958. uInt status=0; /* accumulator */
  959. decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
  960. if (status!=0) decStatus(res, status, set);
  961. #if DECCHECK
  962. decCheckInexact(res, set);
  963. #endif
  964. return res;
  965. } /* decNumberDivide */
  966. /* ------------------------------------------------------------------ */
  967. /* decNumberDivideInteger -- divide and return integer quotient */
  968. /* */
  969. /* This computes C = A # B, where # is the integer divide operator */
  970. /* */
  971. /* res is C, the result. C may be A and/or B (e.g., X=X#X) */
  972. /* lhs is A */
  973. /* rhs is B */
  974. /* set is the context */
  975. /* */
  976. /* C must have space for set->digits digits. */
  977. /* ------------------------------------------------------------------ */
  978. U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivideInteger(decNumber *res, const decNumber *lhs,
  979. const decNumber *rhs, decContext *set) {
  980. uInt status=0; /* accumulator */
  981. decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
  982. if (status!=0) decStatus(res, status, set);
  983. return res;
  984. } /* decNumberDivideInteger */
  985. /* ------------------------------------------------------------------ */
  986. /* decNumberExp -- exponentiation */
  987. /* */
  988. /* This computes C = exp(A) */
  989. /* */
  990. /* res is C, the result. C may be A */
  991. /* rhs is A */
  992. /* set is the context; note that rounding mode has no effect */
  993. /* */
  994. /* C must have space for set->digits digits. */
  995. /* */
  996. /* Mathematical function restrictions apply (see above); a NaN is */
  997. /* returned with Invalid_operation if a restriction is violated. */
  998. /* */
  999. /* Finite results will always be full precision and Inexact, except */
  1000. /* when A is a zero or -Infinity (giving 1 or 0 respectively). */
  1001. /* */
  1002. /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
  1003. /* almost always be correctly rounded, but may be up to 1 ulp in */
  1004. /* error in rare cases. */
  1005. /* ------------------------------------------------------------------ */
  1006. /* This is a wrapper for decExpOp which can handle the slightly wider */
  1007. /* (double) range needed by Ln (which has to be able to calculate */
  1008. /* exp(-a) where a can be the tiniest number (Ntiny). */
  1009. /* ------------------------------------------------------------------ */
  1010. U_CAPI decNumber * U_EXPORT2 uprv_decNumberExp(decNumber *res, const decNumber *rhs,
  1011. decContext *set) {
  1012. uInt status=0; /* accumulator */
  1013. #if DECSUBSET
  1014. decNumber *allocrhs=nullptr; /* non-nullptr if rounded rhs allocated */
  1015. #endif
  1016. #if DECCHECK
  1017. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1018. #endif
  1019. /* Check restrictions; these restrictions ensure that if h=8 (see */
  1020. /* decExpOp) then the result will either overflow or underflow to 0. */
  1021. /* Other math functions restrict the input range, too, for inverses. */
  1022. /* If not violated then carry out the operation. */
  1023. if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
  1024. #if DECSUBSET
  1025. if (!set->extended) {
  1026. /* reduce operand and set lostDigits status, as needed */
  1027. if (rhs->digits>set->digits) {
  1028. allocrhs=decRoundOperand(rhs, set, &status);
  1029. if (allocrhs==nullptr) break;
  1030. rhs=allocrhs;
  1031. }
  1032. }
  1033. #endif
  1034. decExpOp(res, rhs, set, &status);
  1035. } while(0); /* end protected */
  1036. #if DECSUBSET
  1037. if (allocrhs !=nullptr) free(allocrhs); /* drop any storage used */
  1038. #endif
  1039. /* apply significant status */
  1040. if (status!=0) decStatus(res, status, set);
  1041. #if DECCHECK
  1042. decCheckInexact(res, set);
  1043. #endif
  1044. return res;
  1045. } /* decNumberExp */
  1046. /* ------------------------------------------------------------------ */
  1047. /* decNumberFMA -- fused multiply add */
  1048. /* */
  1049. /* This computes D = (A * B) + C with only one rounding */
  1050. /* */
  1051. /* res is D, the result. D may be A or B or C (e.g., X=FMA(X,X,X)) */
  1052. /* lhs is A */
  1053. /* rhs is B */
  1054. /* fhs is C [far hand side] */
  1055. /* set is the context */
  1056. /* */
  1057. /* Mathematical function restrictions apply (see above); a NaN is */
  1058. /* returned with Invalid_operation if a restriction is violated. */
  1059. /* */
  1060. /* C must have space for set->digits digits. */
  1061. /* ------------------------------------------------------------------ */
  1062. U_CAPI decNumber * U_EXPORT2 uprv_decNumberFMA(decNumber *res, const decNumber *lhs,
  1063. const decNumber *rhs, const decNumber *fhs,
  1064. decContext *set) {
  1065. uInt status=0; /* accumulator */
  1066. decContext dcmul; /* context for the multiplication */
  1067. uInt needbytes; /* for space calculations */
  1068. decNumber bufa[D2N(DECBUFFER*2+1)];
  1069. decNumber *allocbufa=nullptr; /* -> allocated bufa, iff allocated */
  1070. decNumber *acc; /* accumulator pointer */
  1071. decNumber dzero; /* work */
  1072. #if DECCHECK
  1073. if (decCheckOperands(res, lhs, rhs, set)) return res;
  1074. if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
  1075. #endif
  1076. do { /* protect allocated storage */
  1077. #if DECSUBSET
  1078. if (!set->extended) { /* [undefined if subset] */
  1079. status|=DEC_Invalid_operation;
  1080. break;}
  1081. #endif
  1082. /* Check math restrictions [these ensure no overflow or underflow] */
  1083. if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
  1084. || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
  1085. || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
  1086. /* set up context for multiply */
  1087. dcmul=*set;
  1088. dcmul.digits=lhs->digits+rhs->digits; /* just enough */
  1089. /* [The above may be an over-estimate for subset arithmetic, but that's OK] */
  1090. dcmul.emax=DEC_MAX_EMAX; /* effectively unbounded .. */
  1091. dcmul.emin=DEC_MIN_EMIN; /* [thanks to Math restrictions] */
  1092. /* set up decNumber space to receive the result of the multiply */
  1093. acc=bufa; /* may fit */
  1094. needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
  1095. if (needbytes>sizeof(bufa)) { /* need malloc space */
  1096. allocbufa=(decNumber *)malloc(needbytes);
  1097. if (allocbufa==nullptr) { /* hopeless -- abandon */
  1098. status|=DEC_Insufficient_storage;
  1099. break;}
  1100. acc=allocbufa; /* use the allocated space */
  1101. }
  1102. /* multiply with extended range and necessary precision */
  1103. /*printf("emin=%ld\n", dcmul.emin); */
  1104. decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
  1105. /* Only Invalid operation (from sNaN or Inf * 0) is possible in */
  1106. /* status; if either is seen than ignore fhs (in case it is */
  1107. /* another sNaN) and set acc to NaN unless we had an sNaN */
  1108. /* [decMultiplyOp leaves that to caller] */
  1109. /* Note sNaN has to go through addOp to shorten payload if */
  1110. /* necessary */
  1111. if ((status&DEC_Invalid_operation)!=0) {
  1112. if (!(status&DEC_sNaN)) { /* but be true invalid */
  1113. uprv_decNumberZero(res); /* acc not yet set */
  1114. res->bits=DECNAN;
  1115. break;
  1116. }
  1117. uprv_decNumberZero(&dzero); /* make 0 (any non-NaN would do) */
  1118. fhs=&dzero; /* use that */
  1119. }
  1120. #if DECCHECK
  1121. else { /* multiply was OK */
  1122. if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);
  1123. }
  1124. #endif
  1125. /* add the third operand and result -> res, and all is done */
  1126. decAddOp(res, acc, fhs, set, 0, &status);
  1127. } while(0); /* end protected */
  1128. if (allocbufa!=nullptr) free(allocbufa); /* drop any storage used */
  1129. if (status!=0) decStatus(res, status, set);
  1130. #if DECCHECK
  1131. decCheckInexact(res, set);
  1132. #endif
  1133. return res;
  1134. } /* decNumberFMA */
  1135. /* ------------------------------------------------------------------ */
  1136. /* decNumberInvert -- invert a Number, digitwise */
  1137. /* */
  1138. /* This computes C = ~A */
  1139. /* */
  1140. /* res is C, the result. C may be A (e.g., X=~X) */
  1141. /* rhs is A */
  1142. /* set is the context (used for result length and error report) */
  1143. /* */
  1144. /* C must have space for set->digits digits. */
  1145. /* */
  1146. /* Logical function restrictions apply (see above); a NaN is */
  1147. /* returned with Invalid_operation if a restriction is violated. */
  1148. /* ------------------------------------------------------------------ */
  1149. U_CAPI decNumber * U_EXPORT2 uprv_decNumberInvert(decNumber *res, const decNumber *rhs,
  1150. decContext *set) {
  1151. const Unit *ua, *msua; /* -> operand and its msu */
  1152. Unit *uc, *msuc; /* -> result and its msu */
  1153. Int msudigs; /* digits in res msu */
  1154. #if DECCHECK
  1155. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1156. #endif
  1157. if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
  1158. decStatus(res, DEC_Invalid_operation, set);
  1159. return res;
  1160. }
  1161. /* operand is valid */
  1162. ua=rhs->lsu; /* bottom-up */
  1163. uc=res->lsu; /* .. */
  1164. msua=ua+D2U(rhs->digits)-1; /* -> msu of rhs */
  1165. msuc=uc+D2U(set->digits)-1; /* -> msu of result */
  1166. msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
  1167. for (; uc<=msuc; ua++, uc++) { /* Unit loop */
  1168. Unit a; /* extract unit */
  1169. Int i, j; /* work */
  1170. if (ua>msua) a=0;
  1171. else a=*ua;
  1172. *uc=0; /* can now write back */
  1173. /* always need to examine all bits in rhs */
  1174. /* This loop could be unrolled and/or use BIN2BCD tables */
  1175. for (i=0; i<DECDPUN; i++) {
  1176. if ((~a)&1) *uc=*uc+(Unit)powers[i]; /* effect INVERT */
  1177. j=a%10;
  1178. a=a/10;
  1179. if (j>1) {
  1180. decStatus(res, DEC_Invalid_operation, set);
  1181. return res;
  1182. }
  1183. if (uc==msuc && i==msudigs-1) break; /* just did final digit */
  1184. } /* each digit */
  1185. } /* each unit */
  1186. /* [here uc-1 is the msu of the result] */
  1187. res->digits=decGetDigits(res->lsu, static_cast<int32_t>(uc - res->lsu));
  1188. res->exponent=0; /* integer */
  1189. res->bits=0; /* sign=0 */
  1190. return res; /* [no status to set] */
  1191. } /* decNumberInvert */
  1192. /* ------------------------------------------------------------------ */
  1193. /* decNumberLn -- natural logarithm */
  1194. /* */
  1195. /* This computes C = ln(A) */
  1196. /* */
  1197. /* res is C, the result. C may be A */
  1198. /* rhs is A */
  1199. /* set is the context; note that rounding mode has no effect */
  1200. /* */
  1201. /* C must have space for set->digits digits. */
  1202. /* */
  1203. /* Notable cases: */
  1204. /* A<0 -> Invalid */
  1205. /* A=0 -> -Infinity (Exact) */
  1206. /* A=+Infinity -> +Infinity (Exact) */
  1207. /* A=1 exactly -> 0 (Exact) */
  1208. /* */
  1209. /* Mathematical function restrictions apply (see above); a NaN is */
  1210. /* returned with Invalid_operation if a restriction is violated. */
  1211. /* */
  1212. /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
  1213. /* almost always be correctly rounded, but may be up to 1 ulp in */
  1214. /* error in rare cases. */
  1215. /* ------------------------------------------------------------------ */
  1216. /* This is a wrapper for decLnOp which can handle the slightly wider */
  1217. /* (+11) range needed by Ln, Log10, etc. (which may have to be able */
  1218. /* to calculate at p+e+2). */
  1219. /* ------------------------------------------------------------------ */
  1220. U_CAPI decNumber * U_EXPORT2 uprv_decNumberLn(decNumber *res, const decNumber *rhs,
  1221. decContext *set) {
  1222. uInt status=0; /* accumulator */
  1223. #if DECSUBSET
  1224. decNumber *allocrhs=nullptr; /* non-nullptr if rounded rhs allocated */
  1225. #endif
  1226. #if DECCHECK
  1227. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1228. #endif
  1229. /* Check restrictions; this is a math function; if not violated */
  1230. /* then carry out the operation. */
  1231. if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
  1232. #if DECSUBSET
  1233. if (!set->extended) {
  1234. /* reduce operand and set lostDigits status, as needed */
  1235. if (rhs->digits>set->digits) {
  1236. allocrhs=decRoundOperand(rhs, set, &status);
  1237. if (allocrhs==nullptr) break;
  1238. rhs=allocrhs;
  1239. }
  1240. /* special check in subset for rhs=0 */
  1241. if (ISZERO(rhs)) { /* +/- zeros -> error */
  1242. status|=DEC_Invalid_operation;
  1243. break;}
  1244. } /* extended=0 */
  1245. #endif
  1246. decLnOp(res, rhs, set, &status);
  1247. } while(0); /* end protected */
  1248. #if DECSUBSET
  1249. if (allocrhs !=nullptr) free(allocrhs); /* drop any storage used */
  1250. #endif
  1251. /* apply significant status */
  1252. if (status!=0) decStatus(res, status, set);
  1253. #if DECCHECK
  1254. decCheckInexact(res, set);
  1255. #endif
  1256. return res;
  1257. } /* decNumberLn */
  1258. /* ------------------------------------------------------------------ */
  1259. /* decNumberLogB - get adjusted exponent, by 754 rules */
  1260. /* */
  1261. /* This computes C = adjustedexponent(A) */
  1262. /* */
  1263. /* res is C, the result. C may be A */
  1264. /* rhs is A */
  1265. /* set is the context, used only for digits and status */
  1266. /* */
  1267. /* C must have space for 10 digits (A might have 10**9 digits and */
  1268. /* an exponent of +999999999, or one digit and an exponent of */
  1269. /* -1999999999). */
  1270. /* */
  1271. /* This returns the adjusted exponent of A after (in theory) padding */
  1272. /* with zeros on the right to set->digits digits while keeping the */
  1273. /* same value. The exponent is not limited by emin/emax. */
  1274. /* */
  1275. /* Notable cases: */
  1276. /* A<0 -> Use |A| */
  1277. /* A=0 -> -Infinity (Division by zero) */
  1278. /* A=Infinite -> +Infinity (Exact) */
  1279. /* A=1 exactly -> 0 (Exact) */
  1280. /* NaNs are propagated as usual */
  1281. /* ------------------------------------------------------------------ */
  1282. U_CAPI decNumber * U_EXPORT2 uprv_decNumberLogB(decNumber *res, const decNumber *rhs,
  1283. decContext *set) {
  1284. uInt status=0; /* accumulator */
  1285. #if DECCHECK
  1286. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1287. #endif
  1288. /* NaNs as usual; Infinities return +Infinity; 0->oops */
  1289. if (decNumberIsNaN(rhs)) decNaNs(res, rhs, nullptr, set, &status);
  1290. else if (decNumberIsInfinite(rhs)) uprv_decNumberCopyAbs(res, rhs);
  1291. else if (decNumberIsZero(rhs)) {
  1292. uprv_decNumberZero(res); /* prepare for Infinity */
  1293. res->bits=DECNEG|DECINF; /* -Infinity */
  1294. status|=DEC_Division_by_zero; /* as per 754 */
  1295. }
  1296. else { /* finite non-zero */
  1297. Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
  1298. uprv_decNumberFromInt32(res, ae); /* lay it out */
  1299. }
  1300. if (status!=0) decStatus(res, status, set);
  1301. return res;
  1302. } /* decNumberLogB */
  1303. /* ------------------------------------------------------------------ */
  1304. /* decNumberLog10 -- logarithm in base 10 */
  1305. /* */
  1306. /* This computes C = log10(A) */
  1307. /* */
  1308. /* res is C, the result. C may be A */
  1309. /* rhs is A */
  1310. /* set is the context; note that rounding mode has no effect */
  1311. /* */
  1312. /* C must have space for set->digits digits. */
  1313. /* */
  1314. /* Notable cases: */
  1315. /* A<0 -> Invalid */
  1316. /* A=0 -> -Infinity (Exact) */
  1317. /* A=+Infinity -> +Infinity (Exact) */
  1318. /* A=10**n (if n is an integer) -> n (Exact) */
  1319. /* */
  1320. /* Mathematical function restrictions apply (see above); a NaN is */
  1321. /* returned with Invalid_operation if a restriction is violated. */
  1322. /* */
  1323. /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
  1324. /* almost always be correctly rounded, but may be up to 1 ulp in */
  1325. /* error in rare cases. */
  1326. /* ------------------------------------------------------------------ */
  1327. /* This calculates ln(A)/ln(10) using appropriate precision. For */
  1328. /* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the */
  1329. /* requested digits and t is the number of digits in the exponent */
  1330. /* (maximum 6). For ln(10) it is p + 3; this is often handled by the */
  1331. /* fastpath in decLnOp. The final division is done to the requested */
  1332. /* precision. */
  1333. /* ------------------------------------------------------------------ */
  1334. #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
  1335. #pragma GCC diagnostic push
  1336. #pragma GCC diagnostic ignored "-Warray-bounds"
  1337. #endif
  1338. U_CAPI decNumber * U_EXPORT2 uprv_decNumberLog10(decNumber *res, const decNumber *rhs,
  1339. decContext *set) {
  1340. uInt status=0, ignore=0; /* status accumulators */
  1341. uInt needbytes; /* for space calculations */
  1342. Int p; /* working precision */
  1343. Int t; /* digits in exponent of A */
  1344. /* buffers for a and b working decimals */
  1345. /* (adjustment calculator, same size) */
  1346. decNumber bufa[D2N(DECBUFFER+2)];
  1347. decNumber *allocbufa=nullptr; /* -> allocated bufa, iff allocated */
  1348. decNumber *a=bufa; /* temporary a */
  1349. decNumber bufb[D2N(DECBUFFER+2)];
  1350. decNumber *allocbufb=nullptr; /* -> allocated bufb, iff allocated */
  1351. decNumber *b=bufb; /* temporary b */
  1352. decNumber bufw[D2N(10)]; /* working 2-10 digit number */
  1353. decNumber *w=bufw; /* .. */
  1354. #if DECSUBSET
  1355. decNumber *allocrhs=nullptr; /* non-nullptr if rounded rhs allocated */
  1356. #endif
  1357. decContext aset; /* working context */
  1358. #if DECCHECK
  1359. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1360. #endif
  1361. /* Check restrictions; this is a math function; if not violated */
  1362. /* then carry out the operation. */
  1363. if (!decCheckMath(rhs, set, &status)) do { /* protect malloc */
  1364. #if DECSUBSET
  1365. if (!set->extended) {
  1366. /* reduce operand and set lostDigits status, as needed */
  1367. if (rhs->digits>set->digits) {
  1368. allocrhs=decRoundOperand(rhs, set, &status);
  1369. if (allocrhs==nullptr) break;
  1370. rhs=allocrhs;
  1371. }
  1372. /* special check in subset for rhs=0 */
  1373. if (ISZERO(rhs)) { /* +/- zeros -> error */
  1374. status|=DEC_Invalid_operation;
  1375. break;}
  1376. } /* extended=0 */
  1377. #endif
  1378. uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
  1379. /* handle exact powers of 10; only check if +ve finite */
  1380. if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
  1381. Int residue=0; /* (no residue) */
  1382. uInt copystat=0; /* clean status */
  1383. /* round to a single digit... */
  1384. aset.digits=1;
  1385. decCopyFit(w, rhs, &aset, &residue, &copystat); /* copy & shorten */
  1386. /* if exact and the digit is 1, rhs is a power of 10 */
  1387. if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
  1388. /* the exponent, conveniently, is the power of 10; making */
  1389. /* this the result needs a little care as it might not fit, */
  1390. /* so first convert it into the working number, and then move */
  1391. /* to res */
  1392. uprv_decNumberFromInt32(w, w->exponent);
  1393. residue=0;
  1394. decCopyFit(res, w, set, &residue, &status); /* copy & round */
  1395. decFinish(res, set, &residue, &status); /* cleanup/set flags */
  1396. break;
  1397. } /* not a power of 10 */
  1398. } /* not a candidate for exact */
  1399. /* simplify the information-content calculation to use 'total */
  1400. /* number of digits in a, including exponent' as compared to the */
  1401. /* requested digits, as increasing this will only rarely cost an */
  1402. /* iteration in ln(a) anyway */
  1403. t=6; /* it can never be >6 */
  1404. /* allocate space when needed... */
  1405. p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
  1406. needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
  1407. if (needbytes>sizeof(bufa)) { /* need malloc space */
  1408. allocbufa=(decNumber *)malloc(needbytes);
  1409. if (allocbufa==nullptr) { /* hopeless -- abandon */
  1410. status|=DEC_Insufficient_storage;
  1411. break;}
  1412. a=allocbufa; /* use the allocated space */
  1413. }
  1414. aset.digits=p; /* as calculated */
  1415. aset.emax=DEC_MAX_MATH; /* usual bounds */
  1416. aset.emin=-DEC_MAX_MATH; /* .. */
  1417. aset.clamp=0; /* and no concrete format */
  1418. decLnOp(a, rhs, &aset, &status); /* a=ln(rhs) */
  1419. /* skip the division if the result so far is infinite, NaN, or */
  1420. /* zero, or there was an error; note NaN from sNaN needs copy */
  1421. if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
  1422. if (a->bits&DECSPECIAL || ISZERO(a)) {
  1423. uprv_decNumberCopy(res, a); /* [will fit] */
  1424. break;}
  1425. /* for ln(10) an extra 3 digits of precision are needed */
  1426. p=set->digits+3;
  1427. needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
  1428. if (needbytes>sizeof(bufb)) { /* need malloc space */
  1429. allocbufb=(decNumber *)malloc(needbytes);
  1430. if (allocbufb==nullptr) { /* hopeless -- abandon */
  1431. status|=DEC_Insufficient_storage;
  1432. break;}
  1433. b=allocbufb; /* use the allocated space */
  1434. }
  1435. uprv_decNumberZero(w); /* set up 10... */
  1436. #if DECDPUN==1
  1437. w->lsu[1]=1; w->lsu[0]=0; /* .. */
  1438. #else
  1439. w->lsu[0]=10; /* .. */
  1440. #endif
  1441. w->digits=2; /* .. */
  1442. aset.digits=p;
  1443. decLnOp(b, w, &aset, &ignore); /* b=ln(10) */
  1444. aset.digits=set->digits; /* for final divide */
  1445. decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result */
  1446. } while(0); /* [for break] */
  1447. if (allocbufa!=nullptr) free(allocbufa); /* drop any storage used */
  1448. if (allocbufb!=nullptr) free(allocbufb); /* .. */
  1449. #if DECSUBSET
  1450. if (allocrhs !=nullptr) free(allocrhs); /* .. */
  1451. #endif
  1452. /* apply significant status */
  1453. if (status!=0) decStatus(res, status, set);
  1454. #if DECCHECK
  1455. decCheckInexact(res, set);
  1456. #endif
  1457. return res;
  1458. } /* decNumberLog10 */
  1459. #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
  1460. #pragma GCC diagnostic pop
  1461. #endif
  1462. /* ------------------------------------------------------------------ */
  1463. /* decNumberMax -- compare two Numbers and return the maximum */
  1464. /* */
  1465. /* This computes C = A ? B, returning the maximum by 754 rules */
  1466. /* */
  1467. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  1468. /* lhs is A */
  1469. /* rhs is B */
  1470. /* set is the context */
  1471. /* */
  1472. /* C must have space for set->digits digits. */
  1473. /* ------------------------------------------------------------------ */
  1474. U_CAPI decNumber * U_EXPORT2 uprv_decNumberMax(decNumber *res, const decNumber *lhs,
  1475. const decNumber *rhs, decContext *set) {
  1476. uInt status=0; /* accumulator */
  1477. decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
  1478. if (status!=0) decStatus(res, status, set);
  1479. #if DECCHECK
  1480. decCheckInexact(res, set);
  1481. #endif
  1482. return res;
  1483. } /* decNumberMax */
  1484. /* ------------------------------------------------------------------ */
  1485. /* decNumberMaxMag -- compare and return the maximum by magnitude */
  1486. /* */
  1487. /* This computes C = A ? B, returning the maximum by 754 rules */
  1488. /* */
  1489. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  1490. /* lhs is A */
  1491. /* rhs is B */
  1492. /* set is the context */
  1493. /* */
  1494. /* C must have space for set->digits digits. */
  1495. /* ------------------------------------------------------------------ */
  1496. U_CAPI decNumber * U_EXPORT2 uprv_decNumberMaxMag(decNumber *res, const decNumber *lhs,
  1497. const decNumber *rhs, decContext *set) {
  1498. uInt status=0; /* accumulator */
  1499. decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
  1500. if (status!=0) decStatus(res, status, set);
  1501. #if DECCHECK
  1502. decCheckInexact(res, set);
  1503. #endif
  1504. return res;
  1505. } /* decNumberMaxMag */
  1506. /* ------------------------------------------------------------------ */
  1507. /* decNumberMin -- compare two Numbers and return the minimum */
  1508. /* */
  1509. /* This computes C = A ? B, returning the minimum by 754 rules */
  1510. /* */
  1511. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  1512. /* lhs is A */
  1513. /* rhs is B */
  1514. /* set is the context */
  1515. /* */
  1516. /* C must have space for set->digits digits. */
  1517. /* ------------------------------------------------------------------ */
  1518. U_CAPI decNumber * U_EXPORT2 uprv_decNumberMin(decNumber *res, const decNumber *lhs,
  1519. const decNumber *rhs, decContext *set) {
  1520. uInt status=0; /* accumulator */
  1521. decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
  1522. if (status!=0) decStatus(res, status, set);
  1523. #if DECCHECK
  1524. decCheckInexact(res, set);
  1525. #endif
  1526. return res;
  1527. } /* decNumberMin */
  1528. /* ------------------------------------------------------------------ */
  1529. /* decNumberMinMag -- compare and return the minimum by magnitude */
  1530. /* */
  1531. /* This computes C = A ? B, returning the minimum by 754 rules */
  1532. /* */
  1533. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  1534. /* lhs is A */
  1535. /* rhs is B */
  1536. /* set is the context */
  1537. /* */
  1538. /* C must have space for set->digits digits. */
  1539. /* ------------------------------------------------------------------ */
  1540. U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinMag(decNumber *res, const decNumber *lhs,
  1541. const decNumber *rhs, decContext *set) {
  1542. uInt status=0; /* accumulator */
  1543. decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
  1544. if (status!=0) decStatus(res, status, set);
  1545. #if DECCHECK
  1546. decCheckInexact(res, set);
  1547. #endif
  1548. return res;
  1549. } /* decNumberMinMag */
  1550. /* ------------------------------------------------------------------ */
  1551. /* decNumberMinus -- prefix minus operator */
  1552. /* */
  1553. /* This computes C = 0 - A */
  1554. /* */
  1555. /* res is C, the result. C may be A */
  1556. /* rhs is A */
  1557. /* set is the context */
  1558. /* */
  1559. /* See also decNumberCopyNegate for a quiet bitwise version of this. */
  1560. /* C must have space for set->digits digits. */
  1561. /* ------------------------------------------------------------------ */
  1562. /* Simply use AddOp for the subtract, which will do the necessary. */
  1563. /* ------------------------------------------------------------------ */
  1564. U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinus(decNumber *res, const decNumber *rhs,
  1565. decContext *set) {
  1566. decNumber dzero;
  1567. uInt status=0; /* accumulator */
  1568. #if DECCHECK
  1569. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1570. #endif
  1571. uprv_decNumberZero(&dzero); /* make 0 */
  1572. dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
  1573. decAddOp(res, &dzero, rhs, set, DECNEG, &status);
  1574. if (status!=0) decStatus(res, status, set);
  1575. #if DECCHECK
  1576. decCheckInexact(res, set);
  1577. #endif
  1578. return res;
  1579. } /* decNumberMinus */
  1580. /* ------------------------------------------------------------------ */
  1581. /* decNumberNextMinus -- next towards -Infinity */
  1582. /* */
  1583. /* This computes C = A - infinitesimal, rounded towards -Infinity */
  1584. /* */
  1585. /* res is C, the result. C may be A */
  1586. /* rhs is A */
  1587. /* set is the context */
  1588. /* */
  1589. /* This is a generalization of 754 NextDown. */
  1590. /* ------------------------------------------------------------------ */
  1591. U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextMinus(decNumber *res, const decNumber *rhs,
  1592. decContext *set) {
  1593. decNumber dtiny; /* constant */
  1594. decContext workset=*set; /* work */
  1595. uInt status=0; /* accumulator */
  1596. #if DECCHECK
  1597. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1598. #endif
  1599. /* +Infinity is the special case */
  1600. if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
  1601. decSetMaxValue(res, set); /* is +ve */
  1602. /* there is no status to set */
  1603. return res;
  1604. }
  1605. uprv_decNumberZero(&dtiny); /* start with 0 */
  1606. dtiny.lsu[0]=1; /* make number that is .. */
  1607. dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
  1608. workset.round=DEC_ROUND_FLOOR;
  1609. decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
  1610. status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */
  1611. if (status!=0) decStatus(res, status, set);
  1612. return res;
  1613. } /* decNumberNextMinus */
  1614. /* ------------------------------------------------------------------ */
  1615. /* decNumberNextPlus -- next towards +Infinity */
  1616. /* */
  1617. /* This computes C = A + infinitesimal, rounded towards +Infinity */
  1618. /* */
  1619. /* res is C, the result. C may be A */
  1620. /* rhs is A */
  1621. /* set is the context */
  1622. /* */
  1623. /* This is a generalization of 754 NextUp. */
  1624. /* ------------------------------------------------------------------ */
  1625. U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextPlus(decNumber *res, const decNumber *rhs,
  1626. decContext *set) {
  1627. decNumber dtiny; /* constant */
  1628. decContext workset=*set; /* work */
  1629. uInt status=0; /* accumulator */
  1630. #if DECCHECK
  1631. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1632. #endif
  1633. /* -Infinity is the special case */
  1634. if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
  1635. decSetMaxValue(res, set);
  1636. res->bits=DECNEG; /* negative */
  1637. /* there is no status to set */
  1638. return res;
  1639. }
  1640. uprv_decNumberZero(&dtiny); /* start with 0 */
  1641. dtiny.lsu[0]=1; /* make number that is .. */
  1642. dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
  1643. workset.round=DEC_ROUND_CEILING;
  1644. decAddOp(res, rhs, &dtiny, &workset, 0, &status);
  1645. status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */
  1646. if (status!=0) decStatus(res, status, set);
  1647. return res;
  1648. } /* decNumberNextPlus */
  1649. /* ------------------------------------------------------------------ */
  1650. /* decNumberNextToward -- next towards rhs */
  1651. /* */
  1652. /* This computes C = A +/- infinitesimal, rounded towards */
  1653. /* +/-Infinity in the direction of B, as per 754-1985 nextafter */
  1654. /* modified during revision but dropped from 754-2008. */
  1655. /* */
  1656. /* res is C, the result. C may be A or B. */
  1657. /* lhs is A */
  1658. /* rhs is B */
  1659. /* set is the context */
  1660. /* */
  1661. /* This is a generalization of 754-1985 NextAfter. */
  1662. /* ------------------------------------------------------------------ */
  1663. U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextToward(decNumber *res, const decNumber *lhs,
  1664. const decNumber *rhs, decContext *set) {
  1665. decNumber dtiny; /* constant */
  1666. decContext workset=*set; /* work */
  1667. Int result; /* .. */
  1668. uInt status=0; /* accumulator */
  1669. #if DECCHECK
  1670. if (decCheckOperands(res, lhs, rhs, set)) return res;
  1671. #endif
  1672. if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
  1673. decNaNs(res, lhs, rhs, set, &status);
  1674. }
  1675. else { /* Is numeric, so no chance of sNaN Invalid, etc. */
  1676. result=decCompare(lhs, rhs, 0); /* sign matters */
  1677. if (result==BADINT) status|=DEC_Insufficient_storage; /* rare */
  1678. else { /* valid compare */
  1679. if (result==0) uprv_decNumberCopySign(res, lhs, rhs); /* easy */
  1680. else { /* differ: need NextPlus or NextMinus */
  1681. uByte sub; /* add or subtract */
  1682. if (result<0) { /* lhs<rhs, do nextplus */
  1683. /* -Infinity is the special case */
  1684. if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
  1685. decSetMaxValue(res, set);
  1686. res->bits=DECNEG; /* negative */
  1687. return res; /* there is no status to set */
  1688. }
  1689. workset.round=DEC_ROUND_CEILING;
  1690. sub=0; /* add, please */
  1691. } /* plus */
  1692. else { /* lhs>rhs, do nextminus */
  1693. /* +Infinity is the special case */
  1694. if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
  1695. decSetMaxValue(res, set);
  1696. return res; /* there is no status to set */
  1697. }
  1698. workset.round=DEC_ROUND_FLOOR;
  1699. sub=DECNEG; /* subtract, please */
  1700. } /* minus */
  1701. uprv_decNumberZero(&dtiny); /* start with 0 */
  1702. dtiny.lsu[0]=1; /* make number that is .. */
  1703. dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
  1704. decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or - */
  1705. /* turn off exceptions if the result is a normal number */
  1706. /* (including Nmin), otherwise let all status through */
  1707. if (uprv_decNumberIsNormal(res, set)) status=0;
  1708. } /* unequal */
  1709. } /* compare OK */
  1710. } /* numeric */
  1711. if (status!=0) decStatus(res, status, set);
  1712. return res;
  1713. } /* decNumberNextToward */
  1714. /* ------------------------------------------------------------------ */
  1715. /* decNumberOr -- OR two Numbers, digitwise */
  1716. /* */
  1717. /* This computes C = A | B */
  1718. /* */
  1719. /* res is C, the result. C may be A and/or B (e.g., X=X|X) */
  1720. /* lhs is A */
  1721. /* rhs is B */
  1722. /* set is the context (used for result length and error report) */
  1723. /* */
  1724. /* C must have space for set->digits digits. */
  1725. /* */
  1726. /* Logical function restrictions apply (see above); a NaN is */
  1727. /* returned with Invalid_operation if a restriction is violated. */
  1728. /* ------------------------------------------------------------------ */
  1729. U_CAPI decNumber * U_EXPORT2 uprv_decNumberOr(decNumber *res, const decNumber *lhs,
  1730. const decNumber *rhs, decContext *set) {
  1731. const Unit *ua, *ub; /* -> operands */
  1732. const Unit *msua, *msub; /* -> operand msus */
  1733. Unit *uc, *msuc; /* -> result and its msu */
  1734. Int msudigs; /* digits in res msu */
  1735. #if DECCHECK
  1736. if (decCheckOperands(res, lhs, rhs, set)) return res;
  1737. #endif
  1738. if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
  1739. || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
  1740. decStatus(res, DEC_Invalid_operation, set);
  1741. return res;
  1742. }
  1743. /* operands are valid */
  1744. ua=lhs->lsu; /* bottom-up */
  1745. ub=rhs->lsu; /* .. */
  1746. uc=res->lsu; /* .. */
  1747. msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
  1748. msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
  1749. msuc=uc+D2U(set->digits)-1; /* -> msu of result */
  1750. msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
  1751. for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
  1752. Unit a, b; /* extract units */
  1753. if (ua>msua) a=0;
  1754. else a=*ua;
  1755. if (ub>msub) b=0;
  1756. else b=*ub;
  1757. *uc=0; /* can now write back */
  1758. if (a|b) { /* maybe 1 bits to examine */
  1759. Int i, j;
  1760. /* This loop could be unrolled and/or use BIN2BCD tables */
  1761. for (i=0; i<DECDPUN; i++) {
  1762. if ((a|b)&1) *uc=*uc+(Unit)powers[i]; /* effect OR */
  1763. j=a%10;
  1764. a=a/10;
  1765. j|=b%10;
  1766. b=b/10;
  1767. if (j>1) {
  1768. decStatus(res, DEC_Invalid_operation, set);
  1769. return res;
  1770. }
  1771. if (uc==msuc && i==msudigs-1) break; /* just did final digit */
  1772. } /* each digit */
  1773. } /* non-zero */
  1774. } /* each unit */
  1775. /* [here uc-1 is the msu of the result] */
  1776. res->digits=decGetDigits(res->lsu, static_cast<int32_t>(uc-res->lsu));
  1777. res->exponent=0; /* integer */
  1778. res->bits=0; /* sign=0 */
  1779. return res; /* [no status to set] */
  1780. } /* decNumberOr */
  1781. /* ------------------------------------------------------------------ */
  1782. /* decNumberPlus -- prefix plus operator */
  1783. /* */
  1784. /* This computes C = 0 + A */
  1785. /* */
  1786. /* res is C, the result. C may be A */
  1787. /* rhs is A */
  1788. /* set is the context */
  1789. /* */
  1790. /* See also decNumberCopy for a quiet bitwise version of this. */
  1791. /* C must have space for set->digits digits. */
  1792. /* ------------------------------------------------------------------ */
  1793. /* This simply uses AddOp; Add will take fast path after preparing A. */
  1794. /* Performance is a concern here, as this routine is often used to */
  1795. /* check operands and apply rounding and overflow/underflow testing. */
  1796. /* ------------------------------------------------------------------ */
  1797. U_CAPI decNumber * U_EXPORT2 uprv_decNumberPlus(decNumber *res, const decNumber *rhs,
  1798. decContext *set) {
  1799. decNumber dzero;
  1800. uInt status=0; /* accumulator */
  1801. #if DECCHECK
  1802. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1803. #endif
  1804. uprv_decNumberZero(&dzero); /* make 0 */
  1805. dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
  1806. decAddOp(res, &dzero, rhs, set, 0, &status);
  1807. if (status!=0) decStatus(res, status, set);
  1808. #if DECCHECK
  1809. decCheckInexact(res, set);
  1810. #endif
  1811. return res;
  1812. } /* decNumberPlus */
  1813. /* ------------------------------------------------------------------ */
  1814. /* decNumberMultiply -- multiply two Numbers */
  1815. /* */
  1816. /* This computes C = A x B */
  1817. /* */
  1818. /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
  1819. /* lhs is A */
  1820. /* rhs is B */
  1821. /* set is the context */
  1822. /* */
  1823. /* C must have space for set->digits digits. */
  1824. /* ------------------------------------------------------------------ */
  1825. U_CAPI decNumber * U_EXPORT2 uprv_decNumberMultiply(decNumber *res, const decNumber *lhs,
  1826. const decNumber *rhs, decContext *set) {
  1827. uInt status=0; /* accumulator */
  1828. decMultiplyOp(res, lhs, rhs, set, &status);
  1829. if (status!=0) decStatus(res, status, set);
  1830. #if DECCHECK
  1831. decCheckInexact(res, set);
  1832. #endif
  1833. return res;
  1834. } /* decNumberMultiply */
  1835. /* ------------------------------------------------------------------ */
  1836. /* decNumberPower -- raise a number to a power */
  1837. /* */
  1838. /* This computes C = A ** B */
  1839. /* */
  1840. /* res is C, the result. C may be A and/or B (e.g., X=X**X) */
  1841. /* lhs is A */
  1842. /* rhs is B */
  1843. /* set is the context */
  1844. /* */
  1845. /* C must have space for set->digits digits. */
  1846. /* */
  1847. /* Mathematical function restrictions apply (see above); a NaN is */
  1848. /* returned with Invalid_operation if a restriction is violated. */
  1849. /* */
  1850. /* However, if 1999999997<=B<=999999999 and B is an integer then the */
  1851. /* restrictions on A and the context are relaxed to the usual bounds, */
  1852. /* for compatibility with the earlier (integer power only) version */
  1853. /* of this function. */
  1854. /* */
  1855. /* When B is an integer, the result may be exact, even if rounded. */
  1856. /* */
  1857. /* The final result is rounded according to the context; it will */
  1858. /* almost always be correctly rounded, but may be up to 1 ulp in */
  1859. /* error in rare cases. */
  1860. /* ------------------------------------------------------------------ */
  1861. U_CAPI decNumber * U_EXPORT2 uprv_decNumberPower(decNumber *res, const decNumber *lhs,
  1862. const decNumber *rhs, decContext *set) {
  1863. #if DECSUBSET
  1864. decNumber *alloclhs=nullptr; /* non-nullptr if rounded lhs allocated */
  1865. decNumber *allocrhs=nullptr; /* .., rhs */
  1866. #endif
  1867. decNumber *allocdac=nullptr; /* -> allocated acc buffer, iff used */
  1868. decNumber *allocinv=nullptr; /* -> allocated 1/x buffer, iff used */
  1869. Int reqdigits=set->digits; /* requested DIGITS */
  1870. Int n; /* rhs in binary */
  1871. Flag rhsint=0; /* 1 if rhs is an integer */
  1872. Flag useint=0; /* 1 if can use integer calculation */
  1873. Flag isoddint=0; /* 1 if rhs is an integer and odd */
  1874. Int i; /* work */
  1875. #if DECSUBSET
  1876. Int dropped; /* .. */
  1877. #endif
  1878. uInt needbytes; /* buffer size needed */
  1879. Flag seenbit; /* seen a bit while powering */
  1880. Int residue=0; /* rounding residue */
  1881. uInt status=0; /* accumulators */
  1882. uByte bits=0; /* result sign if errors */
  1883. decContext aset; /* working context */
  1884. decNumber dnOne; /* work value 1... */
  1885. /* local accumulator buffer [a decNumber, with digits+elength+1 digits] */
  1886. decNumber dacbuff[D2N(DECBUFFER+9)];
  1887. decNumber *dac=dacbuff; /* -> result accumulator */
  1888. /* same again for possible 1/lhs calculation */
  1889. decNumber invbuff[D2N(DECBUFFER+9)];
  1890. #if DECCHECK
  1891. if (decCheckOperands(res, lhs, rhs, set)) return res;
  1892. #endif
  1893. do { /* protect allocated storage */
  1894. #if DECSUBSET
  1895. if (!set->extended) { /* reduce operands and set status, as needed */
  1896. if (lhs->digits>reqdigits) {
  1897. alloclhs=decRoundOperand(lhs, set, &status);
  1898. if (alloclhs==nullptr) break;
  1899. lhs=alloclhs;
  1900. }
  1901. if (rhs->digits>reqdigits) {
  1902. allocrhs=decRoundOperand(rhs, set, &status);
  1903. if (allocrhs==nullptr) break;
  1904. rhs=allocrhs;
  1905. }
  1906. }
  1907. #endif
  1908. /* [following code does not require input rounding] */
  1909. /* handle NaNs and rhs Infinity (lhs infinity is harder) */
  1910. if (SPECIALARGS) {
  1911. if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs */
  1912. decNaNs(res, lhs, rhs, set, &status);
  1913. break;}
  1914. if (decNumberIsInfinite(rhs)) { /* rhs Infinity */
  1915. Flag rhsneg=rhs->bits&DECNEG; /* save rhs sign */
  1916. if (decNumberIsNegative(lhs) /* lhs<0 */
  1917. && !decNumberIsZero(lhs)) /* .. */
  1918. status|=DEC_Invalid_operation;
  1919. else { /* lhs >=0 */
  1920. uprv_decNumberZero(&dnOne); /* set up 1 */
  1921. dnOne.lsu[0]=1;
  1922. uprv_decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1 */
  1923. uprv_decNumberZero(res); /* prepare for 0/1/Infinity */
  1924. if (decNumberIsNegative(dac)) { /* lhs<1 */
  1925. if (rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */
  1926. }
  1927. else if (dac->lsu[0]==0) { /* lhs=1 */
  1928. /* 1**Infinity is inexact, so return fully-padded 1.0000 */
  1929. Int shift=set->digits-1;
  1930. *res->lsu=1; /* was 0, make int 1 */
  1931. res->digits=decShiftToMost(res->lsu, 1, shift);
  1932. res->exponent=-shift; /* make 1.0000... */
  1933. status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
  1934. }
  1935. else { /* lhs>1 */
  1936. if (!rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */
  1937. }
  1938. } /* lhs>=0 */
  1939. break;}
  1940. /* [lhs infinity drops through] */
  1941. } /* specials */
  1942. /* Original rhs may be an integer that fits and is in range */
  1943. n=decGetInt(rhs);
  1944. if (n!=BADINT) { /* it is an integer */
  1945. rhsint=1; /* record the fact for 1**n */
  1946. isoddint=(Flag)n&1; /* [works even if big] */
  1947. if (n!=BIGEVEN && n!=BIGODD) /* can use integer path? */
  1948. useint=1; /* looks good */
  1949. }
  1950. if (decNumberIsNegative(lhs) /* -x .. */
  1951. && isoddint) bits=DECNEG; /* .. to an odd power */
  1952. /* handle LHS infinity */
  1953. if (decNumberIsInfinite(lhs)) { /* [NaNs already handled] */
  1954. uByte rbits=rhs->bits; /* save */
  1955. uprv_decNumberZero(res); /* prepare */
  1956. if (n==0) *res->lsu=1; /* [-]Inf**0 => 1 */
  1957. else {
  1958. /* -Inf**nonint -> error */
  1959. if (!rhsint && decNumberIsNegative(lhs)) {
  1960. status|=DEC_Invalid_operation; /* -Inf**nonint is error */
  1961. break;}
  1962. if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n */
  1963. /* [otherwise will be 0 or -0] */
  1964. res->bits=bits;
  1965. }
  1966. break;}
  1967. /* similarly handle LHS zero */
  1968. if (decNumberIsZero(lhs)) {
  1969. if (n==0) { /* 0**0 => Error */
  1970. #if DECSUBSET
  1971. if (!set->extended) { /* [unless subset] */
  1972. uprv_decNumberZero(res);
  1973. *res->lsu=1; /* return 1 */
  1974. break;}
  1975. #endif
  1976. status|=DEC_Invalid_operation;
  1977. }
  1978. else { /* 0**x */
  1979. uByte rbits=rhs->bits; /* save */
  1980. if (rbits & DECNEG) { /* was a 0**(-n) */
  1981. #if DECSUBSET
  1982. if (!set->extended) { /* [bad if subset] */
  1983. status|=DEC_Invalid_operation;
  1984. break;}
  1985. #endif
  1986. bits|=DECINF;
  1987. }
  1988. uprv_decNumberZero(res); /* prepare */
  1989. /* [otherwise will be 0 or -0] */
  1990. res->bits=bits;
  1991. }
  1992. break;}
  1993. /* here both lhs and rhs are finite; rhs==0 is handled in the */
  1994. /* integer path. Next handle the non-integer cases */
  1995. if (!useint) { /* non-integral rhs */
  1996. /* any -ve lhs is bad, as is either operand or context out of */
  1997. /* bounds */
  1998. if (decNumberIsNegative(lhs)) {
  1999. status|=DEC_Invalid_operation;
  2000. break;}
  2001. if (decCheckMath(lhs, set, &status)
  2002. || decCheckMath(rhs, set, &status)) break; /* variable status */
  2003. uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
  2004. aset.emax=DEC_MAX_MATH; /* usual bounds */
  2005. aset.emin=-DEC_MAX_MATH; /* .. */
  2006. aset.clamp=0; /* and no concrete format */
  2007. /* calculate the result using exp(ln(lhs)*rhs), which can */
  2008. /* all be done into the accumulator, dac. The precision needed */
  2009. /* is enough to contain the full information in the lhs (which */
  2010. /* is the total digits, including exponent), or the requested */
  2011. /* precision, if larger, + 4; 6 is used for the exponent */
  2012. /* maximum length, and this is also used when it is shorter */
  2013. /* than the requested digits as it greatly reduces the >0.5 ulp */
  2014. /* cases at little cost (because Ln doubles digits each */
  2015. /* iteration so a few extra digits rarely causes an extra */
  2016. /* iteration) */
  2017. aset.digits=MAXI(lhs->digits, set->digits)+6+4;
  2018. } /* non-integer rhs */
  2019. else { /* rhs is in-range integer */
  2020. if (n==0) { /* x**0 = 1 */
  2021. /* (0**0 was handled above) */
  2022. uprv_decNumberZero(res); /* result=1 */
  2023. *res->lsu=1; /* .. */
  2024. break;}
  2025. /* rhs is a non-zero integer */
  2026. if (n<0) n=-n; /* use abs(n) */
  2027. aset=*set; /* clone the context */
  2028. aset.round=DEC_ROUND_HALF_EVEN; /* internally use balanced */
  2029. /* calculate the working DIGITS */
  2030. aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
  2031. #if DECSUBSET
  2032. if (!set->extended) aset.digits--; /* use classic precision */
  2033. #endif
  2034. /* it's an error if this is more than can be handled */
  2035. if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
  2036. } /* integer path */
  2037. /* aset.digits is the count of digits for the accumulator needed */
  2038. /* if accumulator is too long for local storage, then allocate */
  2039. needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
  2040. /* [needbytes also used below if 1/lhs needed] */
  2041. if (needbytes>sizeof(dacbuff)) {
  2042. allocdac=(decNumber *)malloc(needbytes);
  2043. if (allocdac==nullptr) { /* hopeless -- abandon */
  2044. status|=DEC_Insufficient_storage;
  2045. break;}
  2046. dac=allocdac; /* use the allocated space */
  2047. }
  2048. /* here, aset is set up and accumulator is ready for use */
  2049. if (!useint) { /* non-integral rhs */
  2050. /* x ** y; special-case x=1 here as it will otherwise always */
  2051. /* reduce to integer 1; decLnOp has a fastpath which detects */
  2052. /* the case of x=1 */
  2053. decLnOp(dac, lhs, &aset, &status); /* dac=ln(lhs) */
  2054. /* [no error possible, as lhs 0 already handled] */
  2055. if (ISZERO(dac)) { /* x==1, 1.0, etc. */
  2056. /* need to return fully-padded 1.0000 etc., but rhsint->1 */
  2057. *dac->lsu=1; /* was 0, make int 1 */
  2058. if (!rhsint) { /* add padding */
  2059. Int shift=set->digits-1;
  2060. dac->digits=decShiftToMost(dac->lsu, 1, shift);
  2061. dac->exponent=-shift; /* make 1.0000... */
  2062. status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
  2063. }
  2064. }
  2065. else {
  2066. decMultiplyOp(dac, dac, rhs, &aset, &status); /* dac=dac*rhs */
  2067. decExpOp(dac, dac, &aset, &status); /* dac=exp(dac) */
  2068. }
  2069. /* and drop through for final rounding */
  2070. } /* non-integer rhs */
  2071. else { /* carry on with integer */
  2072. uprv_decNumberZero(dac); /* acc=1 */
  2073. *dac->lsu=1; /* .. */
  2074. /* if a negative power the constant 1 is needed, and if not subset */
  2075. /* invert the lhs now rather than inverting the result later */
  2076. if (decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */
  2077. decNumber *inv=invbuff; /* assume use fixed buffer */
  2078. uprv_decNumberCopy(&dnOne, dac); /* dnOne=1; [needed now or later] */
  2079. #if DECSUBSET
  2080. if (set->extended) { /* need to calculate 1/lhs */
  2081. #endif
  2082. /* divide lhs into 1, putting result in dac [dac=1/dac] */
  2083. decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
  2084. /* now locate or allocate space for the inverted lhs */
  2085. if (needbytes>sizeof(invbuff)) {
  2086. allocinv=(decNumber *)malloc(needbytes);
  2087. if (allocinv==nullptr) { /* hopeless -- abandon */
  2088. status|=DEC_Insufficient_storage;
  2089. break;}
  2090. inv=allocinv; /* use the allocated space */
  2091. }
  2092. /* [inv now points to big-enough buffer or allocated storage] */
  2093. uprv_decNumberCopy(inv, dac); /* copy the 1/lhs */
  2094. uprv_decNumberCopy(dac, &dnOne); /* restore acc=1 */
  2095. lhs=inv; /* .. and go forward with new lhs */
  2096. #if DECSUBSET
  2097. }
  2098. #endif
  2099. }
  2100. /* Raise-to-the-power loop... */
  2101. seenbit=0; /* set once a 1-bit is encountered */
  2102. for (i=1;;i++){ /* for each bit [top bit ignored] */
  2103. /* abandon if had overflow or terminal underflow */
  2104. if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
  2105. if (status&DEC_Overflow || ISZERO(dac)) break;
  2106. }
  2107. /* [the following two lines revealed an optimizer bug in a C++ */
  2108. /* compiler, with symptom: 5**3 -> 25, when n=n+n was used] */
  2109. n=n<<1; /* move next bit to testable position */
  2110. if (n<0) { /* top bit is set */
  2111. seenbit=1; /* OK, significant bit seen */
  2112. decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x */
  2113. }
  2114. if (i==31) break; /* that was the last bit */
  2115. if (!seenbit) continue; /* no need to square 1 */
  2116. decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square] */
  2117. } /*i*/ /* 32 bits */
  2118. /* complete internal overflow or underflow processing */
  2119. if (status & (DEC_Overflow|DEC_Underflow)) {
  2120. #if DECSUBSET
  2121. /* If subset, and power was negative, reverse the kind of -erflow */
  2122. /* [1/x not yet done] */
  2123. if (!set->extended && decNumberIsNegative(rhs)) {
  2124. if (status & DEC_Overflow)
  2125. status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
  2126. else { /* trickier -- Underflow may or may not be set */
  2127. status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both] */
  2128. status|=DEC_Overflow;
  2129. }
  2130. }
  2131. #endif
  2132. dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign */
  2133. /* round subnormals [to set.digits rather than aset.digits] */
  2134. /* or set overflow result similarly as required */
  2135. decFinalize(dac, set, &residue, &status);
  2136. uprv_decNumberCopy(res, dac); /* copy to result (is now OK length) */
  2137. break;
  2138. }
  2139. #if DECSUBSET
  2140. if (!set->extended && /* subset math */
  2141. decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */
  2142. /* so divide result into 1 [dac=1/dac] */
  2143. decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
  2144. }
  2145. #endif
  2146. } /* rhs integer path */
  2147. /* reduce result to the requested length and copy to result */
  2148. decCopyFit(res, dac, set, &residue, &status);
  2149. decFinish(res, set, &residue, &status); /* final cleanup */
  2150. #if DECSUBSET
  2151. if (!set->extended) decTrim(res, set, 0, 1, &dropped); /* trailing zeros */
  2152. #endif
  2153. } while(0); /* end protected */
  2154. if (allocdac!=nullptr) free(allocdac); /* drop any storage used */
  2155. if (allocinv!=nullptr) free(allocinv); /* .. */
  2156. #if DECSUBSET
  2157. if (alloclhs!=nullptr) free(alloclhs); /* .. */
  2158. if (allocrhs!=nullptr) free(allocrhs); /* .. */
  2159. #endif
  2160. if (status!=0) decStatus(res, status, set);
  2161. #if DECCHECK
  2162. decCheckInexact(res, set);
  2163. #endif
  2164. return res;
  2165. } /* decNumberPower */
  2166. /* ------------------------------------------------------------------ */
  2167. /* decNumberQuantize -- force exponent to requested value */
  2168. /* */
  2169. /* This computes C = op(A, B), where op adjusts the coefficient */
  2170. /* of C (by rounding or shifting) such that the exponent (-scale) */
  2171. /* of C has exponent of B. The numerical value of C will equal A, */
  2172. /* except for the effects of any rounding that occurred. */
  2173. /* */
  2174. /* res is C, the result. C may be A or B */
  2175. /* lhs is A, the number to adjust */
  2176. /* rhs is B, the number with exponent to match */
  2177. /* set is the context */
  2178. /* */
  2179. /* C must have space for set->digits digits. */
  2180. /* */
  2181. /* Unless there is an error or the result is infinite, the exponent */
  2182. /* after the operation is guaranteed to be equal to that of B. */
  2183. /* ------------------------------------------------------------------ */
  2184. U_CAPI decNumber * U_EXPORT2 uprv_decNumberQuantize(decNumber *res, const decNumber *lhs,
  2185. const decNumber *rhs, decContext *set) {
  2186. uInt status=0; /* accumulator */
  2187. decQuantizeOp(res, lhs, rhs, set, 1, &status);
  2188. if (status!=0) decStatus(res, status, set);
  2189. return res;
  2190. } /* decNumberQuantize */
  2191. /* ------------------------------------------------------------------ */
  2192. /* decNumberReduce -- remove trailing zeros */
  2193. /* */
  2194. /* This computes C = 0 + A, and normalizes the result */
  2195. /* */
  2196. /* res is C, the result. C may be A */
  2197. /* rhs is A */
  2198. /* set is the context */
  2199. /* */
  2200. /* C must have space for set->digits digits. */
  2201. /* ------------------------------------------------------------------ */
  2202. /* Previously known as Normalize */
  2203. U_CAPI decNumber * U_EXPORT2 uprv_decNumberNormalize(decNumber *res, const decNumber *rhs,
  2204. decContext *set) {
  2205. return uprv_decNumberReduce(res, rhs, set);
  2206. } /* decNumberNormalize */
  2207. U_CAPI decNumber * U_EXPORT2 uprv_decNumberReduce(decNumber *res, const decNumber *rhs,
  2208. decContext *set) {
  2209. #if DECSUBSET
  2210. decNumber *allocrhs=nullptr; /* non-nullptr if rounded rhs allocated */
  2211. #endif
  2212. uInt status=0; /* as usual */
  2213. Int residue=0; /* as usual */
  2214. Int dropped; /* work */
  2215. #if DECCHECK
  2216. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  2217. #endif
  2218. do { /* protect allocated storage */
  2219. #if DECSUBSET
  2220. if (!set->extended) {
  2221. /* reduce operand and set lostDigits status, as needed */
  2222. if (rhs->digits>set->digits) {
  2223. allocrhs=decRoundOperand(rhs, set, &status);
  2224. if (allocrhs==nullptr) break;
  2225. rhs=allocrhs;
  2226. }
  2227. }
  2228. #endif
  2229. /* [following code does not require input rounding] */
  2230. /* Infinities copy through; NaNs need usual treatment */
  2231. if (decNumberIsNaN(rhs)) {
  2232. decNaNs(res, rhs, nullptr, set, &status);
  2233. break;
  2234. }
  2235. /* reduce result to the requested length and copy to result */
  2236. decCopyFit(res, rhs, set, &residue, &status); /* copy & round */
  2237. decFinish(res, set, &residue, &status); /* cleanup/set flags */
  2238. decTrim(res, set, 1, 0, &dropped); /* normalize in place */
  2239. /* [may clamp] */
  2240. } while(0); /* end protected */
  2241. #if DECSUBSET
  2242. if (allocrhs !=nullptr) free(allocrhs); /* .. */
  2243. #endif
  2244. if (status!=0) decStatus(res, status, set);/* then report status */
  2245. return res;
  2246. } /* decNumberReduce */
  2247. /* ------------------------------------------------------------------ */
  2248. /* decNumberRescale -- force exponent to requested value */
  2249. /* */
  2250. /* This computes C = op(A, B), where op adjusts the coefficient */
  2251. /* of C (by rounding or shifting) such that the exponent (-scale) */
  2252. /* of C has the value B. The numerical value of C will equal A, */
  2253. /* except for the effects of any rounding that occurred. */
  2254. /* */
  2255. /* res is C, the result. C may be A or B */
  2256. /* lhs is A, the number to adjust */
  2257. /* rhs is B, the requested exponent */
  2258. /* set is the context */
  2259. /* */
  2260. /* C must have space for set->digits digits. */
  2261. /* */
  2262. /* Unless there is an error or the result is infinite, the exponent */
  2263. /* after the operation is guaranteed to be equal to B. */
  2264. /* ------------------------------------------------------------------ */
  2265. U_CAPI decNumber * U_EXPORT2 uprv_decNumberRescale(decNumber *res, const decNumber *lhs,
  2266. const decNumber *rhs, decContext *set) {
  2267. uInt status=0; /* accumulator */
  2268. decQuantizeOp(res, lhs, rhs, set, 0, &status);
  2269. if (status!=0) decStatus(res, status, set);
  2270. return res;
  2271. } /* decNumberRescale */
  2272. /* ------------------------------------------------------------------ */
  2273. /* decNumberRemainder -- divide and return remainder */
  2274. /* */
  2275. /* This computes C = A % B */
  2276. /* */
  2277. /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
  2278. /* lhs is A */
  2279. /* rhs is B */
  2280. /* set is the context */
  2281. /* */
  2282. /* C must have space for set->digits digits. */
  2283. /* ------------------------------------------------------------------ */
  2284. U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainder(decNumber *res, const decNumber *lhs,
  2285. const decNumber *rhs, decContext *set) {
  2286. uInt status=0; /* accumulator */
  2287. decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
  2288. if (status!=0) decStatus(res, status, set);
  2289. #if DECCHECK
  2290. decCheckInexact(res, set);
  2291. #endif
  2292. return res;
  2293. } /* decNumberRemainder */
  2294. /* ------------------------------------------------------------------ */
  2295. /* decNumberRemainderNear -- divide and return remainder from nearest */
  2296. /* */
  2297. /* This computes C = A % B, where % is the IEEE remainder operator */
  2298. /* */
  2299. /* res is C, the result. C may be A and/or B (e.g., X=X%X) */
  2300. /* lhs is A */
  2301. /* rhs is B */
  2302. /* set is the context */
  2303. /* */
  2304. /* C must have space for set->digits digits. */
  2305. /* ------------------------------------------------------------------ */
  2306. U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainderNear(decNumber *res, const decNumber *lhs,
  2307. const decNumber *rhs, decContext *set) {
  2308. uInt status=0; /* accumulator */
  2309. decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
  2310. if (status!=0) decStatus(res, status, set);
  2311. #if DECCHECK
  2312. decCheckInexact(res, set);
  2313. #endif
  2314. return res;
  2315. } /* decNumberRemainderNear */
  2316. /* ------------------------------------------------------------------ */
  2317. /* decNumberRotate -- rotate the coefficient of a Number left/right */
  2318. /* */
  2319. /* This computes C = A rot B (in base ten and rotating set->digits */
  2320. /* digits). */
  2321. /* */
  2322. /* res is C, the result. C may be A and/or B (e.g., X=XrotX) */
  2323. /* lhs is A */
  2324. /* rhs is B, the number of digits to rotate (-ve to right) */
  2325. /* set is the context */
  2326. /* */
  2327. /* The digits of the coefficient of A are rotated to the left (if B */
  2328. /* is positive) or to the right (if B is negative) without adjusting */
  2329. /* the exponent or the sign of A. If lhs->digits is less than */
  2330. /* set->digits the coefficient is padded with zeros on the left */
  2331. /* before the rotate. Any leading zeros in the result are removed */
  2332. /* as usual. */
  2333. /* */
  2334. /* B must be an integer (q=0) and in the range -set->digits through */
  2335. /* +set->digits. */
  2336. /* C must have space for set->digits digits. */
  2337. /* NaNs are propagated as usual. Infinities are unaffected (but */
  2338. /* B must be valid). No status is set unless B is invalid or an */
  2339. /* operand is an sNaN. */
  2340. /* ------------------------------------------------------------------ */
  2341. U_CAPI decNumber * U_EXPORT2 uprv_decNumberRotate(decNumber *res, const decNumber *lhs,
  2342. const decNumber *rhs, decContext *set) {
  2343. uInt status=0; /* accumulator */
  2344. Int rotate; /* rhs as an Int */
  2345. #if DECCHECK
  2346. if (decCheckOperands(res, lhs, rhs, set)) return res;
  2347. #endif
  2348. /* NaNs propagate as normal */
  2349. if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
  2350. decNaNs(res, lhs, rhs, set, &status);
  2351. /* rhs must be an integer */
  2352. else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
  2353. status=DEC_Invalid_operation;
  2354. else { /* both numeric, rhs is an integer */
  2355. rotate=decGetInt(rhs); /* [cannot fail] */
  2356. if (rotate==BADINT /* something bad .. */
  2357. || rotate==BIGODD || rotate==BIGEVEN /* .. very big .. */
  2358. || abs(rotate)>set->digits) /* .. or out of range */
  2359. status=DEC_Invalid_operation;
  2360. else { /* rhs is OK */
  2361. uprv_decNumberCopy(res, lhs);
  2362. /* convert -ve rotate to equivalent positive rotation */
  2363. if (rotate<0) rotate=set->digits+rotate;
  2364. if (rotate!=0 && rotate!=set->digits /* zero or full rotation */
  2365. && !decNumberIsInfinite(res)) { /* lhs was infinite */
  2366. /* left-rotate to do; 0 < rotate < set->digits */
  2367. uInt units, shift; /* work */
  2368. uInt msudigits; /* digits in result msu */
  2369. Unit *msu=res->lsu+D2U(res->digits)-1; /* current msu */
  2370. Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu */
  2371. for (msu++; msu<=msumax; msu++) *msu=0; /* ensure high units=0 */
  2372. res->digits=set->digits; /* now full-length */
  2373. msudigits=MSUDIGITS(res->digits); /* actual digits in msu */
  2374. /* rotation here is done in-place, in three steps */
  2375. /* 1. shift all to least up to one unit to unit-align final */
  2376. /* lsd [any digits shifted out are rotated to the left, */
  2377. /* abutted to the original msd (which may require split)] */
  2378. /* */
  2379. /* [if there are no whole units left to rotate, the */
  2380. /* rotation is now complete] */
  2381. /* */
  2382. /* 2. shift to least, from below the split point only, so that */
  2383. /* the final msd is in the right place in its Unit [any */
  2384. /* digits shifted out will fit exactly in the current msu, */
  2385. /* left aligned, no split required] */
  2386. /* */
  2387. /* 3. rotate all the units by reversing left part, right */
  2388. /* part, and then whole */
  2389. /* */
  2390. /* example: rotate right 8 digits (2 units + 2), DECDPUN=3. */
  2391. /* */
  2392. /* start: 00a bcd efg hij klm npq */
  2393. /* */
  2394. /* 1a 000 0ab cde fgh|ijk lmn [pq saved] */
  2395. /* 1b 00p qab cde fgh|ijk lmn */
  2396. /* */
  2397. /* 2a 00p qab cde fgh|00i jkl [mn saved] */
  2398. /* 2b mnp qab cde fgh|00i jkl */
  2399. /* */
  2400. /* 3a fgh cde qab mnp|00i jkl */
  2401. /* 3b fgh cde qab mnp|jkl 00i */
  2402. /* 3c 00i jkl mnp qab cde fgh */
  2403. /* Step 1: amount to shift is the partial right-rotate count */
  2404. rotate=set->digits-rotate; /* make it right-rotate */
  2405. units=rotate/DECDPUN; /* whole units to rotate */
  2406. shift=rotate%DECDPUN; /* left-over digits count */
  2407. if (shift>0) { /* not an exact number of units */
  2408. uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */
  2409. decShiftToLeast(res->lsu, D2U(res->digits), shift);
  2410. if (shift>msudigits) { /* msumax-1 needs >0 digits */
  2411. uInt rem=save%powers[shift-msudigits];/* split save */
  2412. *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert */
  2413. *(msumax-1)=*(msumax-1)
  2414. +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* .. */
  2415. }
  2416. else { /* all fits in msumax */
  2417. *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1] */
  2418. }
  2419. } /* digits shift needed */
  2420. /* If whole units to rotate... */
  2421. if (units>0) { /* some to do */
  2422. /* Step 2: the units to touch are the whole ones in rotate, */
  2423. /* if any, and the shift is DECDPUN-msudigits (which may be */
  2424. /* 0, again) */
  2425. shift=DECDPUN-msudigits;
  2426. if (shift>0) { /* not an exact number of units */
  2427. uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */
  2428. decShiftToLeast(res->lsu, units, shift);
  2429. *msumax=*msumax+(Unit)(save*powers[msudigits]);
  2430. } /* partial shift needed */
  2431. /* Step 3: rotate the units array using triple reverse */
  2432. /* (reversing is easy and fast) */
  2433. decReverse(res->lsu+units, msumax); /* left part */
  2434. decReverse(res->lsu, res->lsu+units-1); /* right part */
  2435. decReverse(res->lsu, msumax); /* whole */
  2436. } /* whole units to rotate */
  2437. /* the rotation may have left an undetermined number of zeros */
  2438. /* on the left, so true length needs to be calculated */
  2439. res->digits=decGetDigits(res->lsu, static_cast<int32_t>(msumax-res->lsu+1));
  2440. } /* rotate needed */
  2441. } /* rhs OK */
  2442. } /* numerics */
  2443. if (status!=0) decStatus(res, status, set);
  2444. return res;
  2445. } /* decNumberRotate */
  2446. /* ------------------------------------------------------------------ */
  2447. /* decNumberSameQuantum -- test for equal exponents */
  2448. /* */
  2449. /* res is the result number, which will contain either 0 or 1 */
  2450. /* lhs is a number to test */
  2451. /* rhs is the second (usually a pattern) */
  2452. /* */
  2453. /* No errors are possible and no context is needed. */
  2454. /* ------------------------------------------------------------------ */
  2455. U_CAPI decNumber * U_EXPORT2 uprv_decNumberSameQuantum(decNumber *res, const decNumber *lhs,
  2456. const decNumber *rhs) {
  2457. Unit ret=0; /* return value */
  2458. #if DECCHECK
  2459. if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
  2460. #endif
  2461. if (SPECIALARGS) {
  2462. if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
  2463. else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
  2464. /* [anything else with a special gives 0] */
  2465. }
  2466. else if (lhs->exponent==rhs->exponent) ret=1;
  2467. uprv_decNumberZero(res); /* OK to overwrite an operand now */
  2468. *res->lsu=ret;
  2469. return res;
  2470. } /* decNumberSameQuantum */
  2471. /* ------------------------------------------------------------------ */
  2472. /* decNumberScaleB -- multiply by a power of 10 */
  2473. /* */
  2474. /* This computes C = A x 10**B where B is an integer (q=0) with */
  2475. /* maximum magnitude 2*(emax+digits) */
  2476. /* */
  2477. /* res is C, the result. C may be A or B */
  2478. /* lhs is A, the number to adjust */
  2479. /* rhs is B, the requested power of ten to use */
  2480. /* set is the context */
  2481. /* */
  2482. /* C must have space for set->digits digits. */
  2483. /* */
  2484. /* The result may underflow or overflow. */
  2485. /* ------------------------------------------------------------------ */
  2486. U_CAPI decNumber * U_EXPORT2 uprv_decNumberScaleB(decNumber *res, const decNumber *lhs,
  2487. const decNumber *rhs, decContext *set) {
  2488. Int reqexp; /* requested exponent change [B] */
  2489. uInt status=0; /* accumulator */
  2490. Int residue; /* work */
  2491. #if DECCHECK
  2492. if (decCheckOperands(res, lhs, rhs, set)) return res;
  2493. #endif
  2494. /* Handle special values except lhs infinite */
  2495. if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
  2496. decNaNs(res, lhs, rhs, set, &status);
  2497. /* rhs must be an integer */
  2498. else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
  2499. status=DEC_Invalid_operation;
  2500. else {
  2501. /* lhs is a number; rhs is a finite with q==0 */
  2502. reqexp=decGetInt(rhs); /* [cannot fail] */
  2503. if (reqexp==BADINT /* something bad .. */
  2504. || reqexp==BIGODD || reqexp==BIGEVEN /* .. very big .. */
  2505. || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range */
  2506. status=DEC_Invalid_operation;
  2507. else { /* rhs is OK */
  2508. uprv_decNumberCopy(res, lhs); /* all done if infinite lhs */
  2509. if (!decNumberIsInfinite(res)) { /* prepare to scale */
  2510. res->exponent+=reqexp; /* adjust the exponent */
  2511. residue=0;
  2512. decFinalize(res, set, &residue, &status); /* .. and check */
  2513. } /* finite LHS */
  2514. } /* rhs OK */
  2515. } /* rhs finite */
  2516. if (status!=0) decStatus(res, status, set);
  2517. return res;
  2518. } /* decNumberScaleB */
  2519. /* ------------------------------------------------------------------ */
  2520. /* decNumberShift -- shift the coefficient of a Number left or right */
  2521. /* */
  2522. /* This computes C = A << B or C = A >> -B (in base ten). */
  2523. /* */
  2524. /* res is C, the result. C may be A and/or B (e.g., X=X<<X) */
  2525. /* lhs is A */
  2526. /* rhs is B, the number of digits to shift (-ve to right) */
  2527. /* set is the context */
  2528. /* */
  2529. /* The digits of the coefficient of A are shifted to the left (if B */
  2530. /* is positive) or to the right (if B is negative) without adjusting */
  2531. /* the exponent or the sign of A. */
  2532. /* */
  2533. /* B must be an integer (q=0) and in the range -set->digits through */
  2534. /* +set->digits. */
  2535. /* C must have space for set->digits digits. */
  2536. /* NaNs are propagated as usual. Infinities are unaffected (but */
  2537. /* B must be valid). No status is set unless B is invalid or an */
  2538. /* operand is an sNaN. */
  2539. /* ------------------------------------------------------------------ */
  2540. U_CAPI decNumber * U_EXPORT2 uprv_decNumberShift(decNumber *res, const decNumber *lhs,
  2541. const decNumber *rhs, decContext *set) {
  2542. uInt status=0; /* accumulator */
  2543. Int shift; /* rhs as an Int */
  2544. #if DECCHECK
  2545. if (decCheckOperands(res, lhs, rhs, set)) return res;
  2546. #endif
  2547. /* NaNs propagate as normal */
  2548. if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
  2549. decNaNs(res, lhs, rhs, set, &status);
  2550. /* rhs must be an integer */
  2551. else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
  2552. status=DEC_Invalid_operation;
  2553. else { /* both numeric, rhs is an integer */
  2554. shift=decGetInt(rhs); /* [cannot fail] */
  2555. if (shift==BADINT /* something bad .. */
  2556. || shift==BIGODD || shift==BIGEVEN /* .. very big .. */
  2557. || abs(shift)>set->digits) /* .. or out of range */
  2558. status=DEC_Invalid_operation;
  2559. else { /* rhs is OK */
  2560. uprv_decNumberCopy(res, lhs);
  2561. if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do */
  2562. if (shift>0) { /* to left */
  2563. if (shift==set->digits) { /* removing all */
  2564. *res->lsu=0; /* so place 0 */
  2565. res->digits=1; /* .. */
  2566. }
  2567. else { /* */
  2568. /* first remove leading digits if necessary */
  2569. if (res->digits+shift>set->digits) {
  2570. decDecap(res, res->digits+shift-set->digits);
  2571. /* that updated res->digits; may have gone to 1 (for a */
  2572. /* single digit or for zero */
  2573. }
  2574. if (res->digits>1 || *res->lsu) /* if non-zero.. */
  2575. res->digits=decShiftToMost(res->lsu, res->digits, shift);
  2576. } /* partial left */
  2577. } /* left */
  2578. else { /* to right */
  2579. if (-shift>=res->digits) { /* discarding all */
  2580. *res->lsu=0; /* so place 0 */
  2581. res->digits=1; /* .. */
  2582. }
  2583. else {
  2584. decShiftToLeast(res->lsu, D2U(res->digits), -shift);
  2585. res->digits-=(-shift);
  2586. }
  2587. } /* to right */
  2588. } /* non-0 non-Inf shift */
  2589. } /* rhs OK */
  2590. } /* numerics */
  2591. if (status!=0) decStatus(res, status, set);
  2592. return res;
  2593. } /* decNumberShift */
  2594. /* ------------------------------------------------------------------ */
  2595. /* decNumberSquareRoot -- square root operator */
  2596. /* */
  2597. /* This computes C = squareroot(A) */
  2598. /* */
  2599. /* res is C, the result. C may be A */
  2600. /* rhs is A */
  2601. /* set is the context; note that rounding mode has no effect */
  2602. /* */
  2603. /* C must have space for set->digits digits. */
  2604. /* ------------------------------------------------------------------ */
  2605. /* This uses the following varying-precision algorithm in: */
  2606. /* */
  2607. /* Properly Rounded Variable Precision Square Root, T. E. Hull and */
  2608. /* A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
  2609. /* pp229-237, ACM, September 1985. */
  2610. /* */
  2611. /* The square-root is calculated using Newton's method, after which */
  2612. /* a check is made to ensure the result is correctly rounded. */
  2613. /* */
  2614. /* % [Reformatted original Numerical Turing source code follows.] */
  2615. /* function sqrt(x : real) : real */
  2616. /* % sqrt(x) returns the properly rounded approximation to the square */
  2617. /* % root of x, in the precision of the calling environment, or it */
  2618. /* % fails if x < 0. */
  2619. /* % t e hull and a abrham, august, 1984 */
  2620. /* if x <= 0 then */
  2621. /* if x < 0 then */
  2622. /* assert false */
  2623. /* else */
  2624. /* result 0 */
  2625. /* end if */
  2626. /* end if */
  2627. /* var f := setexp(x, 0) % fraction part of x [0.1 <= x < 1] */
  2628. /* var e := getexp(x) % exponent part of x */
  2629. /* var approx : real */
  2630. /* if e mod 2 = 0 then */
  2631. /* approx := .259 + .819 * f % approx to root of f */
  2632. /* else */
  2633. /* f := f/l0 % adjustments */
  2634. /* e := e + 1 % for odd */
  2635. /* approx := .0819 + 2.59 * f % exponent */
  2636. /* end if */
  2637. /* */
  2638. /* var p:= 3 */
  2639. /* const maxp := currentprecision + 2 */
  2640. /* loop */
  2641. /* p := min(2*p - 2, maxp) % p = 4,6,10, . . . , maxp */
  2642. /* precision p */
  2643. /* approx := .5 * (approx + f/approx) */
  2644. /* exit when p = maxp */
  2645. /* end loop */
  2646. /* */
  2647. /* % approx is now within 1 ulp of the properly rounded square root */
  2648. /* % of f; to ensure proper rounding, compare squares of (approx - */
  2649. /* % l/2 ulp) and (approx + l/2 ulp) with f. */
  2650. /* p := currentprecision */
  2651. /* begin */
  2652. /* precision p + 2 */
  2653. /* const approxsubhalf := approx - setexp(.5, -p) */
  2654. /* if mulru(approxsubhalf, approxsubhalf) > f then */
  2655. /* approx := approx - setexp(.l, -p + 1) */
  2656. /* else */
  2657. /* const approxaddhalf := approx + setexp(.5, -p) */
  2658. /* if mulrd(approxaddhalf, approxaddhalf) < f then */
  2659. /* approx := approx + setexp(.l, -p + 1) */
  2660. /* end if */
  2661. /* end if */
  2662. /* end */
  2663. /* result setexp(approx, e div 2) % fix exponent */
  2664. /* end sqrt */
  2665. /* ------------------------------------------------------------------ */
  2666. #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
  2667. #pragma GCC diagnostic push
  2668. #pragma GCC diagnostic ignored "-Warray-bounds"
  2669. #endif
  2670. U_CAPI decNumber * U_EXPORT2 uprv_decNumberSquareRoot(decNumber *res, const decNumber *rhs,
  2671. decContext *set) {
  2672. decContext workset, approxset; /* work contexts */
  2673. decNumber dzero; /* used for constant zero */
  2674. Int maxp; /* largest working precision */
  2675. Int workp; /* working precision */
  2676. Int residue=0; /* rounding residue */
  2677. uInt status=0, ignore=0; /* status accumulators */
  2678. uInt rstatus; /* .. */
  2679. Int exp; /* working exponent */
  2680. Int ideal; /* ideal (preferred) exponent */
  2681. Int needbytes; /* work */
  2682. Int dropped; /* .. */
  2683. #if DECSUBSET
  2684. decNumber *allocrhs=nullptr; /* non-nullptr if rounded rhs allocated */
  2685. #endif
  2686. /* buffer for f [needs +1 in case DECBUFFER 0] */
  2687. decNumber buff[D2N(DECBUFFER+1)];
  2688. /* buffer for a [needs +2 to match likely maxp] */
  2689. decNumber bufa[D2N(DECBUFFER+2)];
  2690. /* buffer for temporary, b [must be same size as a] */
  2691. decNumber bufb[D2N(DECBUFFER+2)];
  2692. decNumber *allocbuff=nullptr; /* -> allocated buff, iff allocated */
  2693. decNumber *allocbufa=nullptr; /* -> allocated bufa, iff allocated */
  2694. decNumber *allocbufb=nullptr; /* -> allocated bufb, iff allocated */
  2695. decNumber *f=buff; /* reduced fraction */
  2696. decNumber *a=bufa; /* approximation to result */
  2697. decNumber *b=bufb; /* intermediate result */
  2698. /* buffer for temporary variable, up to 3 digits */
  2699. decNumber buft[D2N(3)];
  2700. decNumber *t=buft; /* up-to-3-digit constant or work */
  2701. #if DECCHECK
  2702. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  2703. #endif
  2704. do { /* protect allocated storage */
  2705. #if DECSUBSET
  2706. if (!set->extended) {
  2707. /* reduce operand and set lostDigits status, as needed */
  2708. if (rhs->digits>set->digits) {
  2709. allocrhs=decRoundOperand(rhs, set, &status);
  2710. if (allocrhs==nullptr) break;
  2711. /* [Note: 'f' allocation below could reuse this buffer if */
  2712. /* used, but as this is rare they are kept separate for clarity.] */
  2713. rhs=allocrhs;
  2714. }
  2715. }
  2716. #endif
  2717. /* [following code does not require input rounding] */
  2718. /* handle infinities and NaNs */
  2719. if (SPECIALARG) {
  2720. if (decNumberIsInfinite(rhs)) { /* an infinity */
  2721. if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
  2722. else uprv_decNumberCopy(res, rhs); /* +Infinity */
  2723. }
  2724. else decNaNs(res, rhs, nullptr, set, &status); /* a NaN */
  2725. break;
  2726. }
  2727. /* calculate the ideal (preferred) exponent [floor(exp/2)] */
  2728. /* [It would be nicer to write: ideal=rhs->exponent>>1, but this */
  2729. /* generates a compiler warning. Generated code is the same.] */
  2730. ideal=(rhs->exponent&~1)/2; /* target */
  2731. /* handle zeros */
  2732. if (ISZERO(rhs)) {
  2733. uprv_decNumberCopy(res, rhs); /* could be 0 or -0 */
  2734. res->exponent=ideal; /* use the ideal [safe] */
  2735. /* use decFinish to clamp any out-of-range exponent, etc. */
  2736. decFinish(res, set, &residue, &status);
  2737. break;
  2738. }
  2739. /* any other -x is an oops */
  2740. if (decNumberIsNegative(rhs)) {
  2741. status|=DEC_Invalid_operation;
  2742. break;
  2743. }
  2744. /* space is needed for three working variables */
  2745. /* f -- the same precision as the RHS, reduced to 0.01->0.99... */
  2746. /* a -- Hull's approximation -- precision, when assigned, is */
  2747. /* currentprecision+1 or the input argument precision, */
  2748. /* whichever is larger (+2 for use as temporary) */
  2749. /* b -- intermediate temporary result (same size as a) */
  2750. /* if any is too long for local storage, then allocate */
  2751. workp=MAXI(set->digits+1, rhs->digits); /* actual rounding precision */
  2752. workp=MAXI(workp, 7); /* at least 7 for low cases */
  2753. maxp=workp+2; /* largest working precision */
  2754. needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
  2755. if (needbytes>(Int)sizeof(buff)) {
  2756. allocbuff=(decNumber *)malloc(needbytes);
  2757. if (allocbuff==nullptr) { /* hopeless -- abandon */
  2758. status|=DEC_Insufficient_storage;
  2759. break;}
  2760. f=allocbuff; /* use the allocated space */
  2761. }
  2762. /* a and b both need to be able to hold a maxp-length number */
  2763. needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
  2764. if (needbytes>(Int)sizeof(bufa)) { /* [same applies to b] */
  2765. allocbufa=(decNumber *)malloc(needbytes);
  2766. allocbufb=(decNumber *)malloc(needbytes);
  2767. if (allocbufa==nullptr || allocbufb==nullptr) { /* hopeless */
  2768. status|=DEC_Insufficient_storage;
  2769. break;}
  2770. a=allocbufa; /* use the allocated spaces */
  2771. b=allocbufb; /* .. */
  2772. }
  2773. /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1 */
  2774. uprv_decNumberCopy(f, rhs);
  2775. exp=f->exponent+f->digits; /* adjusted to Hull rules */
  2776. f->exponent=-(f->digits); /* to range */
  2777. /* set up working context */
  2778. uprv_decContextDefault(&workset, DEC_INIT_DECIMAL64);
  2779. workset.emax=DEC_MAX_EMAX;
  2780. workset.emin=DEC_MIN_EMIN;
  2781. /* [Until further notice, no error is possible and status bits */
  2782. /* (Rounded, etc.) should be ignored, not accumulated.] */
  2783. /* Calculate initial approximation, and allow for odd exponent */
  2784. workset.digits=workp; /* p for initial calculation */
  2785. t->bits=0; t->digits=3;
  2786. a->bits=0; a->digits=3;
  2787. if ((exp & 1)==0) { /* even exponent */
  2788. /* Set t=0.259, a=0.819 */
  2789. t->exponent=-3;
  2790. a->exponent=-3;
  2791. #if DECDPUN>=3
  2792. t->lsu[0]=259;
  2793. a->lsu[0]=819;
  2794. #elif DECDPUN==2
  2795. t->lsu[0]=59; t->lsu[1]=2;
  2796. a->lsu[0]=19; a->lsu[1]=8;
  2797. #else
  2798. t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
  2799. a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
  2800. #endif
  2801. }
  2802. else { /* odd exponent */
  2803. /* Set t=0.0819, a=2.59 */
  2804. f->exponent--; /* f=f/10 */
  2805. exp++; /* e=e+1 */
  2806. t->exponent=-4;
  2807. a->exponent=-2;
  2808. #if DECDPUN>=3
  2809. t->lsu[0]=819;
  2810. a->lsu[0]=259;
  2811. #elif DECDPUN==2
  2812. t->lsu[0]=19; t->lsu[1]=8;
  2813. a->lsu[0]=59; a->lsu[1]=2;
  2814. #else
  2815. t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
  2816. a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
  2817. #endif
  2818. }
  2819. decMultiplyOp(a, a, f, &workset, &ignore); /* a=a*f */
  2820. decAddOp(a, a, t, &workset, 0, &ignore); /* ..+t */
  2821. /* [a is now the initial approximation for sqrt(f), calculated with */
  2822. /* currentprecision, which is also a's precision.] */
  2823. /* the main calculation loop */
  2824. uprv_decNumberZero(&dzero); /* make 0 */
  2825. uprv_decNumberZero(t); /* set t = 0.5 */
  2826. t->lsu[0]=5; /* .. */
  2827. t->exponent=-1; /* .. */
  2828. workset.digits=3; /* initial p */
  2829. for (; workset.digits<maxp;) {
  2830. /* set p to min(2*p - 2, maxp) [hence 3; or: 4, 6, 10, ... , maxp] */
  2831. workset.digits=MINI(workset.digits*2-2, maxp);
  2832. /* a = 0.5 * (a + f/a) */
  2833. /* [calculated at p then rounded to currentprecision] */
  2834. decDivideOp(b, f, a, &workset, DIVIDE, &ignore); /* b=f/a */
  2835. decAddOp(b, b, a, &workset, 0, &ignore); /* b=b+a */
  2836. decMultiplyOp(a, b, t, &workset, &ignore); /* a=b*0.5 */
  2837. } /* loop */
  2838. /* Here, 0.1 <= a < 1 [Hull], and a has maxp digits */
  2839. /* now reduce to length, etc.; this needs to be done with a */
  2840. /* having the correct exponent so as to handle subnormals */
  2841. /* correctly */
  2842. approxset=*set; /* get emin, emax, etc. */
  2843. approxset.round=DEC_ROUND_HALF_EVEN;
  2844. a->exponent+=exp/2; /* set correct exponent */
  2845. rstatus=0; /* clear status */
  2846. residue=0; /* .. and accumulator */
  2847. decCopyFit(a, a, &approxset, &residue, &rstatus); /* reduce (if needed) */
  2848. decFinish(a, &approxset, &residue, &rstatus); /* clean and finalize */
  2849. /* Overflow was possible if the input exponent was out-of-range, */
  2850. /* in which case quit */
  2851. if (rstatus&DEC_Overflow) {
  2852. status=rstatus; /* use the status as-is */
  2853. uprv_decNumberCopy(res, a); /* copy to result */
  2854. break;
  2855. }
  2856. /* Preserve status except Inexact/Rounded */
  2857. status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
  2858. /* Carry out the Hull correction */
  2859. a->exponent-=exp/2; /* back to 0.1->1 */
  2860. /* a is now at final precision and within 1 ulp of the properly */
  2861. /* rounded square root of f; to ensure proper rounding, compare */
  2862. /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f. */
  2863. /* Here workset.digits=maxp and t=0.5, and a->digits determines */
  2864. /* the ulp */
  2865. workset.digits--; /* maxp-1 is OK now */
  2866. t->exponent=-a->digits-1; /* make 0.5 ulp */
  2867. decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp */
  2868. workset.round=DEC_ROUND_UP;
  2869. decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulru(b, b) */
  2870. decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed */
  2871. if (decNumberIsNegative(b)) { /* f < b [i.e., b > f] */
  2872. /* this is the more common adjustment, though both are rare */
  2873. t->exponent++; /* make 1.0 ulp */
  2874. t->lsu[0]=1; /* .. */
  2875. decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp */
  2876. /* assign to approx [round to length] */
  2877. approxset.emin-=exp/2; /* adjust to match a */
  2878. approxset.emax-=exp/2;
  2879. decAddOp(a, &dzero, a, &approxset, 0, &ignore);
  2880. }
  2881. else {
  2882. decAddOp(b, a, t, &workset, 0, &ignore); /* b = a + 0.5 ulp */
  2883. workset.round=DEC_ROUND_DOWN;
  2884. decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulrd(b, b) */
  2885. decCompareOp(b, b, f, &workset, COMPARE, &ignore); /* b ? f */
  2886. if (decNumberIsNegative(b)) { /* b < f */
  2887. t->exponent++; /* make 1.0 ulp */
  2888. t->lsu[0]=1; /* .. */
  2889. decAddOp(a, a, t, &workset, 0, &ignore); /* a = a + 1 ulp */
  2890. /* assign to approx [round to length] */
  2891. approxset.emin-=exp/2; /* adjust to match a */
  2892. approxset.emax-=exp/2;
  2893. decAddOp(a, &dzero, a, &approxset, 0, &ignore);
  2894. }
  2895. }
  2896. /* [no errors are possible in the above, and rounding/inexact during */
  2897. /* estimation are irrelevant, so status was not accumulated] */
  2898. /* Here, 0.1 <= a < 1 (still), so adjust back */
  2899. a->exponent+=exp/2; /* set correct exponent */
  2900. /* count droppable zeros [after any subnormal rounding] by */
  2901. /* trimming a copy */
  2902. uprv_decNumberCopy(b, a);
  2903. decTrim(b, set, 1, 1, &dropped); /* [drops trailing zeros] */
  2904. /* Set Inexact and Rounded. The answer can only be exact if */
  2905. /* it is short enough so that squaring it could fit in workp */
  2906. /* digits, so this is the only (relatively rare) condition that */
  2907. /* a careful check is needed */
  2908. if (b->digits*2-1 > workp) { /* cannot fit */
  2909. status|=DEC_Inexact|DEC_Rounded;
  2910. }
  2911. else { /* could be exact/unrounded */
  2912. uInt mstatus=0; /* local status */
  2913. decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply */
  2914. if (mstatus&DEC_Overflow) { /* result just won't fit */
  2915. status|=DEC_Inexact|DEC_Rounded;
  2916. }
  2917. else { /* plausible */
  2918. decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs */
  2919. if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal */
  2920. else { /* is Exact */
  2921. /* here, dropped is the count of trailing zeros in 'a' */
  2922. /* use closest exponent to ideal... */
  2923. Int todrop=ideal-a->exponent; /* most that can be dropped */
  2924. if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s */
  2925. else { /* unrounded */
  2926. /* there are some to drop, but emax may not allow all */
  2927. Int maxexp=set->emax-set->digits+1;
  2928. Int maxdrop=maxexp-a->exponent;
  2929. if (todrop>maxdrop && set->clamp) { /* apply clamping */
  2930. todrop=maxdrop;
  2931. status|=DEC_Clamped;
  2932. }
  2933. if (dropped<todrop) { /* clamp to those available */
  2934. todrop=dropped;
  2935. status|=DEC_Clamped;
  2936. }
  2937. if (todrop>0) { /* have some to drop */
  2938. decShiftToLeast(a->lsu, D2U(a->digits), todrop);
  2939. a->exponent+=todrop; /* maintain numerical value */
  2940. a->digits-=todrop; /* new length */
  2941. }
  2942. }
  2943. }
  2944. }
  2945. }
  2946. /* double-check Underflow, as perhaps the result could not have */
  2947. /* been subnormal (initial argument too big), or it is now Exact */
  2948. if (status&DEC_Underflow) {
  2949. Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
  2950. /* check if truly subnormal */
  2951. #if DECEXTFLAG /* DEC_Subnormal too */
  2952. if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
  2953. #else
  2954. if (ae>=set->emin*2) status&=~DEC_Underflow;
  2955. #endif
  2956. /* check if truly inexact */
  2957. if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
  2958. }
  2959. uprv_decNumberCopy(res, a); /* a is now the result */
  2960. } while(0); /* end protected */
  2961. if (allocbuff!=nullptr) free(allocbuff); /* drop any storage used */
  2962. if (allocbufa!=nullptr) free(allocbufa); /* .. */
  2963. if (allocbufb!=nullptr) free(allocbufb); /* .. */
  2964. #if DECSUBSET
  2965. if (allocrhs !=nullptr) free(allocrhs); /* .. */
  2966. #endif
  2967. if (status!=0) decStatus(res, status, set);/* then report status */
  2968. #if DECCHECK
  2969. decCheckInexact(res, set);
  2970. #endif
  2971. return res;
  2972. } /* decNumberSquareRoot */
  2973. #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
  2974. #pragma GCC diagnostic pop
  2975. #endif
  2976. /* ------------------------------------------------------------------ */
  2977. /* decNumberSubtract -- subtract two Numbers */
  2978. /* */
  2979. /* This computes C = A - B */
  2980. /* */
  2981. /* res is C, the result. C may be A and/or B (e.g., X=X-X) */
  2982. /* lhs is A */
  2983. /* rhs is B */
  2984. /* set is the context */
  2985. /* */
  2986. /* C must have space for set->digits digits. */
  2987. /* ------------------------------------------------------------------ */
  2988. U_CAPI decNumber * U_EXPORT2 uprv_decNumberSubtract(decNumber *res, const decNumber *lhs,
  2989. const decNumber *rhs, decContext *set) {
  2990. uInt status=0; /* accumulator */
  2991. decAddOp(res, lhs, rhs, set, DECNEG, &status);
  2992. if (status!=0) decStatus(res, status, set);
  2993. #if DECCHECK
  2994. decCheckInexact(res, set);
  2995. #endif
  2996. return res;
  2997. } /* decNumberSubtract */
  2998. /* ------------------------------------------------------------------ */
  2999. /* decNumberToIntegralExact -- round-to-integral-value with InExact */
  3000. /* decNumberToIntegralValue -- round-to-integral-value */
  3001. /* */
  3002. /* res is the result */
  3003. /* rhs is input number */
  3004. /* set is the context */
  3005. /* */
  3006. /* res must have space for any value of rhs. */
  3007. /* */
  3008. /* This implements the IEEE special operators and therefore treats */
  3009. /* special values as valid. For finite numbers it returns */
  3010. /* rescale(rhs, 0) if rhs->exponent is <0. */
  3011. /* Otherwise the result is rhs (so no error is possible, except for */
  3012. /* sNaN). */
  3013. /* */
  3014. /* The context is used for rounding mode and status after sNaN, but */
  3015. /* the digits setting is ignored. The Exact version will signal */
  3016. /* Inexact if the result differs numerically from rhs; the other */
  3017. /* never signals Inexact. */
  3018. /* ------------------------------------------------------------------ */
  3019. U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
  3020. decContext *set) {
  3021. decNumber dn;
  3022. decContext workset; /* working context */
  3023. uInt status=0; /* accumulator */
  3024. #if DECCHECK
  3025. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  3026. #endif
  3027. /* handle infinities and NaNs */
  3028. if (SPECIALARG) {
  3029. if (decNumberIsInfinite(rhs)) uprv_decNumberCopy(res, rhs); /* an Infinity */
  3030. else decNaNs(res, rhs, nullptr, set, &status); /* a NaN */
  3031. }
  3032. else { /* finite */
  3033. /* have a finite number; no error possible (res must be big enough) */
  3034. if (rhs->exponent>=0) return uprv_decNumberCopy(res, rhs);
  3035. /* that was easy, but if negative exponent there is work to do... */
  3036. workset=*set; /* clone rounding, etc. */
  3037. workset.digits=rhs->digits; /* no length rounding */
  3038. workset.traps=0; /* no traps */
  3039. uprv_decNumberZero(&dn); /* make a number with exponent 0 */
  3040. uprv_decNumberQuantize(res, rhs, &dn, &workset);
  3041. status|=workset.status;
  3042. }
  3043. if (status!=0) decStatus(res, status, set);
  3044. return res;
  3045. } /* decNumberToIntegralExact */
  3046. U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
  3047. decContext *set) {
  3048. decContext workset=*set; /* working context */
  3049. workset.traps=0; /* no traps */
  3050. uprv_decNumberToIntegralExact(res, rhs, &workset);
  3051. /* this never affects set, except for sNaNs; NaN will have been set */
  3052. /* or propagated already, so no need to call decStatus */
  3053. set->status|=workset.status&DEC_Invalid_operation;
  3054. return res;
  3055. } /* decNumberToIntegralValue */
  3056. /* ------------------------------------------------------------------ */
  3057. /* decNumberXor -- XOR two Numbers, digitwise */
  3058. /* */
  3059. /* This computes C = A ^ B */
  3060. /* */
  3061. /* res is C, the result. C may be A and/or B (e.g., X=X^X) */
  3062. /* lhs is A */
  3063. /* rhs is B */
  3064. /* set is the context (used for result length and error report) */
  3065. /* */
  3066. /* C must have space for set->digits digits. */
  3067. /* */
  3068. /* Logical function restrictions apply (see above); a NaN is */
  3069. /* returned with Invalid_operation if a restriction is violated. */
  3070. /* ------------------------------------------------------------------ */
  3071. U_CAPI decNumber * U_EXPORT2 uprv_decNumberXor(decNumber *res, const decNumber *lhs,
  3072. const decNumber *rhs, decContext *set) {
  3073. const Unit *ua, *ub; /* -> operands */
  3074. const Unit *msua, *msub; /* -> operand msus */
  3075. Unit *uc, *msuc; /* -> result and its msu */
  3076. Int msudigs; /* digits in res msu */
  3077. #if DECCHECK
  3078. if (decCheckOperands(res, lhs, rhs, set)) return res;
  3079. #endif
  3080. if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
  3081. || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
  3082. decStatus(res, DEC_Invalid_operation, set);
  3083. return res;
  3084. }
  3085. /* operands are valid */
  3086. ua=lhs->lsu; /* bottom-up */
  3087. ub=rhs->lsu; /* .. */
  3088. uc=res->lsu; /* .. */
  3089. msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
  3090. msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
  3091. msuc=uc+D2U(set->digits)-1; /* -> msu of result */
  3092. msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
  3093. for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
  3094. Unit a, b; /* extract units */
  3095. if (ua>msua) a=0;
  3096. else a=*ua;
  3097. if (ub>msub) b=0;
  3098. else b=*ub;
  3099. *uc=0; /* can now write back */
  3100. if (a|b) { /* maybe 1 bits to examine */
  3101. Int i, j;
  3102. /* This loop could be unrolled and/or use BIN2BCD tables */
  3103. for (i=0; i<DECDPUN; i++) {
  3104. if ((a^b)&1) *uc=*uc+(Unit)powers[i]; /* effect XOR */
  3105. j=a%10;
  3106. a=a/10;
  3107. j|=b%10;
  3108. b=b/10;
  3109. if (j>1) {
  3110. decStatus(res, DEC_Invalid_operation, set);
  3111. return res;
  3112. }
  3113. if (uc==msuc && i==msudigs-1) break; /* just did final digit */
  3114. } /* each digit */
  3115. } /* non-zero */
  3116. } /* each unit */
  3117. /* [here uc-1 is the msu of the result] */
  3118. res->digits=decGetDigits(res->lsu, static_cast<int32_t>(uc-res->lsu));
  3119. res->exponent=0; /* integer */
  3120. res->bits=0; /* sign=0 */
  3121. return res; /* [no status to set] */
  3122. } /* decNumberXor */
  3123. /* ================================================================== */
  3124. /* Utility routines */
  3125. /* ================================================================== */
  3126. /* ------------------------------------------------------------------ */
  3127. /* decNumberClass -- return the decClass of a decNumber */
  3128. /* dn -- the decNumber to test */
  3129. /* set -- the context to use for Emin */
  3130. /* returns the decClass enum */
  3131. /* ------------------------------------------------------------------ */
  3132. enum decClass uprv_decNumberClass(const decNumber *dn, decContext *set) {
  3133. if (decNumberIsSpecial(dn)) {
  3134. if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
  3135. if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
  3136. /* must be an infinity */
  3137. if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
  3138. return DEC_CLASS_POS_INF;
  3139. }
  3140. /* is finite */
  3141. if (uprv_decNumberIsNormal(dn, set)) { /* most common */
  3142. if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
  3143. return DEC_CLASS_POS_NORMAL;
  3144. }
  3145. /* is subnormal or zero */
  3146. if (decNumberIsZero(dn)) { /* most common */
  3147. if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
  3148. return DEC_CLASS_POS_ZERO;
  3149. }
  3150. if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
  3151. return DEC_CLASS_POS_SUBNORMAL;
  3152. } /* decNumberClass */
  3153. /* ------------------------------------------------------------------ */
  3154. /* decNumberClassToString -- convert decClass to a string */
  3155. /* */
  3156. /* eclass is a valid decClass */
  3157. /* returns a constant string describing the class (max 13+1 chars) */
  3158. /* ------------------------------------------------------------------ */
  3159. const char *uprv_decNumberClassToString(enum decClass eclass) {
  3160. if (eclass==DEC_CLASS_POS_NORMAL) return DEC_ClassString_PN;
  3161. if (eclass==DEC_CLASS_NEG_NORMAL) return DEC_ClassString_NN;
  3162. if (eclass==DEC_CLASS_POS_ZERO) return DEC_ClassString_PZ;
  3163. if (eclass==DEC_CLASS_NEG_ZERO) return DEC_ClassString_NZ;
  3164. if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
  3165. if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
  3166. if (eclass==DEC_CLASS_POS_INF) return DEC_ClassString_PI;
  3167. if (eclass==DEC_CLASS_NEG_INF) return DEC_ClassString_NI;
  3168. if (eclass==DEC_CLASS_QNAN) return DEC_ClassString_QN;
  3169. if (eclass==DEC_CLASS_SNAN) return DEC_ClassString_SN;
  3170. return DEC_ClassString_UN; /* Unknown */
  3171. } /* decNumberClassToString */
  3172. /* ------------------------------------------------------------------ */
  3173. /* decNumberCopy -- copy a number */
  3174. /* */
  3175. /* dest is the target decNumber */
  3176. /* src is the source decNumber */
  3177. /* returns dest */
  3178. /* */
  3179. /* (dest==src is allowed and is a no-op) */
  3180. /* All fields are updated as required. This is a utility operation, */
  3181. /* so special values are unchanged and no error is possible. */
  3182. /* ------------------------------------------------------------------ */
  3183. U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopy(decNumber *dest, const decNumber *src) {
  3184. #if DECCHECK
  3185. if (src==nullptr) return uprv_decNumberZero(dest);
  3186. #endif
  3187. if (dest==src) return dest; /* no copy required */
  3188. /* Use explicit assignments here as structure assignment could copy */
  3189. /* more than just the lsu (for small DECDPUN). This would not affect */
  3190. /* the value of the results, but could disturb test harness spill */
  3191. /* checking. */
  3192. dest->bits=src->bits;
  3193. dest->exponent=src->exponent;
  3194. dest->digits=src->digits;
  3195. dest->lsu[0]=src->lsu[0];
  3196. if (src->digits>DECDPUN) { /* more Units to come */
  3197. const Unit *smsup, *s; /* work */
  3198. Unit *d; /* .. */
  3199. /* memcpy for the remaining Units would be safe as they cannot */
  3200. /* overlap. However, this explicit loop is faster in short cases. */
  3201. d=dest->lsu+1; /* -> first destination */
  3202. smsup=src->lsu+D2U(src->digits); /* -> source msu+1 */
  3203. for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
  3204. }
  3205. return dest;
  3206. } /* decNumberCopy */
  3207. /* ------------------------------------------------------------------ */
  3208. /* decNumberCopyAbs -- quiet absolute value operator */
  3209. /* */
  3210. /* This sets C = abs(A) */
  3211. /* */
  3212. /* res is C, the result. C may be A */
  3213. /* rhs is A */
  3214. /* */
  3215. /* C must have space for set->digits digits. */
  3216. /* No exception or error can occur; this is a quiet bitwise operation.*/
  3217. /* See also decNumberAbs for a checking version of this. */
  3218. /* ------------------------------------------------------------------ */
  3219. U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
  3220. #if DECCHECK
  3221. if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
  3222. #endif
  3223. uprv_decNumberCopy(res, rhs);
  3224. res->bits&=~DECNEG; /* turn off sign */
  3225. return res;
  3226. } /* decNumberCopyAbs */
  3227. /* ------------------------------------------------------------------ */
  3228. /* decNumberCopyNegate -- quiet negate value operator */
  3229. /* */
  3230. /* This sets C = negate(A) */
  3231. /* */
  3232. /* res is C, the result. C may be A */
  3233. /* rhs is A */
  3234. /* */
  3235. /* C must have space for set->digits digits. */
  3236. /* No exception or error can occur; this is a quiet bitwise operation.*/
  3237. /* See also decNumberMinus for a checking version of this. */
  3238. /* ------------------------------------------------------------------ */
  3239. U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
  3240. #if DECCHECK
  3241. if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
  3242. #endif
  3243. uprv_decNumberCopy(res, rhs);
  3244. res->bits^=DECNEG; /* invert the sign */
  3245. return res;
  3246. } /* decNumberCopyNegate */
  3247. /* ------------------------------------------------------------------ */
  3248. /* decNumberCopySign -- quiet copy and set sign operator */
  3249. /* */
  3250. /* This sets C = A with the sign of B */
  3251. /* */
  3252. /* res is C, the result. C may be A */
  3253. /* lhs is A */
  3254. /* rhs is B */
  3255. /* */
  3256. /* C must have space for set->digits digits. */
  3257. /* No exception or error can occur; this is a quiet bitwise operation.*/
  3258. /* ------------------------------------------------------------------ */
  3259. U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopySign(decNumber *res, const decNumber *lhs,
  3260. const decNumber *rhs) {
  3261. uByte sign; /* rhs sign */
  3262. #if DECCHECK
  3263. if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
  3264. #endif
  3265. sign=rhs->bits & DECNEG; /* save sign bit */
  3266. uprv_decNumberCopy(res, lhs);
  3267. res->bits&=~DECNEG; /* clear the sign */
  3268. res->bits|=sign; /* set from rhs */
  3269. return res;
  3270. } /* decNumberCopySign */
  3271. /* ------------------------------------------------------------------ */
  3272. /* decNumberGetBCD -- get the coefficient in BCD8 */
  3273. /* dn is the source decNumber */
  3274. /* bcd is the uInt array that will receive dn->digits BCD bytes, */
  3275. /* most-significant at offset 0 */
  3276. /* returns bcd */
  3277. /* */
  3278. /* bcd must have at least dn->digits bytes. No error is possible; if */
  3279. /* dn is a NaN or Infinite, digits must be 1 and the coefficient 0. */
  3280. /* ------------------------------------------------------------------ */
  3281. U_CAPI uByte * U_EXPORT2 uprv_decNumberGetBCD(const decNumber *dn, uByte *bcd) {
  3282. uByte *ub=bcd+dn->digits-1; /* -> lsd */
  3283. const Unit *up=dn->lsu; /* Unit pointer, -> lsu */
  3284. #if DECDPUN==1 /* trivial simple copy */
  3285. for (; ub>=bcd; ub--, up++) *ub=*up;
  3286. #else /* chopping needed */
  3287. uInt u=*up; /* work */
  3288. uInt cut=DECDPUN; /* downcounter through unit */
  3289. for (; ub>=bcd; ub--) {
  3290. *ub=(uByte)(u%10); /* [*6554 trick inhibits, here] */
  3291. u=u/10;
  3292. cut--;
  3293. if (cut>0) continue; /* more in this unit */
  3294. up++;
  3295. u=*up;
  3296. cut=DECDPUN;
  3297. }
  3298. #endif
  3299. return bcd;
  3300. } /* decNumberGetBCD */
  3301. /* ------------------------------------------------------------------ */
  3302. /* decNumberSetBCD -- set (replace) the coefficient from BCD8 */
  3303. /* dn is the target decNumber */
  3304. /* bcd is the uInt array that will source n BCD bytes, most- */
  3305. /* significant at offset 0 */
  3306. /* n is the number of digits in the source BCD array (bcd) */
  3307. /* returns dn */
  3308. /* */
  3309. /* dn must have space for at least n digits. No error is possible; */
  3310. /* if dn is a NaN, or Infinite, or is to become a zero, n must be 1 */
  3311. /* and bcd[0] zero. */
  3312. /* ------------------------------------------------------------------ */
  3313. U_CAPI decNumber * U_EXPORT2 uprv_decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
  3314. Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [target pointer] */
  3315. const uByte *ub=bcd; /* -> source msd */
  3316. #if DECDPUN==1 /* trivial simple copy */
  3317. for (; ub<bcd+n; ub++, up--) *up=*ub;
  3318. #else /* some assembly needed */
  3319. /* calculate how many digits in msu, and hence first cut */
  3320. Int cut=MSUDIGITS(n); /* [faster than remainder] */
  3321. for (;up>=dn->lsu; up--) { /* each Unit from msu */
  3322. *up=0; /* will take <=DECDPUN digits */
  3323. for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
  3324. cut=DECDPUN; /* next Unit has all digits */
  3325. }
  3326. #endif
  3327. dn->digits=n; /* set digit count */
  3328. return dn;
  3329. } /* decNumberSetBCD */
  3330. /* ------------------------------------------------------------------ */
  3331. /* decNumberIsNormal -- test normality of a decNumber */
  3332. /* dn is the decNumber to test */
  3333. /* set is the context to use for Emin */
  3334. /* returns 1 if |dn| is finite and >=Nmin, 0 otherwise */
  3335. /* ------------------------------------------------------------------ */
  3336. Int uprv_decNumberIsNormal(const decNumber *dn, decContext *set) {
  3337. Int ae; /* adjusted exponent */
  3338. #if DECCHECK
  3339. if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
  3340. #endif
  3341. if (decNumberIsSpecial(dn)) return 0; /* not finite */
  3342. if (decNumberIsZero(dn)) return 0; /* not non-zero */
  3343. ae=dn->exponent+dn->digits-1; /* adjusted exponent */
  3344. if (ae<set->emin) return 0; /* is subnormal */
  3345. return 1;
  3346. } /* decNumberIsNormal */
  3347. /* ------------------------------------------------------------------ */
  3348. /* decNumberIsSubnormal -- test subnormality of a decNumber */
  3349. /* dn is the decNumber to test */
  3350. /* set is the context to use for Emin */
  3351. /* returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise */
  3352. /* ------------------------------------------------------------------ */
  3353. Int uprv_decNumberIsSubnormal(const decNumber *dn, decContext *set) {
  3354. Int ae; /* adjusted exponent */
  3355. #if DECCHECK
  3356. if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
  3357. #endif
  3358. if (decNumberIsSpecial(dn)) return 0; /* not finite */
  3359. if (decNumberIsZero(dn)) return 0; /* not non-zero */
  3360. ae=dn->exponent+dn->digits-1; /* adjusted exponent */
  3361. if (ae<set->emin) return 1; /* is subnormal */
  3362. return 0;
  3363. } /* decNumberIsSubnormal */
  3364. /* ------------------------------------------------------------------ */
  3365. /* decNumberTrim -- remove insignificant zeros */
  3366. /* */
  3367. /* dn is the number to trim */
  3368. /* returns dn */
  3369. /* */
  3370. /* All fields are updated as required. This is a utility operation, */
  3371. /* so special values are unchanged and no error is possible. The */
  3372. /* zeros are removed unconditionally. */
  3373. /* ------------------------------------------------------------------ */
  3374. U_CAPI decNumber * U_EXPORT2 uprv_decNumberTrim(decNumber *dn) {
  3375. Int dropped; /* work */
  3376. decContext set; /* .. */
  3377. #if DECCHECK
  3378. if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
  3379. #endif
  3380. uprv_decContextDefault(&set, DEC_INIT_BASE); /* clamp=0 */
  3381. return decTrim(dn, &set, 0, 1, &dropped);
  3382. } /* decNumberTrim */
  3383. /* ------------------------------------------------------------------ */
  3384. /* decNumberVersion -- return the name and version of this module */
  3385. /* */
  3386. /* No error is possible. */
  3387. /* ------------------------------------------------------------------ */
  3388. const char * uprv_decNumberVersion() {
  3389. return DECVERSION;
  3390. } /* decNumberVersion */
  3391. /* ------------------------------------------------------------------ */
  3392. /* decNumberZero -- set a number to 0 */
  3393. /* */
  3394. /* dn is the number to set, with space for one digit */
  3395. /* returns dn */
  3396. /* */
  3397. /* No error is possible. */
  3398. /* ------------------------------------------------------------------ */
  3399. /* Memset is not used as it is much slower in some environments. */
  3400. U_CAPI decNumber * U_EXPORT2 uprv_decNumberZero(decNumber *dn) {
  3401. #if DECCHECK
  3402. if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
  3403. #endif
  3404. dn->bits=0;
  3405. dn->exponent=0;
  3406. dn->digits=1;
  3407. dn->lsu[0]=0;
  3408. return dn;
  3409. } /* decNumberZero */
  3410. /* ================================================================== */
  3411. /* Local routines */
  3412. /* ================================================================== */
  3413. /* ------------------------------------------------------------------ */
  3414. /* decToString -- lay out a number into a string */
  3415. /* */
  3416. /* dn is the number to lay out */
  3417. /* string is where to lay out the number */
  3418. /* eng is 1 if Engineering, 0 if Scientific */
  3419. /* */
  3420. /* string must be at least dn->digits+14 characters long */
  3421. /* No error is possible. */
  3422. /* */
  3423. /* Note that this routine can generate a -0 or 0.000. These are */
  3424. /* never generated in subset to-number or arithmetic, but can occur */
  3425. /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234). */
  3426. /* ------------------------------------------------------------------ */
  3427. /* If DECCHECK is enabled the string "?" is returned if a number is */
  3428. /* invalid. */
  3429. static void decToString(const decNumber *dn, char *string, Flag eng) {
  3430. Int exp=dn->exponent; /* local copy */
  3431. Int e; /* E-part value */
  3432. Int pre; /* digits before the '.' */
  3433. Int cut; /* for counting digits in a Unit */
  3434. char *c=string; /* work [output pointer] */
  3435. const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer] */
  3436. uInt u, pow; /* work */
  3437. #if DECCHECK
  3438. if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
  3439. strcpy(string, "?");
  3440. return;}
  3441. #endif
  3442. if (decNumberIsNegative(dn)) { /* Negatives get a minus */
  3443. *c='-';
  3444. c++;
  3445. }
  3446. if (dn->bits&DECSPECIAL) { /* Is a special value */
  3447. if (decNumberIsInfinite(dn)) {
  3448. strcpy(c, "Inf");
  3449. strcpy(c+3, "inity");
  3450. return;}
  3451. /* a NaN */
  3452. if (dn->bits&DECSNAN) { /* signalling NaN */
  3453. *c='s';
  3454. c++;
  3455. }
  3456. strcpy(c, "NaN");
  3457. c+=3; /* step past */
  3458. /* if not a clean non-zero coefficient, that's all there is in a */
  3459. /* NaN string */
  3460. if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
  3461. /* [drop through to add integer] */
  3462. }
  3463. /* calculate how many digits in msu, and hence first cut */
  3464. cut=MSUDIGITS(dn->digits); /* [faster than remainder] */
  3465. cut--; /* power of ten for digit */
  3466. if (exp==0) { /* simple integer [common fastpath] */
  3467. for (;up>=dn->lsu; up--) { /* each Unit from msu */
  3468. u=*up; /* contains DECDPUN digits to lay out */
  3469. for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
  3470. cut=DECDPUN-1; /* next Unit has all digits */
  3471. }
  3472. *c='\0'; /* terminate the string */
  3473. return;}
  3474. /* non-0 exponent -- assume plain form */
  3475. pre=dn->digits+exp; /* digits before '.' */
  3476. e=0; /* no E */
  3477. if ((exp>0) || (pre<-5)) { /* need exponential form */
  3478. e=exp+dn->digits-1; /* calculate E value */
  3479. pre=1; /* assume one digit before '.' */
  3480. if (eng && (e!=0)) { /* engineering: may need to adjust */
  3481. Int adj; /* adjustment */
  3482. /* The C remainder operator is undefined for negative numbers, so */
  3483. /* a positive remainder calculation must be used here */
  3484. if (e<0) {
  3485. adj=(-e)%3;
  3486. if (adj!=0) adj=3-adj;
  3487. }
  3488. else { /* e>0 */
  3489. adj=e%3;
  3490. }
  3491. e=e-adj;
  3492. /* if dealing with zero still produce an exponent which is a */
  3493. /* multiple of three, as expected, but there will only be the */
  3494. /* one zero before the E, still. Otherwise note the padding. */
  3495. if (!ISZERO(dn)) pre+=adj;
  3496. else { /* is zero */
  3497. if (adj!=0) { /* 0.00Esnn needed */
  3498. e=e+3;
  3499. pre=-(2-adj);
  3500. }
  3501. } /* zero */
  3502. } /* eng */
  3503. } /* need exponent */
  3504. /* lay out the digits of the coefficient, adding 0s and . as needed */
  3505. u=*up;
  3506. if (pre>0) { /* xxx.xxx or xx00 (engineering) form */
  3507. Int n=pre;
  3508. for (; pre>0; pre--, c++, cut--) {
  3509. if (cut<0) { /* need new Unit */
  3510. if (up==dn->lsu) break; /* out of input digits (pre>digits) */
  3511. up--;
  3512. cut=DECDPUN-1;
  3513. u=*up;
  3514. }
  3515. TODIGIT(u, cut, c, pow);
  3516. }
  3517. if (n<dn->digits) { /* more to come, after '.' */
  3518. *c='.'; c++;
  3519. for (;; c++, cut--) {
  3520. if (cut<0) { /* need new Unit */
  3521. if (up==dn->lsu) break; /* out of input digits */
  3522. up--;
  3523. cut=DECDPUN-1;
  3524. u=*up;
  3525. }
  3526. TODIGIT(u, cut, c, pow);
  3527. }
  3528. }
  3529. else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed */
  3530. }
  3531. else { /* 0.xxx or 0.000xxx form */
  3532. *c='0'; c++;
  3533. *c='.'; c++;
  3534. for (; pre<0; pre++, c++) *c='0'; /* add any 0's after '.' */
  3535. for (; ; c++, cut--) {
  3536. if (cut<0) { /* need new Unit */
  3537. if (up==dn->lsu) break; /* out of input digits */
  3538. up--;
  3539. cut=DECDPUN-1;
  3540. u=*up;
  3541. }
  3542. TODIGIT(u, cut, c, pow);
  3543. }
  3544. }
  3545. /* Finally add the E-part, if needed. It will never be 0, has a
  3546. base maximum and minimum of +999999999 through -999999999, but
  3547. could range down to -1999999998 for abnormal numbers */
  3548. if (e!=0) {
  3549. Flag had=0; /* 1=had non-zero */
  3550. *c='E'; c++;
  3551. *c='+'; c++; /* assume positive */
  3552. u=e; /* .. */
  3553. if (e<0) {
  3554. *(c-1)='-'; /* oops, need - */
  3555. u=-e; /* uInt, please */
  3556. }
  3557. /* lay out the exponent [_itoa or equivalent is not ANSI C] */
  3558. for (cut=9; cut>=0; cut--) {
  3559. TODIGIT(u, cut, c, pow);
  3560. if (*c=='0' && !had) continue; /* skip leading zeros */
  3561. had=1; /* had non-0 */
  3562. c++; /* step for next */
  3563. } /* cut */
  3564. }
  3565. *c='\0'; /* terminate the string (all paths) */
  3566. return;
  3567. } /* decToString */
  3568. /* ------------------------------------------------------------------ */
  3569. /* decAddOp -- add/subtract operation */
  3570. /* */
  3571. /* This computes C = A + B */
  3572. /* */
  3573. /* res is C, the result. C may be A and/or B (e.g., X=X+X) */
  3574. /* lhs is A */
  3575. /* rhs is B */
  3576. /* set is the context */
  3577. /* negate is DECNEG if rhs should be negated, or 0 otherwise */
  3578. /* status accumulates status for the caller */
  3579. /* */
  3580. /* C must have space for set->digits digits. */
  3581. /* Inexact in status must be 0 for correct Exact zero sign in result */
  3582. /* ------------------------------------------------------------------ */
  3583. /* If possible, the coefficient is calculated directly into C. */
  3584. /* However, if: */
  3585. /* -- a digits+1 calculation is needed because the numbers are */
  3586. /* unaligned and span more than set->digits digits */
  3587. /* -- a carry to digits+1 digits looks possible */
  3588. /* -- C is the same as A or B, and the result would destructively */
  3589. /* overlap the A or B coefficient */
  3590. /* then the result must be calculated into a temporary buffer. In */
  3591. /* this case a local (stack) buffer is used if possible, and only if */
  3592. /* too long for that does malloc become the final resort. */
  3593. /* */
  3594. /* Misalignment is handled as follows: */
  3595. /* Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp. */
  3596. /* BPad: Apply the padding by a combination of shifting (whole */
  3597. /* units) and multiplication (part units). */
  3598. /* */
  3599. /* Addition, especially x=x+1, is speed-critical. */
  3600. /* The static buffer is larger than might be expected to allow for */
  3601. /* calls from higher-level functions (notable exp). */
  3602. /* ------------------------------------------------------------------ */
  3603. static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
  3604. const decNumber *rhs, decContext *set,
  3605. uByte negate, uInt *status) {
  3606. #if DECSUBSET
  3607. decNumber *alloclhs=nullptr; /* non-nullptr if rounded lhs allocated */
  3608. decNumber *allocrhs=nullptr; /* .., rhs */
  3609. #endif
  3610. Int rhsshift; /* working shift (in Units) */
  3611. Int maxdigits; /* longest logical length */
  3612. Int mult; /* multiplier */
  3613. Int residue; /* rounding accumulator */
  3614. uByte bits; /* result bits */
  3615. Flag diffsign; /* non-0 if arguments have different sign */
  3616. Unit *acc; /* accumulator for result */
  3617. Unit accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many */
  3618. /* allocations when called from */
  3619. /* other operations, notable exp] */
  3620. Unit *allocacc=nullptr; /* -> allocated acc buffer, iff allocated */
  3621. Int reqdigits=set->digits; /* local copy; requested DIGITS */
  3622. Int padding; /* work */
  3623. #if DECCHECK
  3624. if (decCheckOperands(res, lhs, rhs, set)) return res;
  3625. #endif
  3626. do { /* protect allocated storage */
  3627. #if DECSUBSET
  3628. if (!set->extended) {
  3629. /* reduce operands and set lostDigits status, as needed */
  3630. if (lhs->digits>reqdigits) {
  3631. alloclhs=decRoundOperand(lhs, set, status);
  3632. if (alloclhs==nullptr) break;
  3633. lhs=alloclhs;
  3634. }
  3635. if (rhs->digits>reqdigits) {
  3636. allocrhs=decRoundOperand(rhs, set, status);
  3637. if (allocrhs==nullptr) break;
  3638. rhs=allocrhs;
  3639. }
  3640. }
  3641. #endif
  3642. /* [following code does not require input rounding] */
  3643. /* note whether signs differ [used all paths] */
  3644. diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
  3645. /* handle infinities and NaNs */
  3646. if (SPECIALARGS) { /* a special bit set */
  3647. if (SPECIALARGS & (DECSNAN | DECNAN)) /* a NaN */
  3648. decNaNs(res, lhs, rhs, set, status);
  3649. else { /* one or two infinities */
  3650. if (decNumberIsInfinite(lhs)) { /* LHS is infinity */
  3651. /* two infinities with different signs is invalid */
  3652. if (decNumberIsInfinite(rhs) && diffsign) {
  3653. *status|=DEC_Invalid_operation;
  3654. break;
  3655. }
  3656. bits=lhs->bits & DECNEG; /* get sign from LHS */
  3657. }
  3658. else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity */
  3659. bits|=DECINF;
  3660. uprv_decNumberZero(res);
  3661. res->bits=bits; /* set +/- infinity */
  3662. } /* an infinity */
  3663. break;
  3664. }
  3665. /* Quick exit for add 0s; return the non-0, modified as need be */
  3666. if (ISZERO(lhs)) {
  3667. Int adjust; /* work */
  3668. Int lexp=lhs->exponent; /* save in case LHS==RES */
  3669. bits=lhs->bits; /* .. */
  3670. residue=0; /* clear accumulator */
  3671. decCopyFit(res, rhs, set, &residue, status); /* copy (as needed) */
  3672. res->bits^=negate; /* flip if rhs was negated */
  3673. #if DECSUBSET
  3674. if (set->extended) { /* exponents on zeros count */
  3675. #endif
  3676. /* exponent will be the lower of the two */
  3677. adjust=lexp-res->exponent; /* adjustment needed [if -ve] */
  3678. if (ISZERO(res)) { /* both 0: special IEEE 754 rules */
  3679. if (adjust<0) res->exponent=lexp; /* set exponent */
  3680. /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0 */
  3681. if (diffsign) {
  3682. if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
  3683. else res->bits=DECNEG; /* preserve 0 sign */
  3684. }
  3685. }
  3686. else { /* non-0 res */
  3687. if (adjust<0) { /* 0-padding needed */
  3688. if ((res->digits-adjust)>set->digits) {
  3689. adjust=res->digits-set->digits; /* to fit exactly */
  3690. *status|=DEC_Rounded; /* [but exact] */
  3691. }
  3692. res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
  3693. res->exponent+=adjust; /* set the exponent. */
  3694. }
  3695. } /* non-0 res */
  3696. #if DECSUBSET
  3697. } /* extended */
  3698. #endif
  3699. decFinish(res, set, &residue, status); /* clean and finalize */
  3700. break;}
  3701. if (ISZERO(rhs)) { /* [lhs is non-zero] */
  3702. Int adjust; /* work */
  3703. Int rexp=rhs->exponent; /* save in case RHS==RES */
  3704. bits=rhs->bits; /* be clean */
  3705. residue=0; /* clear accumulator */
  3706. decCopyFit(res, lhs, set, &residue, status); /* copy (as needed) */
  3707. #if DECSUBSET
  3708. if (set->extended) { /* exponents on zeros count */
  3709. #endif
  3710. /* exponent will be the lower of the two */
  3711. /* [0-0 case handled above] */
  3712. adjust=rexp-res->exponent; /* adjustment needed [if -ve] */
  3713. if (adjust<0) { /* 0-padding needed */
  3714. if ((res->digits-adjust)>set->digits) {
  3715. adjust=res->digits-set->digits; /* to fit exactly */
  3716. *status|=DEC_Rounded; /* [but exact] */
  3717. }
  3718. res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
  3719. res->exponent+=adjust; /* set the exponent. */
  3720. }
  3721. #if DECSUBSET
  3722. } /* extended */
  3723. #endif
  3724. decFinish(res, set, &residue, status); /* clean and finalize */
  3725. break;}
  3726. /* [NB: both fastpath and mainpath code below assume these cases */
  3727. /* (notably 0-0) have already been handled] */
  3728. /* calculate the padding needed to align the operands */
  3729. padding=rhs->exponent-lhs->exponent;
  3730. /* Fastpath cases where the numbers are aligned and normal, the RHS */
  3731. /* is all in one unit, no operand rounding is needed, and no carry, */
  3732. /* lengthening, or borrow is needed */
  3733. if (padding==0
  3734. && rhs->digits<=DECDPUN
  3735. && rhs->exponent>=set->emin /* [some normals drop through] */
  3736. && rhs->exponent<=set->emax-set->digits+1 /* [could clamp] */
  3737. && rhs->digits<=reqdigits
  3738. && lhs->digits<=reqdigits) {
  3739. Int partial=*lhs->lsu;
  3740. if (!diffsign) { /* adding */
  3741. partial+=*rhs->lsu;
  3742. if ((partial<=DECDPUNMAX) /* result fits in unit */
  3743. && (lhs->digits>=DECDPUN || /* .. and no digits-count change */
  3744. partial<(Int)powers[lhs->digits])) { /* .. */
  3745. if (res!=lhs) uprv_decNumberCopy(res, lhs); /* not in place */
  3746. *res->lsu=(Unit)partial; /* [copy could have overwritten RHS] */
  3747. break;
  3748. }
  3749. /* else drop out for careful add */
  3750. }
  3751. else { /* signs differ */
  3752. partial-=*rhs->lsu;
  3753. if (partial>0) { /* no borrow needed, and non-0 result */
  3754. if (res!=lhs) uprv_decNumberCopy(res, lhs); /* not in place */
  3755. *res->lsu=(Unit)partial;
  3756. /* this could have reduced digits [but result>0] */
  3757. res->digits=decGetDigits(res->lsu, D2U(res->digits));
  3758. break;
  3759. }
  3760. /* else drop out for careful subtract */
  3761. }
  3762. }
  3763. /* Now align (pad) the lhs or rhs so they can be added or */
  3764. /* subtracted, as necessary. If one number is much larger than */
  3765. /* the other (that is, if in plain form there is a least one */
  3766. /* digit between the lowest digit of one and the highest of the */
  3767. /* other) padding with up to DIGITS-1 trailing zeros may be */
  3768. /* needed; then apply rounding (as exotic rounding modes may be */
  3769. /* affected by the residue). */
  3770. rhsshift=0; /* rhs shift to left (padding) in Units */
  3771. bits=lhs->bits; /* assume sign is that of LHS */
  3772. mult=1; /* likely multiplier */
  3773. /* [if padding==0 the operands are aligned; no padding is needed] */
  3774. if (padding!=0) {
  3775. /* some padding needed; always pad the RHS, as any required */
  3776. /* padding can then be effected by a simple combination of */
  3777. /* shifts and a multiply */
  3778. Flag swapped=0;
  3779. if (padding<0) { /* LHS needs the padding */
  3780. const decNumber *t;
  3781. padding=-padding; /* will be +ve */
  3782. bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS */
  3783. t=lhs; lhs=rhs; rhs=t;
  3784. swapped=1;
  3785. }
  3786. /* If, after pad, rhs would be longer than lhs by digits+1 or */
  3787. /* more then lhs cannot affect the answer, except as a residue, */
  3788. /* so only need to pad up to a length of DIGITS+1. */
  3789. if (rhs->digits+padding > lhs->digits+reqdigits+1) {
  3790. /* The RHS is sufficient */
  3791. /* for residue use the relative sign indication... */
  3792. Int shift=reqdigits-rhs->digits; /* left shift needed */
  3793. residue=1; /* residue for rounding */
  3794. if (diffsign) residue=-residue; /* signs differ */
  3795. /* copy, shortening if necessary */
  3796. decCopyFit(res, rhs, set, &residue, status);
  3797. /* if it was already shorter, then need to pad with zeros */
  3798. if (shift>0) {
  3799. res->digits=decShiftToMost(res->lsu, res->digits, shift);
  3800. res->exponent-=shift; /* adjust the exponent. */
  3801. }
  3802. /* flip the result sign if unswapped and rhs was negated */
  3803. if (!swapped) res->bits^=negate;
  3804. decFinish(res, set, &residue, status); /* done */
  3805. break;}
  3806. /* LHS digits may affect result */
  3807. rhsshift=D2U(padding+1)-1; /* this much by Unit shift .. */
  3808. mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication */
  3809. } /* padding needed */
  3810. if (diffsign) mult=-mult; /* signs differ */
  3811. /* determine the longer operand */
  3812. maxdigits=rhs->digits+padding; /* virtual length of RHS */
  3813. if (lhs->digits>maxdigits) maxdigits=lhs->digits;
  3814. /* Decide on the result buffer to use; if possible place directly */
  3815. /* into result. */
  3816. acc=res->lsu; /* assume add direct to result */
  3817. /* If destructive overlap, or the number is too long, or a carry or */
  3818. /* borrow to DIGITS+1 might be possible, a buffer must be used. */
  3819. /* [Might be worth more sophisticated tests when maxdigits==reqdigits] */
  3820. if ((maxdigits>=reqdigits) /* is, or could be, too large */
  3821. || (res==rhs && rhsshift>0)) { /* destructive overlap */
  3822. /* buffer needed, choose it; units for maxdigits digits will be */
  3823. /* needed, +1 Unit for carry or borrow */
  3824. Int need=D2U(maxdigits)+1;
  3825. acc=accbuff; /* assume use local buffer */
  3826. if (need*sizeof(Unit)>sizeof(accbuff)) {
  3827. /* printf("malloc add %ld %ld\n", need, sizeof(accbuff)); */
  3828. allocacc=(Unit *)malloc(need*sizeof(Unit));
  3829. if (allocacc==nullptr) { /* hopeless -- abandon */
  3830. *status|=DEC_Insufficient_storage;
  3831. break;}
  3832. acc=allocacc;
  3833. }
  3834. }
  3835. res->bits=(uByte)(bits&DECNEG); /* it's now safe to overwrite.. */
  3836. res->exponent=lhs->exponent; /* .. operands (even if aliased) */
  3837. #if DECTRACE
  3838. decDumpAr('A', lhs->lsu, D2U(lhs->digits));
  3839. decDumpAr('B', rhs->lsu, D2U(rhs->digits));
  3840. printf(" :h: %ld %ld\n", rhsshift, mult);
  3841. #endif
  3842. /* add [A+B*m] or subtract [A+B*(-m)] */
  3843. U_ASSERT(rhs->digits > 0);
  3844. U_ASSERT(lhs->digits > 0);
  3845. res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
  3846. rhs->lsu, D2U(rhs->digits),
  3847. rhsshift, acc, mult)
  3848. *DECDPUN; /* [units -> digits] */
  3849. if (res->digits<0) { /* borrowed... */
  3850. res->digits=-res->digits;
  3851. res->bits^=DECNEG; /* flip the sign */
  3852. }
  3853. #if DECTRACE
  3854. decDumpAr('+', acc, D2U(res->digits));
  3855. #endif
  3856. /* If a buffer was used the result must be copied back, possibly */
  3857. /* shortening. (If no buffer was used then the result must have */
  3858. /* fit, so can't need rounding and residue must be 0.) */
  3859. residue=0; /* clear accumulator */
  3860. if (acc!=res->lsu) {
  3861. #if DECSUBSET
  3862. if (set->extended) { /* round from first significant digit */
  3863. #endif
  3864. /* remove leading zeros that were added due to rounding up to */
  3865. /* integral Units -- before the test for rounding. */
  3866. if (res->digits>reqdigits)
  3867. res->digits=decGetDigits(acc, D2U(res->digits));
  3868. decSetCoeff(res, set, acc, res->digits, &residue, status);
  3869. #if DECSUBSET
  3870. }
  3871. else { /* subset arithmetic rounds from original significant digit */
  3872. /* May have an underestimate. This only occurs when both */
  3873. /* numbers fit in DECDPUN digits and are padding with a */
  3874. /* negative multiple (-10, -100...) and the top digit(s) become */
  3875. /* 0. (This only matters when using X3.274 rules where the */
  3876. /* leading zero could be included in the rounding.) */
  3877. if (res->digits<maxdigits) {
  3878. *(acc+D2U(res->digits))=0; /* ensure leading 0 is there */
  3879. res->digits=maxdigits;
  3880. }
  3881. else {
  3882. /* remove leading zeros that added due to rounding up to */
  3883. /* integral Units (but only those in excess of the original */
  3884. /* maxdigits length, unless extended) before test for rounding. */
  3885. if (res->digits>reqdigits) {
  3886. res->digits=decGetDigits(acc, D2U(res->digits));
  3887. if (res->digits<maxdigits) res->digits=maxdigits;
  3888. }
  3889. }
  3890. decSetCoeff(res, set, acc, res->digits, &residue, status);
  3891. /* Now apply rounding if needed before removing leading zeros. */
  3892. /* This is safe because subnormals are not a possibility */
  3893. if (residue!=0) {
  3894. decApplyRound(res, set, residue, status);
  3895. residue=0; /* did what needed to be done */
  3896. }
  3897. } /* subset */
  3898. #endif
  3899. } /* used buffer */
  3900. /* strip leading zeros [these were left on in case of subset subtract] */
  3901. res->digits=decGetDigits(res->lsu, D2U(res->digits));
  3902. /* apply checks and rounding */
  3903. decFinish(res, set, &residue, status);
  3904. /* "When the sum of two operands with opposite signs is exactly */
  3905. /* zero, the sign of that sum shall be '+' in all rounding modes */
  3906. /* except round toward -Infinity, in which mode that sign shall be */
  3907. /* '-'." [Subset zeros also never have '-', set by decFinish.] */
  3908. if (ISZERO(res) && diffsign
  3909. #if DECSUBSET
  3910. && set->extended
  3911. #endif
  3912. && (*status&DEC_Inexact)==0) {
  3913. if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG; /* sign - */
  3914. else res->bits&=~DECNEG; /* sign + */
  3915. }
  3916. } while(0); /* end protected */
  3917. if (allocacc!=nullptr) free(allocacc); /* drop any storage used */
  3918. #if DECSUBSET
  3919. if (allocrhs!=nullptr) free(allocrhs); /* .. */
  3920. if (alloclhs!=nullptr) free(alloclhs); /* .. */
  3921. #endif
  3922. return res;
  3923. } /* decAddOp */
  3924. /* ------------------------------------------------------------------ */
  3925. /* decDivideOp -- division operation */
  3926. /* */
  3927. /* This routine performs the calculations for all four division */
  3928. /* operators (divide, divideInteger, remainder, remainderNear). */
  3929. /* */
  3930. /* C=A op B */
  3931. /* */
  3932. /* res is C, the result. C may be A and/or B (e.g., X=X/X) */
  3933. /* lhs is A */
  3934. /* rhs is B */
  3935. /* set is the context */
  3936. /* op is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively. */
  3937. /* status is the usual accumulator */
  3938. /* */
  3939. /* C must have space for set->digits digits. */
  3940. /* */
  3941. /* ------------------------------------------------------------------ */
  3942. /* The underlying algorithm of this routine is the same as in the */
  3943. /* 1981 S/370 implementation, that is, non-restoring long division */
  3944. /* with bi-unit (rather than bi-digit) estimation for each unit */
  3945. /* multiplier. In this pseudocode overview, complications for the */
  3946. /* Remainder operators and division residues for exact rounding are */
  3947. /* omitted for clarity. */
  3948. /* */
  3949. /* Prepare operands and handle special values */
  3950. /* Test for x/0 and then 0/x */
  3951. /* Exp =Exp1 - Exp2 */
  3952. /* Exp =Exp +len(var1) -len(var2) */
  3953. /* Sign=Sign1 * Sign2 */
  3954. /* Pad accumulator (Var1) to double-length with 0's (pad1) */
  3955. /* Pad Var2 to same length as Var1 */
  3956. /* msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round */
  3957. /* have=0 */
  3958. /* Do until (have=digits+1 OR residue=0) */
  3959. /* if exp<0 then if integer divide/residue then leave */
  3960. /* this_unit=0 */
  3961. /* Do forever */
  3962. /* compare numbers */
  3963. /* if <0 then leave inner_loop */
  3964. /* if =0 then (* quick exit without subtract *) do */
  3965. /* this_unit=this_unit+1; output this_unit */
  3966. /* leave outer_loop; end */
  3967. /* Compare lengths of numbers (mantissae): */
  3968. /* If same then tops2=msu2pair -- {units 1&2 of var2} */
  3969. /* else tops2=msu2plus -- {0, unit 1 of var2} */
  3970. /* tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
  3971. /* mult=tops1/tops2 -- Good and safe guess at divisor */
  3972. /* if mult=0 then mult=1 */
  3973. /* this_unit=this_unit+mult */
  3974. /* subtract */
  3975. /* end inner_loop */
  3976. /* if have\=0 | this_unit\=0 then do */
  3977. /* output this_unit */
  3978. /* have=have+1; end */
  3979. /* var2=var2/10 */
  3980. /* exp=exp-1 */
  3981. /* end outer_loop */
  3982. /* exp=exp+1 -- set the proper exponent */
  3983. /* if have=0 then generate answer=0 */
  3984. /* Return (Result is defined by Var1) */
  3985. /* */
  3986. /* ------------------------------------------------------------------ */
  3987. /* Two working buffers are needed during the division; one (digits+ */
  3988. /* 1) to accumulate the result, and the other (up to 2*digits+1) for */
  3989. /* long subtractions. These are acc and var1 respectively. */
  3990. /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
  3991. /* The static buffers may be larger than might be expected to allow */
  3992. /* for calls from higher-level functions (notable exp). */
  3993. /* ------------------------------------------------------------------ */
  3994. static decNumber * decDivideOp(decNumber *res,
  3995. const decNumber *lhs, const decNumber *rhs,
  3996. decContext *set, Flag op, uInt *status) {
  3997. #if DECSUBSET
  3998. decNumber *alloclhs=nullptr; /* non-nullptr if rounded lhs allocated */
  3999. decNumber *allocrhs=nullptr; /* .., rhs */
  4000. #endif
  4001. Unit accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer */
  4002. Unit *acc=accbuff; /* -> accumulator array for result */
  4003. Unit *allocacc=nullptr; /* -> allocated buffer, iff allocated */
  4004. Unit *accnext; /* -> where next digit will go */
  4005. Int acclength; /* length of acc needed [Units] */
  4006. Int accunits; /* count of units accumulated */
  4007. Int accdigits; /* count of digits accumulated */
  4008. Unit varbuff[SD2U(DECBUFFER*2+DECDPUN)]; /* buffer for var1 */
  4009. Unit *var1=varbuff; /* -> var1 array for long subtraction */
  4010. Unit *varalloc=nullptr; /* -> allocated buffer, iff used */
  4011. Unit *msu1; /* -> msu of var1 */
  4012. const Unit *var2; /* -> var2 array */
  4013. const Unit *msu2; /* -> msu of var2 */
  4014. Int msu2plus; /* msu2 plus one [does not vary] */
  4015. eInt msu2pair; /* msu2 pair plus one [does not vary] */
  4016. Int var1units, var2units; /* actual lengths */
  4017. Int var2ulen; /* logical length (units) */
  4018. Int var1initpad=0; /* var1 initial padding (digits) */
  4019. Int maxdigits; /* longest LHS or required acc length */
  4020. Int mult; /* multiplier for subtraction */
  4021. Unit thisunit; /* current unit being accumulated */
  4022. Int residue; /* for rounding */
  4023. Int reqdigits=set->digits; /* requested DIGITS */
  4024. Int exponent; /* working exponent */
  4025. Int maxexponent=0; /* DIVIDE maximum exponent if unrounded */
  4026. uByte bits; /* working sign */
  4027. Unit *target; /* work */
  4028. const Unit *source; /* .. */
  4029. uInt const *pow; /* .. */
  4030. Int shift, cut; /* .. */
  4031. #if DECSUBSET
  4032. Int dropped; /* work */
  4033. #endif
  4034. #if DECCHECK
  4035. if (decCheckOperands(res, lhs, rhs, set)) return res;
  4036. #endif
  4037. do { /* protect allocated storage */
  4038. #if DECSUBSET
  4039. if (!set->extended) {
  4040. /* reduce operands and set lostDigits status, as needed */
  4041. if (lhs->digits>reqdigits) {
  4042. alloclhs=decRoundOperand(lhs, set, status);
  4043. if (alloclhs==nullptr) break;
  4044. lhs=alloclhs;
  4045. }
  4046. if (rhs->digits>reqdigits) {
  4047. allocrhs=decRoundOperand(rhs, set, status);
  4048. if (allocrhs==nullptr) break;
  4049. rhs=allocrhs;
  4050. }
  4051. }
  4052. #endif
  4053. /* [following code does not require input rounding] */
  4054. bits=(lhs->bits^rhs->bits)&DECNEG; /* assumed sign for divisions */
  4055. /* handle infinities and NaNs */
  4056. if (SPECIALARGS) { /* a special bit set */
  4057. if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
  4058. decNaNs(res, lhs, rhs, set, status);
  4059. break;
  4060. }
  4061. /* one or two infinities */
  4062. if (decNumberIsInfinite(lhs)) { /* LHS (dividend) is infinite */
  4063. if (decNumberIsInfinite(rhs) || /* two infinities are invalid .. */
  4064. op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity */
  4065. *status|=DEC_Invalid_operation;
  4066. break;
  4067. }
  4068. /* [Note that infinity/0 raises no exceptions] */
  4069. uprv_decNumberZero(res);
  4070. res->bits=bits|DECINF; /* set +/- infinity */
  4071. break;
  4072. }
  4073. else { /* RHS (divisor) is infinite */
  4074. residue=0;
  4075. if (op&(REMAINDER|REMNEAR)) {
  4076. /* result is [finished clone of] lhs */
  4077. decCopyFit(res, lhs, set, &residue, status);
  4078. }
  4079. else { /* a division */
  4080. uprv_decNumberZero(res);
  4081. res->bits=bits; /* set +/- zero */
  4082. /* for DIVIDEINT the exponent is always 0. For DIVIDE, result */
  4083. /* is a 0 with infinitely negative exponent, clamped to minimum */
  4084. if (op&DIVIDE) {
  4085. res->exponent=set->emin-set->digits+1;
  4086. *status|=DEC_Clamped;
  4087. }
  4088. }
  4089. decFinish(res, set, &residue, status);
  4090. break;
  4091. }
  4092. }
  4093. /* handle 0 rhs (x/0) */
  4094. if (ISZERO(rhs)) { /* x/0 is always exceptional */
  4095. if (ISZERO(lhs)) {
  4096. uprv_decNumberZero(res); /* [after lhs test] */
  4097. *status|=DEC_Division_undefined;/* 0/0 will become NaN */
  4098. }
  4099. else {
  4100. uprv_decNumberZero(res);
  4101. if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
  4102. else {
  4103. *status|=DEC_Division_by_zero; /* x/0 */
  4104. res->bits=bits|DECINF; /* .. is +/- Infinity */
  4105. }
  4106. }
  4107. break;}
  4108. /* handle 0 lhs (0/x) */
  4109. if (ISZERO(lhs)) { /* 0/x [x!=0] */
  4110. #if DECSUBSET
  4111. if (!set->extended) uprv_decNumberZero(res);
  4112. else {
  4113. #endif
  4114. if (op&DIVIDE) {
  4115. residue=0;
  4116. exponent=lhs->exponent-rhs->exponent; /* ideal exponent */
  4117. uprv_decNumberCopy(res, lhs); /* [zeros always fit] */
  4118. res->bits=bits; /* sign as computed */
  4119. res->exponent=exponent; /* exponent, too */
  4120. decFinalize(res, set, &residue, status); /* check exponent */
  4121. }
  4122. else if (op&DIVIDEINT) {
  4123. uprv_decNumberZero(res); /* integer 0 */
  4124. res->bits=bits; /* sign as computed */
  4125. }
  4126. else { /* a remainder */
  4127. exponent=rhs->exponent; /* [save in case overwrite] */
  4128. uprv_decNumberCopy(res, lhs); /* [zeros always fit] */
  4129. if (exponent<res->exponent) res->exponent=exponent; /* use lower */
  4130. }
  4131. #if DECSUBSET
  4132. }
  4133. #endif
  4134. break;}
  4135. /* Precalculate exponent. This starts off adjusted (and hence fits */
  4136. /* in 31 bits) and becomes the usual unadjusted exponent as the */
  4137. /* division proceeds. The order of evaluation is important, here, */
  4138. /* to avoid wrap. */
  4139. exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
  4140. /* If the working exponent is -ve, then some quick exits are */
  4141. /* possible because the quotient is known to be <1 */
  4142. /* [for REMNEAR, it needs to be < -1, as -0.5 could need work] */
  4143. if (exponent<0 && !(op==DIVIDE)) {
  4144. if (op&DIVIDEINT) {
  4145. uprv_decNumberZero(res); /* integer part is 0 */
  4146. #if DECSUBSET
  4147. if (set->extended)
  4148. #endif
  4149. res->bits=bits; /* set +/- zero */
  4150. break;}
  4151. /* fastpath remainders so long as the lhs has the smaller */
  4152. /* (or equal) exponent */
  4153. if (lhs->exponent<=rhs->exponent) {
  4154. if (op&REMAINDER || exponent<-1) {
  4155. /* It is REMAINDER or safe REMNEAR; result is [finished */
  4156. /* clone of] lhs (r = x - 0*y) */
  4157. residue=0;
  4158. decCopyFit(res, lhs, set, &residue, status);
  4159. decFinish(res, set, &residue, status);
  4160. break;
  4161. }
  4162. /* [unsafe REMNEAR drops through] */
  4163. }
  4164. } /* fastpaths */
  4165. /* Long (slow) division is needed; roll up the sleeves... */
  4166. /* The accumulator will hold the quotient of the division. */
  4167. /* If it needs to be too long for stack storage, then allocate. */
  4168. acclength=D2U(reqdigits+DECDPUN); /* in Units */
  4169. if (acclength*sizeof(Unit)>sizeof(accbuff)) {
  4170. /* printf("malloc dvacc %ld units\n", acclength); */
  4171. allocacc=(Unit *)malloc(acclength*sizeof(Unit));
  4172. if (allocacc==nullptr) { /* hopeless -- abandon */
  4173. *status|=DEC_Insufficient_storage;
  4174. break;}
  4175. acc=allocacc; /* use the allocated space */
  4176. }
  4177. /* var1 is the padded LHS ready for subtractions. */
  4178. /* If it needs to be too long for stack storage, then allocate. */
  4179. /* The maximum units needed for var1 (long subtraction) is: */
  4180. /* Enough for */
  4181. /* (rhs->digits+reqdigits-1) -- to allow full slide to right */
  4182. /* or (lhs->digits) -- to allow for long lhs */
  4183. /* whichever is larger */
  4184. /* +1 -- for rounding of slide to right */
  4185. /* +1 -- for leading 0s */
  4186. /* +1 -- for pre-adjust if a remainder or DIVIDEINT */
  4187. /* [Note: unused units do not participate in decUnitAddSub data] */
  4188. maxdigits=rhs->digits+reqdigits-1;
  4189. if (lhs->digits>maxdigits) maxdigits=lhs->digits;
  4190. var1units=D2U(maxdigits)+2;
  4191. /* allocate a guard unit above msu1 for REMAINDERNEAR */
  4192. if (!(op&DIVIDE)) var1units++;
  4193. if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
  4194. /* printf("malloc dvvar %ld units\n", var1units+1); */
  4195. varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
  4196. if (varalloc==nullptr) { /* hopeless -- abandon */
  4197. *status|=DEC_Insufficient_storage;
  4198. break;}
  4199. var1=varalloc; /* use the allocated space */
  4200. }
  4201. /* Extend the lhs and rhs to full long subtraction length. The lhs */
  4202. /* is truly extended into the var1 buffer, with 0 padding, so a */
  4203. /* subtract in place is always possible. The rhs (var2) has */
  4204. /* virtual padding (implemented by decUnitAddSub). */
  4205. /* One guard unit was allocated above msu1 for rem=rem+rem in */
  4206. /* REMAINDERNEAR. */
  4207. msu1=var1+var1units-1; /* msu of var1 */
  4208. source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array */
  4209. for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
  4210. for (; target>=var1; target--) *target=0;
  4211. /* rhs (var2) is left-aligned with var1 at the start */
  4212. var2ulen=var1units; /* rhs logical length (units) */
  4213. var2units=D2U(rhs->digits); /* rhs actual length (units) */
  4214. var2=rhs->lsu; /* -> rhs array */
  4215. msu2=var2+var2units-1; /* -> msu of var2 [never changes] */
  4216. /* now set up the variables which will be used for estimating the */
  4217. /* multiplication factor. If these variables are not exact, add */
  4218. /* 1 to make sure that the multiplier is never overestimated. */
  4219. msu2plus=*msu2; /* it's value .. */
  4220. if (var2units>1) msu2plus++; /* .. +1 if any more */
  4221. msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair .. */
  4222. if (var2units>1) { /* .. [else treat 2nd as 0] */
  4223. msu2pair+=*(msu2-1); /* .. */
  4224. if (var2units>2) msu2pair++; /* .. +1 if any more */
  4225. }
  4226. /* The calculation is working in units, which may have leading zeros, */
  4227. /* but the exponent was calculated on the assumption that they are */
  4228. /* both left-aligned. Adjust the exponent to compensate: add the */
  4229. /* number of leading zeros in var1 msu and subtract those in var2 msu. */
  4230. /* [This is actually done by counting the digits and negating, as */
  4231. /* lead1=DECDPUN-digits1, and similarly for lead2.] */
  4232. for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
  4233. for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
  4234. /* Now, if doing an integer divide or remainder, ensure that */
  4235. /* the result will be Unit-aligned. To do this, shift the var1 */
  4236. /* accumulator towards least if need be. (It's much easier to */
  4237. /* do this now than to reassemble the residue afterwards, if */
  4238. /* doing a remainder.) Also ensure the exponent is not negative. */
  4239. if (!(op&DIVIDE)) {
  4240. Unit *u; /* work */
  4241. /* save the initial 'false' padding of var1, in digits */
  4242. var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
  4243. /* Determine the shift to do. */
  4244. if (exponent<0) cut=-exponent;
  4245. else cut=DECDPUN-exponent%DECDPUN;
  4246. decShiftToLeast(var1, var1units, cut);
  4247. exponent+=cut; /* maintain numerical value */
  4248. var1initpad-=cut; /* .. and reduce padding */
  4249. /* clean any most-significant units which were just emptied */
  4250. for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
  4251. } /* align */
  4252. else { /* is DIVIDE */
  4253. maxexponent=lhs->exponent-rhs->exponent; /* save */
  4254. /* optimization: if the first iteration will just produce 0, */
  4255. /* preadjust to skip it [valid for DIVIDE only] */
  4256. if (*msu1<*msu2) {
  4257. var2ulen--; /* shift down */
  4258. exponent-=DECDPUN; /* update the exponent */
  4259. }
  4260. }
  4261. /* ---- start the long-division loops ------------------------------ */
  4262. accunits=0; /* no units accumulated yet */
  4263. accdigits=0; /* .. or digits */
  4264. accnext=acc+acclength-1; /* -> msu of acc [NB: allows digits+1] */
  4265. for (;;) { /* outer forever loop */
  4266. thisunit=0; /* current unit assumed 0 */
  4267. /* find the next unit */
  4268. for (;;) { /* inner forever loop */
  4269. /* strip leading zero units [from either pre-adjust or from */
  4270. /* subtract last time around]. Leave at least one unit. */
  4271. for (; *msu1==0 && msu1>var1; msu1--) var1units--;
  4272. if (var1units<var2ulen) break; /* var1 too low for subtract */
  4273. if (var1units==var2ulen) { /* unit-by-unit compare needed */
  4274. /* compare the two numbers, from msu */
  4275. const Unit *pv1, *pv2;
  4276. Unit v2; /* units to compare */
  4277. pv2=msu2; /* -> msu */
  4278. for (pv1=msu1; ; pv1--, pv2--) {
  4279. /* v1=*pv1 -- always OK */
  4280. v2=0; /* assume in padding */
  4281. if (pv2>=var2) v2=*pv2; /* in range */
  4282. if (*pv1!=v2) break; /* no longer the same */
  4283. if (pv1==var1) break; /* done; leave pv1 as is */
  4284. }
  4285. /* here when all inspected or a difference seen */
  4286. if (*pv1<v2) break; /* var1 too low to subtract */
  4287. if (*pv1==v2) { /* var1 == var2 */
  4288. /* reach here if var1 and var2 are identical; subtraction */
  4289. /* would increase digit by one, and the residue will be 0 so */
  4290. /* the calculation is done; leave the loop with residue=0. */
  4291. thisunit++; /* as though subtracted */
  4292. *var1=0; /* set var1 to 0 */
  4293. var1units=1; /* .. */
  4294. break; /* from inner */
  4295. } /* var1 == var2 */
  4296. /* *pv1>v2. Prepare for real subtraction; the lengths are equal */
  4297. /* Estimate the multiplier (there's always a msu1-1)... */
  4298. /* Bring in two units of var2 to provide a good estimate. */
  4299. mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
  4300. } /* lengths the same */
  4301. else { /* var1units > var2ulen, so subtraction is safe */
  4302. /* The var2 msu is one unit towards the lsu of the var1 msu, */
  4303. /* so only one unit for var2 can be used. */
  4304. mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
  4305. }
  4306. if (mult==0) mult=1; /* must always be at least 1 */
  4307. /* subtraction needed; var1 is > var2 */
  4308. thisunit=(Unit)(thisunit+mult); /* accumulate */
  4309. /* subtract var1-var2, into var1; only the overlap needs */
  4310. /* processing, as this is an in-place calculation */
  4311. shift=var2ulen-var2units;
  4312. #if DECTRACE
  4313. decDumpAr('1', &var1[shift], var1units-shift);
  4314. decDumpAr('2', var2, var2units);
  4315. printf("m=%ld\n", -mult);
  4316. #endif
  4317. decUnitAddSub(&var1[shift], var1units-shift,
  4318. var2, var2units, 0,
  4319. &var1[shift], -mult);
  4320. #if DECTRACE
  4321. decDumpAr('#', &var1[shift], var1units-shift);
  4322. #endif
  4323. /* var1 now probably has leading zeros; these are removed at the */
  4324. /* top of the inner loop. */
  4325. } /* inner loop */
  4326. /* The next unit has been calculated in full; unless it's a */
  4327. /* leading zero, add to acc */
  4328. if (accunits!=0 || thisunit!=0) { /* is first or non-zero */
  4329. *accnext=thisunit; /* store in accumulator */
  4330. /* account exactly for the new digits */
  4331. if (accunits==0) {
  4332. accdigits++; /* at least one */
  4333. for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
  4334. }
  4335. else accdigits+=DECDPUN;
  4336. accunits++; /* update count */
  4337. accnext--; /* ready for next */
  4338. if (accdigits>reqdigits) break; /* have enough digits */
  4339. }
  4340. /* if the residue is zero, the operation is done (unless divide */
  4341. /* or divideInteger and still not enough digits yet) */
  4342. if (*var1==0 && var1units==1) { /* residue is 0 */
  4343. if (op&(REMAINDER|REMNEAR)) break;
  4344. if ((op&DIVIDE) && (exponent<=maxexponent)) break;
  4345. /* [drop through if divideInteger] */
  4346. }
  4347. /* also done enough if calculating remainder or integer */
  4348. /* divide and just did the last ('units') unit */
  4349. if (exponent==0 && !(op&DIVIDE)) break;
  4350. /* to get here, var1 is less than var2, so divide var2 by the per- */
  4351. /* Unit power of ten and go for the next digit */
  4352. var2ulen--; /* shift down */
  4353. exponent-=DECDPUN; /* update the exponent */
  4354. } /* outer loop */
  4355. /* ---- division is complete --------------------------------------- */
  4356. /* here: acc has at least reqdigits+1 of good results (or fewer */
  4357. /* if early stop), starting at accnext+1 (its lsu) */
  4358. /* var1 has any residue at the stopping point */
  4359. /* accunits is the number of digits collected in acc */
  4360. if (accunits==0) { /* acc is 0 */
  4361. accunits=1; /* show have a unit .. */
  4362. accdigits=1; /* .. */
  4363. *accnext=0; /* .. whose value is 0 */
  4364. }
  4365. else accnext++; /* back to last placed */
  4366. /* accnext now -> lowest unit of result */
  4367. residue=0; /* assume no residue */
  4368. if (op&DIVIDE) {
  4369. /* record the presence of any residue, for rounding */
  4370. if (*var1!=0 || var1units>1) residue=1;
  4371. else { /* no residue */
  4372. /* Had an exact division; clean up spurious trailing 0s. */
  4373. /* There will be at most DECDPUN-1, from the final multiply, */
  4374. /* and then only if the result is non-0 (and even) and the */
  4375. /* exponent is 'loose'. */
  4376. #if DECDPUN>1
  4377. Unit lsu=*accnext;
  4378. if (!(lsu&0x01) && (lsu!=0)) {
  4379. /* count the trailing zeros */
  4380. Int drop=0;
  4381. for (;; drop++) { /* [will terminate because lsu!=0] */
  4382. if (exponent>=maxexponent) break; /* don't chop real 0s */
  4383. #if DECDPUN<=4
  4384. if ((lsu-QUOT10(lsu, drop+1)
  4385. *powers[drop+1])!=0) break; /* found non-0 digit */
  4386. #else
  4387. if (lsu%powers[drop+1]!=0) break; /* found non-0 digit */
  4388. #endif
  4389. exponent++;
  4390. }
  4391. if (drop>0) {
  4392. accunits=decShiftToLeast(accnext, accunits, drop);
  4393. accdigits=decGetDigits(accnext, accunits);
  4394. accunits=D2U(accdigits);
  4395. /* [exponent was adjusted in the loop] */
  4396. }
  4397. } /* neither odd nor 0 */
  4398. #endif
  4399. } /* exact divide */
  4400. } /* divide */
  4401. else /* op!=DIVIDE */ {
  4402. /* check for coefficient overflow */
  4403. if (accdigits+exponent>reqdigits) {
  4404. *status|=DEC_Division_impossible;
  4405. break;
  4406. }
  4407. if (op & (REMAINDER|REMNEAR)) {
  4408. /* [Here, the exponent will be 0, because var1 was adjusted */
  4409. /* appropriately.] */
  4410. Int postshift; /* work */
  4411. Flag wasodd=0; /* integer was odd */
  4412. Unit *quotlsu; /* for save */
  4413. Int quotdigits; /* .. */
  4414. bits=lhs->bits; /* remainder sign is always as lhs */
  4415. /* Fastpath when residue is truly 0 is worthwhile [and */
  4416. /* simplifies the code below] */
  4417. if (*var1==0 && var1units==1) { /* residue is 0 */
  4418. Int exp=lhs->exponent; /* save min(exponents) */
  4419. if (rhs->exponent<exp) exp=rhs->exponent;
  4420. uprv_decNumberZero(res); /* 0 coefficient */
  4421. #if DECSUBSET
  4422. if (set->extended)
  4423. #endif
  4424. res->exponent=exp; /* .. with proper exponent */
  4425. res->bits=(uByte)(bits&DECNEG); /* [cleaned] */
  4426. decFinish(res, set, &residue, status); /* might clamp */
  4427. break;
  4428. }
  4429. /* note if the quotient was odd */
  4430. if (*accnext & 0x01) wasodd=1; /* acc is odd */
  4431. quotlsu=accnext; /* save in case need to reinspect */
  4432. quotdigits=accdigits; /* .. */
  4433. /* treat the residue, in var1, as the value to return, via acc */
  4434. /* calculate the unused zero digits. This is the smaller of: */
  4435. /* var1 initial padding (saved above) */
  4436. /* var2 residual padding, which happens to be given by: */
  4437. postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
  4438. /* [the 'exponent' term accounts for the shifts during divide] */
  4439. if (var1initpad<postshift) postshift=var1initpad;
  4440. /* shift var1 the requested amount, and adjust its digits */
  4441. var1units=decShiftToLeast(var1, var1units, postshift);
  4442. accnext=var1;
  4443. accdigits=decGetDigits(var1, var1units);
  4444. accunits=D2U(accdigits);
  4445. exponent=lhs->exponent; /* exponent is smaller of lhs & rhs */
  4446. if (rhs->exponent<exponent) exponent=rhs->exponent;
  4447. /* Now correct the result if doing remainderNear; if it */
  4448. /* (looking just at coefficients) is > rhs/2, or == rhs/2 and */
  4449. /* the integer was odd then the result should be rem-rhs. */
  4450. if (op&REMNEAR) {
  4451. Int compare, tarunits; /* work */
  4452. Unit *up; /* .. */
  4453. /* calculate remainder*2 into the var1 buffer (which has */
  4454. /* 'headroom' of an extra unit and hence enough space) */
  4455. /* [a dedicated 'double' loop would be faster, here] */
  4456. tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
  4457. 0, accnext, 1);
  4458. /* decDumpAr('r', accnext, tarunits); */
  4459. /* Here, accnext (var1) holds tarunits Units with twice the */
  4460. /* remainder's coefficient, which must now be compared to the */
  4461. /* RHS. The remainder's exponent may be smaller than the RHS's. */
  4462. compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
  4463. rhs->exponent-exponent);
  4464. if (compare==BADINT) { /* deep trouble */
  4465. *status|=DEC_Insufficient_storage;
  4466. break;}
  4467. /* now restore the remainder by dividing by two; the lsu */
  4468. /* is known to be even. */
  4469. for (up=accnext; up<accnext+tarunits; up++) {
  4470. Int half; /* half to add to lower unit */
  4471. half=*up & 0x01;
  4472. *up/=2; /* [shift] */
  4473. if (!half) continue;
  4474. *(up-1)+=(DECDPUNMAX+1)/2;
  4475. }
  4476. /* [accunits still describes the original remainder length] */
  4477. if (compare>0 || (compare==0 && wasodd)) { /* adjustment needed */
  4478. Int exp, expunits, exprem; /* work */
  4479. /* This is effectively causing round-up of the quotient, */
  4480. /* so if it was the rare case where it was full and all */
  4481. /* nines, it would overflow and hence division-impossible */
  4482. /* should be raised */
  4483. Flag allnines=0; /* 1 if quotient all nines */
  4484. if (quotdigits==reqdigits) { /* could be borderline */
  4485. for (up=quotlsu; ; up++) {
  4486. if (quotdigits>DECDPUN) {
  4487. if (*up!=DECDPUNMAX) break;/* non-nines */
  4488. }
  4489. else { /* this is the last Unit */
  4490. if (*up==powers[quotdigits]-1) allnines=1;
  4491. break;
  4492. }
  4493. quotdigits-=DECDPUN; /* checked those digits */
  4494. } /* up */
  4495. } /* borderline check */
  4496. if (allnines) {
  4497. *status|=DEC_Division_impossible;
  4498. break;}
  4499. /* rem-rhs is needed; the sign will invert. Again, var1 */
  4500. /* can safely be used for the working Units array. */
  4501. exp=rhs->exponent-exponent; /* RHS padding needed */
  4502. /* Calculate units and remainder from exponent. */
  4503. expunits=exp/DECDPUN;
  4504. exprem=exp%DECDPUN;
  4505. /* subtract [A+B*(-m)]; the result will always be negative */
  4506. accunits=-decUnitAddSub(accnext, accunits,
  4507. rhs->lsu, D2U(rhs->digits),
  4508. expunits, accnext, -(Int)powers[exprem]);
  4509. accdigits=decGetDigits(accnext, accunits); /* count digits exactly */
  4510. accunits=D2U(accdigits); /* and recalculate the units for copy */
  4511. /* [exponent is as for original remainder] */
  4512. bits^=DECNEG; /* flip the sign */
  4513. }
  4514. } /* REMNEAR */
  4515. } /* REMAINDER or REMNEAR */
  4516. } /* not DIVIDE */
  4517. /* Set exponent and bits */
  4518. res->exponent=exponent;
  4519. res->bits=(uByte)(bits&DECNEG); /* [cleaned] */
  4520. /* Now the coefficient. */
  4521. decSetCoeff(res, set, accnext, accdigits, &residue, status);
  4522. decFinish(res, set, &residue, status); /* final cleanup */
  4523. #if DECSUBSET
  4524. /* If a divide then strip trailing zeros if subset [after round] */
  4525. if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);
  4526. #endif
  4527. } while(0); /* end protected */
  4528. if (varalloc!=nullptr) free(varalloc); /* drop any storage used */
  4529. if (allocacc!=nullptr) free(allocacc); /* .. */
  4530. #if DECSUBSET
  4531. if (allocrhs!=nullptr) free(allocrhs); /* .. */
  4532. if (alloclhs!=nullptr) free(alloclhs); /* .. */
  4533. #endif
  4534. return res;
  4535. } /* decDivideOp */
  4536. /* ------------------------------------------------------------------ */
  4537. /* decMultiplyOp -- multiplication operation */
  4538. /* */
  4539. /* This routine performs the multiplication C=A x B. */
  4540. /* */
  4541. /* res is C, the result. C may be A and/or B (e.g., X=X*X) */
  4542. /* lhs is A */
  4543. /* rhs is B */
  4544. /* set is the context */
  4545. /* status is the usual accumulator */
  4546. /* */
  4547. /* C must have space for set->digits digits. */
  4548. /* */
  4549. /* ------------------------------------------------------------------ */
  4550. /* 'Classic' multiplication is used rather than Karatsuba, as the */
  4551. /* latter would give only a minor improvement for the short numbers */
  4552. /* expected to be handled most (and uses much more memory). */
  4553. /* */
  4554. /* There are two major paths here: the general-purpose ('old code') */
  4555. /* path which handles all DECDPUN values, and a fastpath version */
  4556. /* which is used if 64-bit ints are available, DECDPUN<=4, and more */
  4557. /* than two calls to decUnitAddSub would be made. */
  4558. /* */
  4559. /* The fastpath version lumps units together into 8-digit or 9-digit */
  4560. /* chunks, and also uses a lazy carry strategy to minimise expensive */
  4561. /* 64-bit divisions. The chunks are then broken apart again into */
  4562. /* units for continuing processing. Despite this overhead, the */
  4563. /* fastpath can speed up some 16-digit operations by 10x (and much */
  4564. /* more for higher-precision calculations). */
  4565. /* */
  4566. /* A buffer always has to be used for the accumulator; in the */
  4567. /* fastpath, buffers are also always needed for the chunked copies of */
  4568. /* of the operand coefficients. */
  4569. /* Static buffers are larger than needed just for multiply, to allow */
  4570. /* for calls from other operations (notably exp). */
  4571. /* ------------------------------------------------------------------ */
  4572. #define FASTMUL (DECUSE64 && DECDPUN<5)
  4573. static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
  4574. const decNumber *rhs, decContext *set,
  4575. uInt *status) {
  4576. Int accunits; /* Units of accumulator in use */
  4577. Int exponent; /* work */
  4578. Int residue=0; /* rounding residue */
  4579. uByte bits; /* result sign */
  4580. Unit *acc; /* -> accumulator Unit array */
  4581. Int needbytes; /* size calculator */
  4582. void *allocacc=nullptr; /* -> allocated accumulator, iff allocated */
  4583. Unit accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0, */
  4584. /* *4 for calls from other operations) */
  4585. const Unit *mer, *mermsup; /* work */
  4586. Int madlength; /* Units in multiplicand */
  4587. Int shift; /* Units to shift multiplicand by */
  4588. #if FASTMUL
  4589. /* if DECDPUN is 1 or 3 work in base 10**9, otherwise */
  4590. /* (DECDPUN is 2 or 4) then work in base 10**8 */
  4591. #if DECDPUN & 1 /* odd */
  4592. #define FASTBASE 1000000000 /* base */
  4593. #define FASTDIGS 9 /* digits in base */
  4594. #define FASTLAZY 18 /* carry resolution point [1->18] */
  4595. #else
  4596. #define FASTBASE 100000000
  4597. #define FASTDIGS 8
  4598. #define FASTLAZY 1844 /* carry resolution point [1->1844] */
  4599. #endif
  4600. /* three buffers are used, two for chunked copies of the operands */
  4601. /* (base 10**8 or base 10**9) and one base 2**64 accumulator with */
  4602. /* lazy carry evaluation */
  4603. uInt zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
  4604. uInt *zlhi=zlhibuff; /* -> lhs array */
  4605. uInt *alloclhi=nullptr; /* -> allocated buffer, iff allocated */
  4606. uInt zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
  4607. uInt *zrhi=zrhibuff; /* -> rhs array */
  4608. uInt *allocrhi=nullptr; /* -> allocated buffer, iff allocated */
  4609. uLong zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0) */
  4610. /* [allocacc is shared for both paths, as only one will run] */
  4611. uLong *zacc=zaccbuff; /* -> accumulator array for exact result */
  4612. #if DECDPUN==1
  4613. Int zoff; /* accumulator offset */
  4614. #endif
  4615. uInt *lip, *rip; /* item pointers */
  4616. uInt *lmsi, *rmsi; /* most significant items */
  4617. Int ilhs, irhs, iacc; /* item counts in the arrays */
  4618. Int lazy; /* lazy carry counter */
  4619. uLong lcarry; /* uLong carry */
  4620. uInt carry; /* carry (NB not uLong) */
  4621. Int count; /* work */
  4622. const Unit *cup; /* .. */
  4623. Unit *up; /* .. */
  4624. uLong *lp; /* .. */
  4625. Int p; /* .. */
  4626. #endif
  4627. #if DECSUBSET
  4628. decNumber *alloclhs=nullptr; /* -> allocated buffer, iff allocated */
  4629. decNumber *allocrhs=nullptr; /* -> allocated buffer, iff allocated */
  4630. #endif
  4631. #if DECCHECK
  4632. if (decCheckOperands(res, lhs, rhs, set)) return res;
  4633. #endif
  4634. /* precalculate result sign */
  4635. bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
  4636. /* handle infinities and NaNs */
  4637. if (SPECIALARGS) { /* a special bit set */
  4638. if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
  4639. decNaNs(res, lhs, rhs, set, status);
  4640. return res;}
  4641. /* one or two infinities; Infinity * 0 is invalid */
  4642. if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
  4643. ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
  4644. *status|=DEC_Invalid_operation;
  4645. return res;}
  4646. uprv_decNumberZero(res);
  4647. res->bits=bits|DECINF; /* infinity */
  4648. return res;}
  4649. /* For best speed, as in DMSRCN [the original Rexx numerics */
  4650. /* module], use the shorter number as the multiplier (rhs) and */
  4651. /* the longer as the multiplicand (lhs) to minimise the number of */
  4652. /* adds (partial products) */
  4653. if (lhs->digits<rhs->digits) { /* swap... */
  4654. const decNumber *hold=lhs;
  4655. lhs=rhs;
  4656. rhs=hold;
  4657. }
  4658. do { /* protect allocated storage */
  4659. #if DECSUBSET
  4660. if (!set->extended) {
  4661. /* reduce operands and set lostDigits status, as needed */
  4662. if (lhs->digits>set->digits) {
  4663. alloclhs=decRoundOperand(lhs, set, status);
  4664. if (alloclhs==nullptr) break;
  4665. lhs=alloclhs;
  4666. }
  4667. if (rhs->digits>set->digits) {
  4668. allocrhs=decRoundOperand(rhs, set, status);
  4669. if (allocrhs==nullptr) break;
  4670. rhs=allocrhs;
  4671. }
  4672. }
  4673. #endif
  4674. /* [following code does not require input rounding] */
  4675. #if FASTMUL /* fastpath can be used */
  4676. /* use the fast path if there are enough digits in the shorter */
  4677. /* operand to make the setup and takedown worthwhile */
  4678. #define NEEDTWO (DECDPUN*2) /* within two decUnitAddSub calls */
  4679. if (rhs->digits>NEEDTWO) { /* use fastpath... */
  4680. /* calculate the number of elements in each array */
  4681. ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling] */
  4682. irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* .. */
  4683. iacc=ilhs+irhs;
  4684. /* allocate buffers if required, as usual */
  4685. needbytes=ilhs*sizeof(uInt);
  4686. if (needbytes>(Int)sizeof(zlhibuff)) {
  4687. alloclhi=(uInt *)malloc(needbytes);
  4688. zlhi=alloclhi;}
  4689. needbytes=irhs*sizeof(uInt);
  4690. if (needbytes>(Int)sizeof(zrhibuff)) {
  4691. allocrhi=(uInt *)malloc(needbytes);
  4692. zrhi=allocrhi;}
  4693. /* Allocating the accumulator space needs a special case when */
  4694. /* DECDPUN=1 because when converting the accumulator to Units */
  4695. /* after the multiplication each 8-byte item becomes 9 1-byte */
  4696. /* units. Therefore iacc extra bytes are needed at the front */
  4697. /* (rounded up to a multiple of 8 bytes), and the uLong */
  4698. /* accumulator starts offset the appropriate number of units */
  4699. /* to the right to avoid overwrite during the unchunking. */
  4700. /* Make sure no signed int overflow below. This is always true */
  4701. /* if the given numbers have less digits than DEC_MAX_DIGITS. */
  4702. U_ASSERT((uint32_t)iacc <= INT32_MAX/sizeof(uLong));
  4703. needbytes=iacc*sizeof(uLong);
  4704. #if DECDPUN==1
  4705. zoff=(iacc+7)/8; /* items to offset by */
  4706. needbytes+=zoff*8;
  4707. #endif
  4708. if (needbytes>(Int)sizeof(zaccbuff)) {
  4709. allocacc=(uLong *)malloc(needbytes);
  4710. zacc=(uLong *)allocacc;}
  4711. if (zlhi==nullptr||zrhi==nullptr||zacc==nullptr) {
  4712. *status|=DEC_Insufficient_storage;
  4713. break;}
  4714. acc=(Unit *)zacc; /* -> target Unit array */
  4715. #if DECDPUN==1
  4716. zacc+=zoff; /* start uLong accumulator to right */
  4717. #endif
  4718. /* assemble the chunked copies of the left and right sides */
  4719. for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
  4720. for (p=0, *lip=0; p<FASTDIGS && count>0;
  4721. p+=DECDPUN, cup++, count-=DECDPUN)
  4722. *lip+=*cup*powers[p];
  4723. lmsi=lip-1; /* save -> msi */
  4724. for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
  4725. for (p=0, *rip=0; p<FASTDIGS && count>0;
  4726. p+=DECDPUN, cup++, count-=DECDPUN)
  4727. *rip+=*cup*powers[p];
  4728. rmsi=rip-1; /* save -> msi */
  4729. /* zero the accumulator */
  4730. for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
  4731. /* Start the multiplication */
  4732. /* Resolving carries can dominate the cost of accumulating the */
  4733. /* partial products, so this is only done when necessary. */
  4734. /* Each uLong item in the accumulator can hold values up to */
  4735. /* 2**64-1, and each partial product can be as large as */
  4736. /* (10**FASTDIGS-1)**2. When FASTDIGS=9, this can be added to */
  4737. /* itself 18.4 times in a uLong without overflowing, so during */
  4738. /* the main calculation resolution is carried out every 18th */
  4739. /* add -- every 162 digits. Similarly, when FASTDIGS=8, the */
  4740. /* partial products can be added to themselves 1844.6 times in */
  4741. /* a uLong without overflowing, so intermediate carry */
  4742. /* resolution occurs only every 14752 digits. Hence for common */
  4743. /* short numbers usually only the one final carry resolution */
  4744. /* occurs. */
  4745. /* (The count is set via FASTLAZY to simplify experiments to */
  4746. /* measure the value of this approach: a 35% improvement on a */
  4747. /* [34x34] multiply.) */
  4748. lazy=FASTLAZY; /* carry delay count */
  4749. for (rip=zrhi; rip<=rmsi; rip++) { /* over each item in rhs */
  4750. lp=zacc+(rip-zrhi); /* where to add the lhs */
  4751. for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs */
  4752. *lp+=(uLong)(*lip)*(*rip); /* [this should in-line] */
  4753. } /* lip loop */
  4754. lazy--;
  4755. if (lazy>0 && rip!=rmsi) continue;
  4756. lazy=FASTLAZY; /* reset delay count */
  4757. /* spin up the accumulator resolving overflows */
  4758. for (lp=zacc; lp<zacc+iacc; lp++) {
  4759. if (*lp<FASTBASE) continue; /* it fits */
  4760. lcarry=*lp/FASTBASE; /* top part [slow divide] */
  4761. /* lcarry can exceed 2**32-1, so check again; this check */
  4762. /* and occasional extra divide (slow) is well worth it, as */
  4763. /* it allows FASTLAZY to be increased to 18 rather than 4 */
  4764. /* in the FASTDIGS=9 case */
  4765. if (lcarry<FASTBASE) carry=(uInt)lcarry; /* [usual] */
  4766. else { /* two-place carry [fairly rare] */
  4767. uInt carry2=(uInt)(lcarry/FASTBASE); /* top top part */
  4768. *(lp+2)+=carry2; /* add to item+2 */
  4769. *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow] */
  4770. carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline] */
  4771. }
  4772. *(lp+1)+=carry; /* add to item above [inline] */
  4773. *lp-=((uLong)FASTBASE*carry); /* [inline] */
  4774. } /* carry resolution */
  4775. } /* rip loop */
  4776. /* The multiplication is complete; time to convert back into */
  4777. /* units. This can be done in-place in the accumulator and in */
  4778. /* 32-bit operations, because carries were resolved after the */
  4779. /* final add. This needs N-1 divides and multiplies for */
  4780. /* each item in the accumulator (which will become up to N */
  4781. /* units, where 2<=N<=9). */
  4782. for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
  4783. uInt item=(uInt)*lp; /* decapitate to uInt */
  4784. for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
  4785. uInt part=item/(DECDPUNMAX+1);
  4786. *up=(Unit)(item-(part*(DECDPUNMAX+1)));
  4787. item=part;
  4788. } /* p */
  4789. *up=(Unit)item; up++; /* [final needs no division] */
  4790. } /* lp */
  4791. accunits = static_cast<int32_t>(up-acc); /* count of units */
  4792. }
  4793. else { /* here to use units directly, without chunking ['old code'] */
  4794. #endif
  4795. /* if accumulator will be too long for local storage, then allocate */
  4796. acc=accbuff; /* -> assume buffer for accumulator */
  4797. needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
  4798. if (needbytes>(Int)sizeof(accbuff)) {
  4799. allocacc=(Unit *)malloc(needbytes);
  4800. if (allocacc==nullptr) {*status|=DEC_Insufficient_storage; break;}
  4801. acc=(Unit *)allocacc; /* use the allocated space */
  4802. }
  4803. /* Now the main long multiplication loop */
  4804. /* Unlike the equivalent in the IBM Java implementation, there */
  4805. /* is no advantage in calculating from msu to lsu. So, do it */
  4806. /* by the book, as it were. */
  4807. /* Each iteration calculates ACC=ACC+MULTAND*MULT */
  4808. accunits=1; /* accumulator starts at '0' */
  4809. *acc=0; /* .. (lsu=0) */
  4810. shift=0; /* no multiplicand shift at first */
  4811. madlength=D2U(lhs->digits); /* this won't change */
  4812. mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier */
  4813. for (mer=rhs->lsu; mer<mermsup; mer++) {
  4814. /* Here, *mer is the next Unit in the multiplier to use */
  4815. /* If non-zero [optimization] add it... */
  4816. if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
  4817. lhs->lsu, madlength, 0,
  4818. &acc[shift], *mer)
  4819. + shift;
  4820. else { /* extend acc with a 0; it will be used shortly */
  4821. *(acc+accunits)=0; /* [this avoids length of <=0 later] */
  4822. accunits++;
  4823. }
  4824. /* multiply multiplicand by 10**DECDPUN for next Unit to left */
  4825. shift++; /* add this for 'logical length' */
  4826. } /* n */
  4827. #if FASTMUL
  4828. } /* unchunked units */
  4829. #endif
  4830. /* common end-path */
  4831. #if DECTRACE
  4832. decDumpAr('*', acc, accunits); /* Show exact result */
  4833. #endif
  4834. /* acc now contains the exact result of the multiplication, */
  4835. /* possibly with a leading zero unit; build the decNumber from */
  4836. /* it, noting if any residue */
  4837. res->bits=bits; /* set sign */
  4838. res->digits=decGetDigits(acc, accunits); /* count digits exactly */
  4839. /* There can be a 31-bit wrap in calculating the exponent. */
  4840. /* This can only happen if both input exponents are negative and */
  4841. /* both their magnitudes are large. If there was a wrap, set a */
  4842. /* safe very negative exponent, from which decFinalize() will */
  4843. /* raise a hard underflow shortly. */
  4844. exponent=lhs->exponent+rhs->exponent; /* calculate exponent */
  4845. if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
  4846. exponent=-2*DECNUMMAXE; /* force underflow */
  4847. res->exponent=exponent; /* OK to overwrite now */
  4848. /* Set the coefficient. If any rounding, residue records */
  4849. decSetCoeff(res, set, acc, res->digits, &residue, status);
  4850. decFinish(res, set, &residue, status); /* final cleanup */
  4851. } while(0); /* end protected */
  4852. if (allocacc!=nullptr) free(allocacc); /* drop any storage used */
  4853. #if DECSUBSET
  4854. if (allocrhs!=nullptr) free(allocrhs); /* .. */
  4855. if (alloclhs!=nullptr) free(alloclhs); /* .. */
  4856. #endif
  4857. #if FASTMUL
  4858. if (allocrhi!=nullptr) free(allocrhi); /* .. */
  4859. if (alloclhi!=nullptr) free(alloclhi); /* .. */
  4860. #endif
  4861. return res;
  4862. } /* decMultiplyOp */
  4863. /* ------------------------------------------------------------------ */
  4864. /* decExpOp -- effect exponentiation */
  4865. /* */
  4866. /* This computes C = exp(A) */
  4867. /* */
  4868. /* res is C, the result. C may be A */
  4869. /* rhs is A */
  4870. /* set is the context; note that rounding mode has no effect */
  4871. /* */
  4872. /* C must have space for set->digits digits. status is updated but */
  4873. /* not set. */
  4874. /* */
  4875. /* Restrictions: */
  4876. /* */
  4877. /* digits, emax, and -emin in the context must be less than */
  4878. /* 2*DEC_MAX_MATH (1999998), and the rhs must be within these */
  4879. /* bounds or a zero. This is an internal routine, so these */
  4880. /* restrictions are contractual and not enforced. */
  4881. /* */
  4882. /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
  4883. /* almost always be correctly rounded, but may be up to 1 ulp in */
  4884. /* error in rare cases. */
  4885. /* */
  4886. /* Finite results will always be full precision and Inexact, except */
  4887. /* when A is a zero or -Infinity (giving 1 or 0 respectively). */
  4888. /* ------------------------------------------------------------------ */
  4889. /* This approach used here is similar to the algorithm described in */
  4890. /* */
  4891. /* Variable Precision Exponential Function, T. E. Hull and */
  4892. /* A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
  4893. /* pp79-91, ACM, June 1986. */
  4894. /* */
  4895. /* with the main difference being that the iterations in the series */
  4896. /* evaluation are terminated dynamically (which does not require the */
  4897. /* extra variable-precision variables which are expensive in this */
  4898. /* context). */
  4899. /* */
  4900. /* The error analysis in Hull & Abrham's paper applies except for the */
  4901. /* round-off error accumulation during the series evaluation. This */
  4902. /* code does not precalculate the number of iterations and so cannot */
  4903. /* use Horner's scheme. Instead, the accumulation is done at double- */
  4904. /* precision, which ensures that the additions of the terms are exact */
  4905. /* and do not accumulate round-off (and any round-off errors in the */
  4906. /* terms themselves move 'to the right' faster than they can */
  4907. /* accumulate). This code also extends the calculation by allowing, */
  4908. /* in the spirit of other decNumber operators, the input to be more */
  4909. /* precise than the result (the precision used is based on the more */
  4910. /* precise of the input or requested result). */
  4911. /* */
  4912. /* Implementation notes: */
  4913. /* */
  4914. /* 1. This is separated out as decExpOp so it can be called from */
  4915. /* other Mathematical functions (notably Ln) with a wider range */
  4916. /* than normal. In particular, it can handle the slightly wider */
  4917. /* (double) range needed by Ln (which has to be able to calculate */
  4918. /* exp(-x) where x can be the tiniest number (Ntiny). */
  4919. /* */
  4920. /* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop */
  4921. /* iterations by approximately a third with additional (although */
  4922. /* diminishing) returns as the range is reduced to even smaller */
  4923. /* fractions. However, h (the power of 10 used to correct the */
  4924. /* result at the end, see below) must be kept <=8 as otherwise */
  4925. /* the final result cannot be computed. Hence the leverage is a */
  4926. /* sliding value (8-h), where potentially the range is reduced */
  4927. /* more for smaller values. */
  4928. /* */
  4929. /* The leverage that can be applied in this way is severely */
  4930. /* limited by the cost of the raise-to-the power at the end, */
  4931. /* which dominates when the number of iterations is small (less */
  4932. /* than ten) or when rhs is short. As an example, the adjustment */
  4933. /* x**10,000,000 needs 31 multiplications, all but one full-width. */
  4934. /* */
  4935. /* 3. The restrictions (especially precision) could be raised with */
  4936. /* care, but the full decNumber range seems very hard within the */
  4937. /* 32-bit limits. */
  4938. /* */
  4939. /* 4. The working precisions for the static buffers are twice the */
  4940. /* obvious size to allow for calls from decNumberPower. */
  4941. /* ------------------------------------------------------------------ */
  4942. decNumber * decExpOp(decNumber *res, const decNumber *rhs,
  4943. decContext *set, uInt *status) {
  4944. uInt ignore=0; /* working status */
  4945. Int h; /* adjusted exponent for 0.xxxx */
  4946. Int p; /* working precision */
  4947. Int residue; /* rounding residue */
  4948. uInt needbytes; /* for space calculations */
  4949. const decNumber *x=rhs; /* (may point to safe copy later) */
  4950. decContext aset, tset, dset; /* working contexts */
  4951. Int comp; /* work */
  4952. /* the argument is often copied to normalize it, so (unusually) it */
  4953. /* is treated like other buffers, using DECBUFFER, +1 in case */
  4954. /* DECBUFFER is 0 */
  4955. decNumber bufr[D2N(DECBUFFER*2+1)];
  4956. decNumber *allocrhs=nullptr; /* non-nullptr if rhs buffer allocated */
  4957. /* the working precision will be no more than set->digits+8+1 */
  4958. /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER */
  4959. /* is 0 (and twice that for the accumulator) */
  4960. /* buffer for t, term (working precision plus) */
  4961. decNumber buft[D2N(DECBUFFER*2+9+1)];
  4962. decNumber *allocbuft=nullptr; /* -> allocated buft, iff allocated */
  4963. decNumber *t=buft; /* term */
  4964. /* buffer for a, accumulator (working precision * 2), at least 9 */
  4965. decNumber bufa[D2N(DECBUFFER*4+18+1)];
  4966. decNumber *allocbufa=nullptr; /* -> allocated bufa, iff allocated */
  4967. decNumber *a=bufa; /* accumulator */
  4968. /* decNumber for the divisor term; this needs at most 9 digits */
  4969. /* and so can be fixed size [16 so can use standard context] */
  4970. decNumber bufd[D2N(16)];
  4971. decNumber *d=bufd; /* divisor */
  4972. decNumber numone; /* constant 1 */
  4973. #if DECCHECK
  4974. Int iterations=0; /* for later sanity check */
  4975. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  4976. #endif
  4977. do { /* protect allocated storage */
  4978. if (SPECIALARG) { /* handle infinities and NaNs */
  4979. if (decNumberIsInfinite(rhs)) { /* an infinity */
  4980. if (decNumberIsNegative(rhs)) /* -Infinity -> +0 */
  4981. uprv_decNumberZero(res);
  4982. else uprv_decNumberCopy(res, rhs); /* +Infinity -> self */
  4983. }
  4984. else decNaNs(res, rhs, nullptr, set, status); /* a NaN */
  4985. break;}
  4986. if (ISZERO(rhs)) { /* zeros -> exact 1 */
  4987. uprv_decNumberZero(res); /* make clean 1 */
  4988. *res->lsu=1; /* .. */
  4989. break;} /* [no status to set] */
  4990. /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path */
  4991. /* positive and negative tiny cases which will result in inexact */
  4992. /* 1. This also allows the later add-accumulate to always be */
  4993. /* exact (because its length will never be more than twice the */
  4994. /* working precision). */
  4995. /* The comparator (tiny) needs just one digit, so use the */
  4996. /* decNumber d for it (reused as the divisor, etc., below); its */
  4997. /* exponent is such that if x is positive it will have */
  4998. /* set->digits-1 zeros between the decimal point and the digit, */
  4999. /* which is 4, and if x is negative one more zero there as the */
  5000. /* more precise result will be of the form 0.9999999 rather than */
  5001. /* 1.0000001. Hence, tiny will be 0.0000004 if digits=7 and x>0 */
  5002. /* or 0.00000004 if digits=7 and x<0. If RHS not larger than */
  5003. /* this then the result will be 1.000000 */
  5004. uprv_decNumberZero(d); /* clean */
  5005. *d->lsu=4; /* set 4 .. */
  5006. d->exponent=-set->digits; /* * 10**(-d) */
  5007. if (decNumberIsNegative(rhs)) d->exponent--; /* negative case */
  5008. comp=decCompare(d, rhs, 1); /* signless compare */
  5009. if (comp==BADINT) {
  5010. *status|=DEC_Insufficient_storage;
  5011. break;}
  5012. if (comp>=0) { /* rhs < d */
  5013. Int shift=set->digits-1;
  5014. uprv_decNumberZero(res); /* set 1 */
  5015. *res->lsu=1; /* .. */
  5016. res->digits=decShiftToMost(res->lsu, 1, shift);
  5017. res->exponent=-shift; /* make 1.0000... */
  5018. *status|=DEC_Inexact | DEC_Rounded; /* .. inexactly */
  5019. break;} /* tiny */
  5020. /* set up the context to be used for calculating a, as this is */
  5021. /* used on both paths below */
  5022. uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64);
  5023. /* accumulator bounds are as requested (could underflow) */
  5024. aset.emax=set->emax; /* usual bounds */
  5025. aset.emin=set->emin; /* .. */
  5026. aset.clamp=0; /* and no concrete format */
  5027. /* calculate the adjusted (Hull & Abrham) exponent (where the */
  5028. /* decimal point is just to the left of the coefficient msd) */
  5029. h=rhs->exponent+rhs->digits;
  5030. /* if h>8 then 10**h cannot be calculated safely; however, when */
  5031. /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at */
  5032. /* least 6.59E+4342944, so (due to the restriction on Emax/Emin) */
  5033. /* overflow (or underflow to 0) is guaranteed -- so this case can */
  5034. /* be handled by simply forcing the appropriate excess */
  5035. if (h>8) { /* overflow/underflow */
  5036. /* set up here so Power call below will over or underflow to */
  5037. /* zero; set accumulator to either 2 or 0.02 */
  5038. /* [stack buffer for a is always big enough for this] */
  5039. uprv_decNumberZero(a);
  5040. *a->lsu=2; /* not 1 but < exp(1) */
  5041. if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02 */
  5042. h=8; /* clamp so 10**h computable */
  5043. p=9; /* set a working precision */
  5044. }
  5045. else { /* h<=8 */
  5046. Int maxlever=(rhs->digits>8?1:0);
  5047. /* [could/should increase this for precisions >40 or so, too] */
  5048. /* if h is 8, cannot normalize to a lower upper limit because */
  5049. /* the final result will not be computable (see notes above), */
  5050. /* but leverage can be applied whenever h is less than 8. */
  5051. /* Apply as much as possible, up to a MAXLEVER digits, which */
  5052. /* sets the tradeoff against the cost of the later a**(10**h). */
  5053. /* As h is increased, the working precision below also */
  5054. /* increases to compensate for the "constant digits at the */
  5055. /* front" effect. */
  5056. Int lever=MINI(8-h, maxlever); /* leverage attainable */
  5057. Int use=-rhs->digits-lever; /* exponent to use for RHS */
  5058. h+=lever; /* apply leverage selected */
  5059. if (h<0) { /* clamp */
  5060. use+=h; /* [may end up subnormal] */
  5061. h=0;
  5062. }
  5063. /* Take a copy of RHS if it needs normalization (true whenever x>=1) */
  5064. if (rhs->exponent!=use) {
  5065. decNumber *newrhs=bufr; /* assume will fit on stack */
  5066. needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
  5067. if (needbytes>sizeof(bufr)) { /* need malloc space */
  5068. allocrhs=(decNumber *)malloc(needbytes);
  5069. if (allocrhs==nullptr) { /* hopeless -- abandon */
  5070. *status|=DEC_Insufficient_storage;
  5071. break;}
  5072. newrhs=allocrhs; /* use the allocated space */
  5073. }
  5074. uprv_decNumberCopy(newrhs, rhs); /* copy to safe space */
  5075. newrhs->exponent=use; /* normalize; now <1 */
  5076. x=newrhs; /* ready for use */
  5077. /* decNumberShow(x); */
  5078. }
  5079. /* Now use the usual power series to evaluate exp(x). The */
  5080. /* series starts as 1 + x + x^2/2 ... so prime ready for the */
  5081. /* third term by setting the term variable t=x, the accumulator */
  5082. /* a=1, and the divisor d=2. */
  5083. /* First determine the working precision. From Hull & Abrham */
  5084. /* this is set->digits+h+2. However, if x is 'over-precise' we */
  5085. /* need to allow for all its digits to potentially participate */
  5086. /* (consider an x where all the excess digits are 9s) so in */
  5087. /* this case use x->digits+h+2 */
  5088. p=MAXI(x->digits, set->digits)+h+2; /* [h<=8] */
  5089. /* a and t are variable precision, and depend on p, so space */
  5090. /* must be allocated for them if necessary */
  5091. /* the accumulator needs to be able to hold 2p digits so that */
  5092. /* the additions on the second and subsequent iterations are */
  5093. /* sufficiently exact. */
  5094. needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
  5095. if (needbytes>sizeof(bufa)) { /* need malloc space */
  5096. allocbufa=(decNumber *)malloc(needbytes);
  5097. if (allocbufa==nullptr) { /* hopeless -- abandon */
  5098. *status|=DEC_Insufficient_storage;
  5099. break;}
  5100. a=allocbufa; /* use the allocated space */
  5101. }
  5102. /* the term needs to be able to hold p digits (which is */
  5103. /* guaranteed to be larger than x->digits, so the initial copy */
  5104. /* is safe); it may also be used for the raise-to-power */
  5105. /* calculation below, which needs an extra two digits */
  5106. needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
  5107. if (needbytes>sizeof(buft)) { /* need malloc space */
  5108. allocbuft=(decNumber *)malloc(needbytes);
  5109. if (allocbuft==nullptr) { /* hopeless -- abandon */
  5110. *status|=DEC_Insufficient_storage;
  5111. break;}
  5112. t=allocbuft; /* use the allocated space */
  5113. }
  5114. uprv_decNumberCopy(t, x); /* term=x */
  5115. uprv_decNumberZero(a); *a->lsu=1; /* accumulator=1 */
  5116. uprv_decNumberZero(d); *d->lsu=2; /* divisor=2 */
  5117. uprv_decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment */
  5118. /* set up the contexts for calculating a, t, and d */
  5119. uprv_decContextDefault(&tset, DEC_INIT_DECIMAL64);
  5120. dset=tset;
  5121. /* accumulator bounds are set above, set precision now */
  5122. aset.digits=p*2; /* double */
  5123. /* term bounds avoid any underflow or overflow */
  5124. tset.digits=p;
  5125. tset.emin=DEC_MIN_EMIN; /* [emax is plenty] */
  5126. /* [dset.digits=16, etc., are sufficient] */
  5127. /* finally ready to roll */
  5128. for (;;) {
  5129. #if DECCHECK
  5130. iterations++;
  5131. #endif
  5132. /* only the status from the accumulation is interesting */
  5133. /* [but it should remain unchanged after first add] */
  5134. decAddOp(a, a, t, &aset, 0, status); /* a=a+t */
  5135. decMultiplyOp(t, t, x, &tset, &ignore); /* t=t*x */
  5136. decDivideOp(t, t, d, &tset, DIVIDE, &ignore); /* t=t/d */
  5137. /* the iteration ends when the term cannot affect the result, */
  5138. /* if rounded to p digits, which is when its value is smaller */
  5139. /* than the accumulator by p+1 digits. There must also be */
  5140. /* full precision in a. */
  5141. if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
  5142. && (a->digits>=p)) break;
  5143. decAddOp(d, d, &numone, &dset, 0, &ignore); /* d=d+1 */
  5144. } /* iterate */
  5145. #if DECCHECK
  5146. /* just a sanity check; comment out test to show always */
  5147. if (iterations>p+3)
  5148. printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
  5149. (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);
  5150. #endif
  5151. } /* h<=8 */
  5152. /* apply postconditioning: a=a**(10**h) -- this is calculated */
  5153. /* at a slightly higher precision than Hull & Abrham suggest */
  5154. if (h>0) {
  5155. Int seenbit=0; /* set once a 1-bit is seen */
  5156. Int i; /* counter */
  5157. Int n=powers[h]; /* always positive */
  5158. aset.digits=p+2; /* sufficient precision */
  5159. /* avoid the overhead and many extra digits of decNumberPower */
  5160. /* as all that is needed is the short 'multipliers' loop; here */
  5161. /* accumulate the answer into t */
  5162. uprv_decNumberZero(t); *t->lsu=1; /* acc=1 */
  5163. for (i=1;;i++){ /* for each bit [top bit ignored] */
  5164. /* abandon if have had overflow or terminal underflow */
  5165. if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
  5166. if (*status&DEC_Overflow || ISZERO(t)) break;}
  5167. n=n<<1; /* move next bit to testable position */
  5168. if (n<0) { /* top bit is set */
  5169. seenbit=1; /* OK, have a significant bit */
  5170. decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x */
  5171. }
  5172. if (i==31) break; /* that was the last bit */
  5173. if (!seenbit) continue; /* no need to square 1 */
  5174. decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square] */
  5175. } /*i*/ /* 32 bits */
  5176. /* decNumberShow(t); */
  5177. a=t; /* and carry on using t instead of a */
  5178. }
  5179. /* Copy and round the result to res */
  5180. residue=1; /* indicate dirt to right .. */
  5181. if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */
  5182. aset.digits=set->digits; /* [use default rounding] */
  5183. decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
  5184. decFinish(res, set, &residue, status); /* cleanup/set flags */
  5185. } while(0); /* end protected */
  5186. if (allocrhs !=nullptr) free(allocrhs); /* drop any storage used */
  5187. if (allocbufa!=nullptr) free(allocbufa); /* .. */
  5188. if (allocbuft!=nullptr) free(allocbuft); /* .. */
  5189. /* [status is handled by caller] */
  5190. return res;
  5191. } /* decExpOp */
  5192. /* ------------------------------------------------------------------ */
  5193. /* Initial-estimate natural logarithm table */
  5194. /* */
  5195. /* LNnn -- 90-entry 16-bit table for values from .10 through .99. */
  5196. /* The result is a 4-digit encode of the coefficient (c=the */
  5197. /* top 14 bits encoding 0-9999) and a 2-digit encode of the */
  5198. /* exponent (e=the bottom 2 bits encoding 0-3) */
  5199. /* */
  5200. /* The resulting value is given by: */
  5201. /* */
  5202. /* v = -c * 10**(-e-3) */
  5203. /* */
  5204. /* where e and c are extracted from entry k = LNnn[x-10] */
  5205. /* where x is truncated (NB) into the range 10 through 99, */
  5206. /* and then c = k>>2 and e = k&3. */
  5207. /* ------------------------------------------------------------------ */
  5208. static const uShort LNnn[90]={9016, 8652, 8316, 8008, 7724, 7456, 7208,
  5209. 6972, 6748, 6540, 6340, 6148, 5968, 5792, 5628, 5464, 5312,
  5210. 5164, 5020, 4884, 4748, 4620, 4496, 4376, 4256, 4144, 4032,
  5211. 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
  5212. 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
  5213. 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
  5214. 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
  5215. 10197, 9685, 9177, 8677, 8185, 7697, 7213, 6737, 6269, 5801,
  5216. 5341, 4889, 4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
  5217. 10130, 6046, 20055};
  5218. /* ------------------------------------------------------------------ */
  5219. /* decLnOp -- effect natural logarithm */
  5220. /* */
  5221. /* This computes C = ln(A) */
  5222. /* */
  5223. /* res is C, the result. C may be A */
  5224. /* rhs is A */
  5225. /* set is the context; note that rounding mode has no effect */
  5226. /* */
  5227. /* C must have space for set->digits digits. */
  5228. /* */
  5229. /* Notable cases: */
  5230. /* A<0 -> Invalid */
  5231. /* A=0 -> -Infinity (Exact) */
  5232. /* A=+Infinity -> +Infinity (Exact) */
  5233. /* A=1 exactly -> 0 (Exact) */
  5234. /* */
  5235. /* Restrictions (as for Exp): */
  5236. /* */
  5237. /* digits, emax, and -emin in the context must be less than */
  5238. /* DEC_MAX_MATH+11 (1000010), and the rhs must be within these */
  5239. /* bounds or a zero. This is an internal routine, so these */
  5240. /* restrictions are contractual and not enforced. */
  5241. /* */
  5242. /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
  5243. /* almost always be correctly rounded, but may be up to 1 ulp in */
  5244. /* error in rare cases. */
  5245. /* ------------------------------------------------------------------ */
  5246. /* The result is calculated using Newton's method, with each */
  5247. /* iteration calculating a' = a + x * exp(-a) - 1. See, for example, */
  5248. /* Epperson 1989. */
  5249. /* */
  5250. /* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
  5251. /* This has to be calculated at the sum of the precision of x and the */
  5252. /* working precision. */
  5253. /* */
  5254. /* Implementation notes: */
  5255. /* */
  5256. /* 1. This is separated out as decLnOp so it can be called from */
  5257. /* other Mathematical functions (e.g., Log 10) with a wider range */
  5258. /* than normal. In particular, it can handle the slightly wider */
  5259. /* (+9+2) range needed by a power function. */
  5260. /* */
  5261. /* 2. The speed of this function is about 10x slower than exp, as */
  5262. /* it typically needs 4-6 iterations for short numbers, and the */
  5263. /* extra precision needed adds a squaring effect, twice. */
  5264. /* */
  5265. /* 3. Fastpaths are included for ln(10) and ln(2), up to length 40, */
  5266. /* as these are common requests. ln(10) is used by log10(x). */
  5267. /* */
  5268. /* 4. An iteration might be saved by widening the LNnn table, and */
  5269. /* would certainly save at least one if it were made ten times */
  5270. /* bigger, too (for truncated fractions 0.100 through 0.999). */
  5271. /* However, for most practical evaluations, at least four or five */
  5272. /* iterations will be needed -- so this would only speed up by */
  5273. /* 20-25% and that probably does not justify increasing the table */
  5274. /* size. */
  5275. /* */
  5276. /* 5. The static buffers are larger than might be expected to allow */
  5277. /* for calls from decNumberPower. */
  5278. /* ------------------------------------------------------------------ */
  5279. #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
  5280. #pragma GCC diagnostic push
  5281. #pragma GCC diagnostic ignored "-Warray-bounds"
  5282. #endif
  5283. decNumber * decLnOp(decNumber *res, const decNumber *rhs,
  5284. decContext *set, uInt *status) {
  5285. uInt ignore=0; /* working status accumulator */
  5286. uInt needbytes; /* for space calculations */
  5287. Int residue; /* rounding residue */
  5288. Int r; /* rhs=f*10**r [see below] */
  5289. Int p; /* working precision */
  5290. Int pp; /* precision for iteration */
  5291. Int t; /* work */
  5292. /* buffers for a (accumulator, typically precision+2) and b */
  5293. /* (adjustment calculator, same size) */
  5294. decNumber bufa[D2N(DECBUFFER+12)];
  5295. decNumber *allocbufa=nullptr; /* -> allocated bufa, iff allocated */
  5296. decNumber *a=bufa; /* accumulator/work */
  5297. decNumber bufb[D2N(DECBUFFER*2+2)];
  5298. decNumber *allocbufb=nullptr; /* -> allocated bufa, iff allocated */
  5299. decNumber *b=bufb; /* adjustment/work */
  5300. decNumber numone; /* constant 1 */
  5301. decNumber cmp; /* work */
  5302. decContext aset, bset; /* working contexts */
  5303. #if DECCHECK
  5304. Int iterations=0; /* for later sanity check */
  5305. if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  5306. #endif
  5307. do { /* protect allocated storage */
  5308. if (SPECIALARG) { /* handle infinities and NaNs */
  5309. if (decNumberIsInfinite(rhs)) { /* an infinity */
  5310. if (decNumberIsNegative(rhs)) /* -Infinity -> error */
  5311. *status|=DEC_Invalid_operation;
  5312. else uprv_decNumberCopy(res, rhs); /* +Infinity -> self */
  5313. }
  5314. else decNaNs(res, rhs, nullptr, set, status); /* a NaN */
  5315. break;}
  5316. if (ISZERO(rhs)) { /* +/- zeros -> -Infinity */
  5317. uprv_decNumberZero(res); /* make clean */
  5318. res->bits=DECINF|DECNEG; /* set - infinity */
  5319. break;} /* [no status to set] */
  5320. /* Non-zero negatives are bad... */
  5321. if (decNumberIsNegative(rhs)) { /* -x -> error */
  5322. *status|=DEC_Invalid_operation;
  5323. break;}
  5324. /* Here, rhs is positive, finite, and in range */
  5325. /* lookaside fastpath code for ln(2) and ln(10) at common lengths */
  5326. if (rhs->exponent==0 && set->digits<=40) {
  5327. #if DECDPUN==1
  5328. if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10) */
  5329. #else
  5330. if (rhs->lsu[0]==10 && rhs->digits==2) { /* ln(10) */
  5331. #endif
  5332. aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
  5333. #define LN10 "2.302585092994045684017991454684364207601"
  5334. uprv_decNumberFromString(res, LN10, &aset);
  5335. *status|=(DEC_Inexact | DEC_Rounded); /* is inexact */
  5336. break;}
  5337. if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2) */
  5338. aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
  5339. #define LN2 "0.6931471805599453094172321214581765680755"
  5340. uprv_decNumberFromString(res, LN2, &aset);
  5341. *status|=(DEC_Inexact | DEC_Rounded);
  5342. break;}
  5343. } /* integer and short */
  5344. /* Determine the working precision. This is normally the */
  5345. /* requested precision + 2, with a minimum of 9. However, if */
  5346. /* the rhs is 'over-precise' then allow for all its digits to */
  5347. /* potentially participate (consider an rhs where all the excess */
  5348. /* digits are 9s) so in this case use rhs->digits+2. */
  5349. p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
  5350. /* Allocate space for the accumulator and the high-precision */
  5351. /* adjustment calculator, if necessary. The accumulator must */
  5352. /* be able to hold p digits, and the adjustment up to */
  5353. /* rhs->digits+p digits. They are also made big enough for 16 */
  5354. /* digits so that they can be used for calculating the initial */
  5355. /* estimate. */
  5356. needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
  5357. if (needbytes>sizeof(bufa)) { /* need malloc space */
  5358. allocbufa=(decNumber *)malloc(needbytes);
  5359. if (allocbufa==nullptr) { /* hopeless -- abandon */
  5360. *status|=DEC_Insufficient_storage;
  5361. break;}
  5362. a=allocbufa; /* use the allocated space */
  5363. }
  5364. pp=p+rhs->digits;
  5365. needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
  5366. if (needbytes>sizeof(bufb)) { /* need malloc space */
  5367. allocbufb=(decNumber *)malloc(needbytes);
  5368. if (allocbufb==nullptr) { /* hopeless -- abandon */
  5369. *status|=DEC_Insufficient_storage;
  5370. break;}
  5371. b=allocbufb; /* use the allocated space */
  5372. }
  5373. /* Prepare an initial estimate in acc. Calculate this by */
  5374. /* considering the coefficient of x to be a normalized fraction, */
  5375. /* f, with the decimal point at far left and multiplied by */
  5376. /* 10**r. Then, rhs=f*10**r and 0.1<=f<1, and */
  5377. /* ln(x) = ln(f) + ln(10)*r */
  5378. /* Get the initial estimate for ln(f) from a small lookup */
  5379. /* table (see above) indexed by the first two digits of f, */
  5380. /* truncated. */
  5381. uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended */
  5382. r=rhs->exponent+rhs->digits; /* 'normalised' exponent */
  5383. uprv_decNumberFromInt32(a, r); /* a=r */
  5384. uprv_decNumberFromInt32(b, 2302585); /* b=ln(10) (2.302585) */
  5385. b->exponent=-6; /* .. */
  5386. decMultiplyOp(a, a, b, &aset, &ignore); /* a=a*b */
  5387. /* now get top two digits of rhs into b by simple truncate and */
  5388. /* force to integer */
  5389. residue=0; /* (no residue) */
  5390. aset.digits=2; aset.round=DEC_ROUND_DOWN;
  5391. decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten */
  5392. b->exponent=0; /* make integer */
  5393. t=decGetInt(b); /* [cannot fail] */
  5394. if (t<10) t=X10(t); /* adjust single-digit b */
  5395. t=LNnn[t-10]; /* look up ln(b) */
  5396. uprv_decNumberFromInt32(b, t>>2); /* b=ln(b) coefficient */
  5397. b->exponent=-(t&3)-3; /* set exponent */
  5398. b->bits=DECNEG; /* ln(0.10)->ln(0.99) always -ve */
  5399. aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore */
  5400. decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b */
  5401. /* the initial estimate is now in a, with up to 4 digits correct. */
  5402. /* When rhs is at or near Nmax the estimate will be low, so we */
  5403. /* will approach it from below, avoiding overflow when calling exp. */
  5404. uprv_decNumberZero(&numone); *numone.lsu=1; /* constant 1 for adjustment */
  5405. /* accumulator bounds are as requested (could underflow, but */
  5406. /* cannot overflow) */
  5407. aset.emax=set->emax;
  5408. aset.emin=set->emin;
  5409. aset.clamp=0; /* no concrete format */
  5410. /* set up a context to be used for the multiply and subtract */
  5411. bset=aset;
  5412. bset.emax=DEC_MAX_MATH*2; /* use double bounds for the */
  5413. bset.emin=-DEC_MAX_MATH*2; /* adjustment calculation */
  5414. /* [see decExpOp call below] */
  5415. /* for each iteration double the number of digits to calculate, */
  5416. /* up to a maximum of p */
  5417. pp=9; /* initial precision */
  5418. /* [initially 9 as then the sequence starts 7+2, 16+2, and */
  5419. /* 34+2, which is ideal for standard-sized numbers] */
  5420. aset.digits=pp; /* working context */
  5421. bset.digits=pp+rhs->digits; /* wider context */
  5422. for (;;) { /* iterate */
  5423. #if DECCHECK
  5424. iterations++;
  5425. if (iterations>24) break; /* consider 9 * 2**24 */
  5426. #endif
  5427. /* calculate the adjustment (exp(-a)*x-1) into b. This is a */
  5428. /* catastrophic subtraction but it really is the difference */
  5429. /* from 1 that is of interest. */
  5430. /* Use the internal entry point to Exp as it allows the double */
  5431. /* range for calculating exp(-a) when a is the tiniest subnormal. */
  5432. a->bits^=DECNEG; /* make -a */
  5433. decExpOp(b, a, &bset, &ignore); /* b=exp(-a) */
  5434. a->bits^=DECNEG; /* restore sign of a */
  5435. /* now multiply by rhs and subtract 1, at the wider precision */
  5436. decMultiplyOp(b, b, rhs, &bset, &ignore); /* b=b*rhs */
  5437. decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1 */
  5438. /* the iteration ends when the adjustment cannot affect the */
  5439. /* result by >=0.5 ulp (at the requested digits), which */
  5440. /* is when its value is smaller than the accumulator by */
  5441. /* set->digits+1 digits (or it is zero) -- this is a looser */
  5442. /* requirement than for Exp because all that happens to the */
  5443. /* accumulator after this is the final rounding (but note that */
  5444. /* there must also be full precision in a, or a=0). */
  5445. if (decNumberIsZero(b) ||
  5446. (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
  5447. if (a->digits==p) break;
  5448. if (decNumberIsZero(a)) {
  5449. decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ? */
  5450. if (cmp.lsu[0]==0) a->exponent=0; /* yes, exact 0 */
  5451. else *status|=(DEC_Inexact | DEC_Rounded); /* no, inexact */
  5452. break;
  5453. }
  5454. /* force padding if adjustment has gone to 0 before full length */
  5455. if (decNumberIsZero(b)) b->exponent=a->exponent-p;
  5456. }
  5457. /* not done yet ... */
  5458. decAddOp(a, a, b, &aset, 0, &ignore); /* a=a+b for next estimate */
  5459. if (pp==p) continue; /* precision is at maximum */
  5460. /* lengthen the next calculation */
  5461. pp=pp*2; /* double precision */
  5462. if (pp>p) pp=p; /* clamp to maximum */
  5463. aset.digits=pp; /* working context */
  5464. bset.digits=pp+rhs->digits; /* wider context */
  5465. } /* Newton's iteration */
  5466. #if DECCHECK
  5467. /* just a sanity check; remove the test to show always */
  5468. if (iterations>24)
  5469. printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
  5470. (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);
  5471. #endif
  5472. /* Copy and round the result to res */
  5473. residue=1; /* indicate dirt to right */
  5474. if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */
  5475. aset.digits=set->digits; /* [use default rounding] */
  5476. decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
  5477. decFinish(res, set, &residue, status); /* cleanup/set flags */
  5478. } while(0); /* end protected */
  5479. if (allocbufa!=nullptr) free(allocbufa); /* drop any storage used */
  5480. if (allocbufb!=nullptr) free(allocbufb); /* .. */
  5481. /* [status is handled by caller] */
  5482. return res;
  5483. } /* decLnOp */
  5484. #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
  5485. #pragma GCC diagnostic pop
  5486. #endif
  5487. /* ------------------------------------------------------------------ */
  5488. /* decQuantizeOp -- force exponent to requested value */
  5489. /* */
  5490. /* This computes C = op(A, B), where op adjusts the coefficient */
  5491. /* of C (by rounding or shifting) such that the exponent (-scale) */
  5492. /* of C has the value B or matches the exponent of B. */
  5493. /* The numerical value of C will equal A, except for the effects of */
  5494. /* any rounding that occurred. */
  5495. /* */
  5496. /* res is C, the result. C may be A or B */
  5497. /* lhs is A, the number to adjust */
  5498. /* rhs is B, the requested exponent */
  5499. /* set is the context */
  5500. /* quant is 1 for quantize or 0 for rescale */
  5501. /* status is the status accumulator (this can be called without */
  5502. /* risk of control loss) */
  5503. /* */
  5504. /* C must have space for set->digits digits. */
  5505. /* */
  5506. /* Unless there is an error or the result is infinite, the exponent */
  5507. /* after the operation is guaranteed to be that requested. */
  5508. /* ------------------------------------------------------------------ */
  5509. static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
  5510. const decNumber *rhs, decContext *set,
  5511. Flag quant, uInt *status) {
  5512. #if DECSUBSET
  5513. decNumber *alloclhs=nullptr; /* non-nullptr if rounded lhs allocated */
  5514. decNumber *allocrhs=nullptr; /* .., rhs */
  5515. #endif
  5516. const decNumber *inrhs=rhs; /* save original rhs */
  5517. Int reqdigits=set->digits; /* requested DIGITS */
  5518. Int reqexp; /* requested exponent [-scale] */
  5519. Int residue=0; /* rounding residue */
  5520. Int etiny=set->emin-(reqdigits-1);
  5521. #if DECCHECK
  5522. if (decCheckOperands(res, lhs, rhs, set)) return res;
  5523. #endif
  5524. do { /* protect allocated storage */
  5525. #if DECSUBSET
  5526. if (!set->extended) {
  5527. /* reduce operands and set lostDigits status, as needed */
  5528. if (lhs->digits>reqdigits) {
  5529. alloclhs=decRoundOperand(lhs, set, status);
  5530. if (alloclhs==nullptr) break;
  5531. lhs=alloclhs;
  5532. }
  5533. if (rhs->digits>reqdigits) { /* [this only checks lostDigits] */
  5534. allocrhs=decRoundOperand(rhs, set, status);
  5535. if (allocrhs==nullptr) break;
  5536. rhs=allocrhs;
  5537. }
  5538. }
  5539. #endif
  5540. /* [following code does not require input rounding] */
  5541. /* Handle special values */
  5542. if (SPECIALARGS) {
  5543. /* NaNs get usual processing */
  5544. if (SPECIALARGS & (DECSNAN | DECNAN))
  5545. decNaNs(res, lhs, rhs, set, status);
  5546. /* one infinity but not both is bad */
  5547. else if ((lhs->bits ^ rhs->bits) & DECINF)
  5548. *status|=DEC_Invalid_operation;
  5549. /* both infinity: return lhs */
  5550. else uprv_decNumberCopy(res, lhs); /* [nop if in place] */
  5551. break;
  5552. }
  5553. /* set requested exponent */
  5554. if (quant) reqexp=inrhs->exponent; /* quantize -- match exponents */
  5555. else { /* rescale -- use value of rhs */
  5556. /* Original rhs must be an integer that fits and is in range, */
  5557. /* which could be from -1999999997 to +999999999, thanks to */
  5558. /* subnormals */
  5559. reqexp=decGetInt(inrhs); /* [cannot fail] */
  5560. }
  5561. #if DECSUBSET
  5562. if (!set->extended) etiny=set->emin; /* no subnormals */
  5563. #endif
  5564. if (reqexp==BADINT /* bad (rescale only) or .. */
  5565. || reqexp==BIGODD || reqexp==BIGEVEN /* very big (ditto) or .. */
  5566. || (reqexp<etiny) /* < lowest */
  5567. || (reqexp>set->emax)) { /* > emax */
  5568. *status|=DEC_Invalid_operation;
  5569. break;}
  5570. /* the RHS has been processed, so it can be overwritten now if necessary */
  5571. if (ISZERO(lhs)) { /* zero coefficient unchanged */
  5572. uprv_decNumberCopy(res, lhs); /* [nop if in place] */
  5573. res->exponent=reqexp; /* .. just set exponent */
  5574. #if DECSUBSET
  5575. if (!set->extended) res->bits=0; /* subset specification; no -0 */
  5576. #endif
  5577. }
  5578. else { /* non-zero lhs */
  5579. Int adjust=reqexp-lhs->exponent; /* digit adjustment needed */
  5580. /* if adjusted coefficient will definitely not fit, give up now */
  5581. if ((lhs->digits-adjust)>reqdigits) {
  5582. *status|=DEC_Invalid_operation;
  5583. break;
  5584. }
  5585. if (adjust>0) { /* increasing exponent */
  5586. /* this will decrease the length of the coefficient by adjust */
  5587. /* digits, and must round as it does so */
  5588. decContext workset; /* work */
  5589. workset=*set; /* clone rounding, etc. */
  5590. workset.digits=lhs->digits-adjust; /* set requested length */
  5591. /* [note that the latter can be <1, here] */
  5592. decCopyFit(res, lhs, &workset, &residue, status); /* fit to result */
  5593. decApplyRound(res, &workset, residue, status); /* .. and round */
  5594. residue=0; /* [used] */
  5595. /* If just rounded a 999s case, exponent will be off by one; */
  5596. /* adjust back (after checking space), if so. */
  5597. if (res->exponent>reqexp) {
  5598. /* re-check needed, e.g., for quantize(0.9999, 0.001) under */
  5599. /* set->digits==3 */
  5600. if (res->digits==reqdigits) { /* cannot shift by 1 */
  5601. *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these] */
  5602. *status|=DEC_Invalid_operation;
  5603. break;
  5604. }
  5605. res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift */
  5606. res->exponent--; /* (re)adjust the exponent. */
  5607. }
  5608. #if DECSUBSET
  5609. if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0 */
  5610. #endif
  5611. } /* increase */
  5612. else /* adjust<=0 */ { /* decreasing or = exponent */
  5613. /* this will increase the length of the coefficient by -adjust */
  5614. /* digits, by adding zero or more trailing zeros; this is */
  5615. /* already checked for fit, above */
  5616. uprv_decNumberCopy(res, lhs); /* [it will fit] */
  5617. /* if padding needed (adjust<0), add it now... */
  5618. if (adjust<0) {
  5619. res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
  5620. res->exponent+=adjust; /* adjust the exponent */
  5621. }
  5622. } /* decrease */
  5623. } /* non-zero */
  5624. /* Check for overflow [do not use Finalize in this case, as an */
  5625. /* overflow here is a "don't fit" situation] */
  5626. if (res->exponent>set->emax-res->digits+1) { /* too big */
  5627. *status|=DEC_Invalid_operation;
  5628. break;
  5629. }
  5630. else {
  5631. decFinalize(res, set, &residue, status); /* set subnormal flags */
  5632. *status&=~DEC_Underflow; /* suppress Underflow [as per 754] */
  5633. }
  5634. } while(0); /* end protected */
  5635. #if DECSUBSET
  5636. if (allocrhs!=nullptr) free(allocrhs); /* drop any storage used */
  5637. if (alloclhs!=nullptr) free(alloclhs); /* .. */
  5638. #endif
  5639. return res;
  5640. } /* decQuantizeOp */
  5641. /* ------------------------------------------------------------------ */
  5642. /* decCompareOp -- compare, min, or max two Numbers */
  5643. /* */
  5644. /* This computes C = A ? B and carries out one of four operations: */
  5645. /* COMPARE -- returns the signum (as a number) giving the */
  5646. /* result of a comparison unless one or both */
  5647. /* operands is a NaN (in which case a NaN results) */
  5648. /* COMPSIG -- as COMPARE except that a quiet NaN raises */
  5649. /* Invalid operation. */
  5650. /* COMPMAX -- returns the larger of the operands, using the */
  5651. /* 754 maxnum operation */
  5652. /* COMPMAXMAG -- ditto, comparing absolute values */
  5653. /* COMPMIN -- the 754 minnum operation */
  5654. /* COMPMINMAG -- ditto, comparing absolute values */
  5655. /* COMTOTAL -- returns the signum (as a number) giving the */
  5656. /* result of a comparison using 754 total ordering */
  5657. /* */
  5658. /* res is C, the result. C may be A and/or B (e.g., X=X?X) */
  5659. /* lhs is A */
  5660. /* rhs is B */
  5661. /* set is the context */
  5662. /* op is the operation flag */
  5663. /* status is the usual accumulator */
  5664. /* */
  5665. /* C must have space for one digit for COMPARE or set->digits for */
  5666. /* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG. */
  5667. /* ------------------------------------------------------------------ */
  5668. /* The emphasis here is on speed for common cases, and avoiding */
  5669. /* coefficient comparison if possible. */
  5670. /* ------------------------------------------------------------------ */
  5671. static decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
  5672. const decNumber *rhs, decContext *set,
  5673. Flag op, uInt *status) {
  5674. #if DECSUBSET
  5675. decNumber *alloclhs=nullptr; /* non-nullptr if rounded lhs allocated */
  5676. decNumber *allocrhs=nullptr; /* .., rhs */
  5677. #endif
  5678. Int result=0; /* default result value */
  5679. uByte merged; /* work */
  5680. #if DECCHECK
  5681. if (decCheckOperands(res, lhs, rhs, set)) return res;
  5682. #endif
  5683. do { /* protect allocated storage */
  5684. #if DECSUBSET
  5685. if (!set->extended) {
  5686. /* reduce operands and set lostDigits status, as needed */
  5687. if (lhs->digits>set->digits) {
  5688. alloclhs=decRoundOperand(lhs, set, status);
  5689. if (alloclhs==nullptr) {result=BADINT; break;}
  5690. lhs=alloclhs;
  5691. }
  5692. if (rhs->digits>set->digits) {
  5693. allocrhs=decRoundOperand(rhs, set, status);
  5694. if (allocrhs==nullptr) {result=BADINT; break;}
  5695. rhs=allocrhs;
  5696. }
  5697. }
  5698. #endif
  5699. /* [following code does not require input rounding] */
  5700. /* If total ordering then handle differing signs 'up front' */
  5701. if (op==COMPTOTAL) { /* total ordering */
  5702. if (decNumberIsNegative(lhs) && !decNumberIsNegative(rhs)) {
  5703. result=-1;
  5704. break;
  5705. }
  5706. if (!decNumberIsNegative(lhs) && decNumberIsNegative(rhs)) {
  5707. result=+1;
  5708. break;
  5709. }
  5710. }
  5711. /* handle NaNs specially; let infinities drop through */
  5712. /* This assumes sNaN (even just one) leads to NaN. */
  5713. merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
  5714. if (merged) { /* a NaN bit set */
  5715. if (op==COMPARE); /* result will be NaN */
  5716. else if (op==COMPSIG) /* treat qNaN as sNaN */
  5717. *status|=DEC_Invalid_operation | DEC_sNaN;
  5718. else if (op==COMPTOTAL) { /* total ordering, always finite */
  5719. /* signs are known to be the same; compute the ordering here */
  5720. /* as if the signs are both positive, then invert for negatives */
  5721. if (!decNumberIsNaN(lhs)) result=-1;
  5722. else if (!decNumberIsNaN(rhs)) result=+1;
  5723. /* here if both NaNs */
  5724. else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
  5725. else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
  5726. else { /* both NaN or both sNaN */
  5727. /* now it just depends on the payload */
  5728. result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
  5729. rhs->lsu, D2U(rhs->digits), 0);
  5730. /* [Error not possible, as these are 'aligned'] */
  5731. } /* both same NaNs */
  5732. if (decNumberIsNegative(lhs)) result=-result;
  5733. break;
  5734. } /* total order */
  5735. else if (merged & DECSNAN); /* sNaN -> qNaN */
  5736. else { /* here if MIN or MAX and one or two quiet NaNs */
  5737. /* min or max -- 754 rules ignore single NaN */
  5738. if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
  5739. /* just one NaN; force choice to be the non-NaN operand */
  5740. op=COMPMAX;
  5741. if (lhs->bits & DECNAN) result=-1; /* pick rhs */
  5742. else result=+1; /* pick lhs */
  5743. break;
  5744. }
  5745. } /* max or min */
  5746. op=COMPNAN; /* use special path */
  5747. decNaNs(res, lhs, rhs, set, status); /* propagate NaN */
  5748. break;
  5749. }
  5750. /* have numbers */
  5751. if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
  5752. else result=decCompare(lhs, rhs, 0); /* sign matters */
  5753. } while(0); /* end protected */
  5754. if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare */
  5755. else {
  5756. if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum */
  5757. if (op==COMPTOTAL && result==0) {
  5758. /* operands are numerically equal or same NaN (and same sign, */
  5759. /* tested first); if identical, leave result 0 */
  5760. if (lhs->exponent!=rhs->exponent) {
  5761. if (lhs->exponent<rhs->exponent) result=-1;
  5762. else result=+1;
  5763. if (decNumberIsNegative(lhs)) result=-result;
  5764. } /* lexp!=rexp */
  5765. } /* total-order by exponent */
  5766. uprv_decNumberZero(res); /* [always a valid result] */
  5767. if (result!=0) { /* must be -1 or +1 */
  5768. *res->lsu=1;
  5769. if (result<0) res->bits=DECNEG;
  5770. }
  5771. }
  5772. else if (op==COMPNAN); /* special, drop through */
  5773. else { /* MAX or MIN, non-NaN result */
  5774. Int residue=0; /* rounding accumulator */
  5775. /* choose the operand for the result */
  5776. const decNumber *choice;
  5777. if (result==0) { /* operands are numerically equal */
  5778. /* choose according to sign then exponent (see 754) */
  5779. uByte slhs=(lhs->bits & DECNEG);
  5780. uByte srhs=(rhs->bits & DECNEG);
  5781. #if DECSUBSET
  5782. if (!set->extended) { /* subset: force left-hand */
  5783. op=COMPMAX;
  5784. result=+1;
  5785. }
  5786. else
  5787. #endif
  5788. if (slhs!=srhs) { /* signs differ */
  5789. if (slhs) result=-1; /* rhs is max */
  5790. else result=+1; /* lhs is max */
  5791. }
  5792. else if (slhs && srhs) { /* both negative */
  5793. if (lhs->exponent<rhs->exponent) result=+1;
  5794. else result=-1;
  5795. /* [if equal, use lhs, technically identical] */
  5796. }
  5797. else { /* both positive */
  5798. if (lhs->exponent>rhs->exponent) result=+1;
  5799. else result=-1;
  5800. /* [ditto] */
  5801. }
  5802. } /* numerically equal */
  5803. /* here result will be non-0; reverse if looking for MIN */
  5804. if (op==COMPMIN || op==COMPMINMAG) result=-result;
  5805. choice=(result>0 ? lhs : rhs); /* choose */
  5806. /* copy chosen to result, rounding if need be */
  5807. decCopyFit(res, choice, set, &residue, status);
  5808. decFinish(res, set, &residue, status);
  5809. }
  5810. }
  5811. #if DECSUBSET
  5812. if (allocrhs!=nullptr) free(allocrhs); /* free any storage used */
  5813. if (alloclhs!=nullptr) free(alloclhs); /* .. */
  5814. #endif
  5815. return res;
  5816. } /* decCompareOp */
  5817. /* ------------------------------------------------------------------ */
  5818. /* decCompare -- compare two decNumbers by numerical value */
  5819. /* */
  5820. /* This routine compares A ? B without altering them. */
  5821. /* */
  5822. /* Arg1 is A, a decNumber which is not a NaN */
  5823. /* Arg2 is B, a decNumber which is not a NaN */
  5824. /* Arg3 is 1 for a sign-independent compare, 0 otherwise */
  5825. /* */
  5826. /* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
  5827. /* (the only possible failure is an allocation error) */
  5828. /* ------------------------------------------------------------------ */
  5829. static Int decCompare(const decNumber *lhs, const decNumber *rhs,
  5830. Flag abs_c) {
  5831. Int result; /* result value */
  5832. Int sigr; /* rhs signum */
  5833. Int compare; /* work */
  5834. result=1; /* assume signum(lhs) */
  5835. if (ISZERO(lhs)) result=0;
  5836. if (abs_c) {
  5837. if (ISZERO(rhs)) return result; /* LHS wins or both 0 */
  5838. /* RHS is non-zero */
  5839. if (result==0) return -1; /* LHS is 0; RHS wins */
  5840. /* [here, both non-zero, result=1] */
  5841. }
  5842. else { /* signs matter */
  5843. if (result && decNumberIsNegative(lhs)) result=-1;
  5844. sigr=1; /* compute signum(rhs) */
  5845. if (ISZERO(rhs)) sigr=0;
  5846. else if (decNumberIsNegative(rhs)) sigr=-1;
  5847. if (result > sigr) return +1; /* L > R, return 1 */
  5848. if (result < sigr) return -1; /* L < R, return -1 */
  5849. if (result==0) return 0; /* both 0 */
  5850. }
  5851. /* signums are the same; both are non-zero */
  5852. if ((lhs->bits | rhs->bits) & DECINF) { /* one or more infinities */
  5853. if (decNumberIsInfinite(rhs)) {
  5854. if (decNumberIsInfinite(lhs)) result=0;/* both infinite */
  5855. else result=-result; /* only rhs infinite */
  5856. }
  5857. return result;
  5858. }
  5859. /* must compare the coefficients, allowing for exponents */
  5860. if (lhs->exponent>rhs->exponent) { /* LHS exponent larger */
  5861. /* swap sides, and sign */
  5862. const decNumber *temp=lhs;
  5863. lhs=rhs;
  5864. rhs=temp;
  5865. result=-result;
  5866. }
  5867. compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
  5868. rhs->lsu, D2U(rhs->digits),
  5869. rhs->exponent-lhs->exponent);
  5870. if (compare!=BADINT) compare*=result; /* comparison succeeded */
  5871. return compare;
  5872. } /* decCompare */
  5873. /* ------------------------------------------------------------------ */
  5874. /* decUnitCompare -- compare two >=0 integers in Unit arrays */
  5875. /* */
  5876. /* This routine compares A ? B*10**E where A and B are unit arrays */
  5877. /* A is a plain integer */
  5878. /* B has an exponent of E (which must be non-negative) */
  5879. /* */
  5880. /* Arg1 is A first Unit (lsu) */
  5881. /* Arg2 is A length in Units */
  5882. /* Arg3 is B first Unit (lsu) */
  5883. /* Arg4 is B length in Units */
  5884. /* Arg5 is E (0 if the units are aligned) */
  5885. /* */
  5886. /* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
  5887. /* (the only possible failure is an allocation error, which can */
  5888. /* only occur if E!=0) */
  5889. /* ------------------------------------------------------------------ */
  5890. static Int decUnitCompare(const Unit *a, Int alength,
  5891. const Unit *b, Int blength, Int exp) {
  5892. Unit *acc; /* accumulator for result */
  5893. Unit accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer */
  5894. Unit *allocacc=nullptr; /* -> allocated acc buffer, iff allocated */
  5895. Int accunits, need; /* units in use or needed for acc */
  5896. const Unit *l, *r, *u; /* work */
  5897. Int expunits, exprem, result; /* .. */
  5898. if (exp==0) { /* aligned; fastpath */
  5899. if (alength>blength) return 1;
  5900. if (alength<blength) return -1;
  5901. /* same number of units in both -- need unit-by-unit compare */
  5902. l=a+alength-1;
  5903. r=b+alength-1;
  5904. for (;l>=a; l--, r--) {
  5905. if (*l>*r) return 1;
  5906. if (*l<*r) return -1;
  5907. }
  5908. return 0; /* all units match */
  5909. } /* aligned */
  5910. /* Unaligned. If one is >1 unit longer than the other, padded */
  5911. /* approximately, then can return easily */
  5912. if (alength>blength+(Int)D2U(exp)) return 1;
  5913. if (alength+1<blength+(Int)D2U(exp)) return -1;
  5914. /* Need to do a real subtract. For this, a result buffer is needed */
  5915. /* even though only the sign is of interest. Its length needs */
  5916. /* to be the larger of alength and padded blength, +2 */
  5917. need=blength+D2U(exp); /* maximum real length of B */
  5918. if (need<alength) need=alength;
  5919. need+=2;
  5920. acc=accbuff; /* assume use local buffer */
  5921. if (need*sizeof(Unit)>sizeof(accbuff)) {
  5922. allocacc=(Unit *)malloc(need*sizeof(Unit));
  5923. if (allocacc==nullptr) return BADINT; /* hopeless -- abandon */
  5924. acc=allocacc;
  5925. }
  5926. /* Calculate units and remainder from exponent. */
  5927. expunits=exp/DECDPUN;
  5928. exprem=exp%DECDPUN;
  5929. /* subtract [A+B*(-m)] */
  5930. accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
  5931. -(Int)powers[exprem]);
  5932. /* [UnitAddSub result may have leading zeros, even on zero] */
  5933. if (accunits<0) result=-1; /* negative result */
  5934. else { /* non-negative result */
  5935. /* check units of the result before freeing any storage */
  5936. for (u=acc; u<acc+accunits-1 && *u==0;) u++;
  5937. result=(*u==0 ? 0 : +1);
  5938. }
  5939. /* clean up and return the result */
  5940. if (allocacc!=nullptr) free(allocacc); /* drop any storage used */
  5941. return result;
  5942. } /* decUnitCompare */
  5943. /* ------------------------------------------------------------------ */
  5944. /* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays */
  5945. /* */
  5946. /* This routine performs the calculation: */
  5947. /* */
  5948. /* C=A+(B*M) */
  5949. /* */
  5950. /* Where M is in the range -DECDPUNMAX through +DECDPUNMAX. */
  5951. /* */
  5952. /* A may be shorter or longer than B. */
  5953. /* */
  5954. /* Leading zeros are not removed after a calculation. The result is */
  5955. /* either the same length as the longer of A and B (adding any */
  5956. /* shift), or one Unit longer than that (if a Unit carry occurred). */
  5957. /* */
  5958. /* A and B content are not altered unless C is also A or B. */
  5959. /* C may be the same array as A or B, but only if no zero padding is */
  5960. /* requested (that is, C may be B only if bshift==0). */
  5961. /* C is filled from the lsu; only those units necessary to complete */
  5962. /* the calculation are referenced. */
  5963. /* */
  5964. /* Arg1 is A first Unit (lsu) */
  5965. /* Arg2 is A length in Units */
  5966. /* Arg3 is B first Unit (lsu) */
  5967. /* Arg4 is B length in Units */
  5968. /* Arg5 is B shift in Units (>=0; pads with 0 units if positive) */
  5969. /* Arg6 is C first Unit (lsu) */
  5970. /* Arg7 is M, the multiplier */
  5971. /* */
  5972. /* returns the count of Units written to C, which will be non-zero */
  5973. /* and negated if the result is negative. That is, the sign of the */
  5974. /* returned Int is the sign of the result (positive for zero) and */
  5975. /* the absolute value of the Int is the count of Units. */
  5976. /* */
  5977. /* It is the caller's responsibility to make sure that C size is */
  5978. /* safe, allowing space if necessary for a one-Unit carry. */
  5979. /* */
  5980. /* This routine is severely performance-critical; *any* change here */
  5981. /* must be measured (timed) to assure no performance degradation. */
  5982. /* In particular, trickery here tends to be counter-productive, as */
  5983. /* increased complexity of code hurts register optimizations on */
  5984. /* register-poor architectures. Avoiding divisions is nearly */
  5985. /* always a Good Idea, however. */
  5986. /* */
  5987. /* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark */
  5988. /* (IBM Warwick, UK) for some of the ideas used in this routine. */
  5989. /* ------------------------------------------------------------------ */
  5990. static Int decUnitAddSub(const Unit *a, Int alength,
  5991. const Unit *b, Int blength, Int bshift,
  5992. Unit *c, Int m) {
  5993. const Unit *alsu=a; /* A lsu [need to remember it] */
  5994. Unit *clsu=c; /* C ditto */
  5995. Unit *minC; /* low water mark for C */
  5996. Unit *maxC; /* high water mark for C */
  5997. eInt carry=0; /* carry integer (could be Long) */
  5998. Int add; /* work */
  5999. #if DECDPUN<=4 /* myriadal, millenary, etc. */
  6000. Int est; /* estimated quotient */
  6001. #endif
  6002. #if DECTRACE
  6003. if (alength<1 || blength<1)
  6004. printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
  6005. #endif
  6006. maxC=c+alength; /* A is usually the longer */
  6007. minC=c+blength; /* .. and B the shorter */
  6008. if (bshift!=0) { /* B is shifted; low As copy across */
  6009. minC+=bshift;
  6010. /* if in place [common], skip copy unless there's a gap [rare] */
  6011. if (a==c && bshift<=alength) {
  6012. c+=bshift;
  6013. a+=bshift;
  6014. }
  6015. else for (; c<clsu+bshift; a++, c++) { /* copy needed */
  6016. if (a<alsu+alength) *c=*a;
  6017. else *c=0;
  6018. }
  6019. }
  6020. if (minC>maxC) { /* swap */
  6021. Unit *hold=minC;
  6022. minC=maxC;
  6023. maxC=hold;
  6024. }
  6025. /* For speed, do the addition as two loops; the first where both A */
  6026. /* and B contribute, and the second (if necessary) where only one or */
  6027. /* other of the numbers contribute. */
  6028. /* Carry handling is the same (i.e., duplicated) in each case. */
  6029. for (; c<minC; c++) {
  6030. carry+=*a;
  6031. a++;
  6032. carry+=((eInt)*b)*m; /* [special-casing m=1/-1 */
  6033. b++; /* here is not a win] */
  6034. /* here carry is new Unit of digits; it could be +ve or -ve */
  6035. if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */
  6036. *c=(Unit)carry;
  6037. carry=0;
  6038. continue;
  6039. }
  6040. #if DECDPUN==4 /* use divide-by-multiply */
  6041. if (carry>=0) {
  6042. est=(((ueInt)carry>>11)*53687)>>18;
  6043. *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
  6044. carry=est; /* likely quotient [89%] */
  6045. if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
  6046. carry++;
  6047. *c-=DECDPUNMAX+1;
  6048. continue;
  6049. }
  6050. /* negative case */
  6051. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
  6052. est=(((ueInt)carry>>11)*53687)>>18;
  6053. *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6054. carry=est-(DECDPUNMAX+1); /* correctly negative */
  6055. if (*c<DECDPUNMAX+1) continue; /* was OK */
  6056. carry++;
  6057. *c-=DECDPUNMAX+1;
  6058. #elif DECDPUN==3
  6059. if (carry>=0) {
  6060. est=(((ueInt)carry>>3)*16777)>>21;
  6061. *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
  6062. carry=est; /* likely quotient [99%] */
  6063. if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
  6064. carry++;
  6065. *c-=DECDPUNMAX+1;
  6066. continue;
  6067. }
  6068. /* negative case */
  6069. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
  6070. est=(((ueInt)carry>>3)*16777)>>21;
  6071. *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6072. carry=est-(DECDPUNMAX+1); /* correctly negative */
  6073. if (*c<DECDPUNMAX+1) continue; /* was OK */
  6074. carry++;
  6075. *c-=DECDPUNMAX+1;
  6076. #elif DECDPUN<=2
  6077. /* Can use QUOT10 as carry <= 4 digits */
  6078. if (carry>=0) {
  6079. est=QUOT10(carry, DECDPUN);
  6080. *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
  6081. carry=est; /* quotient */
  6082. continue;
  6083. }
  6084. /* negative case */
  6085. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
  6086. est=QUOT10(carry, DECDPUN);
  6087. *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6088. carry=est-(DECDPUNMAX+1); /* correctly negative */
  6089. #else
  6090. /* remainder operator is undefined if negative, so must test */
  6091. if ((ueInt)carry<(DECDPUNMAX+1)*2) { /* fastpath carry +1 */
  6092. *c=(Unit)(carry-(DECDPUNMAX+1)); /* [helps additions] */
  6093. carry=1;
  6094. continue;
  6095. }
  6096. if (carry>=0) {
  6097. *c=(Unit)(carry%(DECDPUNMAX+1));
  6098. carry=carry/(DECDPUNMAX+1);
  6099. continue;
  6100. }
  6101. /* negative case */
  6102. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
  6103. *c=(Unit)(carry%(DECDPUNMAX+1));
  6104. carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
  6105. #endif
  6106. } /* c */
  6107. /* now may have one or other to complete */
  6108. /* [pretest to avoid loop setup/shutdown] */
  6109. if (c<maxC) for (; c<maxC; c++) {
  6110. if (a<alsu+alength) { /* still in A */
  6111. carry+=*a;
  6112. a++;
  6113. }
  6114. else { /* inside B */
  6115. carry+=((eInt)*b)*m;
  6116. b++;
  6117. }
  6118. /* here carry is new Unit of digits; it could be +ve or -ve and */
  6119. /* magnitude up to DECDPUNMAX squared */
  6120. if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */
  6121. *c=(Unit)carry;
  6122. carry=0;
  6123. continue;
  6124. }
  6125. /* result for this unit is negative or >DECDPUNMAX */
  6126. #if DECDPUN==4 /* use divide-by-multiply */
  6127. if (carry>=0) {
  6128. est=(((ueInt)carry>>11)*53687)>>18;
  6129. *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
  6130. carry=est; /* likely quotient [79.7%] */
  6131. if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
  6132. carry++;
  6133. *c-=DECDPUNMAX+1;
  6134. continue;
  6135. }
  6136. /* negative case */
  6137. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
  6138. est=(((ueInt)carry>>11)*53687)>>18;
  6139. *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6140. carry=est-(DECDPUNMAX+1); /* correctly negative */
  6141. if (*c<DECDPUNMAX+1) continue; /* was OK */
  6142. carry++;
  6143. *c-=DECDPUNMAX+1;
  6144. #elif DECDPUN==3
  6145. if (carry>=0) {
  6146. est=(((ueInt)carry>>3)*16777)>>21;
  6147. *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
  6148. carry=est; /* likely quotient [99%] */
  6149. if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
  6150. carry++;
  6151. *c-=DECDPUNMAX+1;
  6152. continue;
  6153. }
  6154. /* negative case */
  6155. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
  6156. est=(((ueInt)carry>>3)*16777)>>21;
  6157. *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6158. carry=est-(DECDPUNMAX+1); /* correctly negative */
  6159. if (*c<DECDPUNMAX+1) continue; /* was OK */
  6160. carry++;
  6161. *c-=DECDPUNMAX+1;
  6162. #elif DECDPUN<=2
  6163. if (carry>=0) {
  6164. est=QUOT10(carry, DECDPUN);
  6165. *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
  6166. carry=est; /* quotient */
  6167. continue;
  6168. }
  6169. /* negative case */
  6170. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
  6171. est=QUOT10(carry, DECDPUN);
  6172. *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6173. carry=est-(DECDPUNMAX+1); /* correctly negative */
  6174. #else
  6175. if ((ueInt)carry<(DECDPUNMAX+1)*2){ /* fastpath carry 1 */
  6176. *c=(Unit)(carry-(DECDPUNMAX+1));
  6177. carry=1;
  6178. continue;
  6179. }
  6180. /* remainder operator is undefined if negative, so must test */
  6181. if (carry>=0) {
  6182. *c=(Unit)(carry%(DECDPUNMAX+1));
  6183. carry=carry/(DECDPUNMAX+1);
  6184. continue;
  6185. }
  6186. /* negative case */
  6187. carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
  6188. *c=(Unit)(carry%(DECDPUNMAX+1));
  6189. carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
  6190. #endif
  6191. } /* c */
  6192. /* OK, all A and B processed; might still have carry or borrow */
  6193. /* return number of Units in the result, negated if a borrow */
  6194. if (carry==0) return static_cast<int32_t>(c-clsu); /* no carry, so no more to do */
  6195. if (carry>0) { /* positive carry */
  6196. *c=(Unit)carry; /* place as new unit */
  6197. c++; /* .. */
  6198. return static_cast<int32_t>(c-clsu);
  6199. }
  6200. /* -ve carry: it's a borrow; complement needed */
  6201. add=1; /* temporary carry... */
  6202. for (c=clsu; c<maxC; c++) {
  6203. add=DECDPUNMAX+add-*c;
  6204. if (add<=DECDPUNMAX) {
  6205. *c=(Unit)add;
  6206. add=0;
  6207. }
  6208. else {
  6209. *c=0;
  6210. add=1;
  6211. }
  6212. }
  6213. /* add an extra unit iff it would be non-zero */
  6214. #if DECTRACE
  6215. printf("UAS borrow: add %ld, carry %ld\n", add, carry);
  6216. #endif
  6217. if ((add-carry-1)!=0) {
  6218. *c=(Unit)(add-carry-1);
  6219. c++; /* interesting, include it */
  6220. }
  6221. return static_cast<int32_t>(clsu-c); /* -ve result indicates borrowed */
  6222. } /* decUnitAddSub */
  6223. /* ------------------------------------------------------------------ */
  6224. /* decTrim -- trim trailing zeros or normalize */
  6225. /* */
  6226. /* dn is the number to trim or normalize */
  6227. /* set is the context to use to check for clamp */
  6228. /* all is 1 to remove all trailing zeros, 0 for just fraction ones */
  6229. /* noclamp is 1 to unconditional (unclamped) trim */
  6230. /* dropped returns the number of discarded trailing zeros */
  6231. /* returns dn */
  6232. /* */
  6233. /* If clamp is set in the context then the number of zeros trimmed */
  6234. /* may be limited if the exponent is high. */
  6235. /* All fields are updated as required. This is a utility operation, */
  6236. /* so special values are unchanged and no error is possible. */
  6237. /* ------------------------------------------------------------------ */
  6238. static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
  6239. Flag noclamp, Int *dropped) {
  6240. Int d, exp; /* work */
  6241. uInt cut; /* .. */
  6242. Unit *up; /* -> current Unit */
  6243. #if DECCHECK
  6244. if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
  6245. #endif
  6246. *dropped=0; /* assume no zeros dropped */
  6247. if ((dn->bits & DECSPECIAL) /* fast exit if special .. */
  6248. || (*dn->lsu & 0x01)) return dn; /* .. or odd */
  6249. if (ISZERO(dn)) { /* .. or 0 */
  6250. dn->exponent=0; /* (sign is preserved) */
  6251. return dn;
  6252. }
  6253. /* have a finite number which is even */
  6254. exp=dn->exponent;
  6255. cut=1; /* digit (1-DECDPUN) in Unit */
  6256. up=dn->lsu; /* -> current Unit */
  6257. for (d=0; d<dn->digits-1; d++) { /* [don't strip the final digit] */
  6258. /* slice by powers */
  6259. #if DECDPUN<=4
  6260. uInt quot=QUOT10(*up, cut);
  6261. if ((*up-quot*powers[cut])!=0) break; /* found non-0 digit */
  6262. #else
  6263. if (*up%powers[cut]!=0) break; /* found non-0 digit */
  6264. #endif
  6265. /* have a trailing 0 */
  6266. if (!all) { /* trimming */
  6267. /* [if exp>0 then all trailing 0s are significant for trim] */
  6268. if (exp<=0) { /* if digit might be significant */
  6269. if (exp==0) break; /* then quit */
  6270. exp++; /* next digit might be significant */
  6271. }
  6272. }
  6273. cut++; /* next power */
  6274. if (cut>DECDPUN) { /* need new Unit */
  6275. up++;
  6276. cut=1;
  6277. }
  6278. } /* d */
  6279. if (d==0) return dn; /* none to drop */
  6280. /* may need to limit drop if clamping */
  6281. if (set->clamp && !noclamp) {
  6282. Int maxd=set->emax-set->digits+1-dn->exponent;
  6283. if (maxd<=0) return dn; /* nothing possible */
  6284. if (d>maxd) d=maxd;
  6285. }
  6286. /* effect the drop */
  6287. decShiftToLeast(dn->lsu, D2U(dn->digits), d);
  6288. dn->exponent+=d; /* maintain numerical value */
  6289. dn->digits-=d; /* new length */
  6290. *dropped=d; /* report the count */
  6291. return dn;
  6292. } /* decTrim */
  6293. /* ------------------------------------------------------------------ */
  6294. /* decReverse -- reverse a Unit array in place */
  6295. /* */
  6296. /* ulo is the start of the array */
  6297. /* uhi is the end of the array (highest Unit to include) */
  6298. /* */
  6299. /* The units ulo through uhi are reversed in place (if the number */
  6300. /* of units is odd, the middle one is untouched). Note that the */
  6301. /* digit(s) in each unit are unaffected. */
  6302. /* ------------------------------------------------------------------ */
  6303. static void decReverse(Unit *ulo, Unit *uhi) {
  6304. Unit temp;
  6305. for (; ulo<uhi; ulo++, uhi--) {
  6306. temp=*ulo;
  6307. *ulo=*uhi;
  6308. *uhi=temp;
  6309. }
  6310. return;
  6311. } /* decReverse */
  6312. /* ------------------------------------------------------------------ */
  6313. /* decShiftToMost -- shift digits in array towards most significant */
  6314. /* */
  6315. /* uar is the array */
  6316. /* digits is the count of digits in use in the array */
  6317. /* shift is the number of zeros to pad with (least significant); */
  6318. /* it must be zero or positive */
  6319. /* */
  6320. /* returns the new length of the integer in the array, in digits */
  6321. /* */
  6322. /* No overflow is permitted (that is, the uar array must be known to */
  6323. /* be large enough to hold the result, after shifting). */
  6324. /* ------------------------------------------------------------------ */
  6325. static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
  6326. Unit *target, *source, *first; /* work */
  6327. Int cut; /* odd 0's to add */
  6328. uInt next; /* work */
  6329. if (shift==0) return digits; /* [fastpath] nothing to do */
  6330. if ((digits+shift)<=DECDPUN) { /* [fastpath] single-unit case */
  6331. *uar=(Unit)(*uar*powers[shift]);
  6332. return digits+shift;
  6333. }
  6334. next=0; /* all paths */
  6335. source=uar+D2U(digits)-1; /* where msu comes from */
  6336. target=source+D2U(shift); /* where upper part of first cut goes */
  6337. cut=DECDPUN-MSUDIGITS(shift); /* where to slice */
  6338. if (cut==0) { /* unit-boundary case */
  6339. for (; source>=uar; source--, target--) *target=*source;
  6340. }
  6341. else {
  6342. first=uar+D2U(digits+shift)-1; /* where msu of source will end up */
  6343. for (; source>=uar; source--, target--) {
  6344. /* split the source Unit and accumulate remainder for next */
  6345. #if DECDPUN<=4
  6346. uInt quot=QUOT10(*source, cut);
  6347. uInt rem=*source-quot*powers[cut];
  6348. next+=quot;
  6349. #else
  6350. uInt rem=*source%powers[cut];
  6351. next+=*source/powers[cut];
  6352. #endif
  6353. if (target<=first) *target=(Unit)next; /* write to target iff valid */
  6354. next=rem*powers[DECDPUN-cut]; /* save remainder for next Unit */
  6355. }
  6356. } /* shift-move */
  6357. /* propagate any partial unit to one below and clear the rest */
  6358. for (; target>=uar; target--) {
  6359. *target=(Unit)next;
  6360. next=0;
  6361. }
  6362. return digits+shift;
  6363. } /* decShiftToMost */
  6364. /* ------------------------------------------------------------------ */
  6365. /* decShiftToLeast -- shift digits in array towards least significant */
  6366. /* */
  6367. /* uar is the array */
  6368. /* units is length of the array, in units */
  6369. /* shift is the number of digits to remove from the lsu end; it */
  6370. /* must be zero or positive and <= than units*DECDPUN. */
  6371. /* */
  6372. /* returns the new length of the integer in the array, in units */
  6373. /* */
  6374. /* Removed digits are discarded (lost). Units not required to hold */
  6375. /* the final result are unchanged. */
  6376. /* ------------------------------------------------------------------ */
  6377. static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
  6378. Unit *target, *up; /* work */
  6379. Int cut, count; /* work */
  6380. Int quot, rem; /* for division */
  6381. if (shift==0) return units; /* [fastpath] nothing to do */
  6382. if (shift==units*DECDPUN) { /* [fastpath] little to do */
  6383. *uar=0; /* all digits cleared gives zero */
  6384. return 1; /* leaves just the one */
  6385. }
  6386. target=uar; /* both paths */
  6387. cut=MSUDIGITS(shift);
  6388. if (cut==DECDPUN) { /* unit-boundary case; easy */
  6389. up=uar+D2U(shift);
  6390. for (; up<uar+units; target++, up++) *target=*up;
  6391. return static_cast<int32_t>(target-uar);
  6392. }
  6393. /* messier */
  6394. up=uar+D2U(shift-cut); /* source; correct to whole Units */
  6395. count=units*DECDPUN-shift; /* the maximum new length */
  6396. #if DECDPUN<=4
  6397. quot=QUOT10(*up, cut);
  6398. #else
  6399. quot=*up/powers[cut];
  6400. #endif
  6401. for (; ; target++) {
  6402. *target=(Unit)quot;
  6403. count-=(DECDPUN-cut);
  6404. if (count<=0) break;
  6405. up++;
  6406. quot=*up;
  6407. #if DECDPUN<=4
  6408. quot=QUOT10(quot, cut);
  6409. rem=*up-quot*powers[cut];
  6410. #else
  6411. rem=quot%powers[cut];
  6412. quot=quot/powers[cut];
  6413. #endif
  6414. *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
  6415. count-=cut;
  6416. if (count<=0) break;
  6417. }
  6418. return static_cast<int32_t>(target-uar+1);
  6419. } /* decShiftToLeast */
  6420. #if DECSUBSET
  6421. /* ------------------------------------------------------------------ */
  6422. /* decRoundOperand -- round an operand [used for subset only] */
  6423. /* */
  6424. /* dn is the number to round (dn->digits is > set->digits) */
  6425. /* set is the relevant context */
  6426. /* status is the status accumulator */
  6427. /* */
  6428. /* returns an allocated decNumber with the rounded result. */
  6429. /* */
  6430. /* lostDigits and other status may be set by this. */
  6431. /* */
  6432. /* Since the input is an operand, it must not be modified. */
  6433. /* Instead, return an allocated decNumber, rounded as required. */
  6434. /* It is the caller's responsibility to free the allocated storage. */
  6435. /* */
  6436. /* If no storage is available then the result cannot be used, so nullptr */
  6437. /* is returned. */
  6438. /* ------------------------------------------------------------------ */
  6439. static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
  6440. uInt *status) {
  6441. decNumber *res; /* result structure */
  6442. uInt newstatus=0; /* status from round */
  6443. Int residue=0; /* rounding accumulator */
  6444. /* Allocate storage for the returned decNumber, big enough for the */
  6445. /* length specified by the context */
  6446. res=(decNumber *)malloc(sizeof(decNumber)
  6447. +(D2U(set->digits)-1)*sizeof(Unit));
  6448. if (res==nullptr) {
  6449. *status|=DEC_Insufficient_storage;
  6450. return nullptr;
  6451. }
  6452. decCopyFit(res, dn, set, &residue, &newstatus);
  6453. decApplyRound(res, set, residue, &newstatus);
  6454. /* If that set Inexact then "lost digits" is raised... */
  6455. if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
  6456. *status|=newstatus;
  6457. return res;
  6458. } /* decRoundOperand */
  6459. #endif
  6460. /* ------------------------------------------------------------------ */
  6461. /* decCopyFit -- copy a number, truncating the coefficient if needed */
  6462. /* */
  6463. /* dest is the target decNumber */
  6464. /* src is the source decNumber */
  6465. /* set is the context [used for length (digits) and rounding mode] */
  6466. /* residue is the residue accumulator */
  6467. /* status contains the current status to be updated */
  6468. /* */
  6469. /* (dest==src is allowed and will be a no-op if fits) */
  6470. /* All fields are updated as required. */
  6471. /* ------------------------------------------------------------------ */
  6472. static void decCopyFit(decNumber *dest, const decNumber *src,
  6473. decContext *set, Int *residue, uInt *status) {
  6474. dest->bits=src->bits;
  6475. dest->exponent=src->exponent;
  6476. decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
  6477. } /* decCopyFit */
  6478. /* ------------------------------------------------------------------ */
  6479. /* decSetCoeff -- set the coefficient of a number */
  6480. /* */
  6481. /* dn is the number whose coefficient array is to be set. */
  6482. /* It must have space for set->digits digits */
  6483. /* set is the context [for size] */
  6484. /* lsu -> lsu of the source coefficient [may be dn->lsu] */
  6485. /* len is digits in the source coefficient [may be dn->digits] */
  6486. /* residue is the residue accumulator. This has values as in */
  6487. /* decApplyRound, and will be unchanged unless the */
  6488. /* target size is less than len. In this case, the */
  6489. /* coefficient is truncated and the residue is updated to */
  6490. /* reflect the previous residue and the dropped digits. */
  6491. /* status is the status accumulator, as usual */
  6492. /* */
  6493. /* The coefficient may already be in the number, or it can be an */
  6494. /* external intermediate array. If it is in the number, lsu must == */
  6495. /* dn->lsu and len must == dn->digits. */
  6496. /* */
  6497. /* Note that the coefficient length (len) may be < set->digits, and */
  6498. /* in this case this merely copies the coefficient (or is a no-op */
  6499. /* if dn->lsu==lsu). */
  6500. /* */
  6501. /* Note also that (only internally, from decQuantizeOp and */
  6502. /* decSetSubnormal) the value of set->digits may be less than one, */
  6503. /* indicating a round to left. This routine handles that case */
  6504. /* correctly; caller ensures space. */
  6505. /* */
  6506. /* dn->digits, dn->lsu (and as required), and dn->exponent are */
  6507. /* updated as necessary. dn->bits (sign) is unchanged. */
  6508. /* */
  6509. /* DEC_Rounded status is set if any digits are discarded. */
  6510. /* DEC_Inexact status is set if any non-zero digits are discarded, or */
  6511. /* incoming residue was non-0 (implies rounded) */
  6512. /* ------------------------------------------------------------------ */
  6513. /* mapping array: maps 0-9 to canonical residues, so that a residue */
  6514. /* can be adjusted in the range [-1, +1] and achieve correct rounding */
  6515. /* 0 1 2 3 4 5 6 7 8 9 */
  6516. static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
  6517. static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
  6518. Int len, Int *residue, uInt *status) {
  6519. Int discard; /* number of digits to discard */
  6520. uInt cut; /* cut point in Unit */
  6521. const Unit *up; /* work */
  6522. Unit *target; /* .. */
  6523. Int count; /* .. */
  6524. #if DECDPUN<=4
  6525. uInt temp; /* .. */
  6526. #endif
  6527. discard=len-set->digits; /* digits to discard */
  6528. if (discard<=0) { /* no digits are being discarded */
  6529. if (dn->lsu!=lsu) { /* copy needed */
  6530. /* copy the coefficient array to the result number; no shift needed */
  6531. count=len; /* avoids D2U */
  6532. up=lsu;
  6533. for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
  6534. *target=*up;
  6535. dn->digits=len; /* set the new length */
  6536. }
  6537. /* dn->exponent and residue are unchanged, record any inexactitude */
  6538. if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
  6539. return;
  6540. }
  6541. /* some digits must be discarded ... */
  6542. dn->exponent+=discard; /* maintain numerical value */
  6543. *status|=DEC_Rounded; /* accumulate Rounded status */
  6544. if (*residue>1) *residue=1; /* previous residue now to right, so reduce */
  6545. if (discard>len) { /* everything, +1, is being discarded */
  6546. /* guard digit is 0 */
  6547. /* residue is all the number [NB could be all 0s] */
  6548. if (*residue<=0) { /* not already positive */
  6549. count=len; /* avoids D2U */
  6550. for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0 */
  6551. *residue=1;
  6552. break; /* no need to check any others */
  6553. }
  6554. }
  6555. if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
  6556. *dn->lsu=0; /* coefficient will now be 0 */
  6557. dn->digits=1; /* .. */
  6558. return;
  6559. } /* total discard */
  6560. /* partial discard [most common case] */
  6561. /* here, at least the first (most significant) discarded digit exists */
  6562. /* spin up the number, noting residue during the spin, until get to */
  6563. /* the Unit with the first discarded digit. When reach it, extract */
  6564. /* it and remember its position */
  6565. count=0;
  6566. for (up=lsu;; up++) {
  6567. count+=DECDPUN;
  6568. if (count>=discard) break; /* full ones all checked */
  6569. if (*up!=0) *residue=1;
  6570. } /* up */
  6571. /* here up -> Unit with first discarded digit */
  6572. cut=discard-(count-DECDPUN)-1;
  6573. if (cut==DECDPUN-1) { /* unit-boundary case (fast) */
  6574. Unit half=(Unit)powers[DECDPUN]>>1;
  6575. /* set residue directly */
  6576. if (*up>=half) {
  6577. if (*up>half) *residue=7;
  6578. else *residue+=5; /* add sticky bit */
  6579. }
  6580. else { /* <half */
  6581. if (*up!=0) *residue=3; /* [else is 0, leave as sticky bit] */
  6582. }
  6583. if (set->digits<=0) { /* special for Quantize/Subnormal :-( */
  6584. *dn->lsu=0; /* .. result is 0 */
  6585. dn->digits=1; /* .. */
  6586. }
  6587. else { /* shift to least */
  6588. count=set->digits; /* now digits to end up with */
  6589. dn->digits=count; /* set the new length */
  6590. up++; /* move to next */
  6591. /* on unit boundary, so shift-down copy loop is simple */
  6592. for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
  6593. *target=*up;
  6594. }
  6595. } /* unit-boundary case */
  6596. else { /* discard digit is in low digit(s), and not top digit */
  6597. uInt discard1; /* first discarded digit */
  6598. uInt quot, rem; /* for divisions */
  6599. if (cut==0) quot=*up; /* is at bottom of unit */
  6600. else /* cut>0 */ { /* it's not at bottom of unit */
  6601. #if DECDPUN<=4
  6602. U_ASSERT(/* cut >= 0 &&*/ cut <= 4);
  6603. quot=QUOT10(*up, cut);
  6604. rem=*up-quot*powers[cut];
  6605. #else
  6606. rem=*up%powers[cut];
  6607. quot=*up/powers[cut];
  6608. #endif
  6609. if (rem!=0) *residue=1;
  6610. }
  6611. /* discard digit is now at bottom of quot */
  6612. #if DECDPUN<=4
  6613. temp=(quot*6554)>>16; /* fast /10 */
  6614. /* Vowels algorithm here not a win (9 instructions) */
  6615. discard1=quot-X10(temp);
  6616. quot=temp;
  6617. #else
  6618. discard1=quot%10;
  6619. quot=quot/10;
  6620. #endif
  6621. /* here, discard1 is the guard digit, and residue is everything */
  6622. /* else [use mapping array to accumulate residue safely] */
  6623. *residue+=resmap[discard1];
  6624. cut++; /* update cut */
  6625. /* here: up -> Unit of the array with bottom digit */
  6626. /* cut is the division point for each Unit */
  6627. /* quot holds the uncut high-order digits for the current unit */
  6628. if (set->digits<=0) { /* special for Quantize/Subnormal :-( */
  6629. *dn->lsu=0; /* .. result is 0 */
  6630. dn->digits=1; /* .. */
  6631. }
  6632. else { /* shift to least needed */
  6633. count=set->digits; /* now digits to end up with */
  6634. dn->digits=count; /* set the new length */
  6635. /* shift-copy the coefficient array to the result number */
  6636. for (target=dn->lsu; ; target++) {
  6637. *target=(Unit)quot;
  6638. count-=(DECDPUN-cut);
  6639. if (count<=0) break;
  6640. up++;
  6641. quot=*up;
  6642. #if DECDPUN<=4
  6643. quot=QUOT10(quot, cut);
  6644. rem=*up-quot*powers[cut];
  6645. #else
  6646. rem=quot%powers[cut];
  6647. quot=quot/powers[cut];
  6648. #endif
  6649. *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
  6650. count-=cut;
  6651. if (count<=0) break;
  6652. } /* shift-copy loop */
  6653. } /* shift to least */
  6654. } /* not unit boundary */
  6655. if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
  6656. return;
  6657. } /* decSetCoeff */
  6658. /* ------------------------------------------------------------------ */
  6659. /* decApplyRound -- apply pending rounding to a number */
  6660. /* */
  6661. /* dn is the number, with space for set->digits digits */
  6662. /* set is the context [for size and rounding mode] */
  6663. /* residue indicates pending rounding, being any accumulated */
  6664. /* guard and sticky information. It may be: */
  6665. /* 6-9: rounding digit is >5 */
  6666. /* 5: rounding digit is exactly half-way */
  6667. /* 1-4: rounding digit is <5 and >0 */
  6668. /* 0: the coefficient is exact */
  6669. /* -1: as 1, but the hidden digits are subtractive, that */
  6670. /* is, of the opposite sign to dn. In this case the */
  6671. /* coefficient must be non-0. This case occurs when */
  6672. /* subtracting a small number (which can be reduced to */
  6673. /* a sticky bit); see decAddOp. */
  6674. /* status is the status accumulator, as usual */
  6675. /* */
  6676. /* This routine applies rounding while keeping the length of the */
  6677. /* coefficient constant. The exponent and status are unchanged */
  6678. /* except if: */
  6679. /* */
  6680. /* -- the coefficient was increased and is all nines (in which */
  6681. /* case Overflow could occur, and is handled directly here so */
  6682. /* the caller does not need to re-test for overflow) */
  6683. /* */
  6684. /* -- the coefficient was decreased and becomes all nines (in which */
  6685. /* case Underflow could occur, and is also handled directly). */
  6686. /* */
  6687. /* All fields in dn are updated as required. */
  6688. /* */
  6689. /* ------------------------------------------------------------------ */
  6690. static void decApplyRound(decNumber *dn, decContext *set, Int residue,
  6691. uInt *status) {
  6692. Int bump; /* 1 if coefficient needs to be incremented */
  6693. /* -1 if coefficient needs to be decremented */
  6694. if (residue==0) return; /* nothing to apply */
  6695. bump=0; /* assume a smooth ride */
  6696. /* now decide whether, and how, to round, depending on mode */
  6697. switch (set->round) {
  6698. case DEC_ROUND_05UP: { /* round zero or five up (for reround) */
  6699. /* This is the same as DEC_ROUND_DOWN unless there is a */
  6700. /* positive residue and the lsd of dn is 0 or 5, in which case */
  6701. /* it is bumped; when residue is <0, the number is therefore */
  6702. /* bumped down unless the final digit was 1 or 6 (in which */
  6703. /* case it is bumped down and then up -- a no-op) */
  6704. Int lsd5=*dn->lsu%5; /* get lsd and quintate */
  6705. if (residue<0 && lsd5!=1) bump=-1;
  6706. else if (residue>0 && lsd5==0) bump=1;
  6707. /* [bump==1 could be applied directly; use common path for clarity] */
  6708. break;} /* r-05 */
  6709. case DEC_ROUND_DOWN: {
  6710. /* no change, except if negative residue */
  6711. if (residue<0) bump=-1;
  6712. break;} /* r-d */
  6713. case DEC_ROUND_HALF_DOWN: {
  6714. if (residue>5) bump=1;
  6715. break;} /* r-h-d */
  6716. case DEC_ROUND_HALF_EVEN: {
  6717. if (residue>5) bump=1; /* >0.5 goes up */
  6718. else if (residue==5) { /* exactly 0.5000... */
  6719. /* 0.5 goes up iff [new] lsd is odd */
  6720. if (*dn->lsu & 0x01) bump=1;
  6721. }
  6722. break;} /* r-h-e */
  6723. case DEC_ROUND_HALF_UP: {
  6724. if (residue>=5) bump=1;
  6725. break;} /* r-h-u */
  6726. case DEC_ROUND_UP: {
  6727. if (residue>0) bump=1;
  6728. break;} /* r-u */
  6729. case DEC_ROUND_CEILING: {
  6730. /* same as _UP for positive numbers, and as _DOWN for negatives */
  6731. /* [negative residue cannot occur on 0] */
  6732. if (decNumberIsNegative(dn)) {
  6733. if (residue<0) bump=-1;
  6734. }
  6735. else {
  6736. if (residue>0) bump=1;
  6737. }
  6738. break;} /* r-c */
  6739. case DEC_ROUND_FLOOR: {
  6740. /* same as _UP for negative numbers, and as _DOWN for positive */
  6741. /* [negative residue cannot occur on 0] */
  6742. if (!decNumberIsNegative(dn)) {
  6743. if (residue<0) bump=-1;
  6744. }
  6745. else {
  6746. if (residue>0) bump=1;
  6747. }
  6748. break;} /* r-f */
  6749. default: { /* e.g., DEC_ROUND_MAX */
  6750. *status|=DEC_Invalid_context;
  6751. #if DECTRACE || (DECCHECK && DECVERB)
  6752. printf("Unknown rounding mode: %d\n", set->round);
  6753. #endif
  6754. break;}
  6755. } /* switch */
  6756. /* now bump the number, up or down, if need be */
  6757. if (bump==0) return; /* no action required */
  6758. /* Simply use decUnitAddSub unless bumping up and the number is */
  6759. /* all nines. In this special case set to 100... explicitly */
  6760. /* and adjust the exponent by one (as otherwise could overflow */
  6761. /* the array) */
  6762. /* Similarly handle all-nines result if bumping down. */
  6763. if (bump>0) {
  6764. Unit *up; /* work */
  6765. uInt count=dn->digits; /* digits to be checked */
  6766. for (up=dn->lsu; ; up++) {
  6767. if (count<=DECDPUN) {
  6768. /* this is the last Unit (the msu) */
  6769. if (*up!=powers[count]-1) break; /* not still 9s */
  6770. /* here if it, too, is all nines */
  6771. *up=(Unit)powers[count-1]; /* here 999 -> 100 etc. */
  6772. for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0 */
  6773. dn->exponent++; /* and bump exponent */
  6774. /* [which, very rarely, could cause Overflow...] */
  6775. if ((dn->exponent+dn->digits)>set->emax+1) {
  6776. decSetOverflow(dn, set, status);
  6777. }
  6778. return; /* done */
  6779. }
  6780. /* a full unit to check, with more to come */
  6781. if (*up!=DECDPUNMAX) break; /* not still 9s */
  6782. count-=DECDPUN;
  6783. } /* up */
  6784. } /* bump>0 */
  6785. else { /* -1 */
  6786. /* here checking for a pre-bump of 1000... (leading 1, all */
  6787. /* other digits zero) */
  6788. Unit *up, *sup; /* work */
  6789. uInt count=dn->digits; /* digits to be checked */
  6790. for (up=dn->lsu; ; up++) {
  6791. if (count<=DECDPUN) {
  6792. /* this is the last Unit (the msu) */
  6793. if (*up!=powers[count-1]) break; /* not 100.. */
  6794. /* here if have the 1000... case */
  6795. sup=up; /* save msu pointer */
  6796. *up=(Unit)powers[count]-1; /* here 100 in msu -> 999 */
  6797. /* others all to all-nines, too */
  6798. for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
  6799. dn->exponent--; /* and bump exponent */
  6800. /* iff the number was at the subnormal boundary (exponent=etiny) */
  6801. /* then the exponent is now out of range, so it will in fact get */
  6802. /* clamped to etiny and the final 9 dropped. */
  6803. /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin, */
  6804. /* dn->exponent, set->digits); */
  6805. if (dn->exponent+1==set->emin-set->digits+1) {
  6806. if (count==1 && dn->digits==1) *sup=0; /* here 9 -> 0[.9] */
  6807. else {
  6808. *sup=(Unit)powers[count-1]-1; /* here 999.. in msu -> 99.. */
  6809. dn->digits--;
  6810. }
  6811. dn->exponent++;
  6812. *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
  6813. }
  6814. return; /* done */
  6815. }
  6816. /* a full unit to check, with more to come */
  6817. if (*up!=0) break; /* not still 0s */
  6818. count-=DECDPUN;
  6819. } /* up */
  6820. } /* bump<0 */
  6821. /* Actual bump needed. Do it. */
  6822. decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
  6823. } /* decApplyRound */
  6824. #if DECSUBSET
  6825. /* ------------------------------------------------------------------ */
  6826. /* decFinish -- finish processing a number */
  6827. /* */
  6828. /* dn is the number */
  6829. /* set is the context */
  6830. /* residue is the rounding accumulator (as in decApplyRound) */
  6831. /* status is the accumulator */
  6832. /* */
  6833. /* This finishes off the current number by: */
  6834. /* 1. If not extended: */
  6835. /* a. Converting a zero result to clean '0' */
  6836. /* b. Reducing positive exponents to 0, if would fit in digits */
  6837. /* 2. Checking for overflow and subnormals (always) */
  6838. /* Note this is just Finalize when no subset arithmetic. */
  6839. /* All fields are updated as required. */
  6840. /* ------------------------------------------------------------------ */
  6841. static void decFinish(decNumber *dn, decContext *set, Int *residue,
  6842. uInt *status) {
  6843. if (!set->extended) {
  6844. if ISZERO(dn) { /* value is zero */
  6845. dn->exponent=0; /* clean exponent .. */
  6846. dn->bits=0; /* .. and sign */
  6847. return; /* no error possible */
  6848. }
  6849. if (dn->exponent>=0) { /* non-negative exponent */
  6850. /* >0; reduce to integer if possible */
  6851. if (set->digits >= (dn->exponent+dn->digits)) {
  6852. dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
  6853. dn->exponent=0;
  6854. }
  6855. }
  6856. } /* !extended */
  6857. decFinalize(dn, set, residue, status);
  6858. } /* decFinish */
  6859. #endif
  6860. /* ------------------------------------------------------------------ */
  6861. /* decFinalize -- final check, clamp, and round of a number */
  6862. /* */
  6863. /* dn is the number */
  6864. /* set is the context */
  6865. /* residue is the rounding accumulator (as in decApplyRound) */
  6866. /* status is the status accumulator */
  6867. /* */
  6868. /* This finishes off the current number by checking for subnormal */
  6869. /* results, applying any pending rounding, checking for overflow, */
  6870. /* and applying any clamping. */
  6871. /* Underflow and overflow conditions are raised as appropriate. */
  6872. /* All fields are updated as required. */
  6873. /* ------------------------------------------------------------------ */
  6874. static void decFinalize(decNumber *dn, decContext *set, Int *residue,
  6875. uInt *status) {
  6876. Int shift; /* shift needed if clamping */
  6877. Int tinyexp=set->emin-dn->digits+1; /* precalculate subnormal boundary */
  6878. /* Must be careful, here, when checking the exponent as the */
  6879. /* adjusted exponent could overflow 31 bits [because it may already */
  6880. /* be up to twice the expected]. */
  6881. /* First test for subnormal. This must be done before any final */
  6882. /* round as the result could be rounded to Nmin or 0. */
  6883. if (dn->exponent<=tinyexp) { /* prefilter */
  6884. Int comp;
  6885. decNumber nmin;
  6886. /* A very nasty case here is dn == Nmin and residue<0 */
  6887. if (dn->exponent<tinyexp) {
  6888. /* Go handle subnormals; this will apply round if needed. */
  6889. decSetSubnormal(dn, set, residue, status);
  6890. return;
  6891. }
  6892. /* Equals case: only subnormal if dn=Nmin and negative residue */
  6893. uprv_decNumberZero(&nmin);
  6894. nmin.lsu[0]=1;
  6895. nmin.exponent=set->emin;
  6896. comp=decCompare(dn, &nmin, 1); /* (signless compare) */
  6897. if (comp==BADINT) { /* oops */
  6898. *status|=DEC_Insufficient_storage; /* abandon... */
  6899. return;
  6900. }
  6901. if (*residue<0 && comp==0) { /* neg residue and dn==Nmin */
  6902. decApplyRound(dn, set, *residue, status); /* might force down */
  6903. decSetSubnormal(dn, set, residue, status);
  6904. return;
  6905. }
  6906. }
  6907. /* now apply any pending round (this could raise overflow). */
  6908. if (*residue!=0) decApplyRound(dn, set, *residue, status);
  6909. /* Check for overflow [redundant in the 'rare' case] or clamp */
  6910. if (dn->exponent<=set->emax-set->digits+1) return; /* neither needed */
  6911. /* here when might have an overflow or clamp to do */
  6912. if (dn->exponent>set->emax-dn->digits+1) { /* too big */
  6913. decSetOverflow(dn, set, status);
  6914. return;
  6915. }
  6916. /* here when the result is normal but in clamp range */
  6917. if (!set->clamp) return;
  6918. /* here when need to apply the IEEE exponent clamp (fold-down) */
  6919. shift=dn->exponent-(set->emax-set->digits+1);
  6920. /* shift coefficient (if non-zero) */
  6921. if (!ISZERO(dn)) {
  6922. dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
  6923. }
  6924. dn->exponent-=shift; /* adjust the exponent to match */
  6925. *status|=DEC_Clamped; /* and record the dirty deed */
  6926. return;
  6927. } /* decFinalize */
  6928. /* ------------------------------------------------------------------ */
  6929. /* decSetOverflow -- set number to proper overflow value */
  6930. /* */
  6931. /* dn is the number (used for sign [only] and result) */
  6932. /* set is the context [used for the rounding mode, etc.] */
  6933. /* status contains the current status to be updated */
  6934. /* */
  6935. /* This sets the sign of a number and sets its value to either */
  6936. /* Infinity or the maximum finite value, depending on the sign of */
  6937. /* dn and the rounding mode, following IEEE 754 rules. */
  6938. /* ------------------------------------------------------------------ */
  6939. static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
  6940. Flag needmax=0; /* result is maximum finite value */
  6941. uByte sign=dn->bits&DECNEG; /* clean and save sign bit */
  6942. if (ISZERO(dn)) { /* zero does not overflow magnitude */
  6943. Int emax=set->emax; /* limit value */
  6944. if (set->clamp) emax-=set->digits-1; /* lower if clamping */
  6945. if (dn->exponent>emax) { /* clamp required */
  6946. dn->exponent=emax;
  6947. *status|=DEC_Clamped;
  6948. }
  6949. return;
  6950. }
  6951. uprv_decNumberZero(dn);
  6952. switch (set->round) {
  6953. case DEC_ROUND_DOWN: {
  6954. needmax=1; /* never Infinity */
  6955. break;} /* r-d */
  6956. case DEC_ROUND_05UP: {
  6957. needmax=1; /* never Infinity */
  6958. break;} /* r-05 */
  6959. case DEC_ROUND_CEILING: {
  6960. if (sign) needmax=1; /* Infinity if non-negative */
  6961. break;} /* r-c */
  6962. case DEC_ROUND_FLOOR: {
  6963. if (!sign) needmax=1; /* Infinity if negative */
  6964. break;} /* r-f */
  6965. default: break; /* Infinity in all other cases */
  6966. }
  6967. if (needmax) {
  6968. decSetMaxValue(dn, set);
  6969. dn->bits=sign; /* set sign */
  6970. }
  6971. else dn->bits=sign|DECINF; /* Value is +/-Infinity */
  6972. *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
  6973. } /* decSetOverflow */
  6974. /* ------------------------------------------------------------------ */
  6975. /* decSetMaxValue -- set number to +Nmax (maximum normal value) */
  6976. /* */
  6977. /* dn is the number to set */
  6978. /* set is the context [used for digits and emax] */
  6979. /* */
  6980. /* This sets the number to the maximum positive value. */
  6981. /* ------------------------------------------------------------------ */
  6982. static void decSetMaxValue(decNumber *dn, decContext *set) {
  6983. Unit *up; /* work */
  6984. Int count=set->digits; /* nines to add */
  6985. dn->digits=count;
  6986. /* fill in all nines to set maximum value */
  6987. for (up=dn->lsu; ; up++) {
  6988. if (count>DECDPUN) *up=DECDPUNMAX; /* unit full o'nines */
  6989. else { /* this is the msu */
  6990. *up=(Unit)(powers[count]-1);
  6991. break;
  6992. }
  6993. count-=DECDPUN; /* filled those digits */
  6994. } /* up */
  6995. dn->bits=0; /* + sign */
  6996. dn->exponent=set->emax-set->digits+1;
  6997. } /* decSetMaxValue */
  6998. /* ------------------------------------------------------------------ */
  6999. /* decSetSubnormal -- process value whose exponent is <Emin */
  7000. /* */
  7001. /* dn is the number (used as input as well as output; it may have */
  7002. /* an allowed subnormal value, which may need to be rounded) */
  7003. /* set is the context [used for the rounding mode] */
  7004. /* residue is any pending residue */
  7005. /* status contains the current status to be updated */
  7006. /* */
  7007. /* If subset mode, set result to zero and set Underflow flags. */
  7008. /* */
  7009. /* Value may be zero with a low exponent; this does not set Subnormal */
  7010. /* but the exponent will be clamped to Etiny. */
  7011. /* */
  7012. /* Otherwise ensure exponent is not out of range, and round as */
  7013. /* necessary. Underflow is set if the result is Inexact. */
  7014. /* ------------------------------------------------------------------ */
  7015. static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
  7016. uInt *status) {
  7017. decContext workset; /* work */
  7018. Int etiny, adjust; /* .. */
  7019. #if DECSUBSET
  7020. /* simple set to zero and 'hard underflow' for subset */
  7021. if (!set->extended) {
  7022. uprv_decNumberZero(dn);
  7023. /* always full overflow */
  7024. *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
  7025. return;
  7026. }
  7027. #endif
  7028. /* Full arithmetic -- allow subnormals, rounded to minimum exponent */
  7029. /* (Etiny) if needed */
  7030. etiny=set->emin-(set->digits-1); /* smallest allowed exponent */
  7031. if ISZERO(dn) { /* value is zero */
  7032. /* residue can never be non-zero here */
  7033. #if DECCHECK
  7034. if (*residue!=0) {
  7035. printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
  7036. *status|=DEC_Invalid_operation;
  7037. }
  7038. #endif
  7039. if (dn->exponent<etiny) { /* clamp required */
  7040. dn->exponent=etiny;
  7041. *status|=DEC_Clamped;
  7042. }
  7043. return;
  7044. }
  7045. *status|=DEC_Subnormal; /* have a non-zero subnormal */
  7046. adjust=etiny-dn->exponent; /* calculate digits to remove */
  7047. if (adjust<=0) { /* not out of range; unrounded */
  7048. /* residue can never be non-zero here, except in the Nmin-residue */
  7049. /* case (which is a subnormal result), so can take fast-path here */
  7050. /* it may already be inexact (from setting the coefficient) */
  7051. if (*status&DEC_Inexact) *status|=DEC_Underflow;
  7052. return;
  7053. }
  7054. /* adjust>0, so need to rescale the result so exponent becomes Etiny */
  7055. /* [this code is similar to that in rescale] */
  7056. workset=*set; /* clone rounding, etc. */
  7057. workset.digits=dn->digits-adjust; /* set requested length */
  7058. workset.emin-=adjust; /* and adjust emin to match */
  7059. /* [note that the latter can be <1, here, similar to Rescale case] */
  7060. decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
  7061. decApplyRound(dn, &workset, *residue, status);
  7062. /* Use 754 default rule: Underflow is set iff Inexact */
  7063. /* [independent of whether trapped] */
  7064. if (*status&DEC_Inexact) *status|=DEC_Underflow;
  7065. /* if rounded up a 999s case, exponent will be off by one; adjust */
  7066. /* back if so [it will fit, because it was shortened earlier] */
  7067. if (dn->exponent>etiny) {
  7068. dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
  7069. dn->exponent--; /* (re)adjust the exponent. */
  7070. }
  7071. /* if rounded to zero, it is by definition clamped... */
  7072. if (ISZERO(dn)) *status|=DEC_Clamped;
  7073. } /* decSetSubnormal */
  7074. /* ------------------------------------------------------------------ */
  7075. /* decCheckMath - check entry conditions for a math function */
  7076. /* */
  7077. /* This checks the context and the operand */
  7078. /* */
  7079. /* rhs is the operand to check */
  7080. /* set is the context to check */
  7081. /* status is unchanged if both are good */
  7082. /* */
  7083. /* returns non-zero if status is changed, 0 otherwise */
  7084. /* */
  7085. /* Restrictions enforced: */
  7086. /* */
  7087. /* digits, emax, and -emin in the context must be less than */
  7088. /* DEC_MAX_MATH (999999), and A must be within these bounds if */
  7089. /* non-zero. Invalid_operation is set in the status if a */
  7090. /* restriction is violated. */
  7091. /* ------------------------------------------------------------------ */
  7092. static uInt decCheckMath(const decNumber *rhs, decContext *set,
  7093. uInt *status) {
  7094. uInt save=*status; /* record */
  7095. if (set->digits>DEC_MAX_MATH
  7096. || set->emax>DEC_MAX_MATH
  7097. || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
  7098. else if ((rhs->digits>DEC_MAX_MATH
  7099. || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
  7100. || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
  7101. && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
  7102. return (*status!=save);
  7103. } /* decCheckMath */
  7104. /* ------------------------------------------------------------------ */
  7105. /* decGetInt -- get integer from a number */
  7106. /* */
  7107. /* dn is the number [which will not be altered] */
  7108. /* */
  7109. /* returns one of: */
  7110. /* BADINT if there is a non-zero fraction */
  7111. /* the converted integer */
  7112. /* BIGEVEN if the integer is even and magnitude > 2*10**9 */
  7113. /* BIGODD if the integer is odd and magnitude > 2*10**9 */
  7114. /* */
  7115. /* This checks and gets a whole number from the input decNumber. */
  7116. /* The sign can be determined from dn by the caller when BIGEVEN or */
  7117. /* BIGODD is returned. */
  7118. /* ------------------------------------------------------------------ */
  7119. static Int decGetInt(const decNumber *dn) {
  7120. Int theInt; /* result accumulator */
  7121. const Unit *up; /* work */
  7122. Int got; /* digits (real or not) processed */
  7123. Int ilength=dn->digits+dn->exponent; /* integral length */
  7124. Flag neg=decNumberIsNegative(dn); /* 1 if -ve */
  7125. /* The number must be an integer that fits in 10 digits */
  7126. /* Assert, here, that 10 is enough for any rescale Etiny */
  7127. #if DEC_MAX_EMAX > 999999999
  7128. #error GetInt may need updating [for Emax]
  7129. #endif
  7130. #if DEC_MIN_EMIN < -999999999
  7131. #error GetInt may need updating [for Emin]
  7132. #endif
  7133. if (ISZERO(dn)) return 0; /* zeros are OK, with any exponent */
  7134. up=dn->lsu; /* ready for lsu */
  7135. theInt=0; /* ready to accumulate */
  7136. if (dn->exponent>=0) { /* relatively easy */
  7137. /* no fractional part [usual]; allow for positive exponent */
  7138. got=dn->exponent;
  7139. }
  7140. else { /* -ve exponent; some fractional part to check and discard */
  7141. Int count=-dn->exponent; /* digits to discard */
  7142. /* spin up whole units until reach the Unit with the unit digit */
  7143. for (; count>=DECDPUN; up++) {
  7144. if (*up!=0) return BADINT; /* non-zero Unit to discard */
  7145. count-=DECDPUN;
  7146. }
  7147. if (count==0) got=0; /* [a multiple of DECDPUN] */
  7148. else { /* [not multiple of DECDPUN] */
  7149. Int rem; /* work */
  7150. /* slice off fraction digits and check for non-zero */
  7151. #if DECDPUN<=4
  7152. theInt=QUOT10(*up, count);
  7153. rem=*up-theInt*powers[count];
  7154. #else
  7155. rem=*up%powers[count]; /* slice off discards */
  7156. theInt=*up/powers[count];
  7157. #endif
  7158. if (rem!=0) return BADINT; /* non-zero fraction */
  7159. /* it looks good */
  7160. got=DECDPUN-count; /* number of digits so far */
  7161. up++; /* ready for next */
  7162. }
  7163. }
  7164. /* now it's known there's no fractional part */
  7165. /* tricky code now, to accumulate up to 9.3 digits */
  7166. if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there */
  7167. if (ilength<11) {
  7168. Int save=theInt;
  7169. /* collect any remaining unit(s) */
  7170. for (; got<ilength; up++) {
  7171. theInt+=*up*powers[got];
  7172. got+=DECDPUN;
  7173. }
  7174. if (ilength==10) { /* need to check for wrap */
  7175. if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
  7176. /* [that test also disallows the BADINT result case] */
  7177. else if (neg && theInt>1999999997) ilength=11;
  7178. else if (!neg && theInt>999999999) ilength=11;
  7179. if (ilength==11) theInt=save; /* restore correct low bit */
  7180. }
  7181. }
  7182. if (ilength>10) { /* too big */
  7183. if (theInt&1) return BIGODD; /* bottom bit 1 */
  7184. return BIGEVEN; /* bottom bit 0 */
  7185. }
  7186. if (neg) theInt=-theInt; /* apply sign */
  7187. return theInt;
  7188. } /* decGetInt */
  7189. /* ------------------------------------------------------------------ */
  7190. /* decDecap -- decapitate the coefficient of a number */
  7191. /* */
  7192. /* dn is the number to be decapitated */
  7193. /* drop is the number of digits to be removed from the left of dn; */
  7194. /* this must be <= dn->digits (if equal, the coefficient is */
  7195. /* set to 0) */
  7196. /* */
  7197. /* Returns dn; dn->digits will be <= the initial digits less drop */
  7198. /* (after removing drop digits there may be leading zero digits */
  7199. /* which will also be removed). Only dn->lsu and dn->digits change. */
  7200. /* ------------------------------------------------------------------ */
  7201. static decNumber *decDecap(decNumber *dn, Int drop) {
  7202. Unit *msu; /* -> target cut point */
  7203. Int cut; /* work */
  7204. if (drop>=dn->digits) { /* losing the whole thing */
  7205. #if DECCHECK
  7206. if (drop>dn->digits)
  7207. printf("decDecap called with drop>digits [%ld>%ld]\n",
  7208. (LI)drop, (LI)dn->digits);
  7209. #endif
  7210. dn->lsu[0]=0;
  7211. dn->digits=1;
  7212. return dn;
  7213. }
  7214. msu=dn->lsu+D2U(dn->digits-drop)-1; /* -> likely msu */
  7215. cut=MSUDIGITS(dn->digits-drop); /* digits to be in use in msu */
  7216. if (cut!=DECDPUN) *msu%=powers[cut]; /* clear left digits */
  7217. /* that may have left leading zero digits, so do a proper count... */
  7218. dn->digits=decGetDigits(dn->lsu, static_cast<int32_t>(msu-dn->lsu+1));
  7219. return dn;
  7220. } /* decDecap */
  7221. /* ------------------------------------------------------------------ */
  7222. /* decBiStr -- compare string with pairwise options */
  7223. /* */
  7224. /* targ is the string to compare */
  7225. /* str1 is one of the strings to compare against (length may be 0) */
  7226. /* str2 is the other; it must be the same length as str1 */
  7227. /* */
  7228. /* returns 1 if strings compare equal, (that is, it is the same */
  7229. /* length as str1 and str2, and each character of targ is in either */
  7230. /* str1 or str2 in the corresponding position), or 0 otherwise */
  7231. /* */
  7232. /* This is used for generic caseless compare, including the awkward */
  7233. /* case of the Turkish dotted and dotless Is. Use as (for example): */
  7234. /* if (decBiStr(test, "mike", "MIKE")) ... */
  7235. /* ------------------------------------------------------------------ */
  7236. static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
  7237. for (;;targ++, str1++, str2++) {
  7238. if (*targ!=*str1 && *targ!=*str2) return 0;
  7239. /* *targ has a match in one (or both, if terminator) */
  7240. if (*targ=='\0') break;
  7241. } /* forever */
  7242. return 1;
  7243. } /* decBiStr */
  7244. /* ------------------------------------------------------------------ */
  7245. /* decNaNs -- handle NaN operand or operands */
  7246. /* */
  7247. /* res is the result number */
  7248. /* lhs is the first operand */
  7249. /* rhs is the second operand, or nullptr if none */
  7250. /* context is used to limit payload length */
  7251. /* status contains the current status */
  7252. /* returns res in case convenient */
  7253. /* */
  7254. /* Called when one or both operands is a NaN, and propagates the */
  7255. /* appropriate result to res. When an sNaN is found, it is changed */
  7256. /* to a qNaN and Invalid operation is set. */
  7257. /* ------------------------------------------------------------------ */
  7258. static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
  7259. const decNumber *rhs, decContext *set,
  7260. uInt *status) {
  7261. /* This decision tree ends up with LHS being the source pointer, */
  7262. /* and status updated if need be */
  7263. if (lhs->bits & DECSNAN)
  7264. *status|=DEC_Invalid_operation | DEC_sNaN;
  7265. else if (rhs==nullptr);
  7266. else if (rhs->bits & DECSNAN) {
  7267. lhs=rhs;
  7268. *status|=DEC_Invalid_operation | DEC_sNaN;
  7269. }
  7270. else if (lhs->bits & DECNAN);
  7271. else lhs=rhs;
  7272. /* propagate the payload */
  7273. if (lhs->digits<=set->digits) uprv_decNumberCopy(res, lhs); /* easy */
  7274. else { /* too long */
  7275. const Unit *ul;
  7276. Unit *ur, *uresp1;
  7277. /* copy safe number of units, then decapitate */
  7278. res->bits=lhs->bits; /* need sign etc. */
  7279. uresp1=res->lsu+D2U(set->digits);
  7280. for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
  7281. res->digits=D2U(set->digits)*DECDPUN;
  7282. /* maybe still too long */
  7283. if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
  7284. }
  7285. res->bits&=~DECSNAN; /* convert any sNaN to NaN, while */
  7286. res->bits|=DECNAN; /* .. preserving sign */
  7287. res->exponent=0; /* clean exponent */
  7288. /* [coefficient was copied/decapitated] */
  7289. return res;
  7290. } /* decNaNs */
  7291. /* ------------------------------------------------------------------ */
  7292. /* decStatus -- apply non-zero status */
  7293. /* */
  7294. /* dn is the number to set if error */
  7295. /* status contains the current status (not yet in context) */
  7296. /* set is the context */
  7297. /* */
  7298. /* If the status is an error status, the number is set to a NaN, */
  7299. /* unless the error was an overflow, divide-by-zero, or underflow, */
  7300. /* in which case the number will have already been set. */
  7301. /* */
  7302. /* The context status is then updated with the new status. Note that */
  7303. /* this may raise a signal, so control may never return from this */
  7304. /* routine (hence resources must be recovered before it is called). */
  7305. /* ------------------------------------------------------------------ */
  7306. static void decStatus(decNumber *dn, uInt status, decContext *set) {
  7307. if (status & DEC_NaNs) { /* error status -> NaN */
  7308. /* if cause was an sNaN, clear and propagate [NaN is already set up] */
  7309. if (status & DEC_sNaN) status&=~DEC_sNaN;
  7310. else {
  7311. uprv_decNumberZero(dn); /* other error: clean throughout */
  7312. dn->bits=DECNAN; /* and make a quiet NaN */
  7313. }
  7314. }
  7315. uprv_decContextSetStatus(set, status); /* [may not return] */
  7316. return;
  7317. } /* decStatus */
  7318. /* ------------------------------------------------------------------ */
  7319. /* decGetDigits -- count digits in a Units array */
  7320. /* */
  7321. /* uar is the Unit array holding the number (this is often an */
  7322. /* accumulator of some sort) */
  7323. /* len is the length of the array in units [>=1] */
  7324. /* */
  7325. /* returns the number of (significant) digits in the array */
  7326. /* */
  7327. /* All leading zeros are excluded, except the last if the array has */
  7328. /* only zero Units. */
  7329. /* ------------------------------------------------------------------ */
  7330. /* This may be called twice during some operations. */
  7331. static Int decGetDigits(Unit *uar, Int len) {
  7332. Unit *up=uar+(len-1); /* -> msu */
  7333. Int digits=(len-1)*DECDPUN+1; /* possible digits excluding msu */
  7334. #if DECDPUN>4
  7335. uInt const *pow; /* work */
  7336. #endif
  7337. /* (at least 1 in final msu) */
  7338. #if DECCHECK
  7339. if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
  7340. #endif
  7341. for (; up>=uar; up--) {
  7342. if (*up==0) { /* unit is all 0s */
  7343. if (digits==1) break; /* a zero has one digit */
  7344. digits-=DECDPUN; /* adjust for 0 unit */
  7345. continue;}
  7346. /* found the first (most significant) non-zero Unit */
  7347. #if DECDPUN>1 /* not done yet */
  7348. if (*up<10) break; /* is 1-9 */
  7349. digits++;
  7350. #if DECDPUN>2 /* not done yet */
  7351. if (*up<100) break; /* is 10-99 */
  7352. digits++;
  7353. #if DECDPUN>3 /* not done yet */
  7354. if (*up<1000) break; /* is 100-999 */
  7355. digits++;
  7356. #if DECDPUN>4 /* count the rest ... */
  7357. for (pow=&powers[4]; *up>=*pow; pow++) digits++;
  7358. #endif
  7359. #endif
  7360. #endif
  7361. #endif
  7362. break;
  7363. } /* up */
  7364. return digits;
  7365. } /* decGetDigits */
  7366. #if DECTRACE | DECCHECK
  7367. /* ------------------------------------------------------------------ */
  7368. /* decNumberShow -- display a number [debug aid] */
  7369. /* dn is the number to show */
  7370. /* */
  7371. /* Shows: sign, exponent, coefficient (msu first), digits */
  7372. /* or: sign, special-value */
  7373. /* ------------------------------------------------------------------ */
  7374. /* this is public so other modules can use it */
  7375. void uprv_decNumberShow(const decNumber *dn) {
  7376. const Unit *up; /* work */
  7377. uInt u, d; /* .. */
  7378. Int cut; /* .. */
  7379. char isign='+'; /* main sign */
  7380. if (dn==nullptr) {
  7381. printf("nullptr\n");
  7382. return;}
  7383. if (decNumberIsNegative(dn)) isign='-';
  7384. printf(" >> %c ", isign);
  7385. if (dn->bits&DECSPECIAL) { /* Is a special value */
  7386. if (decNumberIsInfinite(dn)) printf("Infinity");
  7387. else { /* a NaN */
  7388. if (dn->bits&DECSNAN) printf("sNaN"); /* signalling NaN */
  7389. else printf("NaN");
  7390. }
  7391. /* if coefficient and exponent are 0, no more to do */
  7392. if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
  7393. printf("\n");
  7394. return;}
  7395. /* drop through to report other information */
  7396. printf(" ");
  7397. }
  7398. /* now carefully display the coefficient */
  7399. up=dn->lsu+D2U(dn->digits)-1; /* msu */
  7400. printf("%ld", (LI)*up);
  7401. for (up=up-1; up>=dn->lsu; up--) {
  7402. u=*up;
  7403. printf(":");
  7404. for (cut=DECDPUN-1; cut>=0; cut--) {
  7405. d=u/powers[cut];
  7406. u-=d*powers[cut];
  7407. printf("%ld", (LI)d);
  7408. } /* cut */
  7409. } /* up */
  7410. if (dn->exponent!=0) {
  7411. char esign='+';
  7412. if (dn->exponent<0) esign='-';
  7413. printf(" E%c%ld", esign, (LI)abs(dn->exponent));
  7414. }
  7415. printf(" [%ld]\n", (LI)dn->digits);
  7416. } /* decNumberShow */
  7417. #endif
  7418. #if DECTRACE || DECCHECK
  7419. /* ------------------------------------------------------------------ */
  7420. /* decDumpAr -- display a unit array [debug/check aid] */
  7421. /* name is a single-character tag name */
  7422. /* ar is the array to display */
  7423. /* len is the length of the array in Units */
  7424. /* ------------------------------------------------------------------ */
  7425. static void decDumpAr(char name, const Unit *ar, Int len) {
  7426. Int i;
  7427. const char *spec;
  7428. #if DECDPUN==9
  7429. spec="%09d ";
  7430. #elif DECDPUN==8
  7431. spec="%08d ";
  7432. #elif DECDPUN==7
  7433. spec="%07d ";
  7434. #elif DECDPUN==6
  7435. spec="%06d ";
  7436. #elif DECDPUN==5
  7437. spec="%05d ";
  7438. #elif DECDPUN==4
  7439. spec="%04d ";
  7440. #elif DECDPUN==3
  7441. spec="%03d ";
  7442. #elif DECDPUN==2
  7443. spec="%02d ";
  7444. #else
  7445. spec="%d ";
  7446. #endif
  7447. printf(" :%c: ", name);
  7448. for (i=len-1; i>=0; i--) {
  7449. if (i==len-1) printf("%ld ", (LI)ar[i]);
  7450. else printf(spec, ar[i]);
  7451. }
  7452. printf("\n");
  7453. return;}
  7454. #endif
  7455. #if DECCHECK
  7456. /* ------------------------------------------------------------------ */
  7457. /* decCheckOperands -- check operand(s) to a routine */
  7458. /* res is the result structure (not checked; it will be set to */
  7459. /* quiet NaN if error found (and it is not nullptr)) */
  7460. /* lhs is the first operand (may be DECUNRESU) */
  7461. /* rhs is the second (may be DECUNUSED) */
  7462. /* set is the context (may be DECUNCONT) */
  7463. /* returns 0 if both operands, and the context are clean, or 1 */
  7464. /* otherwise (in which case the context will show an error, */
  7465. /* unless nullptr). Note that res is not cleaned; caller should */
  7466. /* handle this so res=nullptr case is safe. */
  7467. /* The caller is expected to abandon immediately if 1 is returned. */
  7468. /* ------------------------------------------------------------------ */
  7469. static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
  7470. const decNumber *rhs, decContext *set) {
  7471. Flag bad=0;
  7472. if (set==nullptr) { /* oops; hopeless */
  7473. #if DECTRACE || DECVERB
  7474. printf("Reference to context is nullptr.\n");
  7475. #endif
  7476. bad=1;
  7477. return 1;}
  7478. else if (set!=DECUNCONT
  7479. && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
  7480. bad=1;
  7481. #if DECTRACE || DECVERB
  7482. printf("Bad context [digits=%ld round=%ld].\n",
  7483. (LI)set->digits, (LI)set->round);
  7484. #endif
  7485. }
  7486. else {
  7487. if (res==nullptr) {
  7488. bad=1;
  7489. #if DECTRACE
  7490. /* this one not DECVERB as standard tests include nullptr */
  7491. printf("Reference to result is nullptr.\n");
  7492. #endif
  7493. }
  7494. if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
  7495. if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
  7496. }
  7497. if (bad) {
  7498. if (set!=DECUNCONT) uprv_decContextSetStatus(set, DEC_Invalid_operation);
  7499. if (res!=DECUNRESU && res!=nullptr) {
  7500. uprv_decNumberZero(res);
  7501. res->bits=DECNAN; /* qNaN */
  7502. }
  7503. }
  7504. return bad;
  7505. } /* decCheckOperands */
  7506. /* ------------------------------------------------------------------ */
  7507. /* decCheckNumber -- check a number */
  7508. /* dn is the number to check */
  7509. /* returns 0 if the number is clean, or 1 otherwise */
  7510. /* */
  7511. /* The number is considered valid if it could be a result from some */
  7512. /* operation in some valid context. */
  7513. /* ------------------------------------------------------------------ */
  7514. static Flag decCheckNumber(const decNumber *dn) {
  7515. const Unit *up; /* work */
  7516. uInt maxuint; /* .. */
  7517. Int ae, d, digits; /* .. */
  7518. Int emin, emax; /* .. */
  7519. if (dn==nullptr) { /* hopeless */
  7520. #if DECTRACE
  7521. /* this one not DECVERB as standard tests include nullptr */
  7522. printf("Reference to decNumber is nullptr.\n");
  7523. #endif
  7524. return 1;}
  7525. /* check special values */
  7526. if (dn->bits & DECSPECIAL) {
  7527. if (dn->exponent!=0) {
  7528. #if DECTRACE || DECVERB
  7529. printf("Exponent %ld (not 0) for a special value [%02x].\n",
  7530. (LI)dn->exponent, dn->bits);
  7531. #endif
  7532. return 1;}
  7533. /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only */
  7534. if (decNumberIsInfinite(dn)) {
  7535. if (dn->digits!=1) {
  7536. #if DECTRACE || DECVERB
  7537. printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
  7538. #endif
  7539. return 1;}
  7540. if (*dn->lsu!=0) {
  7541. #if DECTRACE || DECVERB
  7542. printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
  7543. #endif
  7544. decDumpAr('I', dn->lsu, D2U(dn->digits));
  7545. return 1;}
  7546. } /* Inf */
  7547. /* 2002.12.26: negative NaNs can now appear through proposed IEEE */
  7548. /* concrete formats (decimal64, etc.). */
  7549. return 0;
  7550. }
  7551. /* check the coefficient */
  7552. if (dn->digits<1 || dn->digits>DECNUMMAXP) {
  7553. #if DECTRACE || DECVERB
  7554. printf("Digits %ld in number.\n", (LI)dn->digits);
  7555. #endif
  7556. return 1;}
  7557. d=dn->digits;
  7558. for (up=dn->lsu; d>0; up++) {
  7559. if (d>DECDPUN) maxuint=DECDPUNMAX;
  7560. else { /* reached the msu */
  7561. maxuint=powers[d]-1;
  7562. if (dn->digits>1 && *up<powers[d-1]) {
  7563. #if DECTRACE || DECVERB
  7564. printf("Leading 0 in number.\n");
  7565. uprv_decNumberShow(dn);
  7566. #endif
  7567. return 1;}
  7568. }
  7569. if (*up>maxuint) {
  7570. #if DECTRACE || DECVERB
  7571. printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
  7572. (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
  7573. #endif
  7574. return 1;}
  7575. d-=DECDPUN;
  7576. }
  7577. /* check the exponent. Note that input operands can have exponents */
  7578. /* which are out of the set->emin/set->emax and set->digits range */
  7579. /* (just as they can have more digits than set->digits). */
  7580. ae=dn->exponent+dn->digits-1; /* adjusted exponent */
  7581. emax=DECNUMMAXE;
  7582. emin=DECNUMMINE;
  7583. digits=DECNUMMAXP;
  7584. if (ae<emin-(digits-1)) {
  7585. #if DECTRACE || DECVERB
  7586. printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
  7587. uprv_decNumberShow(dn);
  7588. #endif
  7589. return 1;}
  7590. if (ae>+emax) {
  7591. #if DECTRACE || DECVERB
  7592. printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
  7593. uprv_decNumberShow(dn);
  7594. #endif
  7595. return 1;}
  7596. return 0; /* it's OK */
  7597. } /* decCheckNumber */
  7598. /* ------------------------------------------------------------------ */
  7599. /* decCheckInexact -- check a normal finite inexact result has digits */
  7600. /* dn is the number to check */
  7601. /* set is the context (for status and precision) */
  7602. /* sets Invalid operation, etc., if some digits are missing */
  7603. /* [this check is not made for DECSUBSET compilation or when */
  7604. /* subnormal is not set] */
  7605. /* ------------------------------------------------------------------ */
  7606. static void decCheckInexact(const decNumber *dn, decContext *set) {
  7607. #if !DECSUBSET && DECEXTFLAG
  7608. if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
  7609. && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
  7610. #if DECTRACE || DECVERB
  7611. printf("Insufficient digits [%ld] on normal Inexact result.\n",
  7612. (LI)dn->digits);
  7613. uprv_decNumberShow(dn);
  7614. #endif
  7615. uprv_decContextSetStatus(set, DEC_Invalid_operation);
  7616. }
  7617. #else
  7618. /* next is a noop for quiet compiler */
  7619. if (dn!=nullptr && dn->digits==0) set->status|=DEC_Invalid_operation;
  7620. #endif
  7621. return;
  7622. } /* decCheckInexact */
  7623. #endif
  7624. #if DECALLOC
  7625. #undef malloc
  7626. #undef free
  7627. /* ------------------------------------------------------------------ */
  7628. /* decMalloc -- accountable allocation routine */
  7629. /* n is the number of bytes to allocate */
  7630. /* */
  7631. /* Semantics is the same as the stdlib malloc routine, but bytes */
  7632. /* allocated are accounted for globally, and corruption fences are */
  7633. /* added before and after the 'actual' storage. */
  7634. /* ------------------------------------------------------------------ */
  7635. /* This routine allocates storage with an extra twelve bytes; 8 are */
  7636. /* at the start and hold: */
  7637. /* 0-3 the original length requested */
  7638. /* 4-7 buffer corruption detection fence (DECFENCE, x4) */
  7639. /* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
  7640. /* ------------------------------------------------------------------ */
  7641. static void *decMalloc(size_t n) {
  7642. uInt size=n+12; /* true size */
  7643. void *alloc; /* -> allocated storage */
  7644. uByte *b, *b0; /* work */
  7645. uInt uiwork; /* for macros */
  7646. alloc=malloc(size); /* -> allocated storage */
  7647. if (alloc==nullptr) return nullptr; /* out of strorage */
  7648. b0=(uByte *)alloc; /* as bytes */
  7649. decAllocBytes+=n; /* account for storage */
  7650. UBFROMUI(alloc, n); /* save n */
  7651. /* printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n); */
  7652. for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
  7653. for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
  7654. return b0+8; /* -> play area */
  7655. } /* decMalloc */
  7656. /* ------------------------------------------------------------------ */
  7657. /* decFree -- accountable free routine */
  7658. /* alloc is the storage to free */
  7659. /* */
  7660. /* Semantics is the same as the stdlib malloc routine, except that */
  7661. /* the global storage accounting is updated and the fences are */
  7662. /* checked to ensure that no routine has written 'out of bounds'. */
  7663. /* ------------------------------------------------------------------ */
  7664. /* This routine first checks that the fences have not been corrupted. */
  7665. /* It then frees the storage using the 'truw' storage address (that */
  7666. /* is, offset by 8). */
  7667. /* ------------------------------------------------------------------ */
  7668. static void decFree(void *alloc) {
  7669. uInt n; /* original length */
  7670. uByte *b, *b0; /* work */
  7671. uInt uiwork; /* for macros */
  7672. if (alloc==nullptr) return; /* allowed; it's a nop */
  7673. b0=(uByte *)alloc; /* as bytes */
  7674. b0-=8; /* -> true start of storage */
  7675. n=UBTOUI(b0); /* lift length */
  7676. for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
  7677. printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
  7678. b-b0-8, (LI)b0);
  7679. for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
  7680. printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
  7681. b-b0-8, (LI)b0, (LI)n);
  7682. free(b0); /* drop the storage */
  7683. decAllocBytes-=n; /* account for storage */
  7684. /* printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n); */
  7685. } /* decFree */
  7686. #define malloc(a) decMalloc(a)
  7687. #define free(a) decFree(a)
  7688. #endif