sysutils.pas 208 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905
  1. {
  2. This file is part of the Pas2JS run time library.
  3. Copyright (c) 2017 by Mattias Gaertner
  4. See the file COPYING.FPC, included in this distribution,
  5. for details about the copyright.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9. **********************************************************************}
  10. unit SysUtils;
  11. {$mode objfpc}
  12. {$modeswitch typehelpers}
  13. {$modeswitch advancedrecords}
  14. interface
  15. uses
  16. RTLConsts, js;
  17. procedure FreeAndNil(var Obj);
  18. type
  19. TProcedure = procedure;
  20. {*****************************************************************************
  21. Various types
  22. *****************************************************************************}
  23. Const
  24. FloatRecDigits = 19;
  25. type
  26. { TFloatRec }
  27. TFloatRec = Record
  28. Exponent: Integer;
  29. Negative: Boolean;
  30. Digits: Array[0..FloatRecDigits-1] of Char;
  31. End;
  32. TEndian = (Little,Big);
  33. TFileName = String;
  34. TByteArray = array [0..32767] of Byte;
  35. TWordArray = array [0..16383] of Word;
  36. TBytes = Array of byte;
  37. TStringArray = array of string;
  38. TMonthNameArray = array [1..12] of string;
  39. TDayTable = array [1..12] of Word;
  40. TWeekNameArray = array [1..7] of string;
  41. TMonthNames = TMonthNameArray;
  42. TDayNames = array[0..6] of string;
  43. {*****************************************************************************
  44. Exception handling
  45. *****************************************************************************}
  46. { Exception }
  47. Exception = class(TObject)
  48. private
  49. fMessage: String;
  50. fHelpContext: Integer;
  51. {$ifdef NodeJS}
  52. FNodeJSError: TJSError;
  53. {$endif}
  54. public
  55. class var
  56. LogMessageOnCreate : Boolean;
  57. Public
  58. constructor Create(const Msg: String); reintroduce;
  59. constructor CreateFmt(const Msg: string; const Args: array of jsvalue);
  60. constructor CreateHelp(const Msg: String; AHelpContext: Integer);
  61. constructor CreateFmtHelp(const Msg: string; const Args: array of jsvalue; AHelpContext: Integer);
  62. function ToString: String; override;
  63. property HelpContext: Integer read fHelpContext write fHelpContext;
  64. property Message: String read fMessage write fMessage;
  65. {$ifdef NodeJS}
  66. property NodeJSError: TJSError read FNodeJSError write FNodeJSError;
  67. {$endif}
  68. end;
  69. ExceptClass = class of Exception;
  70. EExternal = class(Exception);
  71. { General math errors }
  72. EMathError = class(EExternal);
  73. EInvalidOp = class(EMathError);
  74. EZeroDivide = class(EMathError);
  75. EOverflow = class(EMathError);
  76. EUnderflow = class(EMathError);
  77. EAbort = class(Exception);
  78. EInvalidCast = class(Exception);
  79. EAssertionFailed = class(Exception);
  80. EObjectCheck = class(Exception);
  81. { String conversion errors }
  82. EConvertError = class(Exception);
  83. EFormatError = class(Exception);
  84. { integer math exceptions }
  85. EIntError = Class(EExternal);
  86. EDivByZero = Class(EIntError);
  87. ERangeError = Class(EIntError);
  88. EIntOverflow = Class(EIntError);
  89. { General math errors }
  90. { Run-time and I/O Errors }
  91. EInOutError = class(Exception)
  92. public
  93. ErrorCode : Integer;
  94. end;
  95. EHeapMemoryError = class(Exception);
  96. EHeapException = EHeapMemoryError;
  97. EExternalException = class(EExternal);
  98. EInvalidPointer = Class(EHeapMemoryError);
  99. EOutOfMemory = Class(EHeapMemoryError);
  100. { EVariantError }
  101. EVariantError = Class(Exception)
  102. ErrCode : longint;
  103. Constructor CreateCode(Code : Longint);
  104. end;
  105. EAccessViolation = Class(EExternal);
  106. EBusError = Class(EAccessViolation);
  107. EPrivilege = class(EExternal);
  108. EStackOverflow = class(EExternal);
  109. EControlC = class(EExternal);
  110. { String conversion errors }
  111. { Other errors }
  112. EAbstractError = Class(Exception);
  113. EPropReadOnly = class(Exception);
  114. EPropWriteOnly = class(Exception);
  115. EIntfCastError = class(Exception);
  116. EInvalidContainer = class(Exception);
  117. EInvalidInsert = class(Exception);
  118. EPackageError = class(Exception);
  119. EOSError = class(Exception)
  120. public
  121. ErrorCode: Longint;
  122. end;
  123. ESafecallException = class(Exception);
  124. ENoThreadSupport = Class(Exception);
  125. ENoWideStringSupport = Class(Exception);
  126. ENotImplemented = class(Exception);
  127. EArgumentException = class(Exception);
  128. EArgumentOutOfRangeException = class(EArgumentException);
  129. EArgumentNilException = class(EArgumentException);
  130. EPathTooLongException = class(Exception);
  131. ENotSupportedException = class(Exception);
  132. EDirectoryNotFoundException = class(Exception);
  133. EFileNotFoundException = class(Exception);
  134. EPathNotFoundException = class(Exception);
  135. ENoConstructException = class(Exception);
  136. //function GetTickCount: Integer;
  137. {*****************************************************************************
  138. String function
  139. *****************************************************************************}
  140. Const
  141. EmptyStr = '';
  142. EmptyWideStr = ''; // No difference here.
  143. HexDisplayPrefix: string = '$';
  144. LeadBytes = [] unimplemented;
  145. Function CharInSet(Ch: Char;Const CSet : array of char) : Boolean;
  146. function LeftStr(const S: string; Count: Integer): String; assembler;
  147. function RightStr(const S: string; Count: Integer): String; assembler;
  148. function Trim(const S: String): String; assembler;
  149. function TrimLeft(const S: String): String; assembler;
  150. function TrimRight(const S: String): String; assembler;
  151. function UpperCase(const s: String): String; assembler; overload;
  152. function LowerCase(const s: String): String; assembler; overload;
  153. function CompareStr(const s1, s2: String): Integer; assembler;
  154. function SameStr(const s1, s2: String): Boolean; assembler;
  155. function CompareText(const s1, s2: String): Integer; assembler;
  156. function SameText(const s1, s2: String): Boolean; assembler;
  157. function AnsiCompareText(const s1, s2: String): Integer; assembler;
  158. function AnsiSameText(const s1, s2: String): Boolean; assembler;
  159. function AnsiCompareStr(const s1, s2: String): Integer;
  160. procedure AppendStr(var Dest: String; const S: string);
  161. function Format(const Fmt: String; const Args: array of JSValue): String;
  162. function BytesOf(const AVal: string): TBytes;
  163. function StringOf(const ABytes: TBytes): string;
  164. // JavaScript built-in functions
  165. function LocaleCompare(const s1, s2, locales: String): Boolean; assembler; overload;
  166. function NormalizeStr(const S: String; const Norm: String = 'NFC'): String; assembler; overload; // not in IE
  167. function IsValidIdent(const Ident: string; AllowDots: Boolean = False; StrictDots: Boolean = False): Boolean;
  168. Type
  169. TStringReplaceFlag = (rfReplaceAll, rfIgnoreCase);
  170. TReplaceFlag = TStringReplaceFlag;
  171. TStringReplaceFlags = set of TStringReplaceFlag;
  172. TReplaceFlags = TStringReplaceFlags;
  173. function StringReplace(aOriginal, aSearch, aReplace: string; Flags: TStringReplaceFlags): String;
  174. function QuoteString(aOriginal: String; AQuote: Char): String;
  175. function QuotedStr(const s: string; QuoteChar: Char = ''''): string;
  176. function DeQuoteString(aQuoted: String; AQuote: Char): String;
  177. Function LastDelimiter(const Delimiters, S: string): SizeInt;
  178. function IsDelimiter(const Delimiters, S: string; Index: Integer): Boolean;
  179. function AdjustLineBreaks(const S: string): string;
  180. function AdjustLineBreaks(const S: string; Style: TTextLineBreakStyle): string;
  181. function WrapText(const Line, BreakStr: string; const BreakChars: Array of char; MaxCol: Integer): string;
  182. function WrapText(const Line: string; MaxCol: Integer): string;
  183. { *****************************************************************************
  184. Integer conversions
  185. *****************************************************************************}
  186. function IntToStr(const Value: Integer): string;
  187. Function TryStrToInt(const S : String; Out res : Integer) : Boolean;
  188. Function TryStrToInt(const S : String; Out res : NativeInt) : Boolean;
  189. Function StrToIntDef(const S : String; Const aDef : Integer) : Integer;
  190. Function StrToIntDef(const S : String; Const aDef : NativeInt) : NativeInt;
  191. Function StrToInt(const S : String) : Integer;
  192. Function StrToNativeInt(const S : String) : NativeInt;
  193. // For compatibility
  194. Function StrToInt64(const S : String) : NativeLargeInt;
  195. Function StrToInt64Def(const S : String; ADefault : NativeLargeInt) : NativeLargeInt;
  196. Function TryStrToInt64(const S : String; Out res : NativeLargeInt) : Boolean;
  197. Function StrToQWord(const S : String) : NativeLargeUInt;
  198. Function StrToQWordDef(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  199. Function TryStrToQWord(const S : String; Out res : NativeLargeUInt) : Boolean;
  200. Function StrToUInt64(const S : String) : NativeLargeUInt;
  201. Function StrToUInt64Def(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  202. Function TryStrToUInt64(const S : String; Out res : NativeLargeUInt) : Boolean;
  203. Function StrToDWord(const S : String) : DWord;
  204. Function StrToDWordDef(const S : String; ADefault : DWord) : DWord;
  205. Function TryStrToDWord(const S : String; Out res : DWord) : Boolean;
  206. function IntToHex(Value: NativeInt; Digits: Integer): string; overload;
  207. { *****************************************************************************
  208. Float conversions
  209. *****************************************************************************}
  210. const
  211. // Note: Currency is internally a double, multiplied by 10000 and truncated.
  212. // The below values are the safe limits, within every step exists.
  213. // Since currency is a double it can take much larger values, but the result
  214. // may differ from Delphi/FPC
  215. MaxCurrency: Currency = 900719925474.0991; // fpc: 922337203685477.5807;
  216. MinCurrency: Currency = -900719925474.0991; // fpc: -922337203685477.5808;
  217. Type
  218. TFloatFormat = (ffFixed,ffGeneral,ffExponent,ffNumber,ffCurrency);
  219. Function FloatToDecimal(Value : double; Precision, Decimals : integer) : TFloatRec;
  220. Function FloatToStr(Value: Double): String;
  221. Function FloatToStrF(const Value : double; format: TFloatFormat; Precision, Digits: Integer): String;
  222. Function TryStrToFloat(const S : String; Out res : Extended) : Boolean; overload;
  223. Function TryStrToFloat(const S : String; Out res : Double) : Boolean; overload;
  224. Function StrToFloatDef(const S : String; Const aDef : Double) : Double;
  225. Function StrToFloat(const S : String) : Double;
  226. Function FormatFloat (Fmt : String; aValue : Double) : String;
  227. Function SwapEndian(W : Word) : Word;
  228. Function SwapEndian(C : Cardinal) : Cardinal;
  229. { *****************************************************************************
  230. Boolean conversions
  231. *****************************************************************************}
  232. Var
  233. TrueBoolStrs, FalseBoolStrs : Array of String;
  234. function StrToBool(const S: String): Boolean;
  235. function BoolToStr(B: Boolean; UseBoolStrs:Boolean=False): string;
  236. function BoolToStr(B: Boolean; const TrueS, FalseS: String): string;
  237. function StrToBoolDef(const S: String; Default: Boolean): Boolean;
  238. function TryStrToBool(const S: String; out Value: Boolean): Boolean;
  239. {*****************************************************************************
  240. OS/Environment
  241. *****************************************************************************}
  242. Const
  243. ConfigExtension : String = '.cfg';
  244. SysConfigDir : String = '';
  245. type
  246. TOnGetEnvironmentVariable = function(Const EnvVar: String): String;
  247. TOnGetEnvironmentString = function(Index: Integer): String;
  248. TOnGetEnvironmentVariableCount = function: Integer;
  249. TShowExceptionHandler = Procedure (Const Msg : String);
  250. TUncaughtPascalExceptionHandler = reference to Procedure(aObject : TObject);
  251. TUncaughtJSExceptionHandler = reference to Procedure(aObject : TJSObject);
  252. var
  253. OnGetEnvironmentVariable: TOnGetEnvironmentVariable;
  254. OnGetEnvironmentString: TOnGetEnvironmentString;
  255. OnGetEnvironmentVariableCount: TOnGetEnvironmentVariableCount;
  256. // Handler to show an exception (used when showexception is called)
  257. OnShowException : TShowExceptionHandler = nil;
  258. // Set handlers for uncaught exceptions. These will call HookUncaughtExceptions
  259. // They return the old exception handler, if there was any.
  260. Function SetOnUnCaughtExceptionHandler(aValue : TUncaughtPascalExceptionHandler) : TUncaughtPascalExceptionHandler;
  261. Function SetOnUnCaughtExceptionHandler(aValue : TUncaughtJSExceptionHandler) : TUncaughtJSExceptionHandler;
  262. // Hook the rtl handler for uncaught exceptions. If any exception handlers were set, they will be called.
  263. // If none were set, the exceptions will be displayed using ShowException.
  264. Procedure HookUncaughtExceptions;
  265. function GetEnvironmentVariable(Const EnvVar: String): String;
  266. function GetEnvironmentVariableCount: Integer;
  267. function GetEnvironmentString(Index: Integer): String;
  268. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer = Nil);
  269. Procedure Abort;
  270. {*****************************************************************************
  271. Events
  272. *****************************************************************************}
  273. Type
  274. TEventType = (etCustom,etInfo,etWarning,etError,etDebug);
  275. TEventTypes = Set of TEventType;
  276. {*****************************************************************************
  277. Date and time
  278. *****************************************************************************}
  279. Type
  280. TSystemTime = record
  281. Year, Month, Day, DayOfWeek: word;
  282. Hour, Minute, Second, MilliSecond: word;
  283. end ;
  284. TTimeStamp = record
  285. Time: longint; { Number of milliseconds since midnight }
  286. Date: longint; { One plus number of days since 1/1/0001 }
  287. end ;
  288. Var
  289. TimeSeparator : char = ':';
  290. DateSeparator : char = '-';
  291. ShortDateFormat : string = 'yyyy-mm-dd';
  292. LongDateFormat : string = 'ddd, yyyy-mm-dd';
  293. ShortTimeFormat : string = 'hh:nn';
  294. LongTimeFormat : string = 'hh:nn:ss';
  295. DecimalSeparator : string = '.';
  296. ThousandSeparator : string;
  297. TimeAMString : string = 'AM';
  298. TimePMString : string = 'PM';
  299. const
  300. HoursPerDay = 24;
  301. MinsPerHour = 60;
  302. SecsPerMin = 60;
  303. MSecsPerSec = 1000;
  304. MinsPerDay = HoursPerDay * MinsPerHour;
  305. SecsPerDay = MinsPerDay * SecsPerMin;
  306. MSecsPerDay = SecsPerDay * MSecsPerSec;
  307. MaxDateTime: TDateTime = 2958465.99999999;
  308. MinDateTime: TDateTime = -693593.99999999;
  309. JulianEpoch = TDateTime(-2415018.5);
  310. UnixEpoch = JulianEpoch + TDateTime(2440587.5);
  311. DateDelta = 693594; // Days between 1/1/0001 and 12/31/1899
  312. UnixDateDelta = 25569;
  313. { True=Leapyear }
  314. Var
  315. MonthDays : array [Boolean] of TDayTable =
  316. ((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
  317. (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31));
  318. ShortMonthNames : TMonthNames = (
  319. 'Jan',
  320. 'Feb',
  321. 'Mar',
  322. 'Apr',
  323. 'May',
  324. 'Jun',
  325. 'Jul',
  326. 'Aug',
  327. 'Sep',
  328. 'Oct',
  329. 'Nov',
  330. 'Dec');
  331. LongMonthNames : TMonthNames = (
  332. 'January',
  333. 'February',
  334. 'March',
  335. 'April',
  336. 'May',
  337. 'June',
  338. 'July',
  339. 'August',
  340. 'September',
  341. 'October',
  342. 'November',
  343. 'December');
  344. ShortDayNames : TDayNames = (
  345. 'Sun',
  346. 'Mon',
  347. 'Tue',
  348. 'Wed',
  349. 'Thu',
  350. 'Fri',
  351. 'Sat');
  352. LongDayNames : TDayNames = (
  353. 'Sunday',
  354. 'Monday',
  355. 'Tuesday',
  356. 'Wednesday',
  357. 'Thursday',
  358. 'Friday',
  359. 'Saturday');
  360. type
  361. // Stub, for easier porting of FPC/Delphi code.
  362. // Reading/Writing the properties will actually set the global variables
  363. { TFormatSettings }
  364. TFormatSettings = class(TObject)
  365. private
  366. function GetCurrencyDecimals: Byte;
  367. function GetCurrencyFormat: Byte;
  368. function GetCurrencyString: String;
  369. function GetDateSeparator: char;
  370. function GetDecimalSeparator: string;
  371. function GetLongDateFormat: string;
  372. function GetLongDayNames: TDayNames;
  373. function GetLongMonthNames: TMonthNames;
  374. function GetLongTimeFormat: string;
  375. function GetNegCurrFormat: Byte;
  376. function GetShortDateFormat: string;
  377. function GetShortDayNames: TDayNames;
  378. function GetShortMonthNames: TMonthNames;
  379. function GetShortTimeFormat: string;
  380. function GetThousandSeparator: string;
  381. function GetTimeAMString: string;
  382. function GetTimePMString: string;
  383. function GetTimeSeparator: char;
  384. procedure SetCurrencyFormat(AValue: Byte);
  385. procedure SetCurrencyString(AValue: String);
  386. procedure SetDateSeparator(const Value: char);
  387. procedure SetDecimalSeparator(const Value: string);
  388. procedure SetLongDateFormat(const Value: string);
  389. procedure SetLongDayNames(AValue: TDayNames);
  390. procedure SetLongMonthNames(AValue: TMonthNames);
  391. procedure SetLongTimeFormat(const Value: string);
  392. procedure SetNegCurrFormat(AValue: Byte);
  393. procedure SetShortDateFormat(const Value: string);
  394. procedure SetShortDayNames(AValue: TDayNames);
  395. procedure SetShortMonthNames(AValue: TMonthNames);
  396. procedure SetShortTimeFormat(const Value: string);
  397. procedure SetCurrencyDecimals(AValue: Byte);
  398. procedure SetThousandSeparator(const Value: string);
  399. procedure SetTimeAMString(const Value: string);
  400. procedure SetTimePMString(const Value: string);
  401. procedure SetTimeSeparator(const Value: char);
  402. public
  403. class constructor Init;
  404. Property ShortMonthNames : TMonthNames Read GetShortMonthNames Write SetShortMonthNames;
  405. Property LongMonthNames : TMonthNames Read GetLongMonthNames Write SetLongMonthNames;
  406. Property ShortDayNames : TDayNames Read GetShortDayNames Write SetShortDayNames;
  407. Property LongDayNames : TDayNames Read GetLongDayNames Write SetLongDayNames;
  408. property TimeSeparator : char read GetTimeSeparator write SetTimeSeparator;
  409. property DateSeparator : char read GetDateSeparator write SetDateSeparator;
  410. property ShortDateFormat : string read GetShortDateFormat write SetShortDateFormat;
  411. property LongDateFormat : string read GetLongDateFormat write SetLongDateFormat;
  412. property ShortTimeFormat : string read GetShortTimeFormat write SetShortTimeFormat;
  413. property LongTimeFormat : string read GetLongTimeFormat write SetLongTimeFormat;
  414. property DecimalSeparator : string read GetDecimalSeparator write SetDecimalSeparator;
  415. property ThousandSeparator : string read GetThousandSeparator write SetThousandSeparator;
  416. property TimeAMString : string read GetTimeAMString write SetTimeAMString;
  417. property TimePMString : string read GetTimePMString write SetTimePMString;
  418. Property CurrencyFormat : Byte read GetCurrencyFormat Write SetCurrencyFormat;
  419. Property NegCurrFormat : Byte read GetNegCurrFormat Write SetNegCurrFormat;
  420. Property CurrencyDecimals : Byte Read GetCurrencyDecimals Write SetCurrencyDecimals;
  421. Property CurrencyString : String Read GetCurrencyString Write SetCurrencyString;
  422. end;
  423. Var
  424. FormatSettings: TFormatSettings;
  425. TwoDigitYearCenturyWindow : word = 50;
  426. { Threshold to be subtracted from year before age-detection.}
  427. function DateTimeToJSDate(aDateTime : TDateTime) : TJSDate;
  428. function JSDateToDateTime(aDate : TJSDate) : TDateTime;
  429. function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp;
  430. function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
  431. function MSecsToTimeStamp(MSecs: NativeInt): TTimeStamp;
  432. function TimeStampToMSecs(const TimeStamp: TTimeStamp): NativeInt;
  433. function TryEncodeDate(Year, Month, Day: Word; out Date: TDateTime): Boolean;
  434. function TryEncodeTime(Hour, Min, Sec, MSec: Word; out Time: TDateTime): Boolean;
  435. function EncodeDate(Year, Month, Day :word): TDateTime;
  436. function EncodeTime(Hour, Minute, Second, MilliSecond:word): TDateTime;
  437. function ComposeDateTime(Date,Time : TDateTime) : TDateTime;
  438. procedure DecodeDate(Date: TDateTime; out Year, Month, Day: word);
  439. function DecodeDateFully(const DateTime: TDateTime; out Year, Month, Day, DOW: Word): Boolean;
  440. procedure DecodeTime(Time: TDateTime; out Hour, Minute, Second, MilliSecond: word);
  441. procedure DateTimeToSystemTime(DateTime: TDateTime; out SystemTime: TSystemTime);
  442. function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
  443. function DayOfWeek(DateTime: TDateTime): integer;
  444. function Date: TDateTime;
  445. function Time: TDateTime;
  446. function Now: TDateTime;
  447. function IncMonth(const DateTime: TDateTime; NumberOfMonths: integer = 1 ): TDateTime;
  448. procedure IncAMonth(var Year, Month, Day: Word; NumberOfMonths: Integer = 1);
  449. function IsLeapYear(Year: Word): boolean;
  450. function DateToStr(Date: TDateTime): string;
  451. // function DateToStr(Date: TDateTime; const FormatSettings: TFormatSettings): string;
  452. function TimeToStr(Time: TDateTime): string;
  453. // function TimeToStr(Time: TDateTime; const FormatSettings: TFormatSettings): string;
  454. function DateTimeToStr(DateTime: TDateTime; ForceTimeIfZero : Boolean = False): string;
  455. // function DateTimeToStr(DateTime: TDateTime; const FormatSettings: TFormatSettings; ForceTimeIfZero : Boolean = False): string;
  456. function StrToDate(const S: String): TDateTime;
  457. function StrToDate(const S: String; separator : char): TDateTime;
  458. function StrToDate(const S: String; const useformat : string; separator : char): TDateTime;
  459. //function StrToDate(const S: string; FormatSettings : TFormatSettings): TDateTime;
  460. function StrToTime(const S: String): TDateTime;
  461. function StrToTime(const S: String; separator : char): TDateTime;
  462. // function StrToTime(const S: string; FormatSettings : TFormatSettings): TDateTime;
  463. function StrToDateTime(const S: String): TDateTime;
  464. //function StrToDateTime(const s: ShortString; const FormatSettings : TFormatSettings): TDateTime;
  465. function FormatDateTime(const FormatStr: string; const DateTime: TDateTime): string;
  466. // function FormatDateTime(const FormatStr: string; DateTime: TDateTime; const FormatSettings: TFormatSettings; Options : TFormatDateTimeOptions = []): string;
  467. function TryStrToDate(const S: String; out Value: TDateTime): Boolean;
  468. function TryStrToDate(const S: String; out Value: TDateTime; separator : char): Boolean;
  469. function TryStrToDate(const S: String; out Value: TDateTime; const useformat : string; separator : char): Boolean;
  470. // function TryStrToDate(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  471. function TryStrToTime(const S: String; out Value: TDateTime): Boolean;
  472. function TryStrToTime(const S: String; out Value: TDateTime; separator : char): Boolean;
  473. function TryStrToDateTime(const S: String; out Value: TDateTime): Boolean;
  474. // function TryStrToTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  475. // function TryStrToDateTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  476. function StrToDateDef(const S: String; const Defvalue : TDateTime): TDateTime;
  477. function StrToDateDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  478. function StrToTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  479. function StrToTimeDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  480. function StrToDateTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  481. function CurrentYear:Word;
  482. procedure ReplaceTime(var dati: TDateTime; NewTime : TDateTime);
  483. procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime);
  484. Function FloatToDateTime (Const Value : Extended) : TDateTime;
  485. { *****************************************************************************
  486. Currency support
  487. *****************************************************************************}
  488. Var
  489. CurrencyFormat : Byte = 0;
  490. NegCurrFormat : Byte = 0;
  491. CurrencyDecimals : Byte = 2;
  492. CurrencyString : String = '$';
  493. Function FloattoCurr (Const Value : Extended) : Currency;
  494. function TryFloatToCurr(const Value: Extended; var AResult: Currency): Boolean;
  495. Function CurrToStr(Value: Currency): string;
  496. //Function CurrToStr(Value: Currency; Const FormatSettings: TFormatSettings): string;
  497. function StrToCurr(const S: string): Currency;
  498. //function StrToCurr(const S: string; Const FormatSettings: TFormatSettings): Currency;
  499. function TryStrToCurr(const S: string;Out Value : Currency): Boolean;
  500. //function TryStrToCurr(const S: string;Out Value : Currency; Const FormatSettings: TFormatSettings): Boolean;
  501. function StrToCurrDef(const S: string; Default : Currency): Currency;
  502. //function StrToCurrDef(const S: string; Default : Currency; Const FormatSettings: TFormatSettings): Currency;
  503. {*****************************************************************************
  504. File Paths
  505. *****************************************************************************}
  506. type
  507. PathStr = String;
  508. TPathStrArray = Array of PathStr;
  509. function ChangeFileExt(const FileName, Extension: PathStr): PathStr;
  510. function ExtractFilePath(const FileName: PathStr): PathStr;
  511. function ExtractFileDrive(const FileName: PathStr): PathStr;
  512. function ExtractFileName(const FileName: PathStr): PathStr;
  513. function ExtractFileExt(const FileName: PathStr): PathStr;
  514. function ExtractFileDir(Const FileName : PathStr): PathStr;
  515. function ExtractRelativepath (Const BaseName,DestName : PathStr): PathStr;
  516. function IncludeTrailingPathDelimiter(Const Path : PathStr) : PathStr;
  517. function ExcludeTrailingPathDelimiter(Const Path: PathStr): PathStr;
  518. function IncludeLeadingPathDelimiter(Const Path : PathStr) : PathStr;
  519. function ExcludeLeadingPathDelimiter(Const Path: PathStr): PathStr;
  520. function IsPathDelimiter(Const Path: PathStr; Index: Integer): Boolean;
  521. Function SetDirSeparators (Const FileName : PathStr) : PathStr;
  522. Function GetDirs (DirName : PathStr) : TPathStrArray;
  523. function ConcatPaths(const Paths: array of PathStr): PathStr;
  524. {*****************************************************************************
  525. Interfaces
  526. *****************************************************************************}
  527. const
  528. GUID_NULL: TGuid = '{00000000-0000-0000-0000-000000000000}';
  529. function Supports(const Instance: IInterface; const AClass: TClass; out Obj): Boolean; overload;
  530. function Supports(const Instance: IInterface; const IID: TGuid; out Intf): Boolean; overload;
  531. function Supports(const Instance: TObject; const IID: TGuid; out Intf): Boolean; overload;
  532. function Supports(const Instance: TObject; const IID: TGuidString; out Intf): Boolean; overload;
  533. function Supports(const Instance: IInterface; const AClass: TClass): Boolean; overload;
  534. function Supports(const Instance: IInterface; const IID: TGuid): Boolean; overload;
  535. function Supports(const Instance: TObject; const IID: TGuid): Boolean; overload;
  536. function Supports(const Instance: TObject; const IID: TGuidString): Boolean; overload;
  537. function Supports(const AClass: TClass; const IID: TGuid): Boolean; overload;
  538. function Supports(const AClass: TClass; const IID: TGuidString): Boolean; overload;
  539. function TryStringToGUID(const s: string; out Guid: TGuid): Boolean;
  540. function StringToGUID(const S: string): TGuid;
  541. function GUIDToString(const guid: TGuid): string;
  542. function IsEqualGUID(const guid1, guid2: TGuid): Boolean;
  543. function GuidCase(const guid: TGuid; const List: array of TGuid): Integer;
  544. Function CreateGUID(out GUID : TGUID) : Integer;
  545. Function EncodeHTMLEntities (S : String) : String;
  546. { ---------------------------------------------------------------------
  547. Type Helpers
  548. ---------------------------------------------------------------------}
  549. Type
  550. generic TArray<T> = array of T;
  551. TCharArray = Array of char;
  552. TByteBitIndex = 0..7;
  553. TShortIntBitIndex = 0..7;
  554. TWordBitIndex = 0..15;
  555. TSmallIntBitIndex = 0..15;
  556. TCardinalBitIndex = 0..31;
  557. TIntegerBitIndex = 0..31;
  558. TLongIntBitIndex = TIntegerBitIndex;
  559. TQwordBitIndex = 0..52;
  560. TInt64BitIndex = 0..52;
  561. TNativeIntBitIndex = 0..52;
  562. TNativeUIntBitIndex = 0..52;
  563. Const
  564. CPUEndian = {$IFNDEF FPC_LITTLE_ENDIAN}TEndian.Big{$ELSE}TEndian.Little{$ENDIF};
  565. Type
  566. { TGuidHelper }
  567. TGuidHelper = record helper for TGUID
  568. class function Create(Src : TGUID; BigEndian: Boolean): TGUID; overload; static;
  569. class function Create(const Buf : TJSArrayBuffer; AStartIndex: Cardinal; BigEndian: Boolean): TGUID; overload; static;
  570. class function Create(const Data: array of Byte; AStartIndex: Cardinal; BigEndian: Boolean): TGUID; overload; static;
  571. Class Function Create(const B: TBytes; DataEndian: TEndian = CPUEndian): TGUID; overload; static; inline;
  572. Class Function Create(const B: TBytes; AStartIndex: Cardinal; DataEndian: TEndian = CPUEndian): TGUID; overload; static;
  573. Class Function Create(const S: string): TGUID; overload; static;
  574. Class Function Create(A: Integer; B: SmallInt; C: SmallInt; const D: TBytes): TGUID; overload; static;
  575. // Class Function Create(A: Integer; B: SmallInt; C: SmallInt; D, E, F, G, H, I, J, K: Byte): TGUID; overload; static;
  576. Class Function Create(A: Cardinal; B: Word; C: Word; D, E, F, G, H, I, J, K: Byte): TGUID; overload; static;
  577. Class Function NewGuid: TGUID; static;
  578. Function ToByteArray(DataEndian: TEndian = CPUEndian): TBytes;
  579. Function ToString(SkipBrackets: Boolean = False): string;
  580. end;
  581. TCompareOption = system.TCompareOption;
  582. TCompareOptions = system.TCompareOptions;
  583. {$SCOPEDENUMS ON}
  584. TStringSplitOptions = (None, ExcludeEmpty);
  585. {$SCOPEDENUMS OFF}
  586. { TStringHelper }
  587. TStringHelper = Type Helper for String
  588. Private
  589. Function GetChar(AIndex : SizeInt) : Char;
  590. Function GetLength : SizeInt;
  591. public
  592. const Empty = '';
  593. // Methods
  594. Class Function Compare(const A: string; const B: string): Integer; overload; static; //inline;
  595. Class Function Compare(const A: string; const B: string; IgnoreCase: Boolean): Integer; overload; static; //inline; //deprecated 'Use same with TCompareOptions';
  596. Class Function Compare(const A: string; const B: string; Options: TCompareOptions): Integer; overload; static; // inline;
  597. Class Function Compare(const A: string; IndexA: SizeInt; const B: string; IndexB: SizeInt; ALen: SizeInt): Integer; overload; static; // inline;
  598. Class Function Compare(const A: string; IndexA: SizeInt; const B: string; IndexB: SizeInt; ALen: SizeInt; IgnoreCase: Boolean): Integer; overload; static; // inline; //deprecated 'Use same with TCompareOptions';
  599. Class Function Compare(const A: string; IndexA: SizeInt; const B: string; IndexB: SizeInt; ALen: SizeInt; Options: TCompareOptions): Integer; overload; static;// inline;
  600. Class Function CompareOrdinal(const A: string; const B: string): Integer; overload; static;
  601. Class Function CompareOrdinal(const A: string; IndexA: SizeInt; const B: string; IndexB: SizeInt; ALen: SizeInt): Integer; overload; static;
  602. Class Function CompareText(const A: string; const B: string): Integer; static; inline;
  603. Class Function Copy(const Str: string): string; inline; static;
  604. Class Function Create(AChar: Char; ACount: SizeInt): string; overload; inline; static;
  605. Class Function Create(const AValue: array of Char): string; overload; static;
  606. Class Function Create(const AValue: array of Char; StartIndex: SizeInt; ALen: SizeInt): string; overload; static;
  607. Class Function EndsText(const ASubText, AText: string): Boolean; static;
  608. Class Function Equals(const a: string; const b: string): Boolean; overload; static;
  609. Class Function Format(const AFormat: string; const args: array of JSValue): string; overload; static;
  610. Class Function IsNullOrEmpty(const AValue: string): Boolean; static;
  611. Class Function IsNullOrWhiteSpace(const AValue: string): Boolean; static;
  612. Class Function Join(const Separator: string; const Values: array of JSValue): string; overload; static;
  613. Class Function Join(const Separator: string; const Values: array of string): string; overload; static;
  614. Class Function Join(const Separator: string; const Values: array of string; StartIndex: SizeInt; ACount: SizeInt): string; overload; static;
  615. Class Function LowerCase(const S: string): string; overload; static; inline;
  616. Class Function Parse(const AValue: Boolean): string; overload; static; inline;
  617. Class Function Parse(const AValue: Extended): string; overload; static;inline;
  618. Class Function Parse(const AValue: NativeInt): string; overload; static; inline;
  619. Class Function Parse(const AValue: Integer): string; overload; static; inline;
  620. Class Function ToBoolean(const S: string): Boolean; overload; static; inline;
  621. Class Function ToDouble(const S: string): Double; overload; static; inline;
  622. Class Function ToExtended(const S: string): Extended; overload; static; inline;
  623. Class Function ToNativeInt(const S: string): NativeInt; overload; static; inline;
  624. Class Function ToInteger(const S: string): Integer; overload; static; inline;
  625. Class Function UpperCase(const S: string): string; overload; static; inline;
  626. Class Function ToCharArray(const S : String) : TCharArray; static;
  627. Function CompareTo(const B: string): Integer;
  628. Function Contains(const AValue: string): Boolean;
  629. Function CountChar(const C: Char): SizeInt;
  630. Function DeQuotedString: string; overload;
  631. Function DeQuotedString(const AQuoteChar: Char): string; overload;
  632. Function EndsWith(const AValue: string): Boolean; overload; inline;
  633. Function EndsWith(const AValue: string; IgnoreCase: Boolean): Boolean; overload;
  634. Function Equals(const AValue: string): Boolean; overload;
  635. Function Format(const args: array of jsValue): string; overload;
  636. Function GetHashCode: Integer;
  637. Function IndexOf(AValue: Char): SizeInt; overload; inline;
  638. Function IndexOf(const AValue: string): SizeInt; overload; inline;
  639. Function IndexOf(AValue: Char; StartIndex: SizeInt): SizeInt; overload;
  640. Function IndexOf(const AValue: string; StartIndex: SizeInt): SizeInt; overload;
  641. Function IndexOf(AValue: Char; StartIndex: SizeInt; ACount: SizeInt): SizeInt; overload;
  642. Function IndexOf(const AValue: string; StartIndex: SizeInt; ACount: SizeInt): SizeInt; overload;
  643. Function IndexOfUnQuoted(const AValue: string; StartQuote, EndQuote: Char; StartIndex: SizeInt = 0): SizeInt; overload;
  644. Function IndexOfAny(const AnyOf: string): SizeInt; overload;
  645. Function IndexOfAny(const AnyOf: array of Char): SizeInt; overload;
  646. Function IndexOfAny(const AnyOf: String; StartIndex: SizeInt): SizeInt; overload;
  647. Function IndexOfAny(const AnyOf: array of Char; StartIndex: SizeInt): SizeInt; overload;
  648. Function IndexOfAny(const AnyOf: String; StartIndex: SizeInt; ACount: SizeInt): SizeInt; overload;
  649. Function IndexOfAny(const AnyOf: array of Char; StartIndex: SizeInt; ACount: SizeInt): SizeInt; overload;
  650. Function IndexOfAny(const AnyOf: array of String): SizeInt; overload;
  651. Function IndexOfAny(const AnyOf: array of String; StartIndex: SizeInt): SizeInt; overload;
  652. Function IndexOfAny(const AnyOf: array of String; StartIndex: SizeInt; ACount: SizeInt): SizeInt; overload;
  653. Function IndexOfAny(const AnyOf: array of String; StartIndex: SizeInt; ACount: SizeInt; Out AMatch : SizeInt): SizeInt; overload;
  654. Function IndexOfAnyUnquoted(const AnyOf: array of Char; StartQuote, EndQuote: Char): SizeInt; overload;
  655. Function IndexOfAnyUnquoted(const AnyOf: array of Char; StartQuote, EndQuote: Char; StartIndex: SizeInt): SizeInt; overload;
  656. Function IndexOfAnyUnquoted(const AnyOf: array of Char; StartQuote, EndQuote: Char; StartIndex: SizeInt; ACount: SizeInt): SizeInt; overload;
  657. function IndexOfAnyUnquoted(const AnyOf: array of string; StartQuote, EndQuote: Char; StartIndex: SizeInt; Out Matched: SizeInt): SizeInt; overload;
  658. Function Insert(StartIndex: SizeInt; const AValue: string): string;
  659. Function IsDelimiter(const Delimiters: string; Index: SizeInt): Boolean;
  660. Function IsEmpty: Boolean;
  661. Function LastDelimiter(const Delims: string): SizeInt;
  662. Function LastIndexOf(AValue: Char): SizeInt; overload;
  663. Function LastIndexOf(const AValue: string): SizeInt; overload;
  664. Function LastIndexOf(AValue: Char; AStartIndex: SizeInt): SizeInt; overload;
  665. Function LastIndexOf(const AValue: string; AStartIndex: SizeInt): SizeInt; overload;
  666. Function LastIndexOf(AValue: Char; AStartIndex: SizeInt; ACount: SizeInt): SizeInt; overload;
  667. Function LastIndexOf(const AValue: string; AStartIndex: SizeInt; ACount: SizeInt): SizeInt; overload;
  668. Function LastIndexOfAny(const AnyOf: array of Char): SizeInt; overload;
  669. Function LastIndexOfAny(const AnyOf: array of Char; AStartIndex: SizeInt): SizeInt; overload;
  670. Function LastIndexOfAny(const AnyOf: array of Char; AStartIndex: SizeInt; ACount: SizeInt): SizeInt; overload;
  671. Function PadLeft(ATotalWidth: SizeInt): string; overload; inline;
  672. Function PadLeft(ATotalWidth: SizeInt; PaddingChar: Char): string; overload; inline;
  673. Function PadRight(ATotalWidth: SizeInt): string; overload; inline;
  674. Function PadRight(ATotalWidth: SizeInt; PaddingChar: Char): string; overload; inline;
  675. Function QuotedString: string; overload;
  676. Function QuotedString(const AQuoteChar: Char): string; overload;
  677. Function Remove(StartIndex: SizeInt): string; overload; inline;
  678. Function Remove(StartIndex: SizeInt; ACount: SizeInt): string; overload; inline;
  679. Function Replace(OldChar: Char; NewChar: Char): string; overload;
  680. Function Replace(OldChar: Char; NewChar: Char; ReplaceFlags: TReplaceFlags): string; overload;
  681. Function Replace(const OldValue: string; const NewValue: string): string; overload;
  682. Function Replace(const OldValue: string; const NewValue: string; ReplaceFlags: TReplaceFlags): string; overload;
  683. Function Split(const Separators: String): TStringArray; overload;
  684. Function Split(const Separators: array of Char): TStringArray; overload;
  685. Function Split(const Separators: string; ACount: SizeInt): TStringArray; overload;
  686. Function Split(const Separators: array of Char; ACount: SizeInt): TStringArray; overload;
  687. Function Split(const Separators: string; Options: TStringSplitOptions): TStringArray; overload;
  688. Function Split(const Separators: array of Char; Options: TStringSplitOptions): TStringArray; overload;
  689. Function Split(const Separators: string; ACount: SizeInt; Options: TStringSplitOptions): TStringArray; overload;
  690. Function Split(const Separators: array of Char; ACount: SizeInt; Options: TStringSplitOptions): TStringArray; overload;
  691. Function Split(const Separators: array of string): TStringArray; overload;
  692. Function Split(const Separators: array of string; ACount: SizeInt): TStringArray; overload;
  693. Function Split(const Separators: array of string; Options: TStringSplitOptions): TStringArray; overload;
  694. Function Split(const Separators: array of string; ACount: SizeInt; Options: TStringSplitOptions): TStringArray; overload;
  695. Function Split(const Separators: String; AQuote: Char): TStringArray; overload;
  696. Function Split(const Separators: array of Char; AQuote: Char): TStringArray; overload;
  697. Function Split(const Separators: String; AQuoteStart, AQuoteEnd: Char): TStringArray; overload;
  698. Function Split(const Separators: array of Char; AQuoteStart, AQuoteEnd: Char): TStringArray; overload;
  699. Function Split(const Separators: string; AQuoteStart, AQuoteEnd: Char; Options: TStringSplitOptions): TStringArray; overload;
  700. Function Split(const Separators: array of Char; AQuoteStart, AQuoteEnd: Char; Options: TStringSplitOptions): TStringArray; overload;
  701. Function Split(const Separators: string; AQuoteStart, AQuoteEnd: Char; ACount: SizeInt): TStringArray; overload;
  702. Function Split(const Separators: array of Char; AQuoteStart, AQuoteEnd: Char; ACount: SizeInt): TStringArray; overload;
  703. Function Split(const Separators: string; AQuoteStart, AQuoteEnd: Char; ACount: SizeInt; Options: TStringSplitOptions): TStringArray; overload;
  704. Function Split(const Separators: array of Char; AQuoteStart, AQuoteEnd: Char; ACount: SizeInt; Options: TStringSplitOptions): TStringArray; overload;
  705. Function Split(const Separators: array of string; AQuote: Char): TStringArray; overload;
  706. Function Split(const Separators: array of string; AQuoteStart, AQuoteEnd: Char): TStringArray; overload;
  707. Function Split(const Separators: array of string; AQuoteStart, AQuoteEnd: Char; Options: TStringSplitOptions): TStringArray; overload;
  708. Function Split(const Separators: array of string; AQuoteStart, AQuoteEnd: Char; ACount: SizeInt): TStringArray; overload;
  709. Function Split(const Separators: array of string; AQuoteStart, AQuoteEnd: Char; ACount: SizeInt; Options: TStringSplitOptions): TStringArray; overload;
  710. Function StartsWith(const AValue: string): Boolean; overload; inline;
  711. Function StartsWith(const AValue: string; IgnoreCase: Boolean): Boolean; overload;
  712. Function Substring(AStartIndex: SizeInt): string; overload;
  713. Function Substring(AStartIndex: SizeInt; ALen: SizeInt): string; overload;
  714. Function ToBoolean: Boolean; overload; inline;
  715. Function ToInteger: Integer; overload; inline;
  716. Function ToNativeInt: NativeInt; overload; inline;
  717. Function ToDouble: Double; overload; inline;
  718. Function ToExtended: Extended; overload; inline;
  719. Function ToCharArray: TCharArray; overload;
  720. Function ToCharArray(AStartIndex: SizeInt; ALen: SizeInt): TCharArray; overload;
  721. Function ToLower: string; overload; inline;
  722. Function ToLowerInvariant: string;
  723. Function ToUpper: string; overload; inline;
  724. Function ToUpperInvariant: string; inline;
  725. Function Trim: string; overload;
  726. Function TrimLeft: string; overload;
  727. Function TrimRight: string; overload;
  728. Function Trim(const ATrimChars: array of Char): string; overload;
  729. Function TrimLeft(const ATrimChars: array of Char): string; overload;
  730. Function TrimRight(const ATrimChars: array of Char): string; overload;
  731. Function TrimEnd(const ATrimChars: array of Char): string; deprecated 'Use TrimRight';
  732. Function TrimStart(const ATrimChars: array of Char): string; deprecated 'Use TrimLeft';
  733. property Chars[AIndex: SizeInt]: Char read GetChar;
  734. property Length: SizeInt read GetLength;
  735. end;
  736. TDoubleHelper = Type Helper for Double
  737. private
  738. Function GetB(AIndex: Cardinal): Byte;
  739. Function GetW(AIndex: Cardinal): Word;
  740. Function GetE: NativeUInt; inline;
  741. Function GetF: NativeUInt; inline;
  742. Function GetS: Boolean; inline;
  743. Procedure SetS(aValue : Boolean); inline;
  744. procedure SetB(AIndex: Cardinal; const AValue: Byte);
  745. procedure SetW(AIndex: Cardinal; const AValue: Word);
  746. public
  747. const
  748. {$push}
  749. {$R-}
  750. {$Q-}
  751. Epsilon : Double = 4.9406564584124654418e-324;
  752. MaxValue : Double = 1.7976931348623157081e+308;
  753. MinValue : Double = -1.7976931348623157081e+308;
  754. // PositiveInfinity : Double = 1.0/0.0;
  755. // NegativeInfinity : Double = -1.0/0.0;
  756. // NaN : Double = 0.0/0.0;
  757. {$POP}
  758. Class Function IsInfinity(const AValue: Double): Boolean; overload; inline; static;
  759. Class Function IsNan(const AValue: Double): Boolean; overload; inline; static;
  760. Class Function IsNegativeInfinity(const AValue: Double): Boolean; overload; inline; static;
  761. Class Function IsPositiveInfinity(const AValue: Double): Boolean; overload; inline; static;
  762. Class Function Parse(const AString: string): Double; overload; inline; static;
  763. Class Function ToString(const AValue: Double): string; overload; inline; static;
  764. Class Function ToString(const AValue: Double; const AFormat: TFloatFormat; const APrecision, ADigits: Integer): string; overload; inline; static;
  765. Class Function TryParse(const AString: string; out AValue: Double): Boolean; overload; inline; static;
  766. Procedure BuildUp(const ASignFlag: Boolean; const AMantissa: NativeUInt; const AExponent: Integer);
  767. Function Exponent: Integer;
  768. Function Fraction: Extended;
  769. Function IsInfinity: Boolean; overload; inline;
  770. Function IsNan: Boolean; overload; inline;
  771. Function IsNegativeInfinity: Boolean; overload; inline;
  772. Function IsPositiveInfinity: Boolean; overload; inline;
  773. Function Mantissa: NativeUInt;
  774. Function ToString(const AFormat: TFloatFormat; const APrecision, ADigits: Integer): string; overload; inline;
  775. Function ToString: string; overload; inline;
  776. property Bytes[AIndex: Cardinal]: Byte read GetB write SetB; // 0..7
  777. property Words[AIndex: Cardinal]: Word read GetW write SetW; // 0..3
  778. property Sign: Boolean read GetS Write SetS;
  779. property Exp: NativeUInt read GetE;
  780. property Frac: NativeUInt read GetF;
  781. end;
  782. TByteHelper = Type Helper for Byte
  783. public
  784. const
  785. MaxValue = 255;
  786. MinValue = 0;
  787. public
  788. Class Function Parse(const AString: string): Byte; inline; static;
  789. Class Function Size: Integer; inline; static;
  790. Class Function ToString(const AValue: Byte): string; overload; inline; static;
  791. Class Function TryParse(const AString: string; out AValue: Byte): Boolean; inline; static;
  792. Public
  793. Function ToBoolean: Boolean; inline;
  794. Function ToDouble: Double; inline;
  795. Function ToExtended: Extended; inline;
  796. Function ToBinString:string; inline;
  797. Function ToHexString(const AMinDigits: Integer): string; overload; inline;
  798. Function ToHexString: string; overload; inline;
  799. Function ToString: string; overload; inline;
  800. Function SetBit(const Index: TByteBitIndex) : Byte; inline;
  801. Function ClearBit(const Index: TByteBitIndex) : Byte; inline;
  802. Function ToggleBit(const Index: TByteBitIndex) : Byte; inline;
  803. Function TestBit(const Index:TByteBitIndex):Boolean; inline;
  804. end;
  805. TShortIntHelper = Type Helper for ShortInt
  806. public
  807. const
  808. MaxValue = 127;
  809. MinValue = -128;
  810. public
  811. Class Function Parse(const AString: string): ShortInt; inline; static;
  812. Class Function Size: Integer; inline; static;
  813. Class Function ToString(const AValue: ShortInt): string; overload; inline; static;
  814. Class Function TryParse(const AString: string; out AValue: ShortInt): Boolean; inline; static;
  815. public
  816. Function ToBoolean: Boolean; inline;
  817. Function ToDouble: Double; inline;
  818. Function ToExtended: Extended; inline;
  819. Function ToBinString:string; inline;
  820. Function ToHexString(const AMinDigits: Integer): string; overload; inline;
  821. Function ToHexString: string; overload; inline;
  822. Function ToString: string; overload; inline;
  823. Function SetBit(const Index: TShortIntBitIndex): Shortint; inline;
  824. Function ClearBit(const Index: TShortIntBitIndex): Shortint; inline;
  825. Function ToggleBit(const Index: TShortIntBitIndex): Shortint; inline;
  826. Function TestBit(const Index:TShortIntBitIndex):Boolean; inline;
  827. end;
  828. TSmallIntHelper = Type Helper for SmallInt
  829. public
  830. const
  831. MaxValue = 32767;
  832. MinValue = -32768;
  833. public
  834. Class Function Parse(const AString: string): SmallInt; inline; static;
  835. Class Function Size: Integer; inline; static;
  836. Class Function ToString(const AValue: SmallInt): string; overload; inline; static;
  837. Class Function TryParse(const AString: string; out AValue: SmallInt): Boolean; inline; static;
  838. public
  839. Function ToString: string; overload; inline;
  840. Function ToBoolean: Boolean; inline;
  841. Function ToBinString:string; inline;
  842. Function ToHexString: string; overload; inline;
  843. Function ToHexString(const AMinDigits: Integer): string; overload; inline;
  844. Function ToDouble: Double; inline;
  845. Function ToExtended: Extended; inline;
  846. Function SetBit(const Index: TSmallIntBitIndex) : Smallint; inline;
  847. Function ClearBit(const Index: TSmallIntBitIndex) : Smallint; inline;
  848. Function ToggleBit(const Index: TSmallIntBitIndex) : Smallint; inline;
  849. Function TestBit(const Index:TSmallIntBitIndex):Boolean; inline;
  850. end;
  851. TWordHelper = Type Helper for Word
  852. public
  853. const
  854. MaxValue = 65535;
  855. MinValue = 0;
  856. Public
  857. Class Function Parse(const AString: string): Word; inline; static;
  858. Class Function Size: Integer; inline; static;
  859. Class Function ToString(const AValue: Word): string; overload; inline; static;
  860. Class Function TryParse(const AString: string; out AValue: Word): Boolean; inline; static;
  861. Public
  862. Function ToBoolean: Boolean; inline;
  863. Function ToDouble: Double; inline;
  864. Function ToExtended: Extended; inline;
  865. Function ToBinString:string; inline;
  866. Function ToHexString(const AMinDigits: Integer): string; overload; inline;
  867. Function ToHexString: string; overload; inline;
  868. Function ToString: string; overload; inline;
  869. Function SetBit(const Index: TWordBitIndex) : Word; inline;
  870. Function ClearBit(const Index: TWordBitIndex) : Word; inline;
  871. Function ToggleBit(const Index: TWordBitIndex) : Word; inline;
  872. Function TestBit(const Index:TWordBitIndex):Boolean; inline;
  873. end;
  874. TCardinalHelper = Type Helper for Cardinal { for LongWord Type too }
  875. public
  876. const
  877. MaxValue = 4294967295;
  878. MinValue = 0;
  879. Public
  880. Class Function Parse(const AString: string): Cardinal; inline; static;
  881. Class Function Size: Integer; inline; static;
  882. Class Function ToString(const AValue: Cardinal): string; overload; inline; static;
  883. Class Function TryParse(const AString: string; out AValue: Cardinal): Boolean; inline; static;
  884. Public
  885. Function ToBoolean: Boolean; inline;
  886. Function ToDouble: Double; inline;
  887. Function ToExtended: Extended; inline;
  888. Function ToBinString:string; inline;
  889. Function ToHexString(const AMinDigits: Integer): string; overload; inline;
  890. Function ToHexString: string; overload; inline;
  891. Function ToString: string; overload; inline;
  892. Function SetBit(const Index: TCardinalBitIndex) : Cardinal; inline;
  893. Function ClearBit(const Index: TCardinalBitIndex) : Cardinal; inline;
  894. Function ToggleBit(const Index: TCardinalBitIndex) : Cardinal; inline;
  895. Function TestBit(const Index:TCardinalBitIndex):Boolean; inline;
  896. end;
  897. TIntegerHelper = Type Helper for Integer { for LongInt Type too }
  898. public
  899. const
  900. MaxValue = 2147483647;
  901. MinValue = -2147483648;
  902. Public
  903. Class Function Size: Integer; inline; static;
  904. Class Function ToString(const AValue: Integer): string; overload; inline; static;
  905. Class Function Parse(const AString: string): Integer; inline; static;
  906. Class Function TryParse(const AString: string; out AValue: Integer): Boolean; inline; static;
  907. Public
  908. Function ToBoolean: Boolean; inline;
  909. Function ToDouble: Double; inline;
  910. Function ToExtended: Extended; inline;
  911. Function ToBinString:string; inline;
  912. Function ToHexString(const AMinDigits: Integer): string; overload; inline;
  913. Function ToHexString: string; overload; inline;
  914. Function ToString: string; overload; inline;
  915. Function SetBit(const Index: TIntegerBitIndex) : Integer; inline;
  916. Function ClearBit(const Index: TIntegerBitIndex) : Integer; inline;
  917. Function ToggleBit(const Index: TIntegerBitIndex) : Integer; inline;
  918. Function TestBit(const Index:TIntegerBitIndex):Boolean; inline;
  919. end;
  920. TNativeIntHelper = Type Helper for NativeInt
  921. public
  922. const
  923. MaxValue = High(NativeInt);
  924. MinValue = Low(NativeInt);
  925. Public
  926. Class Function Parse(const AString: string): NativeInt; inline; static;
  927. Class Function Size: Integer; inline; static;
  928. Class Function ToString(const AValue: NativeInt): string; overload; inline; static;
  929. Class Function TryParse(const AString: string; out AValue: NativeInt): Boolean; inline; static;
  930. Public
  931. Function ToBoolean: Boolean; inline;
  932. Function ToDouble: Double; inline;
  933. Function ToExtended: Extended; inline;
  934. Function ToBinString:string; inline;
  935. Function ToHexString(const AMinDigits: Integer): string; overload; inline;
  936. Function ToHexString: string; overload; inline;
  937. Function ToString: string; overload; inline;
  938. Function SetBit(const Index: TNativeIntBitIndex) : NativeInt; inline;
  939. Function ClearBit(const Index: TNativeIntBitIndex) : NativeInt; inline;
  940. Function ToggleBit(const Index: TNativeIntBitIndex) : NativeInt; inline;
  941. Function TestBit(const Index:TNativeIntBitIndex):Boolean; inline;
  942. end;
  943. TNativeUIntHelper = Type Helper for NativeUInt
  944. public
  945. const
  946. MaxValue = High(NativeUInt);
  947. MinValue = 0;
  948. Public
  949. Class Function Parse(const AString: string): NativeUInt; inline; static;
  950. Class Function Size: Integer; inline; static;
  951. Class Function ToString(const AValue: NativeUInt): string; overload; inline; static;
  952. Class Function TryParse(const AString: string; out AValue: NativeUInt): Boolean; inline; static;
  953. Public
  954. Function ToBoolean: Boolean; inline;
  955. Function ToDouble: Double; inline;
  956. Function ToExtended: Extended; inline;
  957. Function ToBinString:string; inline;
  958. Function ToHexString(const AMinDigits: Integer): string; overload; inline;
  959. Function ToHexString: string; overload; inline;
  960. Function ToSingle: Single; inline;
  961. Function ToString: string; overload; inline;
  962. Function SetBit(const Index: TNativeUIntBitIndex) : NativeUint; inline;
  963. Function ClearBit(const Index: TNativeUIntBitIndex): NativeUint; inline;
  964. Function ToggleBit(const Index: TNativeUIntBitIndex) : NativeUint; inline;
  965. Function TestBit(const Index:TNativeUIntBitIndex) :Boolean; inline;
  966. end;
  967. {$SCOPEDENUMS ON}
  968. TUseBoolStrs = (False, True);
  969. {$SCOPEDENUMS OFF}
  970. TBooleanHelper = Type Helper for Boolean
  971. public
  972. Class Function Parse(const S: string): Boolean; inline; static;
  973. Class Function Size: Integer; inline; static;
  974. Class Function ToString(const AValue: Boolean; UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline; static;
  975. Class Function TryToParse(const S: string; out AValue: Boolean): Boolean; inline; static;
  976. Public
  977. Function ToInteger: Integer; inline;
  978. Function ToString(UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  979. end;
  980. TByteBoolHelper = Type Helper for ByteBool
  981. public
  982. Class Function Parse(const S: string): Boolean; inline; static;
  983. Class Function Size: Integer; inline; static;
  984. Class Function ToString(const AValue: Boolean; UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline; static;
  985. Class Function TryToParse(const S: string; out AValue: Boolean): Boolean; inline; static;
  986. Public
  987. Function ToInteger: Integer; inline;
  988. Function ToString(UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  989. end;
  990. TWordBoolHelper = Type Helper for WordBool
  991. public
  992. Class Function Parse(const S: string): Boolean; inline; static;
  993. Class Function Size: Integer; inline; static;
  994. Class Function ToString(const AValue: Boolean; UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline; static;
  995. Class Function TryToParse(const S: string; out AValue: Boolean): Boolean; inline; static;
  996. Public
  997. Function ToInteger: Integer; inline;
  998. Function ToString(UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  999. end;
  1000. TLongBoolHelper = Type Helper for LongBool
  1001. public
  1002. Class Function Parse(const S: string): Boolean; inline; static;
  1003. Class Function Size: Integer; inline; static;
  1004. Class Function ToString(const AValue: Boolean; UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline; static;
  1005. Class Function TryToParse(const S: string; out AValue: Boolean): Boolean; inline; static;
  1006. public
  1007. Function ToInteger: Integer; inline;
  1008. Function ToString(UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  1009. end;
  1010. implementation
  1011. { ---------------------------------------------------------------------
  1012. Exception handling
  1013. ---------------------------------------------------------------------}
  1014. Resourcestring
  1015. SAbortError = 'Operation aborted';
  1016. SApplicationException = 'Application raised an exception: ';
  1017. SErrUnknownExceptionType = 'Caught unknown exception type : ';
  1018. procedure DoShowException(S : String);
  1019. begin
  1020. if Assigned(OnShowException) then
  1021. OnShowException(S)
  1022. else
  1023. begin
  1024. {$IFDEF BROWSER}
  1025. asm
  1026. window.alert(S);
  1027. end;
  1028. {$ENDIF}
  1029. {$IFDEF NODEJS}
  1030. Writeln(S);
  1031. {$ENDIF}
  1032. end;
  1033. end;
  1034. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer = Nil);
  1035. Var
  1036. S : String;
  1037. begin
  1038. S:=SApplicationException+ExceptObject.ClassName;
  1039. if ExceptObject is Exception then
  1040. S:=S+' : '+Exception(ExceptObject).Message;
  1041. DoShowException(S);
  1042. if ExceptAddr=nil then;
  1043. end;
  1044. Type
  1045. TRTLExceptionHandler = procedure (aError : JSValue);
  1046. Var
  1047. rtlExceptionHandler : TRTLExceptionHandler; External name 'rtl.onUncaughtException';
  1048. rtlShowUncaughtExceptions : Boolean; External name 'rtl.showUncaughtExceptions';
  1049. OnPascalException : TUncaughtPascalExceptionHandler;
  1050. OnJSException : TUncaughtJSExceptionHandler;
  1051. Procedure RTLExceptionHook(aError : JSValue);
  1052. Var
  1053. S : String;
  1054. begin
  1055. if isClassInstance(aError) then
  1056. begin
  1057. if Assigned(OnPascalException) then
  1058. OnPascalException(TObject(aError))
  1059. else
  1060. ShowException(TObject(aError),Nil);
  1061. end
  1062. else if isObject(aError) then
  1063. begin
  1064. if Assigned(OnJSException) then
  1065. OnJSException(TJSObject(aError))
  1066. else
  1067. begin
  1068. if TJSObject(aError).hasOwnProperty('message') then
  1069. S:=SErrUnknownExceptionType+String(TJSObject(aError).Properties['message'])
  1070. else
  1071. S:=SErrUnknownExceptionType+TJSObject(aError).toString;
  1072. DoShowException(S);
  1073. end
  1074. end
  1075. else
  1076. begin
  1077. S:=SErrUnknownExceptionType+String(aError);
  1078. DoShowException(S);
  1079. end;
  1080. end;
  1081. Function SetOnUnCaughtExceptionHandler(aValue : TUncaughtPascalExceptionHandler) : TUncaughtPascalExceptionHandler;
  1082. begin
  1083. Result:=OnPascalException;
  1084. OnPascalException:=aValue;
  1085. HookUncaughtExceptions;
  1086. end;
  1087. Function SetOnUnCaughtExceptionHandler(aValue : TUncaughtJSExceptionHandler) : TUncaughtJSExceptionHandler;
  1088. begin
  1089. Result:=OnJSException;
  1090. OnJSException:=aValue;
  1091. HookUncaughtExceptions;
  1092. end;
  1093. Procedure HookUncaughtExceptions;
  1094. begin
  1095. rtlExceptionHandler:=@RTLExceptionHook;
  1096. rtlShowUncaughtExceptions:=True;
  1097. end;
  1098. procedure Abort;
  1099. begin
  1100. Raise EAbort.Create(SAbortError);
  1101. end;
  1102. Type
  1103. TCharSet = Set of Char;
  1104. Function CharInSet(Ch: Char;Const CSet : TCharSet) : Boolean;
  1105. begin
  1106. Result:=Ch in CSet;
  1107. end;
  1108. function CharInSet(Ch: Char; const CSet: array of char): Boolean;
  1109. Var
  1110. I : integer;
  1111. begin
  1112. Result:=False;
  1113. I:=Length(CSet)-1;
  1114. While (Not Result) and (I>=0) do
  1115. begin
  1116. Result:=(Ch=CSet[i]);
  1117. Dec(I);
  1118. end;
  1119. end;
  1120. function LeftStr(const S: string; Count: Integer): String; assembler;
  1121. asm
  1122. return (Count>0) ? S.substr(0,Count) : "";
  1123. end;
  1124. function RightStr(const S: string; Count: Integer): String; assembler;
  1125. asm
  1126. var l = S.length;
  1127. return (Count<1) ? "" : ( Count>=l ? S : S.substr(l-Count));
  1128. end;
  1129. function Trim(const S: String): String; assembler;
  1130. asm
  1131. return S.replace(/^[\s\uFEFF\xA0\x00-\x1f]+/,'').replace(/[\s\uFEFF\xA0\x00-\x1f]+$/,'');
  1132. end;
  1133. function TrimLeft(const S: String): String; assembler;
  1134. asm
  1135. return S.replace(/^[\s\uFEFF\xA0\x00-\x1f]+/,'');
  1136. end;
  1137. function TrimRight(const S: String): String; assembler;
  1138. asm
  1139. return S.replace(/[\s\uFEFF\xA0\x00-\x1f]+$/,'');
  1140. end;
  1141. function IntToStr(const Value: Integer): string;
  1142. begin
  1143. Result:=str(Value);
  1144. end;
  1145. function FloatToDecimal(Value: double; Precision, Decimals: integer): TFloatRec;
  1146. Const
  1147. Rounds = '123456789:';
  1148. var
  1149. Buffer: String; //Though str func returns only 25 chars, this might change in the future
  1150. InfNan: string;
  1151. OutPos,Error, N, L, C: Integer;
  1152. GotNonZeroBeforeDot, BeforeDot : boolean;
  1153. begin
  1154. Result.Negative:=False;
  1155. Result.Exponent:=0;
  1156. For C:=0 to FloatRecDigits do
  1157. Result.Digits[C]:='0';
  1158. if Value=0 then
  1159. exit;
  1160. asm
  1161. Buffer=Value.toPrecision(21); // Double precision
  1162. end;
  1163. // Writeln('Buffer :',Buffer);
  1164. N := 1;
  1165. L := Length(Buffer);
  1166. while Buffer[N]=' ' do
  1167. Inc(N);
  1168. Result.Negative := (Buffer[N] = '-');
  1169. if Result.Negative then
  1170. Inc(N)
  1171. else if (Buffer[N] = '+') then
  1172. inc(N);
  1173. { special cases for Inf and Nan }
  1174. if (L>=N+2) then
  1175. begin
  1176. InfNan:=copy(Buffer,N,3);
  1177. if (InfNan='Inf') then
  1178. begin
  1179. Result.Digits[0]:=#0;
  1180. Result.Exponent:=32767;
  1181. exit
  1182. end;
  1183. if (InfNan='Nan') then
  1184. begin
  1185. Result.Digits[0]:=#0;
  1186. Result.Exponent:=-32768;
  1187. exit
  1188. end;
  1189. end;
  1190. //Start := N; //Start of digits
  1191. Outpos:=0;
  1192. Result.Exponent := 0; BeforeDot := true;
  1193. GotNonZeroBeforeDot := false;
  1194. while (L>=N) and (Buffer[N]<>'E') do
  1195. begin
  1196. // Writeln('Examining : ',Buffer[N],'( output pos: ',outPos,')');
  1197. if Buffer[N]='.' then
  1198. BeforeDot := false
  1199. else
  1200. begin
  1201. if BeforeDot then
  1202. begin // Currently this is always 1 char
  1203. Inc(Result.Exponent);
  1204. Result.Digits[Outpos] := Buffer[N];
  1205. if Buffer[N] <> '0' then
  1206. GotNonZeroBeforeDot := true;
  1207. end
  1208. else
  1209. Result.Digits[Outpos] := Buffer[N];
  1210. Inc(outpos);
  1211. end;
  1212. Inc(N);
  1213. end;
  1214. Inc(N); // Pass through 'E'
  1215. if N<=L then
  1216. begin
  1217. Val(Copy(Buffer, N, L-N+1), C, Error); // Get exponent after 'E'
  1218. Inc(Result.Exponent, C);
  1219. end;
  1220. // Calculate number of digits we have from str
  1221. N:=OutPos;
  1222. // Writeln('Number of digits: ',N,' requested precision : ',Precision);
  1223. L:=Length(Result.Digits);
  1224. While N<L do
  1225. begin
  1226. Result.Digits[N]:='0'; //Zero remaining space
  1227. Inc(N);
  1228. end;
  1229. if Decimals + Result.Exponent < Precision Then //After this it is the same as in FloatToDecimal
  1230. N := Decimals + Result.Exponent
  1231. Else
  1232. N := Precision;
  1233. if N >= L Then
  1234. N := L-1;
  1235. // Writeln('Rounding on digit : ',N);
  1236. if N = 0 Then
  1237. begin
  1238. if Result.Digits[0] >= '5' Then
  1239. begin
  1240. Result.Digits[0] := '1';
  1241. Result.Digits[1] := #0;
  1242. Inc(Result.Exponent);
  1243. end
  1244. Else
  1245. Result.Digits[0] := #0;
  1246. end //N=0
  1247. Else if N > 0 Then
  1248. begin
  1249. if Result.Digits[N] >= '5' Then
  1250. begin
  1251. Repeat
  1252. Result.Digits[N] := #0;
  1253. Dec(N);
  1254. // Writeln(N,': ',Result.Digits[N],', Rounding to : ',Rounds[StrToInt(Result.Digits[N])]);
  1255. Result.Digits[N]:=Rounds[StrToInt(Result.Digits[N])+1];
  1256. Until (N = 0) Or (Result.Digits[N] < ':');
  1257. If Result.Digits[0] = ':' Then
  1258. begin
  1259. Result.Digits[0] := '1';
  1260. Inc(Result.Exponent);
  1261. end;
  1262. end
  1263. Else
  1264. begin
  1265. Result.Digits[N] := '0';
  1266. While (N > -1) And (Result.Digits[N] = '0') Do
  1267. begin
  1268. Result.Digits[N] := #0;
  1269. Dec(N);
  1270. end;
  1271. end;
  1272. end //N>0
  1273. Else
  1274. Result.Digits[0] := #0;
  1275. if (Result.Digits[0] = #0) and
  1276. not GotNonZeroBeforeDot then
  1277. begin
  1278. Result.Exponent := 0;
  1279. Result.Negative := False;
  1280. end;
  1281. end;
  1282. function FloatToStr(Value: Double): String;
  1283. begin
  1284. Result:=FloatToStrF(Value,ffGeneral,15,0);
  1285. end;
  1286. function TryStrToFloat(const S: String; out res: Extended): Boolean;
  1287. begin
  1288. Result:=TryStrToFloat(S,double(res));
  1289. end;
  1290. function TryStrToFloat(const S: String; out res: Double): Boolean;
  1291. Var
  1292. J : JSValue;
  1293. N : String;
  1294. begin
  1295. N:=S;
  1296. // Delocalize
  1297. if (ThousandSeparator <>'') then
  1298. N:=StringReplace(N,ThousandSeparator,'',[rfReplaceAll]);
  1299. if (DecimalSeparator<>'.') then
  1300. N:=StringReplace(N,DecimalSeparator,'.',[]);
  1301. J:=parseFloat(N);
  1302. Result:=Not jsIsNaN(J);
  1303. if Result then
  1304. Res:=Double(J);
  1305. end;
  1306. function StrToFloatDef(const S: String; const aDef: Double): Double;
  1307. begin
  1308. if not TryStrToFloat(S,Result) then
  1309. Result:=aDef;
  1310. end;
  1311. function StrToFloat(const S: String): Double;
  1312. begin
  1313. if not TryStrToFloat(S,Result) then
  1314. Raise EConvertError.CreateFmt(SErrInvalidFloat,[S]);
  1315. end;
  1316. function FormatFloat(Fmt: String; aValue: Double): String;
  1317. Type
  1318. TPosArray = Array of Integer;
  1319. const
  1320. MaxPrecision = 18; // Extended precision
  1321. var
  1322. // Input in usable format
  1323. E : Extended; // Value as extended.
  1324. FV: TFloatRec; // Value as floatrec.
  1325. Section : String; // Format can contain 3 sections, semicolon separated: Pos;Neg;Zero. This is the one to use.
  1326. SectionLength : Integer; // Length of section.
  1327. // Calculated based on section. Static during output
  1328. ThousandSep: Boolean; // Thousands separator detected in format ?
  1329. IsScientific: Boolean; // Use Scientific notation ? (E detected in format)
  1330. DecimalPos: Integer; // Position of decimal point in pattern.
  1331. FirstDigit: Integer; // First actual digit in input (# or 0), relative to decimal point
  1332. LastDigit: Integer; // Last required (0) digit, relative to decimal point
  1333. RequestedDigits: Integer; // Number of requested digits, # and 0 alike
  1334. ExpSize : Integer; // Number of digits in exponent
  1335. Available: Integer; // Available digits in FV.
  1336. // These change during output loop
  1337. Current: Integer; // Current digit in available digits
  1338. PadZeroes: Integer; // Difference in requested digits before comma and exponent, needs to be padded with zeroes.
  1339. DistToDecimal: Integer; // Place of current digit, relative to decimal point taking in account PadZeroes!
  1340. Procedure InitVars;
  1341. begin
  1342. E:=aValue;
  1343. Section:='';
  1344. SectionLength:=0;
  1345. ThousandSep:=false;
  1346. IsScientific:=false;
  1347. DecimalPos:=0;
  1348. FirstDigit:=MaxInt;
  1349. LastDigit:=0;
  1350. RequestedDigits:=0;
  1351. ExpSize:=0;
  1352. Available:=-1;
  1353. end;
  1354. procedure ToResult(const AChar: Char);
  1355. begin
  1356. Result:=Result+AChar;
  1357. end;
  1358. procedure AddToResult(const AStr: String);
  1359. begin
  1360. Result:=Result+AStr;
  1361. end;
  1362. procedure WriteDigit(ADigit: Char);
  1363. // Write a digit to result, prepend with decimalseparator or append with 1000 separator
  1364. begin
  1365. if ADigit=#0 then exit;
  1366. // Writeln('WriteDigit: ',ADigit,', DistToDecimal: ',DistToDecimal);
  1367. Dec(DistToDecimal);
  1368. // -1 -> we've arrived behind the decimal
  1369. if (DistToDecimal=-1) then
  1370. begin
  1371. AddToResult(DecimalSeparator);
  1372. ToResult(ADigit);
  1373. end
  1374. else
  1375. begin
  1376. // We're still before the decimal.
  1377. ToResult(ADigit);
  1378. if ThousandSep and ((DistToDecimal mod 3)=0) and (DistToDecimal>1) then
  1379. AddToResult(ThousandSeparator);
  1380. end;
  1381. end;
  1382. Function GetDigit : Char;
  1383. // Return next digit from available digits.
  1384. // May return #0 if none available.
  1385. // Will return '0' if applicable.
  1386. begin
  1387. // Writeln(' DistToDecimal <= LastDigit : ',DistToDecimal,' <= ',LastDigit,' have digit: ',Current<=Available, ' (',Current,')');
  1388. Result:=#0;
  1389. if (Current<=Available) then
  1390. begin
  1391. Result:=FV.Digits[Current];
  1392. Inc(Current);
  1393. end
  1394. else if (DistToDecimal <= LastDigit) then
  1395. Dec(DistToDecimal)
  1396. else
  1397. Result:='0';
  1398. // Writeln('GetDigit ->: ',Result);
  1399. end;
  1400. procedure CopyDigit;
  1401. // Copy a digit (#, 0) to the output with the correct value
  1402. begin
  1403. // Writeln('CopyDigit: Padzeroes: ',PadZeroes,', DistToDecimal: ',DistToDecimal);
  1404. if (PadZeroes=0) then
  1405. WriteDigit(GetDigit) // No shift needed, just copy what is available.
  1406. else if (PadZeroes<0) then
  1407. begin
  1408. // We must prepend zeroes
  1409. Inc(PadZeroes);
  1410. if (DistToDecimal<=FirstDigit) then
  1411. WriteDigit('0')
  1412. else
  1413. Dec(DistToDecimal);
  1414. end
  1415. else
  1416. begin
  1417. // We must append zeroes
  1418. while PadZeroes > 0 do
  1419. begin
  1420. WriteDigit(GetDigit);
  1421. Dec(PadZeroes);
  1422. end;
  1423. WriteDigit(GetDigit);
  1424. end;
  1425. end;
  1426. Function GetSections(Var SP : TPosArray) : Integer;
  1427. var
  1428. FL : Integer;
  1429. i : Integer;
  1430. C,Q : Char;
  1431. inQuote : Boolean;
  1432. begin
  1433. Result:=1;
  1434. SP[1]:=-1;
  1435. SP[2]:=-1;
  1436. SP[3]:=-1;
  1437. inQuote:=False;
  1438. Q:=#0;
  1439. I:=1;
  1440. FL:=Length(Fmt);
  1441. while (I<=FL) do
  1442. begin
  1443. C:=Fmt[I];
  1444. case C of
  1445. ';':
  1446. begin
  1447. if not InQuote then
  1448. begin
  1449. if Result>3 then
  1450. Raise Exception.Create('Invalid float format');
  1451. SP[Result]:=I+1;
  1452. Inc(Result);
  1453. end;
  1454. end;
  1455. '"','''':
  1456. begin
  1457. if InQuote then
  1458. InQuote:=C<>Q
  1459. else
  1460. begin
  1461. InQuote:=True;
  1462. Q:=C;
  1463. end;
  1464. end;
  1465. end;
  1466. Inc(I);
  1467. end;
  1468. if SP[Result]=-1 then
  1469. SP[Result]:=FL+1;
  1470. end;
  1471. Procedure AnalyzeFormat;
  1472. var
  1473. I,Len: Integer;
  1474. Q,C: Char;
  1475. InQuote : Boolean;
  1476. begin
  1477. Len:=Length(Section);
  1478. I:=1;
  1479. InQuote:=False;
  1480. Q:=#0;
  1481. while (I<=Len) do
  1482. begin
  1483. C:=Section[i];
  1484. if C in ['"',''''] then
  1485. begin
  1486. if InQuote then
  1487. InQuote:=C<>Q
  1488. else
  1489. begin
  1490. InQuote:=True;
  1491. Q:=C;
  1492. end;
  1493. end
  1494. else if not InQuote then
  1495. case C of
  1496. '.':
  1497. if (DecimalPos=0) then
  1498. DecimalPos:=RequestedDigits+1;
  1499. ',':
  1500. ThousandSep:=ThousandSeparator<>#0;
  1501. 'e', 'E':
  1502. begin
  1503. Inc(I);
  1504. if (I<Len) then
  1505. begin
  1506. C:=Section[i];
  1507. IsScientific:=C in ['-','+'];
  1508. if IsScientific then
  1509. while (I<Len) and (Section[i+1]='0') do
  1510. begin
  1511. Inc(ExpSize);
  1512. Inc(I);
  1513. end;
  1514. if ExpSize>4 then
  1515. ExpSize:=4;
  1516. end;
  1517. end;
  1518. '#':
  1519. Inc(RequestedDigits);
  1520. '0':
  1521. begin
  1522. if RequestedDigits<FirstDigit then
  1523. FirstDigit:=RequestedDigits+1;
  1524. Inc(RequestedDigits);
  1525. LastDigit:=RequestedDigits+1;
  1526. end;
  1527. end;
  1528. Inc(I);
  1529. end;
  1530. if DecimalPos=0 then
  1531. DecimalPos:=RequestedDigits+1;
  1532. // Writeln('LastDigit: ',DecimalPos,'-',LastDigit);
  1533. LastDigit:=DecimalPos-LastDigit;
  1534. if LastDigit>0 then
  1535. LastDigit:=0;
  1536. // Writeln('FirstDigit: ',DecimalPos,'-',FirstDigit);
  1537. FirstDigit:=DecimalPos-FirstDigit;
  1538. if FirstDigit<0 then
  1539. FirstDigit:=0;
  1540. end;
  1541. Function ValueOutSideScope : Boolean;
  1542. begin
  1543. With FV do
  1544. Result:=((Exponent >= 18) and (not IsScientific)) or (Exponent = $7FF) or (Exponent = $800)
  1545. end;
  1546. Procedure CalcRunVars;
  1547. Var
  1548. D,P: Integer;
  1549. begin
  1550. if IsScientific then
  1551. begin
  1552. P:=RequestedDigits;
  1553. D:=9999;
  1554. end
  1555. else
  1556. begin
  1557. P:=MaxPrecision;
  1558. D:=RequestedDigits-DecimalPos+1;
  1559. end;
  1560. FV:=FloatToDecimal(aValue,P,D);
  1561. // Writeln('Number of digits available : ',Length(FV.Digits));
  1562. // For p:=0 to Length(FV.Digits)-1 do
  1563. // Writeln(P,': ',FV.Digits[p]);
  1564. DistToDecimal:=DecimalPos-1;
  1565. // Writeln('DistToDecimal : ',DistToDecimal);
  1566. if IsScientific then
  1567. PadZeroes:=0 // No padding.
  1568. else
  1569. begin
  1570. PadZeroes:=FV.Exponent-(DecimalPos-1);
  1571. if (PadZeroes>=0) then
  1572. DistToDecimal:=FV.Exponent
  1573. end;
  1574. // Writeln('PadZeroes : ',PadZeroes, ', DistToDecimal : ',DistToDecimal);
  1575. Available:=-1;
  1576. while (Available<High(FV.Digits)) and (FV.Digits[Available+1]<>#0) do
  1577. Inc(Available);
  1578. // Writeln('Available: ',Available);
  1579. end;
  1580. Function FormatExponent(ASign: Char; aExponent: Integer) : String;
  1581. begin
  1582. Result:=IntToStr(aExponent);
  1583. Result:=StringOfChar('0',ExpSize-Length(Result))+Result;
  1584. if (aExponent<0) then
  1585. Result:='-'+Result
  1586. else if (aExponent>0) and (aSign='+') then
  1587. Result:=aSign+Result;
  1588. end;
  1589. var
  1590. I,S : Integer;
  1591. C,Q : Char;
  1592. PA : TPosArray;
  1593. InLiteral : Boolean;
  1594. begin
  1595. SetLength(PA,4);
  1596. Result:='';
  1597. Initvars;
  1598. // What section to use ?
  1599. if (E>0) then
  1600. S:=1
  1601. else if (E<0) then
  1602. S:=2
  1603. else
  1604. S:=3;
  1605. PA[0]:=0;
  1606. I:=GetSections(PA);
  1607. if (I<S) or (PA[S]-PA[S-1]=0) then
  1608. S:=1;
  1609. // Extract correct section
  1610. SectionLength:=PA[S]-PA[S-1]-1;
  1611. Section:=Copy(Fmt,PA[S-1]+1,SectionLength);
  1612. SetLength(Section,SectionLength);
  1613. // Writeln('Section ',I,' : "',Section,'" ',SectionLength);
  1614. AnalyzeFormat;
  1615. // Writeln('RequestedDigits: ',RequestedDigits,', DecimalPos : ',DecimalPos,', LastDigit: ',LastDigit,', FirstDigit: ',FirstDigit);
  1616. CalcRunVars;
  1617. // If we cannot process value using current settings, fallback
  1618. if (SectionLength=0) or ValueOutSideScope then
  1619. begin
  1620. asm
  1621. Section=E.toPrecision(15);
  1622. end;
  1623. Result:=Section;
  1624. end;
  1625. // Get Started
  1626. I:=1;
  1627. Current:=0;
  1628. Q:=' ';
  1629. InLiteral:=False;
  1630. if (FV.Negative) and (S=1) then
  1631. ToResult('-');
  1632. while (I<=SectionLength) do
  1633. begin
  1634. C:=Section[i];
  1635. // Writeln('Analyzing pos ',I,': "',C,'"');
  1636. If (C in ['"', '''']) then
  1637. begin
  1638. if InLiteral then
  1639. InLiteral:=C<>Q
  1640. else
  1641. begin
  1642. inLiteral:=True;
  1643. Q:=C;
  1644. end;
  1645. end
  1646. else if InLiteral then
  1647. ToResult(C)
  1648. else
  1649. case C of
  1650. '0', '#':
  1651. CopyDigit;
  1652. '.', ',':
  1653. ; // Do nothing, handled by CopyDigit
  1654. 'e', 'E':
  1655. begin
  1656. ToResult(C); // Always needed
  1657. Inc(I);
  1658. if I<=Length(Section) then
  1659. begin
  1660. C:=Section[I];
  1661. if (C in ['+','-']) then
  1662. begin
  1663. AddToResult(FormatExponent(C,FV.Exponent-DecimalPos+1));
  1664. // Skip rest
  1665. while (I<SectionLength) and (Section[i+1]='0') do
  1666. Inc(I);
  1667. end;
  1668. end;
  1669. end;
  1670. else
  1671. ToResult(C);
  1672. end;
  1673. Inc(i);
  1674. end;
  1675. end;
  1676. function StrToBool(const S: String): Boolean;
  1677. begin
  1678. if not(TryStrToBool(S,Result)) then
  1679. raise EConvertError.CreateFmt(SInvalidBoolean,[S]);
  1680. end;
  1681. procedure CheckBoolStrs;
  1682. begin
  1683. if Length(TrueBoolStrs)=0 then
  1684. begin
  1685. SetLength(TrueBoolStrs,1);
  1686. TrueBoolStrs[0]:='True';
  1687. end;
  1688. if Length(FalseBoolStrs)=0 then
  1689. begin
  1690. SetLength(FalseBoolStrs,1);
  1691. FalseBoolStrs[0]:='False';
  1692. end;
  1693. end;
  1694. function BoolToStr(B: Boolean; UseBoolStrs: Boolean): string;
  1695. begin
  1696. if UseBoolStrs Then
  1697. begin
  1698. CheckBoolStrs;
  1699. if B then
  1700. Result:=TrueBoolStrs[0]
  1701. else
  1702. Result:=FalseBoolStrs[0];
  1703. end else
  1704. if B then
  1705. Result:='-1'
  1706. else
  1707. Result:='0';
  1708. end;
  1709. function BoolToStr(B: Boolean; const TrueS, FalseS: String): string;
  1710. begin
  1711. if B then Result:=TrueS else Result:=FalseS;
  1712. end;
  1713. function StrToBoolDef(const S: String; Default: Boolean): Boolean;
  1714. begin
  1715. if not TryStrToBool(S,Result) then
  1716. Result:=Default;
  1717. end;
  1718. function TryStrToBool(const S: String; out Value: Boolean): Boolean;
  1719. Var
  1720. Temp : String;
  1721. I : Longint;
  1722. D : Double;
  1723. Code: integer;
  1724. begin
  1725. Temp:=uppercase(S);
  1726. Val(Temp,D,code);
  1727. Result:=true;
  1728. If Code=0 then
  1729. Value:=(D<>0.0)
  1730. else
  1731. begin
  1732. CheckBoolStrs;
  1733. for I:=low(TrueBoolStrs) to High(TrueBoolStrs) do
  1734. if Temp=uppercase(TrueBoolStrs[I]) then
  1735. begin
  1736. Value:=true;
  1737. exit;
  1738. end;
  1739. for I:=low(FalseBoolStrs) to High(FalseBoolStrs) do
  1740. if Temp=uppercase(FalseBoolStrs[I]) then
  1741. begin
  1742. Value:=false;
  1743. exit;
  1744. end;
  1745. Result:=false;
  1746. end;
  1747. end;
  1748. function UpperCase(const s: String): String; assembler;
  1749. asm
  1750. return s.toUpperCase();
  1751. end;
  1752. function LowerCase(const s: String): String; assembler;
  1753. asm
  1754. return s.toLowerCase();
  1755. end;
  1756. function CompareStr(const s1, s2: String): Integer; assembler;
  1757. asm
  1758. var l1 = s1.length;
  1759. var l2 = s2.length;
  1760. if (l1<=l2){
  1761. var s = s2.substr(0,l1);
  1762. if (s1<s){ return -1;
  1763. } else if (s1>s){ return 1;
  1764. } else { return l1<l2 ? -1 : 0; };
  1765. } else {
  1766. var s = s1.substr(0,l2);
  1767. if (s<s2){ return -1;
  1768. } else { return 1; };
  1769. };
  1770. end;
  1771. function SameStr(const s1, s2: String): Boolean; assembler;
  1772. asm
  1773. return s1 == s2;
  1774. end;
  1775. function CompareText(const s1, s2: String): Integer; assembler;
  1776. asm
  1777. var l1 = s1.toLowerCase();
  1778. var l2 = s2.toLowerCase();
  1779. if (l1>l2){ return 1;
  1780. } else if (l1<l2){ return -1;
  1781. } else { return 0; }
  1782. end;
  1783. function SameText(const s1, s2: String): Boolean; assembler;
  1784. asm
  1785. return s1.toLowerCase() == s2.toLowerCase();
  1786. end;
  1787. function AnsiCompareText(const s1, s2: String): Integer; assembler;
  1788. asm
  1789. return s1.localeCompare(s2);
  1790. end;
  1791. function AnsiSameText(const s1, s2: String): Boolean; assembler;
  1792. asm
  1793. return s1.toLowerCase() == s2.toLowerCase();
  1794. end;
  1795. function AnsiCompareStr(const s1, s2: String): Integer;
  1796. begin
  1797. {$IFDEF ECMAScript6}
  1798. Result:=CompareText(TJSString(s1).normalize(),TJSString(s2).normalize());
  1799. {$ELSE}
  1800. Result:=CompareText(s1,s2);
  1801. {$ENDIF}
  1802. end;
  1803. procedure AppendStr(var Dest: String; const S: string);
  1804. begin
  1805. Dest:=Dest+S;
  1806. end;
  1807. Const
  1808. feInvalidFormat = 1;
  1809. feMissingArgument = 2;
  1810. feInvalidArgIndex = 3;
  1811. Procedure DoFormatError (ErrCode : Longint;const fmt: String);
  1812. begin
  1813. //!! must be changed to contain format string...
  1814. Case ErrCode of
  1815. feInvalidFormat : raise EConvertError.Createfmt(SInvalidFormat,[Fmt]);
  1816. feMissingArgument : raise EConvertError.Createfmt(SArgumentMissing,[Fmt]);
  1817. feInvalidArgIndex : raise EConvertError.Createfmt(SInvalidArgIndex,[Fmt]);
  1818. end;
  1819. end;
  1820. Const
  1821. maxdigits = 15;
  1822. Function SwapEndian(W : Word) : Word;
  1823. begin
  1824. Result:=((W and $FF) shl 8) or ((W shr 8) and $FF)
  1825. end;
  1826. Function SwapEndian(C : Cardinal) : Cardinal;
  1827. begin
  1828. Result:=((C and $FF) shl 24)
  1829. or ((C and $FF00) shl 8)
  1830. or ((C shr 8) and $FF00)
  1831. or ((C shr 24) and $FF);
  1832. end;
  1833. Function ReplaceDecimalSep(S: String; Const DS : string) : string;
  1834. Var
  1835. P : Integer;
  1836. begin
  1837. P:=Pos('.',S);
  1838. if P>0 then
  1839. Result:=Copy(S,1,P-1)+DS+Copy(S,P+1,Length(S)-P)
  1840. else
  1841. Result:=S;
  1842. end;
  1843. function FormatGeneralFloat(Value : double; Precision : Integer; DS : String) : string;
  1844. Var
  1845. P, PE, Q, Exponent: Integer;
  1846. Begin
  1847. If (Precision = -1) Or (Precision > maxdigits) Then
  1848. Precision := maxdigits;
  1849. { First convert to scientific format, with correct precision }
  1850. Str(Value:precision+7, Result);
  1851. { Delete leading spaces }
  1852. Result:=TrimLeft(Result);
  1853. P:=Pos('.',Result);
  1854. if P=0 then
  1855. exit;
  1856. { Consider removing exponent }
  1857. PE:=Pos('E',Result);
  1858. if PE=0 then
  1859. begin
  1860. Result:=ReplaceDecimalSep(Result,DS);
  1861. exit;
  1862. end;
  1863. { Read exponent }
  1864. Q:=PE+2;
  1865. Exponent := 0;
  1866. while (Q <= Length(Result)) do
  1867. begin
  1868. Exponent := Exponent*10 + Ord(Result[Q])-Ord('0');
  1869. Inc(Q);
  1870. end;
  1871. if Result[PE+1] = '-' then
  1872. Exponent := -Exponent;
  1873. if (P+Exponent < PE) and (Exponent > -6) then
  1874. begin
  1875. { OK to remove exponent }
  1876. SetLength(Result,PE-1); { Trim exponent }
  1877. if Exponent >= 0 then
  1878. begin
  1879. { Shift point to right }
  1880. for Q := 0 to Exponent-1 do
  1881. begin
  1882. Result[P] := Result[P+1];
  1883. Inc(P);
  1884. end;
  1885. Result[P] := '.';
  1886. P := 1;
  1887. if Result[P] = '-' then
  1888. Inc(P);
  1889. while (Result[P] = '0') and (P < Length(Result)) and (Copy(Result,P+1,Length(DS))<>DS) do
  1890. { Trim leading zeros; conversion above should not give any, but occasionally does
  1891. because of rounding }
  1892. System.Delete(Result,P,1);
  1893. end
  1894. else
  1895. begin
  1896. { Add zeros at start }
  1897. Insert(Copy('00000',1,-Exponent),Result,P-1);
  1898. Result[P-Exponent] := Result[P-Exponent-1]; { Copy leading digit }
  1899. Result[P] := '.';
  1900. if Exponent <> -1 then
  1901. Result[P-Exponent-1] := '0';
  1902. end;
  1903. { Remove trailing zeros }
  1904. Q := Length(Result);
  1905. while (Q > 0) and (Result[Q] = '0') do
  1906. Dec(Q);
  1907. if Result[Q] = '.' then
  1908. Dec(Q); { Remove trailing decimal point }
  1909. if (Q = 0) or ((Q=1) and (Result[1] = '-')) then
  1910. Result := '0'
  1911. else
  1912. SetLength(Result,Q);
  1913. end
  1914. else
  1915. begin
  1916. { Need exponent, but remove superfluous characters }
  1917. { Delete trailing zeros }
  1918. while Result[PE-1] = '0' do
  1919. begin
  1920. System.Delete(Result,PE-1,1);
  1921. Dec(PE);
  1922. end;
  1923. { If number ends in decimal point, remove it }
  1924. if Result[PE-1] = DS then
  1925. begin
  1926. System.Delete(Result,PE-1,1);
  1927. Dec(PE);
  1928. end;
  1929. { delete superfluous + in exponent }
  1930. if Result[PE+1]='+' then
  1931. System.Delete(Result,PE+1,1)
  1932. else
  1933. Inc(PE);
  1934. while Result[PE+1] = '0' do
  1935. { Delete leading zeros in exponent }
  1936. System.Delete(Result,PE+1,1)
  1937. end;
  1938. Result:=ReplaceDecimalSep(Result,DS)
  1939. end;
  1940. function FormatExponentFloat(Value : double; Precision,Digits : Integer;DS : String) : string;
  1941. Var
  1942. P: Integer;
  1943. Begin
  1944. DS:=DecimalSeparator;
  1945. If (Precision = -1) Or (Precision > maxdigits) Then
  1946. Precision := maxdigits;
  1947. Str(Value:Precision+7, Result);
  1948. { Delete leading spaces }
  1949. while Result[1] = ' ' do
  1950. System.Delete(Result, 1, 1);
  1951. P:=Pos('E',Result);
  1952. if P=0 then
  1953. begin
  1954. Result:=ReplaceDecimalSep(Result,DS);
  1955. exit;
  1956. end;
  1957. Inc(P, 2);
  1958. if Digits > 4 then
  1959. Digits:=4;
  1960. Digits:=Length(Result) - P - Digits + 1;
  1961. if Digits < 0 then
  1962. insert(copy('0000',1,-Digits),Result,P)
  1963. else
  1964. while (Digits > 0) and (Result[P] = '0') do
  1965. begin
  1966. System.Delete(Result, P, 1);
  1967. if P > Length(Result) then
  1968. begin
  1969. System.Delete(Result, P - 2, 2);
  1970. break;
  1971. end;
  1972. Dec(Digits);
  1973. end;
  1974. Result:=ReplaceDecimalSep(Result,DS);
  1975. End;
  1976. function FormatFixedFloat(Value : double; Digits : Integer; DS : String) : string;
  1977. Begin
  1978. If Digits = -1 Then
  1979. Digits := 2
  1980. Else If Digits > 18 Then
  1981. Digits := 18;
  1982. Str(Value:0:Digits, Result);
  1983. if (Result<>'') and (Result[1]=' ') then
  1984. Delete(Result,1,1);
  1985. Result:=ReplaceDecimalSep(Result,DS);
  1986. end;
  1987. function FormatNumberFloat(Value : double; Digits : Integer; DS,TS : String) : string;
  1988. Var
  1989. P : integer;
  1990. Begin
  1991. If Digits = -1 Then
  1992. Digits := 2
  1993. else If Digits > maxdigits Then
  1994. Digits := maxdigits;
  1995. Str(Value:0:Digits, Result);
  1996. if (Result<>'') and (Result[1]=' ') then
  1997. Delete(Result,1,1);
  1998. P:=Pos('.',Result);
  1999. if (P<=0) then
  2000. P:=Length(Result)+1;
  2001. Result:=ReplaceDecimalSep(Result,DS);
  2002. Dec(P,3);
  2003. if (TS<>'') and (TS<>#0) then
  2004. While (P>1) Do
  2005. Begin
  2006. If (Result[P-1] <> '-') Then
  2007. Insert(TS, Result, P);
  2008. Dec(P, 3);
  2009. End;
  2010. End;
  2011. function RemoveLeadingNegativeSign(var AValue: String; DS : String): Boolean;
  2012. // removes negative sign in case when result is zero eg. -0.00
  2013. var
  2014. i: PtrInt;
  2015. TS: String;
  2016. StartPos: PtrInt;
  2017. begin
  2018. Result:=False;
  2019. StartPos := 2;
  2020. TS := ThousandSeparator;
  2021. for i :=StartPos to length(AValue) do
  2022. begin
  2023. Result := (AValue[i] in ['0', DS, 'E', '+']) or (aValue[i]=TS);
  2024. if not Result then
  2025. break;
  2026. end;
  2027. if (Result) and (AValue[1]='-') then
  2028. Delete(AValue, 1, 1);
  2029. end;
  2030. Function FormatNumberCurrency(const Value : Currency; Digits : Integer; DS,TS : String) : string;
  2031. Var
  2032. Negative: Boolean;
  2033. P : Integer;
  2034. Begin
  2035. // Writeln('Value ',D);
  2036. If Digits = -1 Then
  2037. Digits := CurrencyDecimals
  2038. Else If Digits > 18 Then
  2039. Digits := 18;
  2040. Str(Value:0:Digits, Result);
  2041. // Writeln('1. Result ',Result,' currencystring : ',CurrencyString);
  2042. Negative:=Result[1] = '-';
  2043. if Negative then
  2044. System.Delete(Result, 1, 1);
  2045. P := Pos('.', Result);
  2046. // Writeln('2. Result ',Result,' currencystring : ',CurrencyString);
  2047. If TS<>'' Then
  2048. begin
  2049. If P <> 0 Then
  2050. Result:=ReplaceDecimalSep(Result,DS)
  2051. else
  2052. P := Length(Result)+1;
  2053. Dec(P, 3);
  2054. While (P > 1) Do
  2055. Begin
  2056. Insert(TS, Result, P);
  2057. Dec(P, 3);
  2058. End;
  2059. end;
  2060. // Writeln('3. Result ',Result,' currencystring : ',CurrencyString);
  2061. if Negative then
  2062. RemoveLeadingNegativeSign(Result,DS);
  2063. // Writeln('4. Result ',Result,' currencystring : ',CurrencyString);
  2064. // Writeln('CurrencyFormat: ',CurrencyFormat,'NegcurrencyFormat: ',NegCurrFormat);
  2065. If Not Negative Then
  2066. Case CurrencyFormat Of
  2067. 0: Result := CurrencyString + Result;
  2068. 1: Result := Result + CurrencyString;
  2069. 2: Result := CurrencyString + ' ' + Result;
  2070. 3: Result := Result + ' ' + CurrencyString;
  2071. end
  2072. else
  2073. Case NegCurrFormat Of
  2074. 0: Result := '(' + CurrencyString + Result + ')';
  2075. 1: Result := '-' + CurrencyString + Result;
  2076. 2: Result := CurrencyString + '-' + Result;
  2077. 3: Result := CurrencyString + Result + '-';
  2078. 4: Result := '(' + Result + CurrencyString + ')';
  2079. 5: Result := '-' + Result + CurrencyString;
  2080. 6: Result := Result + '-' + CurrencyString;
  2081. 7: Result := Result + CurrencyString + '-';
  2082. 8: Result := '-' + Result + ' ' + CurrencyString;
  2083. 9: Result := '-' + CurrencyString + ' ' + Result;
  2084. 10: Result := Result + ' ' + CurrencyString + '-';
  2085. 11: Result := CurrencyString + ' ' + Result + '-';
  2086. 12: Result := CurrencyString + ' ' + '-' + Result;
  2087. 13: Result := Result + '-' + ' ' + CurrencyString;
  2088. 14: Result := '(' + CurrencyString + ' ' + Result + ')';
  2089. 15: Result := '(' + Result + ' ' + CurrencyString + ')';
  2090. end;
  2091. end;
  2092. function FloatToStrF(const Value: double; format: TFloatFormat; Precision,
  2093. Digits: Integer): String;
  2094. Var
  2095. DS: string;
  2096. Begin
  2097. DS:=DecimalSeparator;
  2098. Case format Of
  2099. ffGeneral:
  2100. Result:=FormatGeneralFloat(Value,Precision,DS);
  2101. ffExponent:
  2102. Result:=FormatExponentFloat(Value,Precision,Digits,DS);
  2103. ffFixed:
  2104. Result:=FormatFixedFloat(Value,Digits,DS);
  2105. ffNumber:
  2106. Result:=FormatNumberFloat(Value,Digits,DS,ThousandSeparator);
  2107. ffCurrency:
  2108. Result:=FormatNumberCurrency(Value,Digits,DS,ThousandSeparator);
  2109. end;
  2110. if (Format<>ffCurrency) and (length(Result)>1) and (Result[1]='-') then
  2111. RemoveLeadingNegativeSign(Result,DS);
  2112. end;
  2113. function Format(const Fmt: String; const Args: array of JSValue): String;
  2114. Var ChPos,OldPos,ArgPos,DoArg,Len : SizeInt;
  2115. Hs,ToAdd : String;
  2116. Index : Byte;
  2117. Width,Prec : Longint;
  2118. Left : Boolean;
  2119. Fchar : char;
  2120. vq : nativeint;
  2121. {
  2122. ReadFormat reads the format string. It returns the type character in
  2123. uppercase, and sets index, Width, Prec to their correct values,
  2124. or -1 if not set. It sets Left to true if left alignment was requested.
  2125. In case of an error, DoFormatError is called.
  2126. }
  2127. Function ReadFormat : Char;
  2128. Var Value : NativeInt;
  2129. Procedure ReadInteger;
  2130. var
  2131. Code: integer;
  2132. ArgN: SizeInt;
  2133. begin
  2134. If Value<>-1 then exit; // Was already read.
  2135. OldPos:=ChPos;
  2136. While (ChPos<=Len) and
  2137. (Fmt[ChPos]<='9') and (Fmt[ChPos]>='0') do inc(ChPos);
  2138. If ChPos>len then
  2139. DoFormatError(feInvalidFormat,Fmt);
  2140. If Fmt[ChPos]='*' then
  2141. begin
  2142. if Index=High(byte) then
  2143. ArgN:=Argpos
  2144. else
  2145. begin
  2146. ArgN:=Index;
  2147. Inc(Index);
  2148. end;
  2149. If (ChPos>OldPos) or (ArgN>High(Args)) then
  2150. DoFormatError(feInvalidFormat,Fmt);
  2151. ArgPos:=ArgN+1;
  2152. if IsNumber(Args[ArgN]) and IsInteger(Args[ArgN]) then
  2153. Value:=Integer(Args[ArgN])
  2154. else
  2155. DoFormatError(feInvalidFormat,Fmt);
  2156. Inc(ChPos);
  2157. end
  2158. else
  2159. begin
  2160. If (OldPos<ChPos) Then
  2161. begin
  2162. Val (Copy(Fmt,OldPos,ChPos-OldPos),value,code);
  2163. // This should never happen !!
  2164. If Code>0 then DoFormatError (feInvalidFormat,Fmt);
  2165. end
  2166. else
  2167. Value:=-1;
  2168. end;
  2169. end;
  2170. Procedure ReadIndex;
  2171. begin
  2172. If Fmt[ChPos]<>':' then
  2173. ReadInteger
  2174. else
  2175. value:=0; // Delphi undocumented behaviour, assume 0, #11099
  2176. If Fmt[ChPos]=':' then
  2177. begin
  2178. If Value=-1 then DoFormatError(feMissingArgument,Fmt);
  2179. Index:=Value;
  2180. Value:=-1;
  2181. Inc(ChPos);
  2182. end;
  2183. end;
  2184. Procedure ReadLeft;
  2185. begin
  2186. If Fmt[ChPos]='-' then
  2187. begin
  2188. left:=True;
  2189. Inc(ChPos);
  2190. end
  2191. else
  2192. Left:=False;
  2193. end;
  2194. Procedure ReadWidth;
  2195. begin
  2196. ReadInteger;
  2197. If Value<>-1 then
  2198. begin
  2199. Width:=Value;
  2200. Value:=-1;
  2201. end;
  2202. end;
  2203. Procedure ReadPrec;
  2204. begin
  2205. If Fmt[ChPos]='.' then
  2206. begin
  2207. inc(ChPos);
  2208. ReadInteger;
  2209. If Value=-1 then
  2210. Value:=0;
  2211. prec:=Value;
  2212. end;
  2213. end;
  2214. begin
  2215. Index:=High(byte);
  2216. Width:=-1;
  2217. Prec:=-1;
  2218. Value:=-1;
  2219. inc(ChPos);
  2220. If Fmt[ChPos]='%' then
  2221. begin
  2222. Result:='%';
  2223. exit; // VP fix
  2224. end;
  2225. ReadIndex;
  2226. ReadLeft;
  2227. ReadWidth;
  2228. ReadPrec;
  2229. Result:=Upcase(Fmt[ChPos]);
  2230. end;
  2231. function Checkarg (AT : TJSValueType; err:boolean):boolean;
  2232. {
  2233. Check if argument INDEX is of correct type (AT)
  2234. If Index=-1, ArgPos is used, and argpos is augmented with 1
  2235. DoArg is set to the argument that must be used.
  2236. }
  2237. begin
  2238. result:=false;
  2239. if Index=High(Byte) then
  2240. DoArg:=Argpos
  2241. else
  2242. DoArg:=Index;
  2243. ArgPos:=DoArg+1;
  2244. If (Doarg>High(Args)) or (GetValueTYpe(Args[Doarg])<>AT) then
  2245. begin
  2246. if err then
  2247. DoFormatError(feInvalidArgindex,Fmt);
  2248. dec(ArgPos);
  2249. exit;
  2250. end;
  2251. result:=true;
  2252. end;
  2253. begin
  2254. Result:='';
  2255. Len:=Length(Fmt);
  2256. ChPos:=1;
  2257. OldPos:=1;
  2258. ArgPos:=0;
  2259. While ChPos<=len do
  2260. begin
  2261. While (ChPos<=Len) and (Fmt[ChPos]<>'%') do
  2262. inc(ChPos);
  2263. If ChPos>OldPos Then
  2264. Result:=Result+Copy(Fmt,OldPos,ChPos-Oldpos);
  2265. If ChPos<Len then
  2266. begin
  2267. FChar:=ReadFormat;
  2268. {$ifdef fmtdebug}
  2269. DumpFormat(FCHar);
  2270. {$endif}
  2271. Case FChar of
  2272. 'D' : begin
  2273. Checkarg(jvtinteger,true);
  2274. toAdd:=IntToStr(NativeInt(Args[DoArg]));
  2275. Width:=Abs(width);
  2276. Index:=Prec-Length(ToAdd);
  2277. If ToAdd[1]<>'-' then
  2278. ToAdd:=StringOfChar('0',Index)+ToAdd
  2279. else
  2280. // + 1 to accomodate for - sign in length !!
  2281. Insert(StringOfChar('0',Index+1),toadd,2);
  2282. end;
  2283. 'U' : begin
  2284. Checkarg(jvtinteger,True);
  2285. if NativeInt(Args[Doarg])<0 then
  2286. DoFormatError(feInvalidArgindex,Fmt);
  2287. Toadd:=IntToStr(NativeInt(Args[Doarg]));
  2288. Width:=Abs(width);
  2289. Index:=Prec-Length(ToAdd);
  2290. ToAdd:=StringOfChar('0',Index)+ToAdd
  2291. end;
  2292. 'E' : begin
  2293. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  2294. ToAdd:=FloatToStrF(Double(Args[doarg]),ffFixed,9999,Prec);
  2295. end;
  2296. 'F' : begin
  2297. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  2298. ToAdd:=FloatToStrF(Double(Args[doarg]),ffFixed,9999,Prec);
  2299. end;
  2300. 'G' : begin
  2301. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  2302. ToAdd:=FloatToStrF(Double(Args[doarg]),ffGeneral,Prec,3);
  2303. end;
  2304. 'N' : begin
  2305. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  2306. ToAdd:=FloatToStrF(Double(Args[doarg]),ffNumber,9999,Prec);
  2307. end;
  2308. 'M' : begin
  2309. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  2310. ToAdd:=FloatToStrF(Double(Args[doarg]),ffCurrency,9999,Prec);
  2311. end;
  2312. 'S' : begin
  2313. CheckArg(jvtString,true);
  2314. hs:=String(Args[doarg]);
  2315. Index:=Length(hs);
  2316. If (Prec<>-1) and (Index>Prec) then
  2317. Index:=Prec;
  2318. ToAdd:=Copy(hs,1,Index);
  2319. end;
  2320. 'P' : Begin
  2321. CheckArg(jvtInteger,true);
  2322. ToAdd:=IntToHex(NativeInt(Args[DoArg]),31);
  2323. end;
  2324. 'X' : begin
  2325. Checkarg(jvtinteger,true);
  2326. vq:=nativeInt(Args[Doarg]);
  2327. index:=31; // May need to adjust to NativeInt
  2328. If Prec>index then
  2329. ToAdd:=IntToHex(NativeInt(vq),index)
  2330. else
  2331. begin
  2332. // determine minimum needed number of hex digits.
  2333. Index:=1;
  2334. While (NativeInt(1) shl (Index*4)<=vq) and (index<16) do
  2335. inc(Index);
  2336. If Index>Prec then
  2337. Prec:=Index;
  2338. ToAdd:=IntToHex(vq,Prec);
  2339. end;
  2340. end;
  2341. '%': ToAdd:='%';
  2342. end;
  2343. If Width<>-1 then
  2344. If Length(ToAdd)<Width then
  2345. If not Left then
  2346. ToAdd:=StringOfChar(' ',Width-Length(ToAdd))+ToAdd
  2347. else
  2348. ToAdd:=ToAdd+StringOfChar(' ',Width-Length(ToAdd));
  2349. Result:=Result+ToAdd;
  2350. end;
  2351. inc(ChPos);
  2352. Oldpos:=ChPos;
  2353. end;
  2354. end;
  2355. function BytesOf(const AVal: string): TBytes;
  2356. var
  2357. I: SizeUInt;
  2358. begin
  2359. SetLength(Result, Length(AVal));
  2360. for I := 0 to Length(AVal)-1 do
  2361. Result[I] := Ord(AVal[I+1]);
  2362. end;
  2363. function StringOf(const ABytes: TBytes): string;
  2364. var
  2365. I: Integer;
  2366. begin
  2367. Result:='';
  2368. for I := 0 to Length(ABytes)-1 do
  2369. Result:=Result+Char(ABytes[I]);
  2370. end;
  2371. function LocaleCompare(const s1, s2, locales: String): Boolean; assembler;
  2372. asm
  2373. return s1.localeCompare(s2,locales) == 0;
  2374. end;
  2375. function NormalizeStr(const S: String; const Norm: String): String; assembler;
  2376. asm
  2377. return S.normalize(Norm);
  2378. end;
  2379. function IsValidIdent(const Ident: string; AllowDots: Boolean = False; StrictDots: Boolean = False): Boolean;
  2380. const
  2381. Alpha = ['A'..'Z', 'a'..'z', '_'];
  2382. AlphaNum = Alpha + ['0'..'9'];
  2383. Dot = '.';
  2384. var
  2385. First: Boolean;
  2386. I, Len: Integer;
  2387. begin
  2388. Len := Length(Ident);
  2389. if Len < 1 then
  2390. Exit(False);
  2391. First := True;
  2392. Result:=false;
  2393. I:=1;
  2394. While I<=len do
  2395. begin
  2396. if First then
  2397. begin
  2398. if not (Ident[I] in Alpha) then exit;
  2399. First := False;
  2400. end
  2401. else if AllowDots and (Ident[I] = Dot) then
  2402. begin
  2403. if StrictDots then
  2404. begin
  2405. if I >= Len then exit;
  2406. First := True;
  2407. end;
  2408. end
  2409. else
  2410. if not (Ident[I] in AlphaNum) then exit;
  2411. I:=I+1;
  2412. end;
  2413. Result:=true;
  2414. end;
  2415. procedure FreeAndNil(var Obj);
  2416. var
  2417. o: TObject;
  2418. begin
  2419. o:=TObject(Obj);
  2420. if o=nil then exit;
  2421. TObject(Obj):=nil;
  2422. o.Destroy;
  2423. end;
  2424. { EVariantError }
  2425. constructor EVariantError.CreateCode(Code: Longint);
  2426. begin
  2427. ErrCode:=Code;
  2428. end;
  2429. { Exception }
  2430. constructor Exception.Create(const Msg: String);
  2431. begin
  2432. fMessage:=Msg;
  2433. {$ifdef nodejs}
  2434. FNodeJSError:=TJSError.new;
  2435. {$endif}
  2436. if LogMessageOnCreate then
  2437. Writeln('Created exception ',ClassName,' with message: ',Msg);
  2438. end;
  2439. constructor Exception.CreateFmt(const Msg: string; const Args: array of jsvalue
  2440. );
  2441. begin
  2442. //writeln('Exception.CreateFmt START ',ClassName,' "',Msg,'" Args=',Args);
  2443. Create(Format(Msg,Args));
  2444. //writeln('Exception.CreateFmt END ',ClassName,' "',Msg,'" fMessage=',fMessage);
  2445. end;
  2446. constructor Exception.CreateHelp(const Msg: String; AHelpContext: Integer);
  2447. begin
  2448. Create(Msg);
  2449. fHelpContext:=AHelpContext;
  2450. end;
  2451. constructor Exception.CreateFmtHelp(const Msg: string;
  2452. const Args: array of jsvalue; AHelpContext: Integer);
  2453. begin
  2454. Create(Format(Msg,Args));
  2455. fHelpContext:=AHelpContext;
  2456. end;
  2457. function Exception.ToString: String;
  2458. begin
  2459. Result:=ClassName+': '+Message;
  2460. end;
  2461. Const
  2462. RESpecials = '([\$\+\[\]\(\)\\\.\*\^])';
  2463. function StringReplace(aOriginal, aSearch, aReplace: string;
  2464. Flags: TStringReplaceFlags): String;
  2465. Var
  2466. REFlags : String;
  2467. REString : String;
  2468. begin
  2469. REFlags:='';
  2470. if rfReplaceAll in flags then
  2471. ReFlags:='g';
  2472. if rfIgnoreCase in flags then
  2473. ReFlags:=ReFlags+'i';
  2474. REString:=TJSString(aSearch).replace(TJSRegexp.new(RESpecials,'g'),'\$1');
  2475. Result:=TJSString(aOriginal).replace(TJSRegexp.new(REString,REFlags),aReplace);
  2476. end;
  2477. function QuoteString(aOriginal: String; AQuote: Char): String;
  2478. begin
  2479. Result:=AQuote+StringReplace(aOriginal,aQuote,aQuote+aQuote,[rfReplaceAll])+AQuote;
  2480. end;
  2481. function QuotedStr(const s: string; QuoteChar : Char = ''''): string;
  2482. begin
  2483. Result:=QuoteString(S,QuoteChar);
  2484. end;
  2485. function DeQuoteString(aQuoted: String; AQuote: Char): String;
  2486. var
  2487. i: Integer;
  2488. begin
  2489. Result:=aQuoted;
  2490. if TJSString(Result).substr(0,1)<>AQuote then exit;
  2491. Result:=TJSString(Result).slice(1);
  2492. i:=1;
  2493. while i<=length(Result) do
  2494. begin
  2495. if Result[i]=AQuote then
  2496. begin
  2497. if (i=length(Result)) or (Result[i+1]<>AQuote) then
  2498. begin
  2499. Result:=TJSString(Result).slice(0,i-1);
  2500. exit;
  2501. end
  2502. else
  2503. Result:=TJSString(Result).slice(0,i-1)+TJSString(Result).slice(i);
  2504. end
  2505. else
  2506. inc(i);
  2507. end;
  2508. end;
  2509. function IsDelimiter(const Delimiters, S: string; Index: Integer): Boolean;
  2510. begin
  2511. Result:=False;
  2512. if (Index>0) and (Index<=Length(S)) then
  2513. Result:=Pos(S[Index],Delimiters)<>0; // Note we don't do MBCS yet
  2514. end;
  2515. Function LastDelimiter(const Delimiters, S: string): SizeInt;
  2516. begin
  2517. Result:=Length(S);
  2518. While (Result>0) and (Pos(S[Result],Delimiters)=0) do
  2519. Dec(Result);
  2520. end;
  2521. function AdjustLineBreaks(const S: string): string;
  2522. begin
  2523. Result:=AdjustLineBreaks(S,DefaultTextLineBreakStyle);
  2524. end;
  2525. function AdjustLineBreaks(const S: string; Style: TTextLineBreakStyle): string;
  2526. var
  2527. I,L: Longint;
  2528. Res : String;
  2529. Procedure Add(C : Char);
  2530. begin
  2531. Res:=Res+C;
  2532. end;
  2533. begin
  2534. I:=0;
  2535. L:=Length(S);
  2536. Result:='';
  2537. While (I<=L) do
  2538. case S[I] of
  2539. #10: begin
  2540. if Style in [tlbsCRLF,tlbsCR] then
  2541. Add(#13);
  2542. if Style=tlbsCRLF then
  2543. Add(#10);
  2544. Inc(I);
  2545. end;
  2546. #13: begin
  2547. if Style=tlbsCRLF then
  2548. Add(#13);
  2549. Add(#10);
  2550. Inc(I);
  2551. if S[I]=#10 then
  2552. Inc(I);
  2553. end;
  2554. else
  2555. Add(S[i]);
  2556. Inc(I);
  2557. end;
  2558. Result:=Res;
  2559. end;
  2560. function WrapText(const Line, BreakStr: string;
  2561. const BreakChars: array of char; MaxCol: Integer): string;
  2562. const
  2563. Quotes = ['''', '"'];
  2564. Var
  2565. L : String;
  2566. C,LQ,BC : Char;
  2567. P,BLen,Len : Integer;
  2568. HB,IBC : Boolean;
  2569. begin
  2570. Result:='';
  2571. L:=Line;
  2572. Blen:=Length(BreakStr);
  2573. If (BLen>0) then
  2574. BC:=BreakStr[1]
  2575. else
  2576. BC:=#0;
  2577. Len:=Length(L);
  2578. While (Len>0) do
  2579. begin
  2580. P:=1;
  2581. LQ:=#0;
  2582. HB:=False;
  2583. IBC:=False;
  2584. While ((P<=Len) and ((P<=MaxCol) or not IBC)) and ((LQ<>#0) or Not HB) do
  2585. begin
  2586. C:=L[P];
  2587. If (C=LQ) then
  2588. LQ:=#0
  2589. else If (C in Quotes) then
  2590. LQ:=C;
  2591. If (LQ<>#0) then
  2592. Inc(P)
  2593. else
  2594. begin
  2595. HB:=((C=BC) and (BreakStr=Copy(L,P,BLen)));
  2596. If HB then
  2597. Inc(P,Blen)
  2598. else
  2599. begin
  2600. If (P>=MaxCol) then
  2601. IBC:=CharInSet(C,BreakChars);
  2602. Inc(P);
  2603. end;
  2604. end;
  2605. // Writeln('"',C,'" : IBC : ',IBC,' HB : ',HB,' LQ : ',LQ,' P>MaxCol : ',P>MaxCol);
  2606. end;
  2607. Result:=Result+Copy(L,1,P-1);
  2608. Delete(L,1,P-1);
  2609. Len:=Length(L);
  2610. If (Len>0) and Not HB then
  2611. Result:=Result+BreakStr;
  2612. end;
  2613. end;
  2614. function WrapText(const Line: string; MaxCol: Integer): string;
  2615. begin
  2616. Result:=WrapText(Line,sLineBreak, [' ', '-', #9], MaxCol);
  2617. end;
  2618. function GetEnvironmentVariable(const EnvVar: String): String;
  2619. begin
  2620. if Assigned(OnGetEnvironmentVariable) then
  2621. Result:=OnGetEnvironmentVariable(EnvVar)
  2622. else
  2623. Result:='';
  2624. end;
  2625. function GetEnvironmentVariableCount: Integer;
  2626. begin
  2627. if Assigned(OnGetEnvironmentVariableCount) then
  2628. Result:=OnGetEnvironmentVariableCount()
  2629. else
  2630. Result:=0;
  2631. end;
  2632. function GetEnvironmentString(Index: Integer): String;
  2633. begin
  2634. if Assigned(OnGetEnvironmentString) then
  2635. Result:=OnGetEnvironmentString(Index)
  2636. else
  2637. Result:='';
  2638. end;
  2639. { Date/Time routines}
  2640. Function DoEncodeDate(Year, Month, Day: Word): longint;
  2641. Var
  2642. D : TDateTime;
  2643. begin
  2644. If TryEncodeDate(Year,Month,Day,D) then
  2645. Result:=Trunc(D)
  2646. else
  2647. Result:=0;
  2648. end;
  2649. function DoEncodeTime(Hour, Minute, Second, MilliSecond: word): TDateTime;
  2650. begin
  2651. If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then
  2652. Result:=0;
  2653. end;
  2654. function DateTimeToJSDate(aDateTime: TDateTime): TJSDate;
  2655. Var
  2656. Y,M,D,h,n,s,z : Word;
  2657. begin
  2658. DecodeDate(Trunc(aDateTime),Y,M,D);
  2659. DecodeTime(Frac(aDateTime),H,N,S,Z);
  2660. Result:=TJSDate.New(Y,M-1,D,h,n,s,z);
  2661. end;
  2662. function JSDateToDateTime(aDate: TJSDate): TDateTime;
  2663. begin
  2664. Result:=EncodeDate(ADate.FullYear,ADate.Month+1,ADate.Date) +
  2665. EncodeTime(ADate.Hours,ADate.Minutes,ADate.Seconds,ADate.Milliseconds);
  2666. end;
  2667. { ComposeDateTime converts a Date and a Time into one TDateTime }
  2668. function ComposeDateTime(Date,Time : TDateTime) : TDateTime;
  2669. begin
  2670. if Date < 0 then
  2671. Result := trunc(Date) - Abs(frac(Time))
  2672. else
  2673. Result := trunc(Date) + Abs(frac(Time));
  2674. end;
  2675. function TryEncodeDate(Year, Month, Day: Word; out Date: TDateTime): Boolean;
  2676. var
  2677. c, ya: LongWord;
  2678. begin
  2679. Result:=(Year>0) and (Year<10000) and
  2680. (Month >= 1) and (Month<=12) and
  2681. (Day>0) and (Day<=MonthDays[IsleapYear(Year),Month]);
  2682. If Result then
  2683. begin
  2684. if month > 2 then
  2685. Dec(Month,3)
  2686. else
  2687. begin
  2688. Inc(Month,9);
  2689. Dec(Year);
  2690. end;
  2691. c:= Year DIV 100;
  2692. ya:= Year - 100*c;
  2693. Date := (146097*c) SHR 2 + (1461*ya) SHR 2 + (153*LongWord(Month)+2) DIV 5 + LongWord(Day);
  2694. // Note that this line can't be part of the line above, since TDateTime is
  2695. // signed and c and ya are not
  2696. Date := Date - 693900;
  2697. end
  2698. end;
  2699. function TryEncodeTime(Hour, Min, Sec, MSec: Word; out Time: TDateTime
  2700. ): Boolean;
  2701. begin
  2702. Result:=(Hour<24) and (Min<60) and (Sec<60) and (MSec<1000);
  2703. If Result then
  2704. Time:=TDateTime(LongWord(Hour)*3600000+LongWord(Min)*60000+LongWord(Sec)*1000+MSec)/MSecsPerDay;
  2705. end;
  2706. { EncodeDate packs three variables Year, Month and Day into a
  2707. TDateTime value the result is the number of days since 12/30/1899 }
  2708. function EncodeDate(Year, Month, Day: word): TDateTime;
  2709. begin
  2710. If Not TryEncodeDate(Year,Month,Day,Result) then
  2711. Raise EConvertError.CreateFmt('%s-%s-%s is not a valid date specification',
  2712. [IntToStr(Year),IntToStr(Month),IntToStr(Day)]);
  2713. end;
  2714. { EncodeTime packs four variables Hour, Minute, Second and MilliSecond into
  2715. a TDateTime value }
  2716. function EncodeTime(Hour, Minute, Second, MilliSecond:word):TDateTime;
  2717. begin
  2718. If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then
  2719. Raise EConvertError.CreateFmt('%s:%s:%s.%s is not a valid time specification',
  2720. [IntToStr(Hour),IntToStr(Minute),IntToStr(Second),IntToStr(MilliSecond)]);
  2721. end;
  2722. { DecodeDate unpacks the value Date into three values:
  2723. Year, Month and Day }
  2724. procedure DecodeDate(Date: TDateTime; out Year, Month, Day: word);
  2725. var
  2726. ly,ld,lm,j : LongWord;
  2727. begin
  2728. if Date <= -datedelta then // If Date is before 1-1-1 then return 0-0-0
  2729. begin
  2730. Year := 0;
  2731. Month := 0;
  2732. Day := 0;
  2733. end
  2734. else
  2735. begin
  2736. if Date>0 then
  2737. Date:=(Date+(1/(msecsperday*2)))
  2738. else
  2739. Date:=Date-(1/(msecsperday*2));
  2740. if Date>MaxDateTime then
  2741. Date:=MaxDateTime;
  2742. // Raise EConvertError.CreateFmt('%f is not a valid TDatetime encoding, maximum value is %f.',[Date,MaxDateTime]);
  2743. j := ((Trunc(Date) + 693900) SHL 2)-1;
  2744. ly:= j DIV 146097;
  2745. j:= j - 146097 * LongWord(ly);
  2746. ld := j SHR 2;
  2747. j:=(ld SHL 2 + 3) DIV 1461;
  2748. ld:= ((ld SHL 2) + 7 - 1461*j) SHR 2;
  2749. lm:=(5 * ld-3) DIV 153;
  2750. ld:= (5 * ld +2 - 153*lm) DIV 5;
  2751. ly:= 100 * LongWord(ly) + j;
  2752. if lm < 10 then
  2753. inc(lm,3)
  2754. else
  2755. begin
  2756. dec(lm,9);
  2757. inc(ly);
  2758. end;
  2759. year:=ly;
  2760. month:=lm;
  2761. day:=ld;
  2762. end;
  2763. end;
  2764. function DecodeDateFully(const DateTime: TDateTime; out Year, Month, Day, DOW: Word): Boolean;
  2765. begin
  2766. DecodeDate(DateTime,Year,Month,Day);
  2767. DOW:=DayOfWeek(DateTime);
  2768. Result:=IsLeapYear(Year);
  2769. end;
  2770. { DateTimeToTimeStamp converts DateTime to a TTimeStamp }
  2771. function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp;
  2772. Var
  2773. D : Double;
  2774. begin
  2775. D:=DateTime * Double(MSecsPerDay);
  2776. if D<0 then
  2777. D:=D-0.5
  2778. else
  2779. D:=D+0.5;
  2780. result.Time := Trunc(Abs(Trunc(D)) Mod MSecsPerDay);
  2781. result.Date := DateDelta + (Trunc(D) div MSecsPerDay);
  2782. end;
  2783. { TimeStampToDateTime converts TimeStamp to a TDateTime value }
  2784. function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
  2785. begin
  2786. Result := ComposeDateTime(TimeStamp.Date - DateDelta,TimeStamp.Time/MSecsPerDay)
  2787. end;
  2788. { MSecsToTimeStamp }
  2789. function MSecsToTimeStamp(MSecs: NativeInt): TTimeStamp;
  2790. begin
  2791. result.Date := Trunc(msecs/msecsperday);
  2792. msecs:= msecs-NativeInt(result.date)*msecsperday;
  2793. result.Time := Round(MSecs);
  2794. end;
  2795. function TimeStampToMSecs(const TimeStamp: TTimeStamp): NativeInt;
  2796. begin
  2797. result := TimeStamp.Time + (timestamp.date*msecsperday);
  2798. end ;
  2799. { DecodeTime unpacks Time into four values:
  2800. Hour, Minute, Second and MilliSecond }
  2801. procedure DecodeTime(Time: TDateTime; out Hour, Minute, Second, MilliSecond: word);
  2802. Var
  2803. l : LongWord;
  2804. begin
  2805. l := DateTimeToTimeStamp(Time).Time;
  2806. Hour := l div 3600000;
  2807. l := l mod 3600000;
  2808. Minute := l div 60000;
  2809. l := l mod 60000;
  2810. Second := l div 1000;
  2811. l := l mod 1000;
  2812. MilliSecond := l;
  2813. end;
  2814. { DateTimeToSystemTime converts DateTime value to SystemTime }
  2815. procedure DateTimeToSystemTime(DateTime: TDateTime; out SystemTime: TSystemTime);
  2816. begin
  2817. DecodeDateFully(DateTime, SystemTime.Year, SystemTime.Month, SystemTime.Day,SystemTime.DayOfWeek);
  2818. DecodeTime(DateTime, SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond);
  2819. Dec(SystemTime.DayOfWeek);
  2820. end ;
  2821. { SystemTimeToDateTime converts SystemTime to a TDateTime value }
  2822. function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
  2823. begin
  2824. result := ComposeDateTime(DoEncodeDate(SystemTime.Year, SystemTime.Month, SystemTime.Day),
  2825. DoEncodeTime(SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond));
  2826. end ;
  2827. function DayOfWeek(DateTime: TDateTime): integer;
  2828. begin
  2829. Result:= 1+((Trunc(DateTime) - 1) mod 7);
  2830. If (Result<=0) then
  2831. Inc(Result,7);
  2832. end;
  2833. function Now: TDateTime;
  2834. begin
  2835. Result:=JSDateToDateTime(TJSDate.New());
  2836. end;
  2837. function Date: TDateTime;
  2838. begin
  2839. Result:=Trunc(Now);
  2840. end;
  2841. function Time: TDateTime;
  2842. begin
  2843. Result:=Now-Date;
  2844. end ;
  2845. { IncMonth increments DateTime with NumberOfMonths months,
  2846. NumberOfMonths can be less than zero }
  2847. function IncMonth(const DateTime: TDateTime; NumberOfMonths: integer = 1 ): TDateTime;
  2848. var
  2849. Year, Month, Day : word;
  2850. begin
  2851. DecodeDate(DateTime, Year, Month, Day);
  2852. IncAMonth(Year, Month, Day, NumberOfMonths);
  2853. result := ComposeDateTime(DoEncodeDate(Year, Month, Day), DateTime);
  2854. end ;
  2855. { IncAMonth is the same as IncMonth, but operates on decoded date }
  2856. procedure IncAMonth(var Year, Month, Day: Word; NumberOfMonths: Integer = 1);
  2857. var
  2858. TempMonth, S: Integer;
  2859. begin
  2860. If NumberOfMonths>=0 then
  2861. s:=1
  2862. else
  2863. s:=-1;
  2864. inc(Year,(NumberOfMonths div 12));
  2865. TempMonth:=Month+(NumberOfMonths mod 12)-1;
  2866. if (TempMonth>11) or
  2867. (TempMonth<0) then
  2868. begin
  2869. Dec(TempMonth, S*12);
  2870. Inc(Year, S);
  2871. end;
  2872. Month:=TempMonth+1; { Months from 1 to 12 }
  2873. If (Day>MonthDays[IsLeapYear(Year)][Month]) then
  2874. Day:=MonthDays[IsLeapYear(Year)][Month];
  2875. end;
  2876. { IsLeapYear returns true if Year is a leap year }
  2877. function IsLeapYear(Year: Word): boolean;
  2878. begin
  2879. Result := (Year mod 4 = 0) and ((Year mod 100 <> 0) or (Year mod 400 = 0));
  2880. end;
  2881. { DateToStr returns a string representation of Date using ShortDateFormat }
  2882. function DateToStr(Date: TDateTime): string;
  2883. begin
  2884. Result:=FormatDateTime('ddddd', Date);
  2885. end ;
  2886. { TimeToStr returns a string representation of Time using LongTimeFormat }
  2887. function TimeToStr(Time: TDateTime): string;
  2888. begin
  2889. Result:=FormatDateTime('tt',Time);
  2890. end ;
  2891. { DateTimeToStr returns a string representation of DateTime using LongDateTimeFormat }
  2892. Var
  2893. DateTimeToStrFormat : Array[Boolean] of string = ('c','f');
  2894. function DateTimeToStr(DateTime: TDateTime; ForceTimeIfZero : Boolean = False): string;
  2895. begin
  2896. Result:=FormatDateTime(DateTimeToStrFormat[ForceTimeIfZero], DateTime)
  2897. end ;
  2898. { StrToDate converts the string S to a TDateTime value
  2899. if S does not represent a valid date value
  2900. an EConvertError will be raised }
  2901. function IntStrToDate(Out ErrorMsg : String; const S: String; const useformat : string; separator : char): TDateTime;
  2902. Const
  2903. WhiteSpace = ' '#8#9#10#12#13;
  2904. Digits = '0123456789';
  2905. procedure FixErrorMsg(const errmarg : String);
  2906. begin
  2907. ErrorMsg:=Format(SInvalidDateFormat,[errmarg]);
  2908. end;
  2909. var
  2910. df:string;
  2911. d,m,y,ly,ld,lm:word;
  2912. n,i,len:longint;
  2913. c: integer;
  2914. dp,mp,yp,which : Byte;
  2915. s1:string;
  2916. values: array of integer;
  2917. YearMoreThenTwoDigits : boolean;
  2918. begin
  2919. SetLength(values,4);
  2920. Result:=0;
  2921. Len:=Length(S);
  2922. ErrorMsg:='';
  2923. While (Len>0) and (Pos(S[Len],WhiteSpace)>0) do
  2924. Dec(len);
  2925. if (Len=0) then
  2926. begin
  2927. FixErrorMsg(S);
  2928. exit;
  2929. end;
  2930. YearMoreThenTwoDigits := False;
  2931. if separator = #0 then
  2932. if (DateSeparator<>#0) then
  2933. separator := DateSeparator
  2934. else
  2935. separator:='-';
  2936. // Writeln('Separator: ',Separator);
  2937. df := UpperCase(useFormat);
  2938. { Determine order of D,M,Y }
  2939. yp:=0;
  2940. mp:=0;
  2941. dp:=0;
  2942. Which:=0;
  2943. i:=0;
  2944. while (i<Length(df)) and (Which<3) do
  2945. begin
  2946. inc(i);
  2947. Case df[i] of
  2948. 'Y' :
  2949. if yp=0 then
  2950. begin
  2951. Inc(Which);
  2952. yp:=which;
  2953. end;
  2954. 'M' :
  2955. if mp=0 then
  2956. begin
  2957. Inc(Which);
  2958. mp:=which;
  2959. end;
  2960. 'D' :
  2961. if dp=0 then
  2962. begin
  2963. Inc(Which);
  2964. dp:=which;
  2965. end;
  2966. end;
  2967. end;
  2968. // Writeln('YP: ',Yp,', MP: ',Mp,', DP: ',DP);
  2969. for i := 1 to 3 do
  2970. values[i] := 0;
  2971. s1 := '';
  2972. n := 0;
  2973. for i := 1 to len do
  2974. begin
  2975. if Pos(s[i],Digits)>0 then
  2976. s1 := s1 + s[i];
  2977. { space can be part of the shortdateformat, and is defaultly in slovak
  2978. windows, therefor it shouldn't be taken as separator (unless so specified)
  2979. and ignored }
  2980. if (Separator <> ' ') and (s[i] = ' ') then
  2981. Continue;
  2982. if (s[i] = separator) or ((i = len) and (Pos(s[i],Digits)>0)) then
  2983. begin
  2984. inc(n);
  2985. if n>3 then
  2986. begin
  2987. // Writeln('More than 3 separators');
  2988. FixErrorMsg(S);
  2989. exit;
  2990. end;
  2991. // Check if the year has more then two digits (if n=yp, then we are evaluating the year.)
  2992. if (n=yp) and (length(s1)>2) then YearMoreThenTwoDigits := True;
  2993. val(s1, values[n], c);
  2994. if c<>0 then
  2995. begin
  2996. // Writeln('S1 not a number ',S1);
  2997. FixErrorMsg(s);
  2998. Exit;
  2999. end;
  3000. s1 := '';
  3001. end
  3002. else if (Pos(s[i],Digits)=0) then
  3003. begin
  3004. // Writeln('Not a number at pos ',I,' ',S[i]);
  3005. FixErrorMsg(s);
  3006. Exit;
  3007. end;
  3008. end ;
  3009. // Writeln('Which : ',Which,' N : ',N);
  3010. if (Which<3) and (N>Which) then
  3011. begin
  3012. FixErrorMsg(s);
  3013. Exit;
  3014. end;
  3015. // Fill in values.
  3016. DecodeDate(Date,Ly,LM,LD);
  3017. If N=3 then
  3018. begin
  3019. y:=values[yp];
  3020. m:=values[mp];
  3021. d:=values[dp];
  3022. end
  3023. Else
  3024. begin
  3025. Y:=ly;
  3026. If n<2 then
  3027. begin
  3028. d:=values[1];
  3029. m := LM;
  3030. end
  3031. else
  3032. If dp<mp then
  3033. begin
  3034. d:=values[1];
  3035. m:=values[2];
  3036. end
  3037. else
  3038. begin
  3039. d:=values[2];
  3040. m:=values[1];
  3041. end;
  3042. end;
  3043. if (y >= 0) and (y < 100) and not YearMoreThenTwoDigits then
  3044. begin
  3045. ly := ly - TwoDigitYearCenturyWindow;
  3046. Inc(Y, ly div 100 * 100);
  3047. if (TwoDigitYearCenturyWindow > 0) and (Y < ly) then
  3048. Inc(Y, 100);
  3049. end;
  3050. if not TryEncodeDate(y, m, d, result) then
  3051. errormsg:=SErrInvalidDate;
  3052. end;
  3053. function StrToDate(const S: String; const useformat : string; separator : char): TDateTime;
  3054. Var
  3055. MSg : String;
  3056. begin
  3057. Result:=IntStrToDate(Msg,S,useFormat,Separator);
  3058. If (Msg<>'') then
  3059. Raise EConvertError.Create(Msg);
  3060. end;
  3061. function StrToDate(const S: String; separator : char): TDateTime;
  3062. begin
  3063. result := StrToDate(S,ShortDateFormat,separator)
  3064. end;
  3065. function StrToDate(const S: String): TDateTime;
  3066. begin
  3067. result := StrToDate(S,ShortDateFormat,#0);
  3068. end;
  3069. { StrToTime converts the string S to a TDateTime value
  3070. if S does not represent a valid time value an
  3071. EConvertError will be raised }
  3072. function IntStrToTime(Out ErrorMsg : String; const S: String; Len : integer; separator : char): TDateTime;
  3073. const
  3074. AMPM_None = 0;
  3075. AMPM_AM = 1;
  3076. AMPM_PM = 2;
  3077. tiHour = 0;
  3078. tiMin = 1;
  3079. tiSec = 2;
  3080. tiMSec = 3;
  3081. type
  3082. TTimeValues = array of Word;
  3083. var
  3084. AmPm: integer;
  3085. TimeValues: TTimeValues;
  3086. function SplitElements(out TimeValues: TTimeValues; out AmPm: Integer): Boolean;
  3087. //Strict version. It does not allow #32 as Separator, it will treat it as whitespace always
  3088. const
  3089. Digits = '0123456789';
  3090. var
  3091. Cur, Offset, ElemLen, Err, TimeIndex, FirstSignificantDigit: Integer;
  3092. Value: Integer;
  3093. DigitPending, MSecPending: Boolean;
  3094. AmPmStr: String;
  3095. CurChar: Char;
  3096. I : Integer;
  3097. allowedchars : string;
  3098. begin
  3099. Result := False;
  3100. AmPm := AMPM_None; //No Am or PM in string found yet
  3101. MSecPending := False;
  3102. TimeIndex := 0; //indicating which TTimeValue must be filled next
  3103. For I:=tiHour to tiMSec do
  3104. TimeValues[i]:=0;
  3105. Cur := 1;
  3106. //skip leading blanks
  3107. While (Cur < Len) and (S[Cur] =#32) do Inc(Cur);
  3108. Offset := Cur;
  3109. //First non-blank cannot be Separator or DecimalSeparator
  3110. if (Cur > Len - 1) or (S[Cur] = Separator) or (S[Cur] = Decimalseparator) then
  3111. begin
  3112. // Writeln('Error in sep S[Cur]',S[Cur],' ',separator,' ',GetDecimalSeparator);
  3113. Exit;
  3114. end;
  3115. DigitPending := (Pos(S[Cur],Digits)>0);
  3116. While (Cur <= Len) do
  3117. begin
  3118. //writeln;
  3119. // writeln('Main While loop: Cur = ',Cur,' S[Cur] = "',S[Cur],'" Len = ',Len,' separator : ',Separator);
  3120. CurChar := S[Cur];
  3121. if Pos(CurChar,Digits)>0 then
  3122. begin//Digits
  3123. //HH, MM, SS, or Msec?
  3124. // writeln('Digit: ', CurChar);
  3125. //Digits are only allowed after starting Am/PM or at beginning of string or after Separator
  3126. //and TimeIndex must be <= tiMSec
  3127. //Uncomment "or (#32 = Separator)" and it will allllow #32 as separator
  3128. if (not (DigitPending {or (#32 = Separator)})) or (TimeIndex > tiMSec) then
  3129. begin
  3130. // Writeln('DigitPending',ElemLen);
  3131. Exit;
  3132. end;
  3133. OffSet := Cur;
  3134. if (CurChar <> '0') then FirstSignificantDigit := OffSet else FirstSignificantDigit := -1;
  3135. while (Cur < Len) and (Pos(S[Cur + 1],Digits)>0) do
  3136. begin
  3137. //Mark first Digit that is not '0'
  3138. if (FirstSignificantDigit = -1) and (S[Cur] <> '0') then FirstSignificantDigit := Cur;
  3139. Inc(Cur);
  3140. end;
  3141. if (FirstSignificantDigit = -1) then FirstSignificantDigit := Cur;
  3142. ElemLen := 1+ Cur - FirstSignificantDigit;
  3143. // writeln(' S[FirstSignificantDigit] = ',S[FirstSignificantDigit], ' S[Cur] = ',S[Cur],' ElemLen = ',ElemLen,' -> ', S[Offset], ElemLen);
  3144. // writeln(' Cur = ',Cur);
  3145. //this way we know that Val() will never overflow Value !
  3146. if (ElemLen <= 2) or ((ElemLen <= 3) and (TimeIndex = tiMSec) ) then
  3147. begin
  3148. Val(Copy(S,FirstSignificantDigit, ElemLen), Value, Err);
  3149. // writeln(' Value = ',Value,' HH = ',TimeValues[0],' MM = ',TimeValues[1],' SS = ',TimeValues[2],' MSec = ',Timevalues[3]);
  3150. //This is safe now, because we know Value < High(Word)
  3151. TimeValues[TimeIndex] := Value;
  3152. Inc(TimeIndex);
  3153. DigitPending := False;
  3154. end
  3155. else
  3156. begin
  3157. // Writeln('Wrong elemlen: ',ElemLen, ' timeIndex: ',timeindex);
  3158. Exit; //Value to big, so it must be a wrong timestring
  3159. end;
  3160. end//Digits
  3161. else if (CurChar = #32) then
  3162. begin
  3163. //writeln('#32');
  3164. //just skip, but we must adress this, or it will be parsed by either AM/PM or Separator
  3165. end
  3166. else if (CurChar = Separator) then
  3167. begin
  3168. // writeln('Separator ',Separator);
  3169. if DigitPending or (TimeIndex > tiSec) then
  3170. begin
  3171. // Writeln ('DigitPending ',DigitPending,' or (TimeIndex',Timeindex,' > tiSec,', tiSec,')');
  3172. Exit;
  3173. end;
  3174. DigitPending := True;
  3175. MSecPending := False;
  3176. end
  3177. else if (CurChar = DecimalSeparator) then
  3178. begin
  3179. //writeln('DecimalSeparator');
  3180. if DigitPending or MSecPending or (TimeIndex <> tiMSec) then
  3181. begin
  3182. // Writeln('DigitPending ',DigitPending,' or MSecPending ',MSecPending,' (',TimeIndex,',Timeindex, >', tiMSec,' tiSec)');
  3183. Exit;
  3184. end;
  3185. DigitPending := True;
  3186. MSecPending := True;
  3187. end
  3188. else
  3189. begin//AM/PM?
  3190. //None of the above, so this char _must_ be the start of AM/PM string
  3191. //If we already have found AM/PM or we expect a digit then then timestring must be wrong at this point
  3192. //writeln('AM/PM?');
  3193. if (AmPm <> AMPM_None) or DigitPending then
  3194. begin
  3195. // Writeln('AmPm <> AMPM_None) or DigitPending');
  3196. Exit;
  3197. end;
  3198. OffSet := Cur;
  3199. allowedchars:=DecimalSeparator+' ';
  3200. if Separator<>#0 then
  3201. allowedchars:=allowedchars+Separator;
  3202. while (Cur < Len) and (Pos(S[Cur + 1],AllowedChars)=0)
  3203. and (Pos(S[Cur + 1],Digits)=0) do Inc(Cur);
  3204. ElemLen := 1 + Cur - OffSet;
  3205. // writeln(' S[Offset] = ',S[Offset], ' S[Cur] = ',S[Cur],' ElemLen = ',ElemLen,' -> ', S[1+Offset], ElemLen);
  3206. // writeln(' Cur = ',Cur, ', S =',S);
  3207. AmPmStr := Copy(S,OffSet, ElemLen);
  3208. // writeln('AmPmStr = ',ampmstr,' (',length(ampmstr),')');
  3209. //We must compare to TimeAMString before hardcoded 'AM' for delphi compatibility
  3210. //Also it is perfectly legal, though insane to have TimeAMString = 'PM' and vice versa
  3211. if (CompareText(AmPmStr, TimeAMString) = 0) then AmPm := AMPM_AM
  3212. else if (CompareText(AmPmStr, TimePMString) = 0) then AmPm := AMPM_PM
  3213. else if (CompareText(AmPmStr, 'AM') = 0) then AmPm := AMPM_AM
  3214. else if (CompareText(AmPmStr, 'PM') = 0) then AmPm := AMPM_PM
  3215. else
  3216. begin
  3217. // Writeln('No timestring ',AmPmStr);
  3218. Exit; //If text does not match any of these, timestring must be wrong;
  3219. end;
  3220. //if AM/PM is at beginning of string, then a digit is mandatory after it
  3221. if (TimeIndex = tiHour) then
  3222. begin
  3223. DigitPending := True;
  3224. end
  3225. //otherwise, no more TimeValues allowed after this
  3226. else
  3227. begin
  3228. TimeIndex := tiMSec + 1;
  3229. DigitPending := False;
  3230. end;
  3231. end;//AM/PM
  3232. Inc(Cur)
  3233. end;//while
  3234. //If we arrive here, parsing the elements has been successfull
  3235. //if not at least Hours specified then input is not valid
  3236. //when am/pm is specified Hour must be <= 12 and not 0
  3237. if (TimeIndex = tiHour) or ((AmPm <> AMPM_None) and ((TimeValues[tiHour] > 12) or (TimeValues[tiHour] = 0))) or DigitPending then
  3238. Exit;
  3239. Result := True;
  3240. end;
  3241. begin
  3242. setlength(timevalues,4);
  3243. if separator = #0 then
  3244. if (TimeSeparator<>#0) then
  3245. separator := TimeSeparator
  3246. else
  3247. separator:=':';
  3248. AmPm := AMPM_None;
  3249. if not SplitElements(TimeValues, AmPm) then
  3250. begin
  3251. ErrorMsg:=Format(SErrInvalidTimeFormat,[S]);
  3252. Exit;
  3253. end;
  3254. if (AmPm=AMPM_PM) and (TimeValues[tiHour]<>12) then Inc(TimeValues[tiHour], 12)
  3255. else if (AmPm=AMPM_AM) and (TimeValues[tiHour]=12) then TimeValues[tiHour]:=0;
  3256. // Writeln( TimeValues[tiHour], TimeValues[tiMin], TimeValues[tiSec], TimeValues[tiMSec]);
  3257. if not TryEncodeTime(TimeValues[tiHour], TimeValues[tiMin], TimeValues[tiSec], TimeValues[tiMSec], result) Then
  3258. ErrorMsg:=Format(SErrInvalidTimeFormat,[S]);
  3259. end ;
  3260. function StrToTime(const S: String; separator: char): TDateTime;
  3261. Var
  3262. Msg : String;
  3263. begin
  3264. Result:=IntStrToTime(Msg,S,Length(S),Separator);
  3265. If (Msg<>'') then
  3266. Raise EConvertError.Create(Msg);
  3267. end;
  3268. function StrToTime(const S: String): TDateTime;
  3269. begin
  3270. result:= StrToTime(s, TimeSeparator);
  3271. end;
  3272. { StrToDateTime converts the string S to a TDateTime value
  3273. if S does not represent a valid date and/or time value
  3274. an EConvertError will be raised }
  3275. function SplitDateTimeStr(DateTimeStr: String; out DateStr, TimeStr: String): Integer;
  3276. { Helper function for StrToDateTime
  3277. Pre-condition
  3278. Date is before Time
  3279. If either Date or Time is omitted then see what fits best, a time or a date (issue #0020522)
  3280. Date and Time are separated by whitespace (space Tab, Linefeed or carriage return)
  3281. FS.DateSeparator can be the same as FS.TimeSeparator (issue #0020522)
  3282. If they are both #32 and TrimWhite(DateTimeStr) contains a #32 a date is assumed.
  3283. Post-condition
  3284. DateStr holds date as string or is empty
  3285. TimeStr holds time as string or is empty
  3286. Result = number of strings returned, 0 = error
  3287. }
  3288. const
  3289. WhiteSpace = #9#10#13#32;
  3290. var
  3291. p: Integer;
  3292. DummyDT: TDateTime;
  3293. begin
  3294. Result := 0;
  3295. DateStr := '';
  3296. TimeStr := '';
  3297. DateTimeStr := Trim(DateTimeStr);
  3298. if Length(DateTimeStr) = 0 then exit;
  3299. if (DateSeparator = #32) and (TimeSeparator = #32) and (Pos(#32, DateTimeStr) > 0) then
  3300. begin
  3301. DateStr:=DateTimeStr;
  3302. {
  3303. Assume a date: dd [mm [yy]].
  3304. Really fancy would be counting the number of whitespace occurrences and decide
  3305. and split accordingly
  3306. }
  3307. Exit(1);
  3308. end;
  3309. p:=1;
  3310. //find separator
  3311. if (DateSeparator<>#32) then
  3312. begin
  3313. while (p<Length(DateTimeStr)) and (not (Pos(DateTimeStr[p+1],WhiteSpace)>0)) do
  3314. Inc(p);
  3315. end
  3316. else
  3317. begin
  3318. p:=Pos(TimeSeparator, DateTimeStr);
  3319. if (p<>0) then
  3320. repeat
  3321. Dec(p);
  3322. until (p=0) or (Pos(DateTimeStr[p],WhiteSpace)>0);
  3323. end;
  3324. //Always fill DateStr, it eases the algorithm later
  3325. if (p=0) then
  3326. p:=Length(DateTimeStr);
  3327. DateStr:=Copy(DateTimeStr,1,p);
  3328. TimeStr:=Trim(Copy(DateTimeStr,p+1,100));
  3329. if (Length(TimeStr)<>0) then
  3330. Result:=2
  3331. else
  3332. begin
  3333. Result:=1; //found 1 string
  3334. // 2 cases when DateTimeStr only contains a time:
  3335. // Date/time separator differ, and string contains a timeseparator
  3336. // Date/time separators are equal, but transformation to date fails.
  3337. if ((DateSeparator<>TimeSeparator) and (Pos(TimeSeparator,DateStr) > 0))
  3338. or ((DateSeparator=TimeSeparator) and (not TryStrToDate(DateStr, DummyDT))) then
  3339. begin
  3340. TimeStr := DateStr;
  3341. DateStr := '';
  3342. end;
  3343. end;
  3344. end;
  3345. function StrToDateTime(const S: String): TDateTime;
  3346. var
  3347. TimeStr, DateStr: String;
  3348. PartsFound: Integer;
  3349. begin
  3350. PartsFound := SplitDateTimeStr(S, DateStr, TimeStr);
  3351. case PartsFound of
  3352. 0: Result:=StrToDate('');
  3353. 1: if (Length(DateStr) > 0) then
  3354. Result := StrToDate(DateStr,ShortDateFormat,DateSeparator)
  3355. else
  3356. Result := StrToTime(TimeStr);
  3357. 2: Result := ComposeDateTime(StrTodate(DateStr,ShortDateFormat,DateSeparator),
  3358. StrToTime(TimeStr));
  3359. end;
  3360. end;
  3361. function FormatDateTime(const FormatStr: string; const DateTime: TDateTime
  3362. ): string;
  3363. procedure StoreStr(APos,Len: Integer);
  3364. begin
  3365. // Writeln('StoreStr: ',Result,'+',Copy(FormatStr,APos,Len));
  3366. Result:=Result+Copy(FormatStr,APos,Len);
  3367. end;
  3368. procedure StoreString(const AStr: string);
  3369. begin
  3370. // Writeln('StoreString: ',Result,'+',AStr);
  3371. Result:=Result+AStr;
  3372. end;
  3373. procedure StoreInt(Value, Digits: Integer);
  3374. var
  3375. S: string;
  3376. begin
  3377. S:=IntToStr(Value);
  3378. While (Length(S)<Digits) do
  3379. S:='0'+S;
  3380. StoreString(S);
  3381. end;
  3382. var
  3383. Year, Month, Day, DayOfWeek, Hour, Minute, Second, MilliSecond: word;
  3384. procedure StoreFormat(const FormatStr: string; Nesting: Integer; TimeFlag: Boolean);
  3385. var
  3386. Token, lastformattoken, prevlasttoken: char;
  3387. Count: integer;
  3388. Clock12: boolean;
  3389. tmp: integer;
  3390. isInterval: Boolean;
  3391. P,FormatCurrent,FormatEnd : Integer;
  3392. begin
  3393. if Nesting > 1 then // 0 is original string, 1 is included FormatString
  3394. Exit;
  3395. FormatCurrent := 1;
  3396. FormatEnd := Length(FormatStr);
  3397. Clock12 := false;
  3398. isInterval := false;
  3399. // look for unquoted 12-hour clock token
  3400. P:=1;
  3401. while P<=FormatEnd do
  3402. begin
  3403. Token := FormatStr[P];
  3404. case Token of
  3405. '''', '"':
  3406. begin
  3407. Inc(P);
  3408. while (P < FormatEnd) and (FormatStr[P]<>Token) do
  3409. Inc(P);
  3410. end;
  3411. 'A', 'a':
  3412. begin
  3413. if (CompareText(Copy(FormatStr,P,3),'A/P')=0) or
  3414. (CompareText(Copy(FormatStr,P,4),'AMPM')=0) or
  3415. (CompareText(Copy(FormatStr,P,5),'AM/PM')=0) then
  3416. begin
  3417. Clock12 := true;
  3418. break;
  3419. end;
  3420. end;
  3421. end; // case
  3422. Inc(P);
  3423. end ;
  3424. token := #255;
  3425. lastformattoken := ' ';
  3426. prevlasttoken := 'H';
  3427. while FormatCurrent <= FormatEnd do
  3428. begin
  3429. Token := UpperCase(FormatStr[FormatCurrent])[1];
  3430. // Writeln('Treating token at pos ',FormatCurrent,', : ',Token,' (',FormatStr,')');
  3431. Count := 1;
  3432. P := FormatCurrent + 1;
  3433. case Token of
  3434. '''', '"':
  3435. begin
  3436. while (P < FormatEnd) and (FormatStr[P]<>Token) do
  3437. Inc(P);
  3438. Inc(P);
  3439. Count := P - FormatCurrent;
  3440. StoreStr(FormatCurrent + 1, Count - 2);
  3441. end ;
  3442. 'A':
  3443. begin
  3444. if CompareText(Copy(FormatStr,FormatCurrent,4), 'AMPM') = 0 then
  3445. begin
  3446. Count := 4;
  3447. if Hour < 12 then
  3448. StoreString(TimeAMString)
  3449. else
  3450. StoreString(TimePMString);
  3451. end
  3452. else if CompareText(Copy(FormatStr,FormatCurrent,5), 'AM/PM') = 0 then
  3453. begin
  3454. Count := 5;
  3455. if Hour < 12 then StoreStr(FormatCurrent, 2)
  3456. else StoreStr(FormatCurrent+3, 2);
  3457. end
  3458. else if CompareText(Copy(FormatStr,FormatCurrent,3), 'A/P') = 0 then
  3459. begin
  3460. Count := 3;
  3461. if Hour < 12 then StoreStr(FormatCurrent, 1)
  3462. else StoreStr(FormatCurrent+2, 1);
  3463. end
  3464. else
  3465. raise EConvertError.Create('Illegal character in format string');
  3466. end ;
  3467. '/':
  3468. begin
  3469. // Writeln('Detected date separator');
  3470. StoreString(DateSeparator);
  3471. end;
  3472. ':': StoreString(TimeSeparator);
  3473. ' ', 'C', 'D', 'H', 'M', 'N', 'S', 'T', 'Y', 'Z', 'F' :
  3474. begin
  3475. // Writeln(FormatCurrent,' Special Token: ',Token,', Count: ',Count,', P: ',P);
  3476. while (P <= FormatEnd) and (UpperCase(FormatStr[P]) = Token) do
  3477. Inc(P);
  3478. Count := P - FormatCurrent;
  3479. // Writeln(FormatCurrent,' Special Token: ',Token,', Count: ',Count,', P: ',P);
  3480. case Token of
  3481. ' ': StoreStr(FormatCurrent, Count);
  3482. 'Y': begin
  3483. if Count > 2 then
  3484. StoreInt(Year, 4)
  3485. else
  3486. StoreInt(Year mod 100, 2);
  3487. end;
  3488. 'M': begin
  3489. if isInterval and ((prevlasttoken = 'H') or TimeFlag) then
  3490. StoreInt(Minute + (Hour + trunc(abs(DateTime))*24)*60, 0)
  3491. else
  3492. if (lastformattoken = 'H') or TimeFlag then
  3493. begin
  3494. if Count = 1 then
  3495. StoreInt(Minute, 0)
  3496. else
  3497. StoreInt(Minute, 2);
  3498. end
  3499. else
  3500. begin
  3501. case Count of
  3502. 1: StoreInt(Month, 0);
  3503. 2: StoreInt(Month, 2);
  3504. 3: StoreString(ShortMonthNames[Month]);
  3505. else
  3506. StoreString(LongMonthNames[Month]);
  3507. end;
  3508. end;
  3509. end;
  3510. 'D': begin
  3511. case Count of
  3512. 1: StoreInt(Day, 0);
  3513. 2: StoreInt(Day, 2);
  3514. 3: StoreString(ShortDayNames[DayOfWeek-1]);
  3515. 4: StoreString(LongDayNames[DayOfWeek-1]);
  3516. 5: StoreFormat(ShortDateFormat, Nesting+1, False);
  3517. else
  3518. StoreFormat(LongDateFormat, Nesting+1, False);
  3519. end ;
  3520. end ;
  3521. 'H':
  3522. if isInterval then
  3523. StoreInt(Hour + trunc(abs(DateTime))*24, 0)
  3524. else
  3525. if Clock12 then
  3526. begin
  3527. tmp := hour mod 12;
  3528. if tmp=0 then tmp:=12;
  3529. if Count = 1 then
  3530. StoreInt(tmp, 0)
  3531. else
  3532. StoreInt(tmp, 2);
  3533. end
  3534. else begin
  3535. if Count = 1 then
  3536. StoreInt(Hour, 0)
  3537. else
  3538. StoreInt(Hour, 2);
  3539. end;
  3540. 'N': if isInterval then
  3541. StoreInt(Minute + (Hour + trunc(abs(DateTime))*24)*60, 0)
  3542. else
  3543. if Count = 1 then
  3544. StoreInt(Minute, 0)
  3545. else
  3546. StoreInt(Minute, 2);
  3547. 'S': if isInterval then
  3548. StoreInt(Second + (Minute + (Hour + trunc(abs(DateTime))*24)*60)*60, 0)
  3549. else
  3550. if Count = 1 then
  3551. StoreInt(Second, 0)
  3552. else
  3553. StoreInt(Second, 2);
  3554. 'Z': if Count = 1 then
  3555. StoreInt(MilliSecond, 0)
  3556. else
  3557. StoreInt(MilliSecond, 3);
  3558. 'T': if Count = 1 then
  3559. StoreFormat(ShortTimeFormat, Nesting+1, True)
  3560. else
  3561. StoreFormat(LongTimeFormat, Nesting+1, True);
  3562. 'C': begin
  3563. StoreFormat(ShortDateFormat, Nesting+1, False);
  3564. if (Hour<>0) or (Minute<>0) or (Second<>0) then
  3565. begin
  3566. StoreString(' ');
  3567. StoreFormat(LongTimeFormat, Nesting+1, True);
  3568. end;
  3569. end;
  3570. 'F': begin
  3571. StoreFormat(ShortDateFormat, Nesting+1, False);
  3572. StoreString(' ');
  3573. StoreFormat(LongTimeFormat, Nesting+1, True);
  3574. end;
  3575. end;
  3576. prevlasttoken := lastformattoken;
  3577. lastformattoken := token;
  3578. end;
  3579. else
  3580. StoreString(Token);
  3581. end ;
  3582. Inc(FormatCurrent, Count);
  3583. end;
  3584. end;
  3585. begin
  3586. DecodeDateFully(DateTime, Year, Month, Day, DayOfWeek);
  3587. DecodeTime(DateTime, Hour, Minute, Second, MilliSecond);
  3588. // Writeln(DateTime,'->',Year,',', Month, ',',Day, ',',DayOfWeek,',',Hour, ',',Minute, ',',Second, ',',MilliSecond);
  3589. if FormatStr <> '' then
  3590. StoreFormat(FormatStr, 0, False)
  3591. else
  3592. StoreFormat('C', 0, False);
  3593. end ;
  3594. function CurrentYear: Word;
  3595. begin
  3596. Result:=TJSDate.New().FullYear;
  3597. end;
  3598. function TryStrToDate(const S: String; out Value: TDateTime): Boolean;
  3599. begin
  3600. Result:=TryStrToDate(S,Value,ShortDateFormat,#0);
  3601. end;
  3602. function TryStrToDate(const S: String; out Value: TDateTime; separator : char): Boolean;
  3603. begin
  3604. Result:=TryStrToDate(S,Value,ShortDateFormat,Separator);
  3605. end;
  3606. function TryStrToDate(const S: String; out Value: TDateTime;
  3607. const useformat : string; separator : char = #0): Boolean;
  3608. Var
  3609. Msg : String;
  3610. begin
  3611. Result:=Length(S)<>0;
  3612. If Result then
  3613. begin
  3614. Value:=IntStrToDate(Msg,S,useformat,Separator);
  3615. Result:=(Msg='');
  3616. end;
  3617. end;
  3618. function TryStrToTime(const S: String; out Value: TDateTime; separator : char): Boolean;
  3619. Var
  3620. Msg : String;
  3621. begin
  3622. Result:=Length(S)<>0;
  3623. If Result then
  3624. begin
  3625. Value:=IntStrToTime(Msg,S,Length(S),Separator);
  3626. Result:=(Msg='');
  3627. end;
  3628. end;
  3629. function TryStrToTime(const S: String; out Value: TDateTime): Boolean;
  3630. begin
  3631. result:=TryStrToTime(S,Value,#0);
  3632. end;
  3633. function TryStrToDateTime(const S: String; out Value: TDateTime): Boolean;
  3634. var
  3635. I: integer;
  3636. dtdate, dttime :TDateTime;
  3637. begin
  3638. result:=false;
  3639. I:=Pos(TimeSeparator,S);
  3640. If (I>0) then
  3641. begin
  3642. While (I>0) and (S[I]<>' ') do
  3643. Dec(I);
  3644. If I>0 then
  3645. begin
  3646. if not TryStrToDate(Copy(S,1,I-1),dtdate) then
  3647. exit;
  3648. if not TryStrToTime(Copy(S,i+1, Length(S)-i),dttime) then
  3649. exit;
  3650. Value:=ComposeDateTime(dtdate,dttime);
  3651. result:=true;
  3652. end
  3653. else
  3654. result:=TryStrToTime(s,Value);
  3655. end
  3656. else
  3657. result:=TryStrToDate(s,Value);
  3658. end;
  3659. function StrToDateDef(const S: String; const Defvalue : TDateTime): TDateTime;
  3660. begin
  3661. result := StrToDateDef(S,DefValue,#0);
  3662. end;
  3663. function StrToTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  3664. begin
  3665. result := StrToTimeDef(S,DefValue,#0);
  3666. end;
  3667. function StrToDateTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  3668. begin
  3669. if not TryStrToDateTime(s,Result) Then
  3670. result:=defvalue;
  3671. end;
  3672. function StrToDateDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  3673. begin
  3674. if not TryStrToDate(s,Result, separator) Then
  3675. result:=defvalue;
  3676. end;
  3677. function StrToTimeDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  3678. begin
  3679. if not TryStrToTime(s,Result, separator) Then
  3680. result:=defvalue;
  3681. end;
  3682. procedure ReplaceTime(var dati:TDateTime; NewTime : TDateTime);
  3683. begin
  3684. dati:= ComposeDateTime(dati, newtime);
  3685. end;
  3686. procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime);
  3687. var
  3688. tmp : TDateTime;
  3689. begin
  3690. tmp:=NewDate;
  3691. ReplaceTime(tmp,DateTime);
  3692. DateTime:=tmp;
  3693. end;
  3694. function FloatToDateTime(const Value: Extended): TDateTime;
  3695. begin
  3696. If (Value<MinDateTime) or (Value>MaxDateTime) then
  3697. Raise EConvertError.CreateFmt (SInvalidDateTime,[FloatToStr(Value)]);
  3698. Result:=Value;
  3699. end;
  3700. function FloattoCurr(const Value: Extended): Currency;
  3701. begin
  3702. if not TryFloatToCurr(Value, Result) then
  3703. Raise EConvertError.CreateFmt(SInvalidCurrency, [FloatToStr(Value)]);
  3704. end;
  3705. function TryFloatToCurr(const Value: Extended; var AResult: Currency): Boolean;
  3706. begin
  3707. Result:=(Value>=MinCurrency) and (Value<=MaxCurrency);
  3708. if Result then
  3709. AResult := Value;
  3710. end;
  3711. function CurrToStr(Value: Currency): string;
  3712. begin
  3713. Result:=FloatToStrF(Value,ffGeneral,-1,0);
  3714. end;
  3715. (*
  3716. function CurrToStr(Value: Currency; const FormatSettings: TFormatSettings): string;
  3717. begin
  3718. end;
  3719. *)
  3720. function StrToCurr(const S: string): Currency;
  3721. begin
  3722. if not TryStrToCurr(S,Result) then
  3723. Raise EConvertError.createfmt(SInvalidCurrency,[S]);
  3724. end;
  3725. (*
  3726. function StrToCurr(const S: string; const FormatSettings: TFormatSettings): Currency;
  3727. begin
  3728. end;
  3729. *)
  3730. function TryStrToCurr(const S: string; out Value: Currency): Boolean;
  3731. Var
  3732. D : Double;
  3733. begin
  3734. Result:=TryStrToFloat(S,D);
  3735. if Result then
  3736. Value:=D;
  3737. end;
  3738. (*
  3739. function TryStrToCurr(const S: string; out Value: Currency; const FormatSettings: TFormatSettings): Boolean;
  3740. begin
  3741. end;
  3742. *)
  3743. function StrToCurrDef(const S: string; Default: Currency): Currency;
  3744. Var
  3745. R : Currency;
  3746. begin
  3747. if TryStrToCurr(S,R) then
  3748. Result:=R
  3749. else
  3750. Result:=Default;
  3751. end;
  3752. (*
  3753. function StrToCurrDef(const S: string; Default: Currency; const FormatSettings: TFormatSettings): Currency;
  3754. begin
  3755. end;
  3756. *)
  3757. { ---------------------------------------------------------------------
  3758. Interface related
  3759. ---------------------------------------------------------------------}
  3760. function Supports(const Instance: IInterface; const AClass: TClass; out Obj
  3761. ): Boolean;
  3762. begin
  3763. Result := (Instance<>nil) and (Instance.QueryInterface(IObjectInstance,Obj)=S_OK)
  3764. and (TObject(Obj).InheritsFrom(AClass));
  3765. end;
  3766. function Supports(const Instance: IInterface; const IID: TGuid; out Intf
  3767. ): Boolean;
  3768. begin
  3769. Result:=(Instance<>nil) and (Instance.QueryInterface(IID,Intf)=S_OK);
  3770. end;
  3771. function Supports(const Instance: TObject; const IID: TGuid; out Intf): Boolean;
  3772. begin
  3773. Result:=(Instance<>nil) and Instance.GetInterface(IID,Intf);
  3774. end;
  3775. function Supports(const Instance: TObject; const IID: TGuidString; out Intf
  3776. ): Boolean;
  3777. begin
  3778. Result:=(Instance<>nil) and Instance.GetInterfaceByStr(IID,Intf);
  3779. end;
  3780. function Supports(const Instance: IInterface; const AClass: TClass): Boolean;
  3781. var
  3782. Temp: TObject;
  3783. begin
  3784. Result:=Supports(Instance,AClass,Temp);
  3785. end;
  3786. function Supports(const Instance: IInterface; const IID: TGuid): Boolean;
  3787. var
  3788. Temp: IInterface;
  3789. begin
  3790. Result:=Supports(Instance,IID,Temp);
  3791. end;
  3792. function Supports(const Instance: TObject; const IID: TGuid): Boolean;
  3793. var
  3794. Temp: TJSObject;
  3795. begin
  3796. Result:=Supports(Instance,IID,Temp);
  3797. asm
  3798. if (Temp && Temp.$kind==='com') Temp._Release();
  3799. end;
  3800. end;
  3801. function Supports(const Instance: TObject; const IID: TGuidString): Boolean;
  3802. var
  3803. Temp: TJSObject;
  3804. begin
  3805. Result:=Supports(Instance,IID,Temp);
  3806. asm
  3807. if (Temp && Temp.$kind==='com') Temp._Release();
  3808. end;
  3809. end;
  3810. function Supports(const AClass: TClass; const IID: TGuid): Boolean;
  3811. var
  3812. maps: JSValue;
  3813. begin
  3814. if AClass=nil then exit(false);
  3815. maps := TJSObject(AClass)['$intfmaps'];
  3816. if not maps then exit(false);
  3817. if TJSObject(maps)[GUIDToString(IID)] then exit(true);
  3818. Result:=false;
  3819. end;
  3820. function Supports(const AClass: TClass; const IID: TGuidString): Boolean;
  3821. var
  3822. maps: JSValue;
  3823. begin
  3824. if AClass=nil then exit(false);
  3825. maps := TJSObject(AClass)['$intfmaps'];
  3826. if not maps then exit(false);
  3827. if TJSObject(maps)[uppercase(IID)] then exit(true);
  3828. Result:=false;
  3829. end;
  3830. function TryStringToGUID(const s: string; out Guid: TGuid): Boolean;
  3831. var
  3832. re: TJSRegexp;
  3833. begin
  3834. if Length(s)<>38 then Exit(False);
  3835. re:=TJSRegexp.new('^\{[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\}$');
  3836. Result:=re.test(s);
  3837. if not Result then
  3838. begin
  3839. Guid.D1:=0;
  3840. exit;
  3841. end;
  3842. asm
  3843. rtl.strToGUIDR(s,Guid);
  3844. end;
  3845. Result:=true;
  3846. end;
  3847. function StringToGUID(const S: string): TGuid;
  3848. begin
  3849. if not TryStringToGUID(S, Result) then
  3850. raise EConvertError.CreateFmt(SInvalidGUID, [S]);
  3851. end;
  3852. function GUIDToString(const guid: TGuid): string;
  3853. begin
  3854. Result:=System.GUIDToString(guid);
  3855. end;
  3856. function IsEqualGUID(const guid1, guid2: TGuid): Boolean;
  3857. var
  3858. i: integer;
  3859. begin
  3860. if (guid1.D1<>guid2.D1) or (guid1.D2<>guid2.D2) or (guid1.D3<>guid2.D3) then
  3861. exit(false);
  3862. for i:=0 to 7 do if guid1.D4[i]<>guid2.D4[i] then exit(false);
  3863. Result:=true;
  3864. end;
  3865. function GuidCase(const guid: TGuid; const List: array of TGuid): Integer;
  3866. begin
  3867. for Result := High(List) downto 0 do
  3868. if IsEqualGUID(guid, List[Result]) then
  3869. Exit;
  3870. Result := -1;
  3871. end;
  3872. function CreateGUID(out GUID: TGUID): Integer;
  3873. Function R(B: Integer) : NativeInt;
  3874. Var
  3875. v : NativeInt;
  3876. begin
  3877. v:=Random(256);
  3878. While B>1 do
  3879. begin
  3880. v:=v*256+Random(256);
  3881. Dec(B);
  3882. end;
  3883. Result:=V;
  3884. end;
  3885. Var
  3886. I : Integer;
  3887. begin
  3888. Result:=0;
  3889. GUID.D1:= R(4);
  3890. GUID.D2:= R(2);
  3891. GUID.D3:= R(2);
  3892. For I:=0 to 7 do
  3893. GUID.D4[I]:=R(1);
  3894. end;
  3895. { ---------------------------------------------------------------------
  3896. Integer/Ordinal related
  3897. ---------------------------------------------------------------------}
  3898. function TryStrToInt(const S: String; out res: Integer): Boolean;
  3899. Var
  3900. NI : NativeInt;
  3901. begin
  3902. Result:=TryStrToInt(S,NI);
  3903. if Result then
  3904. res:=NI;
  3905. end;
  3906. function TryStrToInt(const S: String; out res: NativeInt): Boolean;
  3907. Var
  3908. Radix : Integer = 10;
  3909. N : String;
  3910. J : JSValue;
  3911. begin
  3912. N:=S;
  3913. // Javascript Parseint allows 1.0 or 1E0 to be an integer, so we must check for this to get the same behaviour as FPC/Delphi.
  3914. if (Pos(DecimalSeparator,N)<>0) or (Pos('.',N)<>0) then
  3915. exit(False);
  3916. case Copy(N,1,1) of
  3917. '$': Radix:=16;
  3918. '&': Radix:=8;
  3919. '%': Radix:=2;
  3920. end;
  3921. // Check for E after we know radix
  3922. if (Radix<>16) and (Pos('e',LowerCase(N))<>0) then
  3923. exit(False);
  3924. If Radix<>10 then
  3925. Delete(N,1,1);
  3926. J:=parseInt(N,Radix);
  3927. Result:=Not jsIsNan(j);
  3928. if Result then
  3929. res:=NativeInt(J);
  3930. end;
  3931. function StrToIntDef(const S: String; const aDef: Integer): Integer;
  3932. Var
  3933. R : NativeInt;
  3934. begin
  3935. if TryStrToInt(S,R) then
  3936. Result:=R
  3937. else
  3938. Result:=aDef;
  3939. end;
  3940. function StrToIntDef(const S: String; const aDef: NativeInt): NativeInt;
  3941. Var
  3942. R : NativeInt;
  3943. begin
  3944. if TryStrToInt(S,R) then
  3945. Result:=R
  3946. else
  3947. Result:=aDef;
  3948. end;
  3949. function StrToInt(const S: String): Integer;
  3950. Var
  3951. R : NativeInt;
  3952. begin
  3953. if not TryStrToInt(S,R) then
  3954. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3955. Result:=R;
  3956. end;
  3957. function StrToNativeInt(const S: String): NativeInt;
  3958. begin
  3959. if not TryStrToInt(S,Result) then
  3960. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3961. end;
  3962. function StrToInt64(const S: String): NativeLargeInt;
  3963. Var
  3964. N : NativeInt;
  3965. begin
  3966. if not TryStrToInt(S,N) then
  3967. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3968. Result:=N;
  3969. end;
  3970. function TryStrToInt64(const S: String; out res: NativeLargeInt): Boolean;
  3971. Var
  3972. R : nativeint;
  3973. begin
  3974. Result:=TryStrToInt(S,R);
  3975. If Result then
  3976. Res:=R;
  3977. end;
  3978. function StrToInt64Def(const S: String; ADefault: NativeLargeInt
  3979. ): NativeLargeInt;
  3980. begin
  3981. if not TryStrToInt64(S,Result) then
  3982. Result:=ADefault;
  3983. end;
  3984. function StrToQWord(const S: String): NativeLargeUInt;
  3985. Var
  3986. N : NativeInt;
  3987. begin
  3988. if (not TryStrToInt(S,N)) or (N<0) then
  3989. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3990. Result:=N;
  3991. end;
  3992. function TryStrToQWord(const S: String; out res: NativeLargeUInt): Boolean;
  3993. Var
  3994. R : nativeint;
  3995. begin
  3996. Result:=TryStrToInt(S,R) and (R>=0);
  3997. If Result then
  3998. Res:=R;
  3999. end;
  4000. function StrToQWordDef(const S: String; ADefault: NativeLargeUInt
  4001. ): NativeLargeUInt;
  4002. begin
  4003. if Not TryStrToQword(S,Result) then
  4004. Result:=ADefault;
  4005. end;
  4006. function StrToUInt64(const S: String): NativeLargeUInt;
  4007. Var
  4008. N : NativeInt;
  4009. begin
  4010. if (not TryStrToInt(S,N)) or (N<0) then
  4011. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  4012. Result:=N;
  4013. end;
  4014. function TryStrToUInt64(const S: String; out res: NativeLargeUInt): Boolean;
  4015. Var
  4016. R : nativeint;
  4017. begin
  4018. Result:=TryStrToInt(S,R) and (R>=0);
  4019. If Result then
  4020. Res:=R;
  4021. end;
  4022. function StrToUInt64Def(const S: String; ADefault: NativeLargeUInt
  4023. ): NativeLargeUInt;
  4024. begin
  4025. if Not TryStrToUInt64(S,Result) then
  4026. Result:=ADefault;
  4027. end;
  4028. function TryStrToDWord(const S: String; out res: DWord): Boolean;
  4029. Var
  4030. R : nativeint;
  4031. begin
  4032. Result:=TryStrToInt(S,R) and (R>=0) and (R<=DWord($FFFFFFFF));
  4033. If Result then
  4034. Res:=R;
  4035. end;
  4036. function StrToDWord(const S: String): DWord;
  4037. begin
  4038. if not TryStrToDWord(S,Result) then
  4039. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  4040. end;
  4041. function StrToDWordDef(const S: String; ADefault: DWord): DWord;
  4042. begin
  4043. if Not TryStrToDWord(S,Result) then
  4044. Result:=ADefault;
  4045. end;
  4046. function IntToHex(Value: NativeInt; Digits: integer): string;
  4047. begin
  4048. // Result:=HexStr(Value,Digits); // TestNegLongintHelper Failed: "ToHexString" expected: <FFFE0000> but was: <00-20000> !
  4049. Result:='';
  4050. if Value<0 then
  4051. asm
  4052. if (Value<0) Value = 0xFFFFFFFF + Value + 1;
  4053. end;
  4054. asm
  4055. Result=Value.toString(16);
  4056. end;
  4057. Result:=UpperCase(Result);
  4058. while (Length(Result)<Digits) do
  4059. Result:='0'+Result;
  4060. end;
  4061. { TFormatSettings }
  4062. function TFormatSettings.GetCurrencyDecimals: Byte;
  4063. begin
  4064. Result:=Sysutils.CurrencyDecimals;
  4065. end;
  4066. function TFormatSettings.GetCurrencyFormat: Byte;
  4067. begin
  4068. Result:=Sysutils.CurrencyFormat;
  4069. end;
  4070. function TFormatSettings.GetCurrencyString: String;
  4071. begin
  4072. Result:=Sysutils.CurrencyString;
  4073. end;
  4074. function TFormatSettings.GetDateSeparator: char;
  4075. begin
  4076. Result := SysUtils.DateSeparator;
  4077. end;
  4078. function TFormatSettings.GetDecimalSeparator: string;
  4079. begin
  4080. Result := SysUtils.DecimalSeparator;
  4081. end;
  4082. function TFormatSettings.GetLongDateFormat: string;
  4083. begin
  4084. Result := SysUtils.LongDateFormat;
  4085. end;
  4086. function TFormatSettings.GetLongDayNames: TDayNames;
  4087. begin
  4088. Result:=Sysutils.LongDayNames;
  4089. end;
  4090. function TFormatSettings.GetLongMonthNames: TMonthNames;
  4091. begin
  4092. Result:=Sysutils.LongMonthNames;
  4093. end;
  4094. function TFormatSettings.GetLongTimeFormat: string;
  4095. begin
  4096. Result := SysUtils.LongTimeFormat;
  4097. end;
  4098. function TFormatSettings.GetNegCurrFormat: Byte;
  4099. begin
  4100. Result:=Sysutils.NegCurrFormat;
  4101. end;
  4102. function TFormatSettings.GetShortDateFormat: string;
  4103. begin
  4104. Result := SysUtils.ShortDateFormat;
  4105. end;
  4106. function TFormatSettings.GetShortDayNames: TDayNames;
  4107. begin
  4108. Result:=Sysutils.ShortDayNames;
  4109. end;
  4110. function TFormatSettings.GetShortMonthNames: TMonthNames;
  4111. begin
  4112. Result:=Sysutils.ShortMonthNames;
  4113. end;
  4114. function TFormatSettings.GetShortTimeFormat: string;
  4115. begin
  4116. Result := SysUtils.ShortTimeFormat;
  4117. end;
  4118. function TFormatSettings.GetThousandSeparator: string;
  4119. begin
  4120. Result := SysUtils.ThousandSeparator;
  4121. end;
  4122. function TFormatSettings.GetTimeAMString: string;
  4123. begin
  4124. Result := SysUtils.TimeAMString;
  4125. end;
  4126. function TFormatSettings.GetTimePMString: string;
  4127. begin
  4128. Result := SysUtils.TimePMString;
  4129. end;
  4130. function TFormatSettings.GetTimeSeparator: char;
  4131. begin
  4132. Result := SysUtils.TimeSeparator;
  4133. end;
  4134. procedure TFormatSettings.SetCurrencyFormat(AValue: Byte);
  4135. begin
  4136. Sysutils.CurrencyFormat:=AValue;
  4137. end;
  4138. procedure TFormatSettings.SetCurrencyString(AValue: String);
  4139. begin
  4140. Sysutils.CurrencyString:=AValue;
  4141. end;
  4142. procedure TFormatSettings.SetDateSeparator(const Value: char);
  4143. begin
  4144. SysUtils.DateSeparator := Value;
  4145. end;
  4146. procedure TFormatSettings.SetDecimalSeparator(const Value: string);
  4147. begin
  4148. SysUtils.DecimalSeparator := Value;
  4149. end;
  4150. procedure TFormatSettings.SetLongDateFormat(const Value: string);
  4151. begin
  4152. SysUtils.LongDateFormat := Value;
  4153. end;
  4154. procedure TFormatSettings.SetLongDayNames(AValue: TDayNames);
  4155. begin
  4156. SysUtils.LongDayNames:=AValue;
  4157. end;
  4158. procedure TFormatSettings.SetLongMonthNames(AValue: TMonthNames);
  4159. begin
  4160. SysUtils.LongMonthNames:=AValue;
  4161. end;
  4162. procedure TFormatSettings.SetLongTimeFormat(const Value: string);
  4163. begin
  4164. SysUtils.LongTimeFormat := Value;
  4165. end;
  4166. procedure TFormatSettings.SetNegCurrFormat(AValue: Byte);
  4167. begin
  4168. Sysutils.NegCurrFormat:=AValue;
  4169. end;
  4170. procedure TFormatSettings.SetShortDateFormat(const Value: string);
  4171. begin
  4172. SysUtils.ShortDateFormat := Value;
  4173. end;
  4174. procedure TFormatSettings.SetShortDayNames(AValue: TDayNames);
  4175. begin
  4176. SysUtils.ShortDayNames:=AValue;
  4177. end;
  4178. procedure TFormatSettings.SetShortMonthNames(AValue: TMonthNames);
  4179. begin
  4180. SysUtils.ShortMonthNames:=AValue;
  4181. end;
  4182. procedure TFormatSettings.SetShortTimeFormat(const Value: string);
  4183. begin
  4184. SysUtils.ShortTimeFormat := Value;
  4185. end;
  4186. procedure TFormatSettings.SetCurrencyDecimals(AValue: Byte);
  4187. begin
  4188. Sysutils.CurrencyDecimals:=aValue;
  4189. end;
  4190. procedure TFormatSettings.SetThousandSeparator(const Value: string);
  4191. begin
  4192. SysUtils.ThousandSeparator := Value;
  4193. end;
  4194. procedure TFormatSettings.SetTimeAMString(const Value: string);
  4195. begin
  4196. SysUtils.TimeAMString := Value;
  4197. end;
  4198. procedure TFormatSettings.SetTimePMString(const Value: string);
  4199. begin
  4200. SysUtils.TimePMString := Value;
  4201. end;
  4202. procedure TFormatSettings.SetTimeSeparator(const Value: char);
  4203. begin
  4204. SysUtils.TimeSeparator := Value;
  4205. end;
  4206. class constructor TFormatSettings.Init;
  4207. begin
  4208. FormatSettings := TFormatSettings.Create;
  4209. end;
  4210. { ---------------------------------------------------------------------
  4211. FileNames
  4212. ---------------------------------------------------------------------}
  4213. function ChangeFileExt(const FileName, Extension: PathStr): PathStr;
  4214. var
  4215. i : longint;
  4216. EndSep : Set of Char;
  4217. SOF : Boolean;
  4218. begin
  4219. i := Length(FileName);
  4220. EndSep:=AllowDirectorySeparators+AllowDriveSeparators+[ExtensionSeparator];
  4221. while (I > 0) and not(FileName[I] in EndSep) do
  4222. Dec(I);
  4223. if (I = 0) or (FileName[I] <> ExtensionSeparator) then
  4224. I := Length(FileName)+1
  4225. else
  4226. begin
  4227. SOF:=(I=1) or (FileName[i-1] in AllowDirectorySeparators);
  4228. if (SOF) and not FirstDotAtFileNameStartIsExtension then
  4229. I:=Length(FileName)+1;
  4230. end;
  4231. Result := Copy(FileName, 1, I - 1) + Extension;
  4232. end;
  4233. function ExtractFilePath(const FileName: PathStr): PathStr;
  4234. var
  4235. i : longint;
  4236. EndSep : Set of Char;
  4237. begin
  4238. i := Length(FileName);
  4239. EndSep:=AllowDirectorySeparators+AllowDriveSeparators;
  4240. while (i > 0) and not CharInSet(FileName[i],EndSep) do
  4241. Dec(i);
  4242. If I>0 then
  4243. Result := Copy(FileName, 1, i)
  4244. else
  4245. Result:='';
  4246. end;
  4247. function ExtractFileDir(const FileName: PathStr): PathStr;
  4248. var
  4249. i : longint;
  4250. EndSep : Set of Char;
  4251. begin
  4252. I := Length(FileName);
  4253. EndSep:=AllowDirectorySeparators+AllowDriveSeparators;
  4254. while (I > 0) and not CharInSet(FileName[I],EndSep) do
  4255. Dec(I);
  4256. if (I > 1) and CharInSet(FileName[I],AllowDirectorySeparators) and
  4257. not CharInSet(FileName[I - 1],EndSep) then
  4258. Dec(I);
  4259. Result := Copy(FileName, 1, I);
  4260. end;
  4261. function ExtractFileDrive(const FileName: PathStr): PathStr;
  4262. var
  4263. i,l: longint;
  4264. begin
  4265. Result := '';
  4266. l:=Length(FileName);
  4267. if (l<2) then
  4268. exit;
  4269. If CharInSet(FileName[2],AllowDriveSeparators) then
  4270. result:=Copy(FileName,1,2)
  4271. else if CharInSet(FileName[1],AllowDirectorySeparators) and
  4272. CharInSet(FileName[2],AllowDirectorySeparators) then
  4273. begin
  4274. i := 2;
  4275. { skip share }
  4276. While (i<l) and Not CharInSet(Filename[i+1],AllowDirectorySeparators) do
  4277. inc(i);
  4278. inc(i);
  4279. While (i<l) and Not CharInSet(Filename[i+1],AllowDirectorySeparators) do
  4280. inc(i);
  4281. Result:=Copy(FileName,1,i);
  4282. end;
  4283. end;
  4284. function ExtractFileName(const FileName: PathStr): PathStr;
  4285. var
  4286. i : longint;
  4287. EndSep : Set of Char;
  4288. begin
  4289. I := Length(FileName);
  4290. EndSep:=AllowDirectorySeparators+AllowDriveSeparators;
  4291. while (I > 0) and not CharInSet(FileName[I],EndSep) do
  4292. Dec(I);
  4293. Result := Copy(FileName, I + 1, MaxInt);
  4294. end;
  4295. function ExtractFileExt(const FileName: PathStr): PathStr;
  4296. var
  4297. i : longint;
  4298. EndSep : Set of Char;
  4299. SOF : Boolean; // Dot at Start of filename ?
  4300. begin
  4301. Result:='';
  4302. I := Length(FileName);
  4303. EndSep:=AllowDirectorySeparators+AllowDriveSeparators+[ExtensionSeparator];
  4304. while (I > 0) and not CharInSet(FileName[I],EndSep) do
  4305. Dec(I);
  4306. if (I > 0) and (FileName[I] = ExtensionSeparator) then
  4307. begin
  4308. SOF:=(I=1) or (FileName[i-1] in AllowDirectorySeparators);
  4309. if (Not SOF) or FirstDotAtFileNameStartIsExtension then
  4310. Result := Copy(FileName, I, MaxInt);
  4311. end
  4312. else
  4313. Result := '';
  4314. end;
  4315. function ExtractRelativepath(const BaseName, DestName: PathStr): PathStr;
  4316. Var
  4317. OneLevelBack,Source, Dest : PathStr;
  4318. Sc,Dc,I,J : Longint;
  4319. SD,DD : TPathStrArray;
  4320. begin
  4321. OneLevelBack := '..'+PathDelim;
  4322. If Uppercase(ExtractFileDrive(BaseName))<>Uppercase(ExtractFileDrive(DestName)) Then
  4323. begin
  4324. Result:=DestName;
  4325. exit;
  4326. end;
  4327. Source:=ExcludeTrailingPathDelimiter(ExtractFilePath(BaseName));
  4328. Dest:=ExcludeTrailingPathDelimiter(ExtractFilePath(DestName));
  4329. SD:=GetDirs (Source);
  4330. SC:=Length(SD);
  4331. DD:=GetDirs (Dest);
  4332. DC:=Length(SD);
  4333. I:=0;
  4334. While (I<DC) and (I<SC) do
  4335. begin
  4336. If SameText(DD[i],SD[i]) then
  4337. Inc(i)
  4338. else
  4339. Break;
  4340. end;
  4341. Result:='';
  4342. For J:=I to SC do Result:=Result+OneLevelBack;
  4343. For J:=I to DC do Result:=Result+DD[J]+PathDelim;
  4344. Result:=Result+ExtractFileName(DestName);
  4345. end;
  4346. function SetDirSeparators(const FileName: PathStr): PathStr;
  4347. Var
  4348. I : integer;
  4349. begin
  4350. Result:=FileName;
  4351. For I:=1 to Length(Result) do
  4352. If CharInSet(Result[I],AllowDirectorySeparators) then
  4353. Result[i]:=PathDelim;
  4354. end;
  4355. function GetDirs(DirName: PathStr): TPathStrArray;
  4356. Var
  4357. I,J,L : Longint;
  4358. D : String;
  4359. begin
  4360. I:=1;
  4361. J:=0;
  4362. L:=0;
  4363. SetLength(Result,Length(DirName));
  4364. While I<=Length(DirName) do
  4365. begin
  4366. If CharInSet(DirName[i],AllowDirectorySeparators) then
  4367. begin
  4368. D:=Copy(DirName,J+1,J-I);
  4369. if (D<>'') then
  4370. begin
  4371. Result[L]:=D;
  4372. Inc(L);
  4373. end;
  4374. J:=I;
  4375. end;
  4376. Inc(I);
  4377. end;
  4378. SetLength(Result,L);
  4379. end;
  4380. function IncludeTrailingPathDelimiter(const Path: PathStr): PathStr;
  4381. Var
  4382. l : Integer;
  4383. begin
  4384. Result:=Path;
  4385. l:=Length(Result);
  4386. If (L=0) or not CharInSet(Result[l],AllowDirectorySeparators) then
  4387. Result:=Result+PathDelim;
  4388. end;
  4389. function ExcludeTrailingPathDelimiter(const Path: PathStr): PathStr;
  4390. Var
  4391. L : Integer;
  4392. begin
  4393. L:=Length(Path);
  4394. If (L>0) and CharInSet(Path[L],AllowDirectorySeparators) then
  4395. Dec(L);
  4396. Result:=Copy(Path,1,L);
  4397. end;
  4398. function IncludeLeadingPathDelimiter(const Path: PathStr): PathStr;
  4399. Var
  4400. l : Integer;
  4401. begin
  4402. Result:=Path;
  4403. l:=Length(Result);
  4404. If (L=0) or not CharInSet(Result[1],AllowDirectorySeparators) then
  4405. Result:=PathDelim+Result;
  4406. end;
  4407. function ExcludeLeadingPathDelimiter(const Path: PathStr): PathStr;
  4408. Var
  4409. L : Integer;
  4410. begin
  4411. Result:=Path;
  4412. L:=Length(Result);
  4413. If (L>0) and CharInSet(Result[1],AllowDirectorySeparators) then
  4414. Delete(Result,1,1);
  4415. end;
  4416. function IsPathDelimiter(const Path: PathStr; Index: Integer): Boolean;
  4417. begin
  4418. Result:=(Index>0) and (Index<=Length(Path)) and CharInSet(Path[Index],AllowDirectorySeparators);
  4419. end;
  4420. function ConcatPaths(const Paths: array of PathStr): PathStr;
  4421. var
  4422. I: Integer;
  4423. begin
  4424. if Length(Paths) > 0 then
  4425. begin
  4426. Result := Paths[0];
  4427. for I := 1 to Length(Paths) - 1 do
  4428. Result := IncludeTrailingPathDelimiter(Result) + ExcludeLeadingPathDelimiter(Paths[I]);
  4429. end else
  4430. Result := '';
  4431. end;
  4432. Function EncodeHTMLEntities (S : String) : String;
  4433. begin
  4434. Result:='';
  4435. if S='' then exit;
  4436. asm
  4437. return S.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
  4438. return '&#'+i.charCodeAt(0)+';';
  4439. });
  4440. end;
  4441. end;
  4442. { ---------------------------------------------------------------------
  4443. Type helpers implementation
  4444. ---------------------------------------------------------------------}
  4445. { ---------------------------------------------------------------------
  4446. TGUIDHelper
  4447. ---------------------------------------------------------------------}
  4448. Procedure NotImplemented(S : String);
  4449. begin
  4450. Raise Exception.Create('Not yet implemented : '+S);
  4451. end;
  4452. class function TGuidHelper.Create(Src: TGUID; BigEndian: Boolean): TGUID;
  4453. begin
  4454. Result:=Src;
  4455. if Not Bigendian then
  4456. begin
  4457. Result.D1:=SwapEndian(Result.D1);
  4458. Result.D2:=SwapEndian(Result.D2);
  4459. Result.D3:=SwapEndian(Result.D3);
  4460. end;
  4461. end;
  4462. class function TGuidHelper.Create(const Buf: TJSArrayBuffer; AStartIndex: Cardinal; BigEndian: Boolean): TGUID;
  4463. Var
  4464. A : Cardinal;
  4465. B,C : Word;
  4466. V : TJSDataView;
  4467. begin
  4468. V:=TJSDataView.New(Buf);
  4469. // The get functions return by default correct endianness.
  4470. if BigEndian then
  4471. begin
  4472. A:=V.getUint32(aStartIndex);
  4473. B:=V.getUint16(AStartIndex+4);
  4474. C:=V.getUint16(AStartIndex+6);
  4475. end
  4476. else
  4477. begin
  4478. A:=SwapEndian(V.getUint32(aStartIndex));
  4479. B:=SwapEndian(V.getUint16(AStartIndex+4));
  4480. C:=SwapEndian(V.getUint16(AStartIndex+6));
  4481. end;
  4482. Result:=Create(A,B,C,V.GetUint8(AStartIndex+8),V.GetUint8(AStartIndex+9),V.GetUint8(AStartIndex+10),V.GetUint8(AStartIndex+11),V.GetUint8(AStartIndex+12),V.GetUint8(AStartIndex+13),V.GetUint8(AStartIndex+14),V.GetUint8(AStartIndex+15));
  4483. end;
  4484. class function TGuidHelper.Create(const Data: array of Byte; AStartIndex: Cardinal; BigEndian: Boolean): TGUID;
  4485. Var
  4486. D : TJSUint8Array;
  4487. begin
  4488. if ((System.Length(Data)-AStartIndex)<16) then
  4489. raise EArgumentException.CreateFmt('The length of a GUID array must be at least %d',[]);
  4490. D:=TJSUint8Array.From(Data);
  4491. Result:=Create(D.buffer,aStartIndex,BigEndian);
  4492. end;
  4493. class function TGuidHelper.Create(const B: TBytes; DataEndian: TEndian): TGUID;
  4494. begin
  4495. Result:=Create(B,0,DataEndian);
  4496. end;
  4497. class function TGuidHelper.Create(const B: TBytes; AStartIndex: Cardinal; DataEndian: TEndian): TGUID;
  4498. begin
  4499. if ((System.Length(B)-AStartIndex)<16) then
  4500. raise EArgumentException.CreateFmt('The length of a GUID array must be at least %d',[]);
  4501. Result:=Create(B,AStartIndex,DataEndian=TEndian.Big);
  4502. end;
  4503. class function TGuidHelper.Create(const S: string): TGUID;
  4504. begin
  4505. Result:=StringToGUID(S);
  4506. end;
  4507. class function TGuidHelper.Create(A: Integer; B: SmallInt; C: SmallInt; const D: TBytes): TGUID;
  4508. begin
  4509. if (System.Length(D)<>8) then
  4510. raise EArgumentException.CreateFmt('The length of a GUID array must be %d',[]);
  4511. Result:=Create(Cardinal(A),Word(B),Word(C),D[0],D[1],D[2],D[3],D[4],D[5],D[6],D[7]);
  4512. end;
  4513. (*
  4514. class function TGuidHelper.Create(A: Integer; B: SmallInt; C: SmallInt; D, E, F, G, H, I, J, K: Byte): TGUID;
  4515. begin
  4516. Result:=Create(Cardinal(A),Word(B),Word(C),D,E,F,G,H,I,J,K);
  4517. end;
  4518. *)
  4519. class function TGuidHelper.Create(A: Cardinal; B: Word; C: Word; D, E, F, G, H, I, J, K: Byte): TGUID;
  4520. begin
  4521. Result.D1 := Cardinal(A);
  4522. Result.D2 := Word(B);
  4523. Result.D3 := Word(C);
  4524. Result.D4[0] := D;
  4525. Result.D4[1] := E;
  4526. Result.D4[2] := F;
  4527. Result.D4[3] := G;
  4528. Result.D4[4] := H;
  4529. Result.D4[5] := I;
  4530. Result.D4[6] := J;
  4531. Result.D4[7] := K;
  4532. end;
  4533. class function TGuidHelper.NewGuid: TGUID;
  4534. begin
  4535. CreateGUID(Result)
  4536. end;
  4537. function TGuidHelper.ToByteArray(DataEndian: TEndian): TBytes;
  4538. Var
  4539. D : TJSUint8Array;
  4540. V : TJSDataView;
  4541. I : Integer;
  4542. begin
  4543. D:=TJSUint8array.New(16);
  4544. V:=TJSDataView.New(D.buffer);
  4545. V.setUint32(0,D1,DataEndian=TEndian.Little);
  4546. V.setUint16(4,D2,DataEndian=TEndian.Little);
  4547. V.setUint16(6,D3,DataEndian=TEndian.Little);
  4548. for I:=0 to 7 do
  4549. V.setUint8(8+I,D4[i]);
  4550. SetLength(Result, 16);
  4551. for I:=0 to 15 do
  4552. Result[i]:=V.getUint8(I);
  4553. end;
  4554. function TGuidHelper.ToString(SkipBrackets: Boolean): string;
  4555. begin
  4556. Result:=GuidToString(Self);
  4557. If SkipBrackets then
  4558. Result:=Copy(Result,2,Length(Result)-2);
  4559. end;
  4560. { ---------------------------------------------------------------------
  4561. TStringHelper
  4562. ---------------------------------------------------------------------}
  4563. Function HaveChar(AChar : Char; const AList: array of Char) : Boolean;
  4564. Var
  4565. I : SizeInt;
  4566. begin
  4567. I:=0;
  4568. Result:=False;
  4569. While (Not Result) and (I<Length(AList)) do
  4570. begin
  4571. Result:=(AList[i]=AChar);
  4572. Inc(I);
  4573. end;
  4574. end;
  4575. function TStringHelper.GetChar(AIndex: SizeInt): Char;
  4576. begin
  4577. Result:=Self[AIndex+1];
  4578. end;
  4579. function TStringHelper.GetLength: SizeInt;
  4580. begin
  4581. Result:=System.Length(Self);
  4582. end;
  4583. class function TStringHelper.Compare(const A: string; const B: string): Integer;
  4584. begin
  4585. Result:=Compare(A,0,B,0,System.Length(B),[]);
  4586. end;
  4587. class function TStringHelper.Compare(const A: string; const B: string;
  4588. IgnoreCase: Boolean): Integer; //deprecated 'Use same with TCompareOptions';
  4589. begin
  4590. if IgnoreCase then
  4591. Result:=Compare(A,B,[coIgnoreCase])
  4592. else
  4593. Result:=Compare(A,B,[]);
  4594. end;
  4595. class function TStringHelper.Compare(const A: string; const B: string;
  4596. Options: TCompareOptions): Integer;
  4597. begin
  4598. Result:=Compare(A,0,B,0,System.Length(B),Options);
  4599. end;
  4600. class function TStringHelper.Compare(const A: string; IndexA: SizeInt;
  4601. const B: string; IndexB: SizeInt; ALen: SizeInt): Integer;
  4602. begin
  4603. Result:=Compare(A,IndexA,B,IndexB,ALen,[]);
  4604. end;
  4605. class function TStringHelper.Compare(const A: string; IndexA: SizeInt;
  4606. const B: string; IndexB: SizeInt; ALen: SizeInt; IgnoreCase: Boolean
  4607. ): Integer; //deprecated 'Use same with TCompareOptions';
  4608. begin
  4609. if IgnoreCase then
  4610. Result:=Compare(A,IndexA,B,IndexB,ALen,[coIgnoreCase])
  4611. else
  4612. Result:=Compare(A,IndexA,B,IndexB,ALen,[])
  4613. end;
  4614. class function TStringHelper.Compare(const A: string; IndexA: SizeInt;
  4615. const B: string; IndexB: SizeInt; ALen: SizeInt; Options: TCompareOptions
  4616. ): Integer;
  4617. Var
  4618. AL,BL : String;
  4619. begin
  4620. AL:=System.Copy(A,IndexA+1,aLen);
  4621. BL:=System.Copy(B,IndexB+1,aLen);
  4622. if (coIgnoreCase in Options) then
  4623. Result:=TJSString(UpperCase(AL)).localeCompare(UpperCase(BL))
  4624. else
  4625. Result:=TJSString(AL).localeCompare(BL)
  4626. end;
  4627. class function TStringHelper.CompareOrdinal(const A: string; const B: string
  4628. ): Integer;
  4629. Var
  4630. L : SizeInt;
  4631. begin
  4632. L:=System.Length(B);
  4633. if L>System.Length(A) then
  4634. L:=System.Length(A);
  4635. Result:=CompareOrdinal(A,0,B,0,L);
  4636. end;
  4637. class function TStringHelper.CompareOrdinal(const A: string; IndexA: SizeInt;
  4638. const B: string; IndexB: SizeInt; ALen: SizeInt): Integer;
  4639. Var
  4640. I,M : integer;
  4641. begin
  4642. M:=System.Length(A)-IndexA;
  4643. If M>(System.Length(B)-IndexB) then
  4644. M:=(System.Length(B)-IndexB);
  4645. if M>aLen then
  4646. M:=aLen;
  4647. I:=0;
  4648. Result:=0;
  4649. While (Result=0) and (I<M) do
  4650. begin
  4651. Result:=TJSString(A).charCodeAt(IndexA+I)-TJSString(B).charCodeAt(IndexB+I);
  4652. Inc(I);
  4653. end;
  4654. end;
  4655. class function TStringHelper.CompareText(const A: string; const B: string
  4656. ): Integer;
  4657. begin
  4658. Result:=Sysutils.CompareText(A,B);
  4659. end;
  4660. class function TStringHelper.Copy(const Str: string): string;
  4661. begin
  4662. Result:=Str;
  4663. end;
  4664. class function TStringHelper.Create(AChar: Char; ACount: SizeInt): string;
  4665. begin
  4666. Result:=StringOfChar(AChar,ACount);
  4667. end;
  4668. class function TStringHelper.Create(const AValue: array of Char): string;
  4669. begin
  4670. Result:=Create(AValue,0,System.Length(AValue));
  4671. end;
  4672. class function TStringHelper.Create(const AValue: array of Char;
  4673. StartIndex: SizeInt; ALen: SizeInt): string;
  4674. Var
  4675. I : Integer;
  4676. begin
  4677. SetLength(Result,ALen);
  4678. For I:=1 to ALen do
  4679. Result[I]:=AValue[StartIndex+I-1];
  4680. end;
  4681. class function TStringHelper.EndsText(const ASubText, AText: string): Boolean;
  4682. begin
  4683. Result:=(ASubText<>'') and (sysutils.CompareText(System.Copy(AText,System.Length(AText)-System.Length(ASubText)+1,System.Length(ASubText)),ASubText)=0);
  4684. end;
  4685. class function TStringHelper.Equals(const a: string; const b: string): Boolean;
  4686. begin
  4687. Result:=A=B;
  4688. end;
  4689. class function TStringHelper.Format(const AFormat: string; const args: array of JSValue): string;
  4690. begin
  4691. Result:=Sysutils.Format(AFormat,Args);
  4692. end;
  4693. class function TStringHelper.IsNullOrEmpty(const AValue: string): Boolean;
  4694. begin
  4695. Result:=system.Length(AValue)=0;
  4696. end;
  4697. class function TStringHelper.IsNullOrWhiteSpace(const AValue: string): Boolean;
  4698. begin
  4699. Result:=system.Length(sysutils.Trim(AValue))=0;
  4700. end;
  4701. class function TStringHelper.Join(const Separator: string; const Values: array of JSValue): string;
  4702. begin
  4703. Result:=TJSArray(Values).Join(Separator);
  4704. end;
  4705. class function TStringHelper.Join(const Separator: string;
  4706. const Values: array of string): string;
  4707. begin
  4708. Result:=TJSArray(Values).Join(Separator);
  4709. end;
  4710. class function TStringHelper.Join(const Separator: string;
  4711. const Values: array of string; StartIndex: SizeInt; ACount: SizeInt): string;
  4712. Var
  4713. VLen : SizeInt;
  4714. begin
  4715. VLen:=High(Values);
  4716. If (ACount<0) or ((StartIndex>0) and (StartIndex>VLen)) then
  4717. raise ERangeError.Create(SRangeError);
  4718. If (ACount=0) or (VLen<0) then
  4719. Result:=''
  4720. else
  4721. Result:=TJSArray(Values).Slice(StartIndex,StartIndex+aCount).Join(Separator);
  4722. end;
  4723. class function TStringHelper.LowerCase(const S: string): string;
  4724. begin
  4725. Result:=sysutils.Lowercase(S);
  4726. end;
  4727. class function TStringHelper.Parse(const AValue: Boolean): string;
  4728. begin
  4729. Result:=BoolToStr(AValue);
  4730. end;
  4731. class function TStringHelper.Parse(const AValue: Extended): string;
  4732. begin
  4733. Result:=FloatToStr(AValue);
  4734. end;
  4735. class function TStringHelper.Parse(const AValue: NativeInt): string;
  4736. begin
  4737. Result:=IntToStr(AValue);
  4738. end;
  4739. class function TStringHelper.Parse(const AValue: Integer): string;
  4740. begin
  4741. Result:=IntToStr(AValue);
  4742. end;
  4743. class function TStringHelper.ToBoolean(const S: string): Boolean;
  4744. begin
  4745. Result:=StrToBool(S);
  4746. end;
  4747. class function TStringHelper.ToDouble(const S: string): Double;
  4748. begin
  4749. Result:=StrToFloat(S);
  4750. end;
  4751. class function TStringHelper.ToExtended(const S: string): Extended;
  4752. begin
  4753. Result:=StrToFloat(S);
  4754. end;
  4755. class function TStringHelper.ToNativeInt(const S: string): NativeInt;
  4756. begin
  4757. Result:=StrToInt64(S);
  4758. end;
  4759. class function TStringHelper.ToInteger(const S: string): Integer;
  4760. begin
  4761. Result:=StrToInt(S);
  4762. end;
  4763. class function TStringHelper.UpperCase(const S: string): string;
  4764. begin
  4765. Result:=sysutils.Uppercase(S);
  4766. end;
  4767. class function TStringHelper.ToCharArray(const S: String): TCharArray;
  4768. Var
  4769. I,Len: integer;
  4770. begin
  4771. Len:=System.Length(S);
  4772. SetLength(Result,Len);
  4773. For I:=1 to Len do
  4774. Result[I-1]:=S[I];
  4775. end;
  4776. function TStringHelper.CompareTo(const B: string): Integer;
  4777. begin
  4778. // Order is important
  4779. Result:=Compare(Self,B);
  4780. end;
  4781. function TStringHelper.Contains(const AValue: string): Boolean;
  4782. begin
  4783. Result:=(AValue<>'') and (Pos(AValue,Self)>0);
  4784. end;
  4785. function TStringHelper.CountChar(const C: Char): SizeInt;
  4786. Var
  4787. S : Char;
  4788. begin
  4789. Result:=0;
  4790. For S in Self do
  4791. if (S=C) then
  4792. Inc(Result);
  4793. end;
  4794. function TStringHelper.DeQuotedString: string;
  4795. begin
  4796. Result:=DeQuotedString('''');
  4797. end;
  4798. function TStringHelper.DeQuotedString(const AQuoteChar: Char): string;
  4799. var
  4800. L,I : SizeInt;
  4801. Res : Array of Char;
  4802. PS,PD : SizeInt;
  4803. IsQuote : Boolean;
  4804. begin
  4805. L:=System.Length(Self);
  4806. if (L<2) or Not ((Self[1]=AQuoteChar) and (Self[L]=AQuoteChar)) then
  4807. Exit(Self);
  4808. SetLength(Res,L);
  4809. IsQuote:=False;
  4810. PS:=2;
  4811. PD:=1;
  4812. For I:=2 to L-1 do
  4813. begin
  4814. if (Self[PS]=AQuoteChar) then
  4815. begin
  4816. IsQuote:=Not IsQuote;
  4817. if Not IsQuote then
  4818. begin
  4819. Result[PD]:=Self[PS];
  4820. Inc(PD);
  4821. end;
  4822. end
  4823. else
  4824. begin
  4825. if IsQuote then
  4826. IsQuote:=false;
  4827. Result[PD]:=Self[PS];
  4828. Inc(PD);
  4829. end;
  4830. Inc(PS);
  4831. end;
  4832. SetLength(Result,PD-1);
  4833. end;
  4834. function TStringHelper.EndsWith(const AValue: string): Boolean;
  4835. begin
  4836. Result:=EndsWith(AValue,False);
  4837. end;
  4838. function TStringHelper.EndsWith(const AValue: string; IgnoreCase: Boolean): Boolean;
  4839. Var
  4840. L : SizeInt;
  4841. S : String;
  4842. begin
  4843. L:=system.Length(AVAlue);
  4844. Result:=L=0;
  4845. if Not Result then
  4846. begin
  4847. S:=system.Copy(Self,Length-L+1,L);
  4848. Result:=system.Length(S)=L;
  4849. if Result then
  4850. if IgnoreCase then
  4851. Result:=CompareText(S,AValue)=0
  4852. else
  4853. Result:=S=AValue;
  4854. end;
  4855. end;
  4856. function TStringHelper.Equals(const AValue: string): Boolean;
  4857. begin
  4858. Result:=(Self=AValue);
  4859. end;
  4860. function TStringHelper.Format(const args: array of jsValue): string;
  4861. begin
  4862. Result:=Sysutils.Format(Self,Args);
  4863. end;
  4864. function TStringHelper.GetHashCode: Integer;
  4865. // Taken from contnrs, fphash
  4866. var
  4867. P,pmax : Integer;
  4868. L : TJSString;
  4869. begin
  4870. {$push}
  4871. {$Q-}
  4872. L:=TJSString(Self);
  4873. Result:=0;
  4874. P:=1;
  4875. pmax:=length+1;
  4876. while (p<pmax) do
  4877. begin
  4878. Result:=LongWord(LongInt(Result shl 5) - LongInt(Result)) xor L.CharCodeAt(P);
  4879. Inc(p);
  4880. end;
  4881. {$pop}
  4882. end;
  4883. function TStringHelper.IndexOf(AValue: Char): SizeInt;
  4884. begin
  4885. Result:=IndexOf(AValue,0,Length);
  4886. end;
  4887. function TStringHelper.IndexOf(const AValue: string): SizeInt;
  4888. begin
  4889. Result:=IndexOf(AValue,0,Length);
  4890. end;
  4891. function TStringHelper.IndexOf(AValue: Char; StartIndex: SizeInt): SizeInt;
  4892. begin
  4893. Result:=IndexOf(AValue,StartIndex,Length);
  4894. end;
  4895. function TStringHelper.IndexOf(const AValue: string; StartIndex: SizeInt
  4896. ): SizeInt;
  4897. begin
  4898. Result:=IndexOf(AValue,StartIndex,Length);
  4899. end;
  4900. function TStringHelper.IndexOf(AValue: Char; StartIndex: SizeInt;
  4901. ACount: SizeInt): SizeInt;
  4902. Var
  4903. S : String;
  4904. begin
  4905. S:=System.Copy(Self,StartIndex+1,ACount);
  4906. Result:=Pos(AValue,S)-1;
  4907. if Result<>-1 then
  4908. Result:=Result+StartIndex;
  4909. end;
  4910. function TStringHelper.IndexOf(const AValue: string; StartIndex: SizeInt;
  4911. ACount: SizeInt): SizeInt;
  4912. Var
  4913. S : String;
  4914. begin
  4915. S:=System.Copy(Self,StartIndex+1,ACount);
  4916. Result:=Pos(AValue,S)-1;
  4917. if Result<>-1 then
  4918. Result:=Result+StartIndex;
  4919. end;
  4920. function TStringHelper.IndexOfUnQuoted(const AValue: string; StartQuote,
  4921. EndQuote: Char; StartIndex: SizeInt = 0): SizeInt;
  4922. Var
  4923. LV : SizeInt;
  4924. S : String;
  4925. Function MatchAt(I : SizeInt) : Boolean ; Inline;
  4926. Var
  4927. J : SizeInt;
  4928. begin
  4929. J:=1;
  4930. Repeat
  4931. Result:=(S[I+J-1]=AValue[j]);
  4932. Inc(J);
  4933. Until (Not Result) or (J>LV);
  4934. end;
  4935. Var
  4936. I,L,Q: SizeInt;
  4937. begin
  4938. S:=Self;
  4939. Result:=-1;
  4940. LV:=system.Length(AValue);
  4941. L:=Length-LV+1;
  4942. if L<0 then
  4943. L:=0;
  4944. I:=StartIndex+1;
  4945. Q:=0;
  4946. if StartQuote=EndQuote then
  4947. begin
  4948. While (Result=-1) and (I<=L) do
  4949. begin
  4950. if (S[I]=StartQuote) then
  4951. Q:=1-Q;
  4952. if (Q=0) and MatchAt(i) then
  4953. Result:=I-1;
  4954. Inc(I);
  4955. end;
  4956. end
  4957. else
  4958. begin
  4959. While (Result=-1) and (I<=L) do
  4960. begin
  4961. if S[I]=StartQuote then
  4962. Inc(Q)
  4963. else if (S[I]=EndQuote) and (Q>0) then
  4964. Dec(Q);
  4965. if (Q=0) and MatchAt(i) then
  4966. Result:=I-1;
  4967. Inc(I);
  4968. end;
  4969. end;
  4970. end;
  4971. function TStringHelper.IndexOfAny(const AnyOf: string): SizeInt;
  4972. begin
  4973. Result:=IndexOfAny(AnyOf.ToCharArray);
  4974. end;
  4975. function TStringHelper.IndexOfAny(const AnyOf: array of Char): SizeInt;
  4976. begin
  4977. Result:=IndexOfAny(AnyOf,0,Length);
  4978. end;
  4979. function TStringHelper.IndexOfAny(const AnyOf: String; StartIndex: SizeInt): SizeInt;
  4980. begin
  4981. Result:=IndexOfAny(AnyOf.ToCharArray,StartIndex);
  4982. end;
  4983. function TStringHelper.IndexOfAny(const AnyOf: array of Char;
  4984. StartIndex: SizeInt): SizeInt;
  4985. begin
  4986. Result:=IndexOfAny(AnyOf,StartIndex,Length);
  4987. end;
  4988. function TStringHelper.IndexOfAny(const AnyOf: String; StartIndex: SizeInt; ACount: SizeInt): SizeInt;
  4989. begin
  4990. Result:=IndexOfAny(AnyOf.ToCharArray,StartIndex,aCount);
  4991. end;
  4992. function TStringHelper.IndexOfAny(const AnyOf: array of Char;
  4993. StartIndex: SizeInt; ACount: SizeInt): SizeInt;
  4994. Var
  4995. i,L : SizeInt;
  4996. begin
  4997. I:=StartIndex+1;
  4998. L:=I+ACount-1;
  4999. If L>Length then
  5000. L:=Length;
  5001. Result:=-1;
  5002. While (Result=-1) and (I<=L) do
  5003. begin
  5004. if HaveChar(Self[i],AnyOf) then
  5005. Result:=I-1;
  5006. Inc(I);
  5007. end;
  5008. end;
  5009. function TStringHelper.IndexOfAny(const AnyOf: array of String): SizeInt;
  5010. begin
  5011. Result:=IndexOfAny(AnyOf,0,Length);
  5012. end;
  5013. function TStringHelper.IndexOfAny(const AnyOf: array of String;
  5014. StartIndex: SizeInt): SizeInt;
  5015. begin
  5016. Result:=IndexOfAny(AnyOf,StartIndex,Length-StartIndex);
  5017. end;
  5018. function TStringHelper.IndexOfAny(const AnyOf: array of String;
  5019. StartIndex: SizeInt; ACount: SizeInt): SizeInt;
  5020. Var
  5021. M : SizeInt;
  5022. begin
  5023. Result:=IndexOfAny(AnyOf,StartIndex,ACount,M);
  5024. end;
  5025. function TStringHelper.IndexOfAny(const AnyOf: array of String;
  5026. StartIndex: SizeInt; ACount: SizeInt; out AMatch: SizeInt): SizeInt;
  5027. Var
  5028. L,I : SizeInt;
  5029. begin
  5030. Result:=-1;
  5031. For I:=0 to System.Length(AnyOf)-1 do
  5032. begin
  5033. L:=IndexOf(AnyOf[i],StartIndex,ACount);
  5034. If (L>=0) and ((Result=-1) or (L<Result)) then
  5035. begin
  5036. Result:=L;
  5037. AMatch:=I;
  5038. end;
  5039. end;
  5040. end;
  5041. function TStringHelper.IndexOfAnyUnquoted(const AnyOf: array of Char;
  5042. StartQuote, EndQuote: Char): SizeInt;
  5043. begin
  5044. Result:=IndexOfAnyUnquoted(AnyOf,StartQuote,EndQuote,0,Length);
  5045. end;
  5046. function TStringHelper.IndexOfAnyUnquoted(const AnyOf: array of Char;
  5047. StartQuote, EndQuote: Char; StartIndex: SizeInt): SizeInt;
  5048. begin
  5049. Result:=IndexOfAnyUnquoted(AnyOf,StartQuote,EndQuote,StartIndex,Length);
  5050. end;
  5051. function TStringHelper.IndexOfAnyUnquoted(const AnyOf: array of Char;
  5052. StartQuote, EndQuote: Char; StartIndex: SizeInt; ACount: SizeInt): SizeInt;
  5053. Var
  5054. I,L : SizeInt;
  5055. Q : SizeInt;
  5056. begin
  5057. Result:=-1;
  5058. L:=StartIndex+ACount-1;
  5059. if L>Length then
  5060. L:=Length;
  5061. I:=StartIndex+1;
  5062. Q:=0;
  5063. if StartQuote=EndQuote then
  5064. begin
  5065. While (Result=-1) and (I<=L) do
  5066. begin
  5067. if (Self[I]=StartQuote) then
  5068. Q:=1-Q;
  5069. if (Q=0) and HaveChar(Self[i],AnyOf) then
  5070. Result:=I-1;
  5071. Inc(I);
  5072. end;
  5073. end
  5074. else
  5075. begin
  5076. While (Result=-1) and (I<=L) do
  5077. begin
  5078. if Self[I]=StartQuote then
  5079. Inc(Q)
  5080. else if (Self[I]=EndQuote) and (Q>0) then
  5081. Dec(Q);
  5082. if (Q=0) and HaveChar(Self[i],AnyOf) then
  5083. Result:=I-1;
  5084. Inc(I);
  5085. end;
  5086. end;
  5087. end;
  5088. function TStringHelper.IndexOfAnyUnquoted(const AnyOf: array of string;
  5089. StartQuote, EndQuote: Char; StartIndex: SizeInt; out Matched: SizeInt
  5090. ): SizeInt;
  5091. Var
  5092. L,I : SizeInt;
  5093. begin
  5094. Result:=-1;
  5095. For I:=0 to System.Length(AnyOf)-1 do
  5096. begin
  5097. L:=IndexOfUnquoted(AnyOf[i],StartQuote,EndQuote,StartIndex);
  5098. If (L>=0) and ((Result=-1) or (L<Result)) then
  5099. begin
  5100. Result:=L;
  5101. Matched:=I;
  5102. end;
  5103. end;
  5104. end;
  5105. function TStringHelper.Insert(StartIndex: SizeInt; const AValue: string
  5106. ): string;
  5107. begin
  5108. system.Insert(AValue,Self,StartIndex+1);
  5109. Result:=Self;
  5110. end;
  5111. function TStringHelper.IsDelimiter(const Delimiters: string; Index: SizeInt
  5112. ): Boolean;
  5113. begin
  5114. Result:=sysutils.IsDelimiter(Delimiters,Self,Index+1);
  5115. end;
  5116. function TStringHelper.IsEmpty: Boolean;
  5117. begin
  5118. Result:=(Length=0)
  5119. end;
  5120. function TStringHelper.LastDelimiter(const Delims: string): SizeInt;
  5121. begin
  5122. Result:=sysutils.LastDelimiter(Delims,Self)-1;
  5123. end;
  5124. function TStringHelper.LastIndexOf(AValue: Char): SizeInt;
  5125. begin
  5126. Result:=LastIndexOf(AValue,Length-1,Length);
  5127. end;
  5128. function TStringHelper.LastIndexOf(const AValue: string): SizeInt;
  5129. begin
  5130. Result:=LastIndexOf(AValue,Length-1,Length);
  5131. end;
  5132. function TStringHelper.LastIndexOf(AValue: Char; AStartIndex: SizeInt): SizeInt;
  5133. begin
  5134. Result:=LastIndexOf(AValue,AStartIndex,Length);
  5135. end;
  5136. function TStringHelper.LastIndexOf(const AValue: string; AStartIndex: SizeInt
  5137. ): SizeInt;
  5138. begin
  5139. Result:=LastIndexOf(AValue,AStartIndex,Length);
  5140. end;
  5141. function TStringHelper.LastIndexOf(AValue: Char; AStartIndex: SizeInt;
  5142. ACount: SizeInt): SizeInt;
  5143. Var
  5144. Min : SizeInt;
  5145. begin
  5146. Result:=AStartIndex+1;
  5147. Min:=Result-ACount+1;
  5148. If Min<1 then
  5149. Min:=1;
  5150. While (Result>=Min) and (Self[Result]<>AValue) do
  5151. Dec(Result);
  5152. if Result<Min then
  5153. Result:=-1
  5154. else
  5155. Result:=Result-1;
  5156. end;
  5157. function TStringHelper.LastIndexOf(const AValue: string; AStartIndex: SizeInt; ACount: SizeInt): SizeInt;
  5158. begin
  5159. Result:=TJSString(Self).lastIndexOf(aValue,aStartIndex);
  5160. if (aStartIndex-Result)>aCount then
  5161. Result:=-1;
  5162. end;
  5163. function TStringHelper.LastIndexOfAny(const AnyOf: array of Char): SizeInt;
  5164. begin
  5165. Result:=LastIndexOfAny(AnyOf,Length-1,Length);
  5166. end;
  5167. function TStringHelper.LastIndexOfAny(const AnyOf: array of Char;
  5168. AStartIndex: SizeInt): SizeInt;
  5169. begin
  5170. Result:=LastIndexOfAny(AnyOf,AStartIndex,Length);
  5171. end;
  5172. function TStringHelper.LastIndexOfAny(const AnyOf: array of Char;
  5173. AStartIndex: SizeInt; ACount: SizeInt): SizeInt;
  5174. Var
  5175. Min : SizeInt;
  5176. begin
  5177. Result:=AStartIndex+1;
  5178. Min:=Result-ACount+1;
  5179. If Min<1 then
  5180. Min:=1;
  5181. While (Result>=Min) and Not HaveChar(Self[Result],AnyOf) do
  5182. Dec(Result);
  5183. if Result<Min then
  5184. Result:=-1
  5185. else
  5186. Result:=Result-1;
  5187. end;
  5188. function TStringHelper.PadLeft(ATotalWidth: SizeInt): string;
  5189. begin
  5190. Result:=PadLeft(ATotalWidth,' ');
  5191. end;
  5192. function TStringHelper.PadLeft(ATotalWidth: SizeInt; PaddingChar: Char): string;
  5193. Var
  5194. L : SizeInt;
  5195. begin
  5196. Result:=Self;
  5197. L:=ATotalWidth-Length;
  5198. If L>0 then
  5199. Result:=StringOfChar(PaddingChar,L)+Result;
  5200. end;
  5201. function TStringHelper.PadRight(ATotalWidth: SizeInt): string;
  5202. begin
  5203. Result:=PadRight(ATotalWidth,' ');
  5204. end;
  5205. function TStringHelper.PadRight(ATotalWidth: SizeInt; PaddingChar: Char
  5206. ): string;
  5207. Var
  5208. L : SizeInt;
  5209. begin
  5210. Result:=Self;
  5211. L:=ATotalWidth-Length;
  5212. If L>0 then
  5213. Result:=Result+StringOfChar(PaddingChar,L);
  5214. end;
  5215. function TStringHelper.QuotedString: string;
  5216. begin
  5217. Result:=QuotedStr(Self);
  5218. end;
  5219. function TStringHelper.QuotedString(const AQuoteChar: Char): string;
  5220. begin
  5221. Result:=QuotedStr(Self,AQuoteChar);
  5222. end;
  5223. function TStringHelper.Remove(StartIndex: SizeInt): string;
  5224. begin
  5225. Result:=Remove(StartIndex,Self.Length-StartIndex);
  5226. end;
  5227. function TStringHelper.Remove(StartIndex: SizeInt; ACount: SizeInt): string;
  5228. begin
  5229. Result:=Self;
  5230. System.Delete(Result,StartIndex+1,ACount);
  5231. end;
  5232. function TStringHelper.Replace(OldChar: Char; NewChar: Char): string;
  5233. begin
  5234. Result:=Replace(OldChar,NewChar,[rfReplaceAll]);
  5235. end;
  5236. function TStringHelper.Replace(OldChar: Char; NewChar: Char;
  5237. ReplaceFlags: TReplaceFlags): string;
  5238. begin
  5239. Result:=StringReplace(Self,OldChar,NewChar,ReplaceFlags);
  5240. end;
  5241. function TStringHelper.Replace(const OldValue: string; const NewValue: string
  5242. ): string;
  5243. begin
  5244. Result:=Replace(OldValue,NewValue,[rfReplaceAll]);
  5245. end;
  5246. function TStringHelper.Replace(const OldValue: string; const NewValue: string;
  5247. ReplaceFlags: TReplaceFlags): string;
  5248. begin
  5249. Result:=StringReplace(Self,OldValue,NewValue,ReplaceFlags);
  5250. end;
  5251. function TStringHelper.Split(const Separators: String): TStringArray;
  5252. begin
  5253. Result:=Split(Separators.ToCharArray);
  5254. end;
  5255. function TStringHelper.Split(const Separators: array of Char): TStringArray;
  5256. begin
  5257. Result:=Split(Separators,#0,#0,Length+1,TStringSplitOptions.None);
  5258. end;
  5259. function TStringHelper.Split(const Separators: string; ACount: SizeInt): TStringArray;
  5260. begin
  5261. Result:=Split(Separators.ToCharArray,aCount);
  5262. end;
  5263. function TStringHelper.Split(const Separators: array of Char; ACount: SizeInt
  5264. ): TStringArray;
  5265. begin
  5266. Result:=Split(Separators,#0,#0,ACount,TStringSplitOptions.None);
  5267. end;
  5268. function TStringHelper.Split(const Separators: string; Options: TStringSplitOptions): TStringArray;
  5269. begin
  5270. Result:=Split(Separators.ToCharArray,Options);
  5271. end;
  5272. function TStringHelper.Split(const Separators: array of Char;
  5273. Options: TStringSplitOptions): TStringArray;
  5274. begin
  5275. Result:=Split(Separators,Length+1,Options);
  5276. end;
  5277. function TStringHelper.Split(const Separators: string; ACount: SizeInt; Options: TStringSplitOptions): TStringArray;
  5278. begin
  5279. Result:=Split(Separators.ToCharArray,aCount,Options);
  5280. end;
  5281. function TStringHelper.Split(const Separators: array of Char; ACount: SizeInt;
  5282. Options: TStringSplitOptions): TStringArray;
  5283. begin
  5284. Result:=Split(Separators,#0,#0,ACount,Options);
  5285. end;
  5286. function TStringHelper.Split(const Separators: array of string): TStringArray;
  5287. begin
  5288. Result:=Split(Separators,Length+1);
  5289. end;
  5290. function TStringHelper.Split(const Separators: array of string; ACount: SizeInt
  5291. ): TStringArray;
  5292. begin
  5293. Result:=Split(Separators,ACount,TStringSplitOptions.None);
  5294. end;
  5295. function TStringHelper.Split(const Separators: array of string;
  5296. Options: TStringSplitOptions): TStringArray;
  5297. begin
  5298. Result:=Split(Separators,Length+1,Options);
  5299. end;
  5300. function TStringHelper.Split(const Separators: array of string;
  5301. ACount: SizeInt; Options: TStringSplitOptions): TStringArray;
  5302. begin
  5303. Result:=Split(Separators,#0,#0,ACount,Options);
  5304. end;
  5305. function TStringHelper.Split(const Separators: String; AQuote: Char): TStringArray;
  5306. begin
  5307. Result:=Split(Separators.ToCharArray,aQuote);
  5308. end;
  5309. function TStringHelper.Split(const Separators: array of Char; AQuote: Char
  5310. ): TStringArray;
  5311. begin
  5312. Result:=Split(Separators,AQuote,AQuote);
  5313. end;
  5314. function TStringHelper.Split(const Separators: String; AQuoteStart, AQuoteEnd: Char): TStringArray;
  5315. begin
  5316. Result:=Split(Separators.ToCharArray,aQuoteStart,aQuoteEnd);
  5317. end;
  5318. function TStringHelper.Split(const Separators: array of Char; AQuoteStart,
  5319. AQuoteEnd: Char): TStringArray;
  5320. begin
  5321. Result:=Split(Separators,AQuoteStart,AQuoteEnd,TStringSplitOptions.None);
  5322. end;
  5323. function TStringHelper.Split(const Separators: string; AQuoteStart, AQuoteEnd: Char; Options: TStringSplitOptions): TStringArray;
  5324. begin
  5325. Result:=Split(Separators.ToCharArray,aQuoteStart,aQuoteEnd,Options);
  5326. end;
  5327. function TStringHelper.Split(const Separators: array of Char; AQuoteStart,
  5328. AQuoteEnd: Char; Options: TStringSplitOptions): TStringArray;
  5329. begin
  5330. Result:=Split(Separators,AQuoteStart,AQuoteEnd,Length+1,Options);
  5331. end;
  5332. function TStringHelper.Split(const Separators: string; AQuoteStart, AQuoteEnd: Char; ACount: SizeInt): TStringArray;
  5333. begin
  5334. Result:=Split(Separators.ToCharArray,aQuoteStart,aQuoteEnd,aCount);
  5335. end;
  5336. function TStringHelper.Split(const Separators: array of Char; AQuoteStart,
  5337. AQuoteEnd: Char; ACount: SizeInt): TStringArray;
  5338. begin
  5339. Result:=Split(Separators,AQuoteStart,AQuoteEnd,ACount,TStringSplitOptions.None);
  5340. end;
  5341. function TStringHelper.Split(const Separators: string; AQuoteStart, AQuoteEnd: Char; ACount: SizeInt; Options: TStringSplitOptions
  5342. ): TStringArray;
  5343. begin
  5344. Result:=Split(Separators.ToCharArray,aQuoteStart,aQuoteEnd,aCount,Options);
  5345. end;
  5346. function TStringHelper.Split(const Separators: array of Char; AQuoteStart,
  5347. AQuoteEnd: Char; ACount: SizeInt; Options: TStringSplitOptions): TStringArray;
  5348. Const
  5349. BlockSize = 10;
  5350. Var
  5351. S : String;
  5352. Function NextSep(StartIndex : SizeInt) : SizeInt;
  5353. begin
  5354. if (AQuoteStart<>#0) then
  5355. Result:=S.IndexOfAnyUnQuoted(Separators,AQuoteStart,AQuoteEnd,StartIndex)
  5356. else
  5357. Result:=S.IndexOfAny(Separators,StartIndex);
  5358. end;
  5359. Procedure MaybeGrow(Curlen : SizeInt);
  5360. begin
  5361. if System.Length(Result)<=CurLen then
  5362. SetLength(Result,System.Length(Result)+BlockSize);
  5363. end;
  5364. Var
  5365. Sep,LastSep,Len : SizeInt;
  5366. T : String;
  5367. begin
  5368. S:=Self;
  5369. SetLength(Result,BlockSize);
  5370. Len:=0;
  5371. LastSep:=0;
  5372. Sep:=NextSep(0);
  5373. While (Sep<>-1) and ((ACount=0) or (Len<ACount)) do
  5374. begin
  5375. T:=SubString(LastSep,Sep-LastSep);
  5376. // Writeln('Examining >',T,'< at pos ',LastSep,', till pos ',Sep);
  5377. If (T<>'') or (not (TStringSplitOptions.ExcludeEmpty=Options)) then
  5378. begin
  5379. MaybeGrow(Len);
  5380. Result[Len]:=T;
  5381. Inc(Len);
  5382. end;
  5383. LastSep:=Sep+1;
  5384. Sep:=NextSep(LastSep);
  5385. end;
  5386. if (LastSep<=Length) and ((ACount=0) or (Len<ACount)) then
  5387. begin
  5388. T:=SubString(LastSep);
  5389. // Writeln('Examining >',T,'< at pos,',LastSep,' till pos ',Sep);
  5390. If (T<>'') or (not (TStringSplitOptions.ExcludeEmpty=Options)) then
  5391. begin
  5392. MaybeGrow(Len);
  5393. Result[Len]:=T;
  5394. Inc(Len);
  5395. end;
  5396. end;
  5397. SetLength(Result,Len);
  5398. end;
  5399. function TStringHelper.Split(const Separators: array of string; AQuote: Char
  5400. ): TStringArray;
  5401. begin
  5402. Result:=SPlit(Separators,AQuote,AQuote);
  5403. end;
  5404. function TStringHelper.Split(const Separators: array of string; AQuoteStart,
  5405. AQuoteEnd: Char): TStringArray;
  5406. begin
  5407. Result:=SPlit(Separators,AQuoteStart,AQuoteEnd,Length+1,TStringSplitOptions.None);
  5408. end;
  5409. function TStringHelper.Split(const Separators: array of string; AQuoteStart,
  5410. AQuoteEnd: Char; Options: TStringSplitOptions): TStringArray;
  5411. begin
  5412. Result:=SPlit(Separators,AQuoteStart,AQuoteEnd,Length+1,Options);
  5413. end;
  5414. function TStringHelper.Split(const Separators: array of string; AQuoteStart,
  5415. AQuoteEnd: Char; ACount: SizeInt): TStringArray;
  5416. begin
  5417. Result:=SPlit(Separators,AQuoteStart,AQuoteEnd,ACount,TStringSplitOptions.None);
  5418. end;
  5419. function TStringHelper.Split(const Separators: array of string; AQuoteStart,
  5420. AQuoteEnd: Char; ACount: SizeInt; Options: TStringSplitOptions): TStringArray;
  5421. Const
  5422. BlockSize = 10;
  5423. Var
  5424. S : String;
  5425. Function NextSep(StartIndex : SizeInt; out Match : SizeInt) : SizeInt;
  5426. begin
  5427. if (AQuoteStart<>#0) then
  5428. Result:=S.IndexOfAnyUnQuoted(Separators,AQuoteStart,AQuoteEnd,StartIndex,Match)
  5429. else
  5430. Result:=S.IndexOfAny(Separators,StartIndex,Length,Match);
  5431. end;
  5432. Procedure MaybeGrow(Curlen : SizeInt);
  5433. begin
  5434. if System.Length(Result)<=CurLen then
  5435. SetLength(Result,System.Length(Result)+BlockSize);
  5436. end;
  5437. Var
  5438. Sep,LastSep,Len,Match : SizeInt;
  5439. T : String;
  5440. begin
  5441. S:=Self;
  5442. SetLength(Result,BlockSize);
  5443. Len:=0;
  5444. LastSep:=0;
  5445. Sep:=NextSep(0,Match);
  5446. While (Sep<>-1) and ((ACount=0) or (Len<ACount)) do
  5447. begin
  5448. T:=SubString(LastSep,Sep-LastSep);
  5449. If (T<>'') or (not (TStringSplitOptions.ExcludeEmpty=Options)) then
  5450. begin
  5451. MaybeGrow(Len);
  5452. Result[Len]:=T;
  5453. Inc(Len);
  5454. end;
  5455. LastSep:=Sep+System.Length(Separators[Match]);
  5456. Sep:=NextSep(LastSep,Match);
  5457. end;
  5458. if (LastSep<=Length) and ((ACount=0) or (Len<ACount)) then
  5459. begin
  5460. T:=SubString(LastSep);
  5461. // Writeln('Examining >',T,'< at pos,',LastSep,' till pos ',Sep);
  5462. If (T<>'') or (not (TStringSplitOptions.ExcludeEmpty=Options)) then
  5463. begin
  5464. MaybeGrow(Len);
  5465. Result[Len]:=T;
  5466. Inc(Len);
  5467. end;
  5468. end;
  5469. SetLength(Result,Len);
  5470. end;
  5471. function TStringHelper.StartsWith(const AValue: string): Boolean;
  5472. begin
  5473. Result:=StartsWith(AValue,False);
  5474. end;
  5475. function TStringHelper.StartsWith(const AValue: string; IgnoreCase: Boolean
  5476. ): Boolean;
  5477. Var
  5478. L : SizeInt;
  5479. S : String;
  5480. begin
  5481. L:=System.Length(AValue);
  5482. Result:=L<=0;
  5483. if not Result then
  5484. begin
  5485. S:=System.Copy(Self,1,L);
  5486. Result:=(System.Length(S)=L);
  5487. if Result then
  5488. if IgnoreCase then
  5489. Result:=SameText(S,aValue)
  5490. else
  5491. Result:=SameStr(S,AValue);
  5492. end;
  5493. end;
  5494. function TStringHelper.Substring(AStartIndex: SizeInt): string;
  5495. begin
  5496. Result:=Self.SubString(AStartIndex,Self.Length-AStartIndex);
  5497. end;
  5498. function TStringHelper.Substring(AStartIndex: SizeInt; ALen: SizeInt): string;
  5499. begin
  5500. Result:=system.Copy(Self,AStartIndex+1,ALen);
  5501. end;
  5502. function TStringHelper.ToBoolean: Boolean;
  5503. begin
  5504. Result:=StrToBool(Self);
  5505. end;
  5506. function TStringHelper.ToInteger: Integer;
  5507. begin
  5508. Result:=StrToInt(Self);
  5509. end;
  5510. function TStringHelper.ToNativeInt: NativeInt;
  5511. begin
  5512. Result:=StrToNativeInt(Self);
  5513. end;
  5514. function TStringHelper.ToDouble: Double;
  5515. begin
  5516. Result:=StrToFLoat(Self);
  5517. end;
  5518. function TStringHelper.ToExtended: Extended;
  5519. begin
  5520. Result:=StrToFLoat(Self);
  5521. end;
  5522. function TStringHelper.ToCharArray: TCharArray;
  5523. begin
  5524. Result:=ToCharArray(0,Self.Length);
  5525. end;
  5526. function TStringHelper.ToCharArray(AStartIndex: SizeInt; ALen: SizeInt
  5527. ): TCharArray;
  5528. Var
  5529. I : SizeInt;
  5530. begin
  5531. SetLength(Result,ALen);
  5532. For I:=0 to ALen-1 do
  5533. Result[I]:=Self[AStartIndex+I+1];
  5534. end;
  5535. function TStringHelper.ToLower: string;
  5536. begin
  5537. Result:=LowerCase(Self);
  5538. end;
  5539. function TStringHelper.ToLowerInvariant: string;
  5540. begin
  5541. Result:=LowerCase(Self);
  5542. end;
  5543. function TStringHelper.ToUpper: string;
  5544. begin
  5545. Result:=UpperCase(Self);
  5546. end;
  5547. function TStringHelper.ToUpperInvariant: string;
  5548. begin
  5549. Result:=UpperCase(Self);
  5550. end;
  5551. function TStringHelper.Trim: string;
  5552. begin
  5553. Result:=SysUtils.Trim(self);
  5554. end;
  5555. function TStringHelper.TrimLeft: string;
  5556. begin
  5557. Result:=SysUtils.TrimLeft(Self);
  5558. end;
  5559. function TStringHelper.TrimRight: string;
  5560. begin
  5561. Result:=SysUtils.TrimRight(Self);
  5562. end;
  5563. function TStringHelper.Trim(const ATrimChars: array of Char): string;
  5564. begin
  5565. Result:=Self.TrimLeft(ATrimChars).TrimRight(ATrimChars);
  5566. end;
  5567. function TStringHelper.TrimLeft(const ATrimChars: array of Char): string;
  5568. Var
  5569. I,Len : SizeInt;
  5570. begin
  5571. I:=1;
  5572. Len:=Self.Length;
  5573. While (I<=Len) and HaveChar(Self[i],ATrimChars) do Inc(I);
  5574. if I=1 then
  5575. Result:=Self
  5576. else if I>Len then
  5577. Result:=''
  5578. else
  5579. Result:=system.Copy(Self,I,Len-I+1);
  5580. end;
  5581. function TStringHelper.TrimRight(const ATrimChars: array of Char): string;
  5582. Var
  5583. I,Len : SizeInt;
  5584. begin
  5585. Len:=Self.Length;
  5586. I:=Len;
  5587. While (I>=1) and HaveChar(Self[i],ATrimChars) do Dec(I);
  5588. if I<1 then
  5589. Result:=''
  5590. else if I=Len then
  5591. Result:=Self
  5592. else
  5593. Result:=system.Copy(Self,1,I);
  5594. end;
  5595. function TStringHelper.TrimEnd(const ATrimChars: array of Char): string;
  5596. begin
  5597. Result:=TrimRight(ATrimChars);
  5598. end;
  5599. function TStringHelper.TrimStart(const ATrimChars: array of Char): string;
  5600. begin
  5601. Result:=TrimLeft(ATrimChars);
  5602. end;
  5603. { ---------------------------------------------------------------------
  5604. TDoubleHelper
  5605. ---------------------------------------------------------------------}
  5606. Class Function TDoubleHelper.IsNan(const AValue: Double): Boolean; overload; inline;
  5607. begin
  5608. Result:=JS.jsIsNaN(AValue);
  5609. end;
  5610. Class Function TDoubleHelper.IsInfinity(const AValue: Double): Boolean; overload; inline;
  5611. begin
  5612. Result:=Not jsIsFinite(aValue);
  5613. end;
  5614. Class Function TDoubleHelper.IsNegativeInfinity(const AValue: Double): Boolean; overload; inline;
  5615. begin
  5616. asm
  5617. return (AValue=Number.NEGATIVE_INFINITY);
  5618. end;
  5619. Result:=aValue=0; // Fool compiler
  5620. end;
  5621. Class Function TDoubleHelper.IsPositiveInfinity(const AValue: Double): Boolean; overload; inline;
  5622. begin
  5623. asm
  5624. return (AValue=Number.POSITIVE_INFINITY);
  5625. end;
  5626. Result:=aValue=0; // Fool compiler.
  5627. end;
  5628. Class Function TDoubleHelper.Parse(const AString: string): Double; overload; inline;
  5629. begin
  5630. Result:=StrToFloat(AString);
  5631. end;
  5632. Class Function TDoubleHelper.ToString(const AValue: Double): string; overload; inline;
  5633. begin
  5634. Result:=FloatToStr(AValue);
  5635. end;
  5636. Class Function TDoubleHelper.ToString(const AValue: Double; const AFormat: TFloatFormat; const APrecision, ADigits: Integer): string; overload; inline;
  5637. begin
  5638. Result:=FloatToStrF(AValue,AFormat,APrecision,ADigits);
  5639. end;
  5640. Class Function TDoubleHelper.TryParse(const AString: string; out AValue: Double): Boolean; overload; inline;
  5641. begin
  5642. Result:=TryStrToFloat(AString,AValue);
  5643. end;
  5644. Function TDoubleHelper.GetB(AIndex: Cardinal): Byte;
  5645. var
  5646. F : TJSFloat64Array;
  5647. B : TJSUInt8array;
  5648. begin
  5649. F:=TJSFloat64Array.New(1);
  5650. B:=TJSUInt8array.New(F.Buffer);
  5651. F[0]:=Self;
  5652. Result:=B[AIndex];
  5653. end;
  5654. Function TDoubleHelper.GetW(AIndex: Cardinal): Word;
  5655. var
  5656. F : TJSFloat64Array;
  5657. W : TJSUInt16array;
  5658. begin
  5659. F:=TJSFloat64Array.New(1);
  5660. W:=TJSUInt16array.New(F.Buffer);
  5661. F[0]:=Self;
  5662. Result:=W[AIndex];
  5663. end;
  5664. Type
  5665. TFloatParts = Record
  5666. sign : boolean;
  5667. exp : integer;
  5668. mantissa : double;
  5669. end;
  5670. // See https://stackoverflow.com/questions/9383593/extracting-the-exponent-and-mantissa-of-a-javascript-number
  5671. Function FloatToParts(aValue : Double) : TFloatParts;
  5672. var
  5673. F : TJSFloat64Array;
  5674. B : TJSUInt8array;
  5675. begin
  5676. F:=TJSFloat64Array.New(1);
  5677. B:=TJSUInt8array.New(F.Buffer);
  5678. F[0]:=aValue;
  5679. Result.Sign:=(B[7] shr 7)=0;
  5680. Result.exp:=(((B[7] and $7f) shl 4) or (B[6] shr 4))- $3ff;
  5681. B[3]:=$3F;
  5682. B[6]:=B[6] or $F0;
  5683. Result.Mantissa:=F[0];
  5684. end;
  5685. Function TDoubleHelper.GetE: NativeUInt; inline;
  5686. begin
  5687. Result:=FloatToParts(Self).Exp;
  5688. end;
  5689. Function TDoubleHelper.GetF: NativeUInt; inline;
  5690. begin
  5691. Result:=0;
  5692. NotImplemented('GetF');
  5693. end;
  5694. Function TDoubleHelper.GetS: Boolean; inline;
  5695. begin
  5696. Result:=FloatToParts(Self).Sign;
  5697. end;
  5698. procedure TDoubleHelper.SetB(AIndex: Cardinal; const AValue: Byte);
  5699. var
  5700. F : TJSFloat64Array;
  5701. B : TJSUInt8array;
  5702. begin
  5703. if (AIndex>=8) then
  5704. raise ERangeError.Create(SRangeError);
  5705. F:=TJSFloat64Array.New(1);
  5706. B:=TJSUInt8array.New(F.Buffer);
  5707. F[0]:=Self;
  5708. B[AIndex]:=aValue;
  5709. Self:=F[0];
  5710. end;
  5711. procedure TDoubleHelper.SetW(AIndex: Cardinal; const AValue: Word);
  5712. Var
  5713. F : TJSFloat64Array;
  5714. W : TJSUInt16array;
  5715. begin
  5716. if (AIndex>=4) then
  5717. raise ERangeError.Create(SRangeError);
  5718. F:=TJSFloat64Array.New(1);
  5719. W:=TJSUInt16array.New(F.Buffer);
  5720. F[0]:=Self;
  5721. W[AIndex]:=aValue;
  5722. Self:=F[0];
  5723. end;
  5724. procedure TDoubleHelper.SetS(AValue: Boolean);
  5725. Var
  5726. F : TJSFloat64Array;
  5727. B : TJSUInt8array;
  5728. begin
  5729. F:=TJSFloat64Array.New(1);
  5730. B:=TJSUInt8array.New(F.Buffer);
  5731. F[0]:=Self;
  5732. if aValue then
  5733. B[7]:=B[7] or (1 shr 7)
  5734. else
  5735. B[7]:=B[7] and not (1 shr 7);
  5736. Self:=F[0];
  5737. end;
  5738. Procedure TDoubleHelper.BuildUp(const ASignFlag: Boolean; const AMantissa: NativeUInt; const AExponent: Integer);
  5739. begin
  5740. NotImplemented('BuildUp');
  5741. // Following statement is just to fool the compiler
  5742. if ASignFlag and (AMantissa>0) and (AExponent<0) then exit;
  5743. // TFloatRec(Self).BuildUp(ASignFlag, AMantissa, AExponent);
  5744. end;
  5745. Function TDoubleHelper.Exponent: Integer;
  5746. begin
  5747. Result:=FloatToParts(Self).Exp;
  5748. end;
  5749. Function TDoubleHelper.Fraction: Extended;
  5750. begin
  5751. Result:=system.Frac(Self);
  5752. end;
  5753. Function TDoubleHelper.IsInfinity: Boolean; overload; inline;
  5754. begin
  5755. Result:=Double.IsInfinity(Self);
  5756. end;
  5757. Function TDoubleHelper.IsNan: Boolean; overload; inline;
  5758. begin
  5759. Result:=Double.IsNan(Self);
  5760. end;
  5761. Function TDoubleHelper.IsNegativeInfinity: Boolean; overload; inline;
  5762. begin
  5763. Result:=Double.IsNegativeInfinity(Self);
  5764. end;
  5765. Function TDoubleHelper.IsPositiveInfinity: Boolean; overload; inline;
  5766. begin
  5767. Result:=Double.IsPositiveInfinity(Self);
  5768. end;
  5769. Function TDoubleHelper.Mantissa: NativeUInt;
  5770. begin
  5771. Result:=Trunc(FloatToParts(Self).mantissa);
  5772. end;
  5773. Function TDoubleHelper.ToString(const AFormat: TFloatFormat; const APrecision, ADigits: Integer): string; overload; inline;
  5774. begin
  5775. Result:=FloatToStrF(Self,AFormat,APrecision,ADigits);
  5776. end;
  5777. Function TDoubleHelper.ToString: string; overload; inline;
  5778. begin
  5779. Result:=FloatToStr(Self);
  5780. end;
  5781. { ---------------------------------------------------------------------
  5782. TByteHelper
  5783. ---------------------------------------------------------------------}
  5784. Class Function TByteHelper.Parse(const AString: string): Byte; inline;
  5785. begin
  5786. Result:=StrToInt(AString);
  5787. end;
  5788. Class Function TByteHelper.Size: Integer; inline;
  5789. begin
  5790. Result:=1;
  5791. end;
  5792. Class Function TByteHelper.ToString(const AValue: Byte): string; overload; inline;
  5793. begin
  5794. Result:=IntToStr(AValue);
  5795. end;
  5796. Class Function TByteHelper.TryParse(const AString: string; out AValue: Byte): Boolean; inline;
  5797. Var
  5798. C : Integer;
  5799. begin
  5800. Val(AString,AValue,C);
  5801. Result:=(C=0);
  5802. end;
  5803. Function TByteHelper.ToBoolean: Boolean; inline;
  5804. begin
  5805. Result:=(Self<>0);
  5806. end;
  5807. Function TByteHelper.ToDouble: Double; inline;
  5808. begin
  5809. Result:=Self;
  5810. end;
  5811. Function TByteHelper.ToExtended: Extended; inline;
  5812. begin
  5813. Result:=Self;
  5814. end;
  5815. Function TByteHelper.ToBinString: string; inline;
  5816. begin
  5817. Result:=BinStr(Self,Size*8);
  5818. end;
  5819. Function TByteHelper.ToHexString(const AMinDigits: Integer): string;
  5820. overload; inline;
  5821. begin
  5822. Result:=IntToHex(Self,AMinDigits);
  5823. end;
  5824. Function TByteHelper.ToHexString: string; overload; inline;
  5825. begin
  5826. Result:=IntToHex(Self,Size*2);
  5827. end;
  5828. Function TByteHelper.ToString: string; overload; inline;
  5829. begin
  5830. Result:=IntToStr(Self);
  5831. end;
  5832. Function TByteHelper.SetBit(const index: TByteBitIndex) : Byte; inline;
  5833. begin
  5834. Self := Self or (Byte(1) shl index);
  5835. Result:=Self;
  5836. end;
  5837. Function TByteHelper.ClearBit(const index: TByteBitIndex) : Byte; inline;
  5838. begin
  5839. Self:=Self and not Byte((Byte(1) shl index));
  5840. Result:=Self;
  5841. end;
  5842. Function TByteHelper.ToggleBit(const index: TByteBitIndex) : Byte; inline;
  5843. begin
  5844. Self := Self xor Byte((Byte(1) shl index));
  5845. Result:=Self;
  5846. end;
  5847. Function TByteHelper.TestBit(const Index: TByteBitIndex):Boolean; inline;
  5848. begin
  5849. Result := (Self and Byte((Byte(1) shl index)))<>0;
  5850. end;
  5851. { ---------------------------------------------------------------------
  5852. TShortintHelper
  5853. ---------------------------------------------------------------------}
  5854. Class Function TShortIntHelper.Parse(const AString: string): ShortInt; inline;
  5855. begin
  5856. Result:=StrToInt(AString);
  5857. end;
  5858. Class Function TShortIntHelper.Size: Integer; inline;
  5859. begin
  5860. Result:=1;
  5861. end;
  5862. Class Function TShortIntHelper.ToString(const AValue: ShortInt): string; overload; inline;
  5863. begin
  5864. Result:=IntToStr(AValue);
  5865. end;
  5866. Class Function TShortIntHelper.TryParse(const AString: string; out AValue: ShortInt): Boolean; inline;
  5867. Var
  5868. C : Integer;
  5869. begin
  5870. Val(AString,AValue,C);
  5871. Result:=(C=0);
  5872. end;
  5873. Function TShortIntHelper.ToBoolean: Boolean; inline;
  5874. begin
  5875. Result:=(Self<>0);
  5876. end;
  5877. Function TShortIntHelper.ToDouble: Double; inline;
  5878. begin
  5879. Result:=Self;
  5880. end;
  5881. Function TShortIntHelper.ToExtended: Extended; inline;
  5882. begin
  5883. Result:=Self;
  5884. end;
  5885. Function TShortIntHelper.ToBinString: string; inline;
  5886. begin
  5887. Result:=BinStr(Self,Size*8);
  5888. end;
  5889. Function TShortIntHelper.ToHexString(const AMinDigits: Integer): string; overload; inline;
  5890. Var
  5891. B : Word;
  5892. U : TJSUInt8Array;
  5893. S : TJSInt8array;
  5894. begin
  5895. if Self>=0 then
  5896. B:=Self
  5897. else
  5898. begin
  5899. S:=TJSInt8Array.New(1);
  5900. S[0]:=Self;
  5901. U:=TJSUInt8Array.New(S);
  5902. B:=U[0];
  5903. if AMinDigits>2 then
  5904. B:=$FF00+B;
  5905. end;
  5906. Result:=IntToHex(B,AMinDigits);
  5907. end;
  5908. Function TShortIntHelper.ToHexString: string; overload; inline;
  5909. begin
  5910. Result:=ToHexString(Size*2);
  5911. end;
  5912. Function TShortIntHelper.ToString: string; overload; inline;
  5913. begin
  5914. Result:=IntToStr(Self);
  5915. end;
  5916. Function TShortIntHelper.SetBit(const index: TShortIntBitIndex) : ShortInt; inline;
  5917. begin
  5918. Self := Self or (ShortInt(1) shl index);
  5919. Result:=Self;
  5920. end;
  5921. Function TShortIntHelper.ClearBit(const index: TShortIntBitIndex) : ShortInt; inline;
  5922. begin
  5923. Self:=Self and not ShortInt((ShortInt(1) shl index));
  5924. Result:=Self;
  5925. end;
  5926. Function TShortIntHelper.ToggleBit(const index: TShortIntBitIndex) : ShortInt; inline;
  5927. begin
  5928. Self := Self xor ShortInt((ShortInt(1) shl index));
  5929. Result:=Self;
  5930. end;
  5931. Function TShortIntHelper.TestBit(const Index: TShortIntBitIndex):Boolean; inline;
  5932. begin
  5933. Result := (Self and ShortInt((ShortInt(1) shl index)))<>0;
  5934. end;
  5935. { ---------------------------------------------------------------------
  5936. TSmallintHelper
  5937. ---------------------------------------------------------------------}
  5938. Class Function TSmallIntHelper.Parse(const AString: string): SmallInt; inline;
  5939. begin
  5940. Result:=StrToInt(AString);
  5941. end;
  5942. Class Function TSmallIntHelper.Size: Integer; inline;
  5943. begin
  5944. Result:=2;
  5945. end;
  5946. Class Function TSmallIntHelper.ToString(const AValue: SmallInt): string; overload; inline;
  5947. begin
  5948. Result:=IntToStr(AValue);
  5949. end;
  5950. Class Function TSmallIntHelper.TryParse(const AString: string; out AValue: SmallInt): Boolean; inline;
  5951. Var
  5952. C : Integer;
  5953. begin
  5954. Val(AString,AValue,C);
  5955. Result:=(C=0);
  5956. end;
  5957. Function TSmallIntHelper.ToBoolean: Boolean; inline;
  5958. begin
  5959. Result:=(Self<>0);
  5960. end;
  5961. Function TSmallIntHelper.ToDouble: Double; inline;
  5962. begin
  5963. Result:=Self;
  5964. end;
  5965. Function TSmallIntHelper.ToExtended: Extended; inline;
  5966. begin
  5967. Result:=Self;
  5968. end;
  5969. Function TSmallIntHelper.ToBinString: string; inline;
  5970. begin
  5971. Result:=BinStr(Self,Size*8);
  5972. end;
  5973. Function TSmallIntHelper.ToHexString(const AMinDigits: Integer): string; overload; inline;
  5974. Var
  5975. B : Cardinal;
  5976. U : TJSUInt16Array;
  5977. S : TJSInt16array;
  5978. begin
  5979. if Self>=0 then
  5980. B:=Self
  5981. else
  5982. begin
  5983. S:=TJSInt16Array.New(1);
  5984. S[0]:=Self;
  5985. U:=TJSUInt16Array.New(S);
  5986. B:=U[0];
  5987. if AMinDigits>6 then
  5988. B:=$FFFF0000+B
  5989. else if AMinDigits>4 then
  5990. B:=$FF0000+B;
  5991. end;
  5992. Result:=IntToHex(B,AMinDigits);
  5993. end;
  5994. Function TSmallIntHelper.ToHexString: string; overload; inline;
  5995. begin
  5996. Result:=ToHexString(Size*2);
  5997. end;
  5998. Function TSmallIntHelper.ToString: string; overload; inline;
  5999. begin
  6000. Result:=IntToStr(Self);
  6001. end;
  6002. Function TSmallIntHelper.SetBit(const index: TSmallIntBitIndex) : SmallInt; inline;
  6003. begin
  6004. Self := Self or (SmallInt(1) shl index);
  6005. Result:=Self;
  6006. end;
  6007. Function TSmallIntHelper.ClearBit(const index: TSmallIntBitIndex) : SmallInt; inline;
  6008. begin
  6009. Self:=Self and not SmallInt((SmallInt(1) shl index));
  6010. Result:=Self;
  6011. end;
  6012. Function TSmallIntHelper.ToggleBit(const index: TSmallIntBitIndex) : SmallInt; inline;
  6013. begin
  6014. Self := Self xor SmallInt((SmallInt(1) shl index));
  6015. Result:=Self;
  6016. end;
  6017. Function TSmallIntHelper.TestBit(const Index: TSmallIntBitIndex):Boolean; inline;
  6018. begin
  6019. Result := (Self and SmallInt((SmallInt(1) shl index)))<>0;
  6020. end;
  6021. { ---------------------------------------------------------------------
  6022. TWordHelper
  6023. ---------------------------------------------------------------------}
  6024. Class Function TWordHelper.Parse(const AString: string): Word; inline;
  6025. begin
  6026. Result:=StrToInt(AString);
  6027. end;
  6028. Class Function TWordHelper.Size: Integer; inline;
  6029. begin
  6030. Result:=2;
  6031. end;
  6032. Class Function TWordHelper.ToString(const AValue: Word): string; overload; inline;
  6033. begin
  6034. Result:=IntToStr(AValue);
  6035. end;
  6036. Class Function TWordHelper.TryParse(const AString: string; out AValue: Word): Boolean; inline;
  6037. Var
  6038. C : Integer;
  6039. begin
  6040. Val(AString,AValue,C);
  6041. Result:=(C=0);
  6042. end;
  6043. Function TWordHelper.ToBoolean: Boolean; inline;
  6044. begin
  6045. Result:=(Self<>0);
  6046. end;
  6047. Function TWordHelper.ToDouble: Double; inline;
  6048. begin
  6049. Result:=Self;
  6050. end;
  6051. Function TWordHelper.ToExtended: Extended; inline;
  6052. begin
  6053. Result:=Self;
  6054. end;
  6055. Function TWordHelper.ToBinString: string; inline;
  6056. begin
  6057. Result:=BinStr(Self,Size*8);
  6058. end;
  6059. Function TWordHelper.ToHexString(const AMinDigits: Integer): string;
  6060. overload; inline;
  6061. begin
  6062. Result:=IntToHex(Self,AMinDigits);
  6063. end;
  6064. Function TWordHelper.ToHexString: string; overload; inline;
  6065. begin
  6066. Result:=IntToHex(Self,Size*2);
  6067. end;
  6068. Function TWordHelper.ToString: string; overload; inline;
  6069. begin
  6070. Result:=IntToStr(Self);
  6071. end;
  6072. Function TWordHelper.SetBit(const index: TWordBitIndex) : Word; inline;
  6073. begin
  6074. Self := Self or (Word(1) shl index);
  6075. Result:=Self;
  6076. end;
  6077. Function TWordHelper.ClearBit(const index: TWordBitIndex) : Word; inline;
  6078. begin
  6079. Self:=Self and not Word((Word(1) shl index));
  6080. Result:=Self;
  6081. end;
  6082. Function TWordHelper.ToggleBit(const index: TWordBitIndex) : Word; inline;
  6083. begin
  6084. Self := Self xor Word((Word(1) shl index));
  6085. Result:=Self;
  6086. end;
  6087. Function TWordHelper.TestBit(const Index: TWordBitIndex):Boolean; inline;
  6088. begin
  6089. Result := (Self and Word((Word(1) shl index)))<>0;
  6090. end;
  6091. { ---------------------------------------------------------------------
  6092. TCardinalHelper
  6093. ---------------------------------------------------------------------}
  6094. Class Function TCardinalHelper.Parse(const AString: string): Cardinal; inline;
  6095. begin
  6096. Result:=StrToInt(AString);
  6097. end;
  6098. Class Function TCardinalHelper.Size: Integer; inline;
  6099. begin
  6100. Result:=4;
  6101. end;
  6102. Class Function TCardinalHelper.ToString(const AValue: Cardinal): string; overload; inline;
  6103. begin
  6104. Result:=IntToStr(AValue);
  6105. end;
  6106. Class Function TCardinalHelper.TryParse(const AString: string; out AValue: Cardinal): Boolean; inline;
  6107. Var
  6108. C : Integer;
  6109. begin
  6110. Val(AString,AValue,C);
  6111. Result:=(C=0);
  6112. end;
  6113. Function TCardinalHelper.ToBoolean: Boolean; inline;
  6114. begin
  6115. Result:=(Self<>0);
  6116. end;
  6117. Function TCardinalHelper.ToDouble: Double; inline;
  6118. begin
  6119. Result:=Self;
  6120. end;
  6121. Function TCardinalHelper.ToExtended: Extended; inline;
  6122. begin
  6123. Result:=Self;
  6124. end;
  6125. Function TCardinalHelper.ToBinString: string; inline;
  6126. begin
  6127. Result:=BinStr(Self,Size*8);
  6128. end;
  6129. Function TCardinalHelper.ToHexString(const AMinDigits: Integer): string;
  6130. overload; inline;
  6131. begin
  6132. Result:=IntToHex(Self,AMinDigits);
  6133. end;
  6134. Function TCardinalHelper.ToHexString: string; overload; inline;
  6135. begin
  6136. Result:=ToHexString(Size*2);
  6137. end;
  6138. Function TCardinalHelper.ToString: string; overload; inline;
  6139. begin
  6140. Result:=IntToStr(Self);
  6141. end;
  6142. Function TCardinalHelper.SetBit(const index: TCardinalBitIndex) : Cardinal; inline;
  6143. begin
  6144. Self := Self or (Cardinal(1) shl index);
  6145. Result:=Self;
  6146. end;
  6147. Function TCardinalHelper.ClearBit(const index: TCardinalBitIndex) : Cardinal; inline;
  6148. begin
  6149. Self:=Self and not Cardinal((Cardinal(1) shl index));
  6150. Result:=Self;
  6151. end;
  6152. Function TCardinalHelper.ToggleBit(const index: TCardinalBitIndex) : Cardinal; inline;
  6153. begin
  6154. Self := Self xor Cardinal((Cardinal(1) shl index));
  6155. Result:=Self;
  6156. end;
  6157. Function TCardinalHelper.TestBit(const Index: TCardinalBitIndex):Boolean; inline;
  6158. begin
  6159. Result := (Self and Cardinal((Cardinal(1) shl index)))<>0;
  6160. end;
  6161. { ---------------------------------------------------------------------
  6162. TIntegerHelper
  6163. ---------------------------------------------------------------------}
  6164. Class Function TIntegerHelper.Parse(const AString: string): Integer; inline;
  6165. begin
  6166. Result:=StrToInt(AString);
  6167. end;
  6168. Class Function TIntegerHelper.Size: Integer; inline;
  6169. begin
  6170. Result:=4;
  6171. end;
  6172. Class Function TIntegerHelper.ToString(const AValue: Integer): string; overload; inline;
  6173. begin
  6174. Result:=IntToStr(AValue);
  6175. end;
  6176. Class Function TIntegerHelper.TryParse(const AString: string; out AValue: Integer): Boolean; inline;
  6177. Var
  6178. C : Integer;
  6179. begin
  6180. Val(AString,AValue,C);
  6181. Result:=(C=0);
  6182. end;
  6183. Function TIntegerHelper.ToBoolean: Boolean; inline;
  6184. begin
  6185. Result:=(Self<>0);
  6186. end;
  6187. Function TIntegerHelper.ToDouble: Double; inline;
  6188. begin
  6189. Result:=Self;
  6190. end;
  6191. Function TIntegerHelper.ToExtended: Extended; inline;
  6192. begin
  6193. Result:=Self;
  6194. end;
  6195. Function TIntegerHelper.ToBinString: string; inline;
  6196. begin
  6197. Result:=BinStr(Self,Size*8);
  6198. end;
  6199. Function TIntegerHelper.ToHexString(const AMinDigits: Integer): string;
  6200. overload; inline;
  6201. Var
  6202. B : Word;
  6203. U : TJSUInt32Array;
  6204. S : TJSInt32array;
  6205. begin
  6206. if Self>=0 then
  6207. B:=Self
  6208. else
  6209. begin
  6210. S:=TJSInt32Array.New(1);
  6211. S[0]:=Self;
  6212. U:=TJSUInt32Array.New(S);
  6213. B:=U[0];
  6214. end;
  6215. Result:=IntToHex(B,AMinDigits);
  6216. end;
  6217. Function TIntegerHelper.ToHexString: string; overload; inline;
  6218. begin
  6219. Result:=ToHexString(Size*2);
  6220. end;
  6221. Function TIntegerHelper.ToString: string; overload; inline;
  6222. begin
  6223. Result:=IntToStr(Self);
  6224. end;
  6225. Function TIntegerHelper.SetBit(const index: TIntegerBitIndex) : Integer; inline;
  6226. begin
  6227. Self := Self or (Integer(1) shl index);
  6228. Result:=Self;
  6229. end;
  6230. Function TIntegerHelper.ClearBit(const index: TIntegerBitIndex) : Integer; inline;
  6231. begin
  6232. Self:=Self and not Integer((Integer(1) shl index));
  6233. Result:=Self;
  6234. end;
  6235. Function TIntegerHelper.ToggleBit(const index: TIntegerBitIndex) : Integer; inline;
  6236. begin
  6237. Self := Self xor Integer((Integer(1) shl index));
  6238. Result:=Self;
  6239. end;
  6240. Function TIntegerHelper.TestBit(const Index: TIntegerBitIndex):Boolean; inline;
  6241. begin
  6242. Result := (Self and Integer((Integer(1) shl index)))<>0;
  6243. end;
  6244. { ---------------------------------------------------------------------
  6245. TNativeIntHelper
  6246. ---------------------------------------------------------------------}
  6247. Class Function TNativeIntHelper.Parse(const AString: string): NativeInt; inline;
  6248. begin
  6249. Result:=StrToInt(AString);
  6250. end;
  6251. Class Function TNativeIntHelper.Size: Integer; inline;
  6252. begin
  6253. Result:=7;
  6254. end;
  6255. Class Function TNativeIntHelper.ToString(const AValue: NativeInt): string; overload; inline;
  6256. begin
  6257. Result:=IntToStr(AValue);
  6258. end;
  6259. Class Function TNativeIntHelper.TryParse(const AString: string; out AValue: NativeInt): Boolean; inline;
  6260. Var
  6261. C : Integer;
  6262. begin
  6263. Val(AString,AValue,C);
  6264. Result:=(C=0);
  6265. end;
  6266. Function TNativeIntHelper.ToBoolean: Boolean; inline;
  6267. begin
  6268. Result:=(Self<>0);
  6269. end;
  6270. Function TNativeIntHelper.ToDouble: Double; inline;
  6271. begin
  6272. Result:=Self;
  6273. end;
  6274. Function TNativeIntHelper.ToExtended: Extended; inline;
  6275. begin
  6276. Result:=Self;
  6277. end;
  6278. Function TNativeIntHelper.ToBinString: string; inline;
  6279. begin
  6280. Result:=BinStr(Self,Size*8);
  6281. end;
  6282. Function TNativeIntHelper.ToHexString(const AMinDigits: Integer): string;
  6283. overload; inline;
  6284. begin
  6285. Result:=IntToHex(Self,AMinDigits);
  6286. end;
  6287. Function TNativeIntHelper.ToHexString: string; overload; inline;
  6288. begin
  6289. Result:=IntToHex(Self,Size*2);
  6290. end;
  6291. Function TNativeIntHelper.ToString: string; overload; inline;
  6292. begin
  6293. Result:=IntToStr(Self);
  6294. end;
  6295. Function TNativeIntHelper.SetBit(const index: TNativeIntBitIndex) : NativeInt; inline;
  6296. begin
  6297. Self := Self or (NativeInt(1) shl index);
  6298. Result:=Self;
  6299. end;
  6300. Function TNativeIntHelper.ClearBit(const index: TNativeIntBitIndex) : NativeInt; inline;
  6301. begin
  6302. Self:=Self and not NativeInt((NativeInt(1) shl index));
  6303. Result:=Self;
  6304. end;
  6305. Function TNativeIntHelper.ToggleBit(const index: TNativeIntBitIndex) : NativeInt; inline;
  6306. begin
  6307. Self := Self xor NativeInt((NativeInt(1) shl index));
  6308. Result:=Self;
  6309. end;
  6310. Function TNativeIntHelper.TestBit(const Index: TNativeIntBitIndex):Boolean; inline;
  6311. begin
  6312. Result := (Self and NativeInt((NativeInt(1) shl index)))<>0;
  6313. end;
  6314. { ---------------------------------------------------------------------
  6315. TNativeUIntHelper
  6316. ---------------------------------------------------------------------}
  6317. Class Function TNativeUIntHelper.Parse(const AString: string): NativeUInt; inline;
  6318. begin
  6319. Result:=StrToInt(AString);
  6320. end;
  6321. Class Function TNativeUIntHelper.Size: Integer; inline;
  6322. begin
  6323. Result:=7;
  6324. end;
  6325. Class Function TNativeUIntHelper.ToString(const AValue: NativeUInt): string; overload; inline;
  6326. begin
  6327. Result:=IntToStr(AValue);
  6328. end;
  6329. Class Function TNativeUIntHelper.TryParse(const AString: string; out AValue: NativeUInt): Boolean; inline;
  6330. Var
  6331. C : Integer;
  6332. begin
  6333. Val(AString,AValue,C);
  6334. Result:=(C=0);
  6335. end;
  6336. Function TNativeUIntHelper.ToBoolean: Boolean; inline;
  6337. begin
  6338. Result:=(Self<>0);
  6339. end;
  6340. Function TNativeUIntHelper.ToDouble: Double; inline;
  6341. begin
  6342. Result:=Self;
  6343. end;
  6344. Function TNativeUIntHelper.ToExtended: Extended; inline;
  6345. begin
  6346. Result:=Self;
  6347. end;
  6348. Function TNativeUIntHelper.ToBinString: string; inline;
  6349. begin
  6350. Result:=BinStr(Self,Size*8);
  6351. end;
  6352. Function TNativeUIntHelper.ToHexString(const AMinDigits: Integer): string;
  6353. overload; inline;
  6354. begin
  6355. Result:=IntToHex(Self,AMinDigits);
  6356. end;
  6357. Function TNativeUIntHelper.ToHexString: string; overload; inline;
  6358. begin
  6359. Result:=IntToHex(Self,Size*2);
  6360. end;
  6361. Function TNativeUIntHelper.ToSingle: Single; inline;
  6362. begin
  6363. Result:=Self;
  6364. end;
  6365. Function TNativeUIntHelper.ToString: string; overload; inline;
  6366. begin
  6367. Result:=IntToStr(Self);
  6368. end;
  6369. Function TNativeUIntHelper.SetBit(const index: TNativeUIntBitIndex) : NativeUInt; inline;
  6370. begin
  6371. Self := Self or (NativeUInt(1) shl index);
  6372. Result:=Self;
  6373. end;
  6374. Function TNativeUIntHelper.ClearBit(const index: TNativeUIntBitIndex) : NativeUInt; inline;
  6375. begin
  6376. Self:=Self and not NativeUInt((NativeUInt(1) shl index));
  6377. Result:=Self;
  6378. end;
  6379. Function TNativeUIntHelper.ToggleBit(const index: TNativeUIntBitIndex) : NativeUInt; inline;
  6380. begin
  6381. Self := Self xor NativeUInt((NativeUInt(1) shl index));
  6382. Result:=Self;
  6383. end;
  6384. Function TNativeUIntHelper.TestBit(const Index: TNativeUIntBitIndex):Boolean; inline;
  6385. begin
  6386. Result := (Self and NativeUInt((NativeUInt(1) shl index)))<>0;
  6387. end;
  6388. { ---------------------------------------------------------------------
  6389. TBooleanHelper
  6390. ---------------------------------------------------------------------}
  6391. Class Function TBooleanHelper.Parse(const S: string): Boolean; inline;
  6392. begin
  6393. Result:=StrToBool(S);
  6394. end;
  6395. Class Function TBooleanHelper.Size: Integer; inline;
  6396. begin
  6397. Result:=1;
  6398. end;
  6399. Class Function TBooleanHelper.ToString(const AValue: Boolean; UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6400. begin
  6401. Result:=BoolToStr(AValue,UseBoolStrs=TUseBoolStrs.True);
  6402. end;
  6403. Class Function TBooleanHelper.TryToParse(const S: string; out AValue: Boolean): Boolean; inline;
  6404. begin
  6405. Result:=TryStrToBool(S,AValue);
  6406. end;
  6407. Function TBooleanHelper.ToInteger: Integer; inline;
  6408. begin
  6409. Result:=Integer(Self);
  6410. end;
  6411. Function TBooleanHelper.ToString(UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6412. begin
  6413. Result:=BoolToStr(Self,UseBoolStrs=TUseBoolStrs.True);
  6414. end;
  6415. { ---------------------------------------------------------------------
  6416. TByteBoolHelper
  6417. ---------------------------------------------------------------------}
  6418. Class Function TByteBoolHelper.Parse(const S: string): Boolean; inline;
  6419. begin
  6420. Result:=StrToBool(S);
  6421. end;
  6422. Class Function TByteBoolHelper.Size: Integer; inline;
  6423. begin
  6424. Result:=1;
  6425. end;
  6426. Class Function TByteBoolHelper.ToString(const AValue: Boolean; UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6427. begin
  6428. Result:=BoolToStr(AValue,UseBoolStrs=TUseBoolStrs.True);
  6429. end;
  6430. Class Function TByteBoolHelper.TryToParse(const S: string; out AValue: Boolean): Boolean; inline;
  6431. begin
  6432. Result:=TryStrToBool(S,AValue);
  6433. end;
  6434. Function TByteBoolHelper.ToInteger: Integer; inline;
  6435. begin
  6436. Result:=Integer(Self);
  6437. end;
  6438. Function TByteBoolHelper.ToString(UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6439. begin
  6440. Result:=BoolToStr(Self,UseBoolStrs=TUseBoolStrs.True);
  6441. end;
  6442. { ---------------------------------------------------------------------
  6443. TWordBoolHelper
  6444. ---------------------------------------------------------------------}
  6445. Class Function TWordBoolHelper.Parse(const S: string): Boolean; inline;
  6446. begin
  6447. Result:=StrToBool(S);
  6448. end;
  6449. Class Function TWordBoolHelper.Size: Integer; inline;
  6450. begin
  6451. Result:=2;
  6452. end;
  6453. Class Function TWordBoolHelper.ToString(const AValue: Boolean; UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6454. begin
  6455. Result:=BoolToStr(AValue,UseBoolStrs=TUseBoolStrs.True);
  6456. end;
  6457. Class Function TWordBoolHelper.TryToParse(const S: string; out AValue: Boolean): Boolean; inline;
  6458. begin
  6459. Result:=TryStrToBool(S,AValue);
  6460. end;
  6461. Function TWordBoolHelper.ToInteger: Integer; inline;
  6462. begin
  6463. Result:=Integer(Self);
  6464. end;
  6465. Function TWordBoolHelper.ToString(UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6466. begin
  6467. Result:=BoolToStr(Self,UseBoolStrs=TUseBoolStrs.True);
  6468. end;
  6469. { ---------------------------------------------------------------------
  6470. TLongBoolHelper
  6471. ---------------------------------------------------------------------}
  6472. Class Function TLongBoolHelper.Parse(const S: string): Boolean; inline;
  6473. begin
  6474. Result:=StrToBool(S);
  6475. end;
  6476. Class Function TLongBoolHelper.Size: Integer; inline;
  6477. begin
  6478. Result:=4;
  6479. end;
  6480. Class Function TLongBoolHelper.ToString(const AValue: Boolean; UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6481. begin
  6482. Result:=BoolToStr(AValue,UseBoolStrs=TUseBoolStrs.True);
  6483. end;
  6484. Class Function TLongBoolHelper.TryToParse(const S: string; out AValue: Boolean): Boolean; inline;
  6485. begin
  6486. Result:=TryStrToBool(S,AValue);
  6487. end;
  6488. Function TLongBoolHelper.ToInteger: Integer; inline;
  6489. begin
  6490. Result:=Integer(Self);
  6491. end;
  6492. Function TLongBoolHelper.ToString(UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6493. begin
  6494. Result:=BoolToStr(Self,UseBoolStrs=TUseBoolStrs.True);
  6495. end;
  6496. end.