sysutils.pas 207 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899
  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. case Copy(N,1,1) of
  3914. '$': Radix:=16;
  3915. '&': Radix:=8;
  3916. '%': Radix:=2;
  3917. end;
  3918. If Radix<>10 then
  3919. Delete(N,1,1);
  3920. J:=parseInt(N,Radix);
  3921. Result:=Not jsIsNan(j);
  3922. if Result then
  3923. res:=NativeInt(J);
  3924. end;
  3925. function StrToIntDef(const S: String; const aDef: Integer): Integer;
  3926. Var
  3927. R : NativeInt;
  3928. begin
  3929. if TryStrToInt(S,R) then
  3930. Result:=R
  3931. else
  3932. Result:=aDef;
  3933. end;
  3934. function StrToIntDef(const S: String; const aDef: NativeInt): NativeInt;
  3935. Var
  3936. R : NativeInt;
  3937. begin
  3938. if TryStrToInt(S,R) then
  3939. Result:=R
  3940. else
  3941. Result:=aDef;
  3942. end;
  3943. function StrToInt(const S: String): Integer;
  3944. Var
  3945. R : NativeInt;
  3946. begin
  3947. if not TryStrToInt(S,R) then
  3948. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3949. Result:=R;
  3950. end;
  3951. function StrToNativeInt(const S: String): NativeInt;
  3952. begin
  3953. if not TryStrToInt(S,Result) then
  3954. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3955. end;
  3956. function StrToInt64(const S: String): NativeLargeInt;
  3957. Var
  3958. N : NativeInt;
  3959. begin
  3960. if not TryStrToInt(S,N) then
  3961. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3962. Result:=N;
  3963. end;
  3964. function TryStrToInt64(const S: String; out res: NativeLargeInt): Boolean;
  3965. Var
  3966. R : nativeint;
  3967. begin
  3968. Result:=TryStrToInt(S,R);
  3969. If Result then
  3970. Res:=R;
  3971. end;
  3972. function StrToInt64Def(const S: String; ADefault: NativeLargeInt
  3973. ): NativeLargeInt;
  3974. begin
  3975. if not TryStrToInt64(S,Result) then
  3976. Result:=ADefault;
  3977. end;
  3978. function StrToQWord(const S: String): NativeLargeUInt;
  3979. Var
  3980. N : NativeInt;
  3981. begin
  3982. if (not TryStrToInt(S,N)) or (N<0) then
  3983. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3984. Result:=N;
  3985. end;
  3986. function TryStrToQWord(const S: String; out res: NativeLargeUInt): Boolean;
  3987. Var
  3988. R : nativeint;
  3989. begin
  3990. Result:=TryStrToInt(S,R) and (R>=0);
  3991. If Result then
  3992. Res:=R;
  3993. end;
  3994. function StrToQWordDef(const S: String; ADefault: NativeLargeUInt
  3995. ): NativeLargeUInt;
  3996. begin
  3997. if Not TryStrToQword(S,Result) then
  3998. Result:=ADefault;
  3999. end;
  4000. function StrToUInt64(const S: String): NativeLargeUInt;
  4001. Var
  4002. N : NativeInt;
  4003. begin
  4004. if (not TryStrToInt(S,N)) or (N<0) then
  4005. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  4006. Result:=N;
  4007. end;
  4008. function TryStrToUInt64(const S: String; out res: NativeLargeUInt): Boolean;
  4009. Var
  4010. R : nativeint;
  4011. begin
  4012. Result:=TryStrToInt(S,R) and (R>=0);
  4013. If Result then
  4014. Res:=R;
  4015. end;
  4016. function StrToUInt64Def(const S: String; ADefault: NativeLargeUInt
  4017. ): NativeLargeUInt;
  4018. begin
  4019. if Not TryStrToUInt64(S,Result) then
  4020. Result:=ADefault;
  4021. end;
  4022. function TryStrToDWord(const S: String; out res: DWord): Boolean;
  4023. Var
  4024. R : nativeint;
  4025. begin
  4026. Result:=TryStrToInt(S,R) and (R>=0) and (R<=DWord($FFFFFFFF));
  4027. If Result then
  4028. Res:=R;
  4029. end;
  4030. function StrToDWord(const S: String): DWord;
  4031. begin
  4032. if not TryStrToDWord(S,Result) then
  4033. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  4034. end;
  4035. function StrToDWordDef(const S: String; ADefault: DWord): DWord;
  4036. begin
  4037. if Not TryStrToDWord(S,Result) then
  4038. Result:=ADefault;
  4039. end;
  4040. function IntToHex(Value: NativeInt; Digits: integer): string;
  4041. begin
  4042. // Result:=HexStr(Value,Digits); // TestNegLongintHelper Failed: "ToHexString" expected: <FFFE0000> but was: <00-20000> !
  4043. Result:='';
  4044. if Value<0 then
  4045. asm
  4046. if (Value<0) Value = 0xFFFFFFFF + Value + 1;
  4047. end;
  4048. asm
  4049. Result=Value.toString(16);
  4050. end;
  4051. Result:=UpperCase(Result);
  4052. while (Length(Result)<Digits) do
  4053. Result:='0'+Result;
  4054. end;
  4055. { TFormatSettings }
  4056. function TFormatSettings.GetCurrencyDecimals: Byte;
  4057. begin
  4058. Result:=Sysutils.CurrencyDecimals;
  4059. end;
  4060. function TFormatSettings.GetCurrencyFormat: Byte;
  4061. begin
  4062. Result:=Sysutils.CurrencyFormat;
  4063. end;
  4064. function TFormatSettings.GetCurrencyString: String;
  4065. begin
  4066. Result:=Sysutils.CurrencyString;
  4067. end;
  4068. function TFormatSettings.GetDateSeparator: char;
  4069. begin
  4070. Result := SysUtils.DateSeparator;
  4071. end;
  4072. function TFormatSettings.GetDecimalSeparator: string;
  4073. begin
  4074. Result := SysUtils.DecimalSeparator;
  4075. end;
  4076. function TFormatSettings.GetLongDateFormat: string;
  4077. begin
  4078. Result := SysUtils.LongDateFormat;
  4079. end;
  4080. function TFormatSettings.GetLongDayNames: TDayNames;
  4081. begin
  4082. Result:=Sysutils.LongDayNames;
  4083. end;
  4084. function TFormatSettings.GetLongMonthNames: TMonthNames;
  4085. begin
  4086. Result:=Sysutils.LongMonthNames;
  4087. end;
  4088. function TFormatSettings.GetLongTimeFormat: string;
  4089. begin
  4090. Result := SysUtils.LongTimeFormat;
  4091. end;
  4092. function TFormatSettings.GetNegCurrFormat: Byte;
  4093. begin
  4094. Result:=Sysutils.NegCurrFormat;
  4095. end;
  4096. function TFormatSettings.GetShortDateFormat: string;
  4097. begin
  4098. Result := SysUtils.ShortDateFormat;
  4099. end;
  4100. function TFormatSettings.GetShortDayNames: TDayNames;
  4101. begin
  4102. Result:=Sysutils.ShortDayNames;
  4103. end;
  4104. function TFormatSettings.GetShortMonthNames: TMonthNames;
  4105. begin
  4106. Result:=Sysutils.ShortMonthNames;
  4107. end;
  4108. function TFormatSettings.GetShortTimeFormat: string;
  4109. begin
  4110. Result := SysUtils.ShortTimeFormat;
  4111. end;
  4112. function TFormatSettings.GetThousandSeparator: string;
  4113. begin
  4114. Result := SysUtils.ThousandSeparator;
  4115. end;
  4116. function TFormatSettings.GetTimeAMString: string;
  4117. begin
  4118. Result := SysUtils.TimeAMString;
  4119. end;
  4120. function TFormatSettings.GetTimePMString: string;
  4121. begin
  4122. Result := SysUtils.TimePMString;
  4123. end;
  4124. function TFormatSettings.GetTimeSeparator: char;
  4125. begin
  4126. Result := SysUtils.TimeSeparator;
  4127. end;
  4128. procedure TFormatSettings.SetCurrencyFormat(AValue: Byte);
  4129. begin
  4130. Sysutils.CurrencyFormat:=AValue;
  4131. end;
  4132. procedure TFormatSettings.SetCurrencyString(AValue: String);
  4133. begin
  4134. Sysutils.CurrencyString:=AValue;
  4135. end;
  4136. procedure TFormatSettings.SetDateSeparator(const Value: char);
  4137. begin
  4138. SysUtils.DateSeparator := Value;
  4139. end;
  4140. procedure TFormatSettings.SetDecimalSeparator(const Value: string);
  4141. begin
  4142. SysUtils.DecimalSeparator := Value;
  4143. end;
  4144. procedure TFormatSettings.SetLongDateFormat(const Value: string);
  4145. begin
  4146. SysUtils.LongDateFormat := Value;
  4147. end;
  4148. procedure TFormatSettings.SetLongDayNames(AValue: TDayNames);
  4149. begin
  4150. SysUtils.LongDayNames:=AValue;
  4151. end;
  4152. procedure TFormatSettings.SetLongMonthNames(AValue: TMonthNames);
  4153. begin
  4154. SysUtils.LongMonthNames:=AValue;
  4155. end;
  4156. procedure TFormatSettings.SetLongTimeFormat(const Value: string);
  4157. begin
  4158. SysUtils.LongTimeFormat := Value;
  4159. end;
  4160. procedure TFormatSettings.SetNegCurrFormat(AValue: Byte);
  4161. begin
  4162. Sysutils.NegCurrFormat:=AValue;
  4163. end;
  4164. procedure TFormatSettings.SetShortDateFormat(const Value: string);
  4165. begin
  4166. SysUtils.ShortDateFormat := Value;
  4167. end;
  4168. procedure TFormatSettings.SetShortDayNames(AValue: TDayNames);
  4169. begin
  4170. SysUtils.ShortDayNames:=AValue;
  4171. end;
  4172. procedure TFormatSettings.SetShortMonthNames(AValue: TMonthNames);
  4173. begin
  4174. SysUtils.ShortMonthNames:=AValue;
  4175. end;
  4176. procedure TFormatSettings.SetShortTimeFormat(const Value: string);
  4177. begin
  4178. SysUtils.ShortTimeFormat := Value;
  4179. end;
  4180. procedure TFormatSettings.SetCurrencyDecimals(AValue: Byte);
  4181. begin
  4182. Sysutils.CurrencyDecimals:=aValue;
  4183. end;
  4184. procedure TFormatSettings.SetThousandSeparator(const Value: string);
  4185. begin
  4186. SysUtils.ThousandSeparator := Value;
  4187. end;
  4188. procedure TFormatSettings.SetTimeAMString(const Value: string);
  4189. begin
  4190. SysUtils.TimeAMString := Value;
  4191. end;
  4192. procedure TFormatSettings.SetTimePMString(const Value: string);
  4193. begin
  4194. SysUtils.TimePMString := Value;
  4195. end;
  4196. procedure TFormatSettings.SetTimeSeparator(const Value: char);
  4197. begin
  4198. SysUtils.TimeSeparator := Value;
  4199. end;
  4200. class constructor TFormatSettings.Init;
  4201. begin
  4202. FormatSettings := TFormatSettings.Create;
  4203. end;
  4204. { ---------------------------------------------------------------------
  4205. FileNames
  4206. ---------------------------------------------------------------------}
  4207. function ChangeFileExt(const FileName, Extension: PathStr): PathStr;
  4208. var
  4209. i : longint;
  4210. EndSep : Set of Char;
  4211. SOF : Boolean;
  4212. begin
  4213. i := Length(FileName);
  4214. EndSep:=AllowDirectorySeparators+AllowDriveSeparators+[ExtensionSeparator];
  4215. while (I > 0) and not(FileName[I] in EndSep) do
  4216. Dec(I);
  4217. if (I = 0) or (FileName[I] <> ExtensionSeparator) then
  4218. I := Length(FileName)+1
  4219. else
  4220. begin
  4221. SOF:=(I=1) or (FileName[i-1] in AllowDirectorySeparators);
  4222. if (SOF) and not FirstDotAtFileNameStartIsExtension then
  4223. I:=Length(FileName)+1;
  4224. end;
  4225. Result := Copy(FileName, 1, I - 1) + Extension;
  4226. end;
  4227. function ExtractFilePath(const FileName: PathStr): PathStr;
  4228. var
  4229. i : longint;
  4230. EndSep : Set of Char;
  4231. begin
  4232. i := Length(FileName);
  4233. EndSep:=AllowDirectorySeparators+AllowDriveSeparators;
  4234. while (i > 0) and not CharInSet(FileName[i],EndSep) do
  4235. Dec(i);
  4236. If I>0 then
  4237. Result := Copy(FileName, 1, i)
  4238. else
  4239. Result:='';
  4240. end;
  4241. function ExtractFileDir(const FileName: PathStr): PathStr;
  4242. var
  4243. i : longint;
  4244. EndSep : Set of Char;
  4245. begin
  4246. I := Length(FileName);
  4247. EndSep:=AllowDirectorySeparators+AllowDriveSeparators;
  4248. while (I > 0) and not CharInSet(FileName[I],EndSep) do
  4249. Dec(I);
  4250. if (I > 1) and CharInSet(FileName[I],AllowDirectorySeparators) and
  4251. not CharInSet(FileName[I - 1],EndSep) then
  4252. Dec(I);
  4253. Result := Copy(FileName, 1, I);
  4254. end;
  4255. function ExtractFileDrive(const FileName: PathStr): PathStr;
  4256. var
  4257. i,l: longint;
  4258. begin
  4259. Result := '';
  4260. l:=Length(FileName);
  4261. if (l<2) then
  4262. exit;
  4263. If CharInSet(FileName[2],AllowDriveSeparators) then
  4264. result:=Copy(FileName,1,2)
  4265. else if CharInSet(FileName[1],AllowDirectorySeparators) and
  4266. CharInSet(FileName[2],AllowDirectorySeparators) then
  4267. begin
  4268. i := 2;
  4269. { skip share }
  4270. While (i<l) and Not CharInSet(Filename[i+1],AllowDirectorySeparators) do
  4271. inc(i);
  4272. inc(i);
  4273. While (i<l) and Not CharInSet(Filename[i+1],AllowDirectorySeparators) do
  4274. inc(i);
  4275. Result:=Copy(FileName,1,i);
  4276. end;
  4277. end;
  4278. function ExtractFileName(const FileName: PathStr): PathStr;
  4279. var
  4280. i : longint;
  4281. EndSep : Set of Char;
  4282. begin
  4283. I := Length(FileName);
  4284. EndSep:=AllowDirectorySeparators+AllowDriveSeparators;
  4285. while (I > 0) and not CharInSet(FileName[I],EndSep) do
  4286. Dec(I);
  4287. Result := Copy(FileName, I + 1, MaxInt);
  4288. end;
  4289. function ExtractFileExt(const FileName: PathStr): PathStr;
  4290. var
  4291. i : longint;
  4292. EndSep : Set of Char;
  4293. SOF : Boolean; // Dot at Start of filename ?
  4294. begin
  4295. Result:='';
  4296. I := Length(FileName);
  4297. EndSep:=AllowDirectorySeparators+AllowDriveSeparators+[ExtensionSeparator];
  4298. while (I > 0) and not CharInSet(FileName[I],EndSep) do
  4299. Dec(I);
  4300. if (I > 0) and (FileName[I] = ExtensionSeparator) then
  4301. begin
  4302. SOF:=(I=1) or (FileName[i-1] in AllowDirectorySeparators);
  4303. if (Not SOF) or FirstDotAtFileNameStartIsExtension then
  4304. Result := Copy(FileName, I, MaxInt);
  4305. end
  4306. else
  4307. Result := '';
  4308. end;
  4309. function ExtractRelativepath(const BaseName, DestName: PathStr): PathStr;
  4310. Var
  4311. OneLevelBack,Source, Dest : PathStr;
  4312. Sc,Dc,I,J : Longint;
  4313. SD,DD : TPathStrArray;
  4314. begin
  4315. OneLevelBack := '..'+PathDelim;
  4316. If Uppercase(ExtractFileDrive(BaseName))<>Uppercase(ExtractFileDrive(DestName)) Then
  4317. begin
  4318. Result:=DestName;
  4319. exit;
  4320. end;
  4321. Source:=ExcludeTrailingPathDelimiter(ExtractFilePath(BaseName));
  4322. Dest:=ExcludeTrailingPathDelimiter(ExtractFilePath(DestName));
  4323. SD:=GetDirs (Source);
  4324. SC:=Length(SD);
  4325. DD:=GetDirs (Dest);
  4326. DC:=Length(SD);
  4327. I:=0;
  4328. While (I<DC) and (I<SC) do
  4329. begin
  4330. If SameText(DD[i],SD[i]) then
  4331. Inc(i)
  4332. else
  4333. Break;
  4334. end;
  4335. Result:='';
  4336. For J:=I to SC do Result:=Result+OneLevelBack;
  4337. For J:=I to DC do Result:=Result+DD[J]+PathDelim;
  4338. Result:=Result+ExtractFileName(DestName);
  4339. end;
  4340. function SetDirSeparators(const FileName: PathStr): PathStr;
  4341. Var
  4342. I : integer;
  4343. begin
  4344. Result:=FileName;
  4345. For I:=1 to Length(Result) do
  4346. If CharInSet(Result[I],AllowDirectorySeparators) then
  4347. Result[i]:=PathDelim;
  4348. end;
  4349. function GetDirs(DirName: PathStr): TPathStrArray;
  4350. Var
  4351. I,J,L : Longint;
  4352. D : String;
  4353. begin
  4354. I:=1;
  4355. J:=0;
  4356. L:=0;
  4357. SetLength(Result,Length(DirName));
  4358. While I<=Length(DirName) do
  4359. begin
  4360. If CharInSet(DirName[i],AllowDirectorySeparators) then
  4361. begin
  4362. D:=Copy(DirName,J+1,J-I);
  4363. if (D<>'') then
  4364. begin
  4365. Result[L]:=D;
  4366. Inc(L);
  4367. end;
  4368. J:=I;
  4369. end;
  4370. Inc(I);
  4371. end;
  4372. SetLength(Result,L);
  4373. end;
  4374. function IncludeTrailingPathDelimiter(const Path: PathStr): PathStr;
  4375. Var
  4376. l : Integer;
  4377. begin
  4378. Result:=Path;
  4379. l:=Length(Result);
  4380. If (L=0) or not CharInSet(Result[l],AllowDirectorySeparators) then
  4381. Result:=Result+PathDelim;
  4382. end;
  4383. function ExcludeTrailingPathDelimiter(const Path: PathStr): PathStr;
  4384. Var
  4385. L : Integer;
  4386. begin
  4387. L:=Length(Path);
  4388. If (L>0) and CharInSet(Path[L],AllowDirectorySeparators) then
  4389. Dec(L);
  4390. Result:=Copy(Path,1,L);
  4391. end;
  4392. function IncludeLeadingPathDelimiter(const Path: PathStr): PathStr;
  4393. Var
  4394. l : Integer;
  4395. begin
  4396. Result:=Path;
  4397. l:=Length(Result);
  4398. If (L=0) or not CharInSet(Result[1],AllowDirectorySeparators) then
  4399. Result:=PathDelim+Result;
  4400. end;
  4401. function ExcludeLeadingPathDelimiter(const Path: PathStr): PathStr;
  4402. Var
  4403. L : Integer;
  4404. begin
  4405. Result:=Path;
  4406. L:=Length(Result);
  4407. If (L>0) and CharInSet(Result[1],AllowDirectorySeparators) then
  4408. Delete(Result,1,1);
  4409. end;
  4410. function IsPathDelimiter(const Path: PathStr; Index: Integer): Boolean;
  4411. begin
  4412. Result:=(Index>0) and (Index<=Length(Path)) and CharInSet(Path[Index],AllowDirectorySeparators);
  4413. end;
  4414. function ConcatPaths(const Paths: array of PathStr): PathStr;
  4415. var
  4416. I: Integer;
  4417. begin
  4418. if Length(Paths) > 0 then
  4419. begin
  4420. Result := Paths[0];
  4421. for I := 1 to Length(Paths) - 1 do
  4422. Result := IncludeTrailingPathDelimiter(Result) + ExcludeLeadingPathDelimiter(Paths[I]);
  4423. end else
  4424. Result := '';
  4425. end;
  4426. Function EncodeHTMLEntities (S : String) : String;
  4427. begin
  4428. Result:='';
  4429. if S='' then exit;
  4430. asm
  4431. return S.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
  4432. return '&#'+i.charCodeAt(0)+';';
  4433. });
  4434. end;
  4435. end;
  4436. { ---------------------------------------------------------------------
  4437. Type helpers implementation
  4438. ---------------------------------------------------------------------}
  4439. { ---------------------------------------------------------------------
  4440. TGUIDHelper
  4441. ---------------------------------------------------------------------}
  4442. Procedure NotImplemented(S : String);
  4443. begin
  4444. Raise Exception.Create('Not yet implemented : '+S);
  4445. end;
  4446. class function TGuidHelper.Create(Src: TGUID; BigEndian: Boolean): TGUID;
  4447. begin
  4448. Result:=Src;
  4449. if Not Bigendian then
  4450. begin
  4451. Result.D1:=SwapEndian(Result.D1);
  4452. Result.D2:=SwapEndian(Result.D2);
  4453. Result.D3:=SwapEndian(Result.D3);
  4454. end;
  4455. end;
  4456. class function TGuidHelper.Create(const Buf: TJSArrayBuffer; AStartIndex: Cardinal; BigEndian: Boolean): TGUID;
  4457. Var
  4458. A : Cardinal;
  4459. B,C : Word;
  4460. V : TJSDataView;
  4461. begin
  4462. V:=TJSDataView.New(Buf);
  4463. // The get functions return by default correct endianness.
  4464. if BigEndian then
  4465. begin
  4466. A:=V.getUint32(aStartIndex);
  4467. B:=V.getUint16(AStartIndex+4);
  4468. C:=V.getUint16(AStartIndex+6);
  4469. end
  4470. else
  4471. begin
  4472. A:=SwapEndian(V.getUint32(aStartIndex));
  4473. B:=SwapEndian(V.getUint16(AStartIndex+4));
  4474. C:=SwapEndian(V.getUint16(AStartIndex+6));
  4475. end;
  4476. 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));
  4477. end;
  4478. class function TGuidHelper.Create(const Data: array of Byte; AStartIndex: Cardinal; BigEndian: Boolean): TGUID;
  4479. Var
  4480. D : TJSUint8Array;
  4481. begin
  4482. if ((System.Length(Data)-AStartIndex)<16) then
  4483. raise EArgumentException.CreateFmt('The length of a GUID array must be at least %d',[]);
  4484. D:=TJSUint8Array.From(Data);
  4485. Result:=Create(D.buffer,aStartIndex,BigEndian);
  4486. end;
  4487. class function TGuidHelper.Create(const B: TBytes; DataEndian: TEndian): TGUID;
  4488. begin
  4489. Result:=Create(B,0,DataEndian);
  4490. end;
  4491. class function TGuidHelper.Create(const B: TBytes; AStartIndex: Cardinal; DataEndian: TEndian): TGUID;
  4492. begin
  4493. if ((System.Length(B)-AStartIndex)<16) then
  4494. raise EArgumentException.CreateFmt('The length of a GUID array must be at least %d',[]);
  4495. Result:=Create(B,AStartIndex,DataEndian=TEndian.Big);
  4496. end;
  4497. class function TGuidHelper.Create(const S: string): TGUID;
  4498. begin
  4499. Result:=StringToGUID(S);
  4500. end;
  4501. class function TGuidHelper.Create(A: Integer; B: SmallInt; C: SmallInt; const D: TBytes): TGUID;
  4502. begin
  4503. if (System.Length(D)<>8) then
  4504. raise EArgumentException.CreateFmt('The length of a GUID array must be %d',[]);
  4505. Result:=Create(Cardinal(A),Word(B),Word(C),D[0],D[1],D[2],D[3],D[4],D[5],D[6],D[7]);
  4506. end;
  4507. (*
  4508. class function TGuidHelper.Create(A: Integer; B: SmallInt; C: SmallInt; D, E, F, G, H, I, J, K: Byte): TGUID;
  4509. begin
  4510. Result:=Create(Cardinal(A),Word(B),Word(C),D,E,F,G,H,I,J,K);
  4511. end;
  4512. *)
  4513. class function TGuidHelper.Create(A: Cardinal; B: Word; C: Word; D, E, F, G, H, I, J, K: Byte): TGUID;
  4514. begin
  4515. Result.D1 := Cardinal(A);
  4516. Result.D2 := Word(B);
  4517. Result.D3 := Word(C);
  4518. Result.D4[0] := D;
  4519. Result.D4[1] := E;
  4520. Result.D4[2] := F;
  4521. Result.D4[3] := G;
  4522. Result.D4[4] := H;
  4523. Result.D4[5] := I;
  4524. Result.D4[6] := J;
  4525. Result.D4[7] := K;
  4526. end;
  4527. class function TGuidHelper.NewGuid: TGUID;
  4528. begin
  4529. CreateGUID(Result)
  4530. end;
  4531. function TGuidHelper.ToByteArray(DataEndian: TEndian): TBytes;
  4532. Var
  4533. D : TJSUint8Array;
  4534. V : TJSDataView;
  4535. I : Integer;
  4536. begin
  4537. D:=TJSUint8array.New(16);
  4538. V:=TJSDataView.New(D.buffer);
  4539. V.setUint32(0,D1,DataEndian=TEndian.Little);
  4540. V.setUint16(4,D2,DataEndian=TEndian.Little);
  4541. V.setUint16(6,D3,DataEndian=TEndian.Little);
  4542. for I:=0 to 7 do
  4543. V.setUint8(8+I,D4[i]);
  4544. SetLength(Result, 16);
  4545. for I:=0 to 15 do
  4546. Result[i]:=V.getUint8(I);
  4547. end;
  4548. function TGuidHelper.ToString(SkipBrackets: Boolean): string;
  4549. begin
  4550. Result:=GuidToString(Self);
  4551. If SkipBrackets then
  4552. Result:=Copy(Result,2,Length(Result)-2);
  4553. end;
  4554. { ---------------------------------------------------------------------
  4555. TStringHelper
  4556. ---------------------------------------------------------------------}
  4557. Function HaveChar(AChar : Char; const AList: array of Char) : Boolean;
  4558. Var
  4559. I : SizeInt;
  4560. begin
  4561. I:=0;
  4562. Result:=False;
  4563. While (Not Result) and (I<Length(AList)) do
  4564. begin
  4565. Result:=(AList[i]=AChar);
  4566. Inc(I);
  4567. end;
  4568. end;
  4569. function TStringHelper.GetChar(AIndex: SizeInt): Char;
  4570. begin
  4571. Result:=Self[AIndex+1];
  4572. end;
  4573. function TStringHelper.GetLength: SizeInt;
  4574. begin
  4575. Result:=System.Length(Self);
  4576. end;
  4577. class function TStringHelper.Compare(const A: string; const B: string): Integer;
  4578. begin
  4579. Result:=Compare(A,0,B,0,System.Length(B),[]);
  4580. end;
  4581. class function TStringHelper.Compare(const A: string; const B: string;
  4582. IgnoreCase: Boolean): Integer; //deprecated 'Use same with TCompareOptions';
  4583. begin
  4584. if IgnoreCase then
  4585. Result:=Compare(A,B,[coIgnoreCase])
  4586. else
  4587. Result:=Compare(A,B,[]);
  4588. end;
  4589. class function TStringHelper.Compare(const A: string; const B: string;
  4590. Options: TCompareOptions): Integer;
  4591. begin
  4592. Result:=Compare(A,0,B,0,System.Length(B),Options);
  4593. end;
  4594. class function TStringHelper.Compare(const A: string; IndexA: SizeInt;
  4595. const B: string; IndexB: SizeInt; ALen: SizeInt): Integer;
  4596. begin
  4597. Result:=Compare(A,IndexA,B,IndexB,ALen,[]);
  4598. end;
  4599. class function TStringHelper.Compare(const A: string; IndexA: SizeInt;
  4600. const B: string; IndexB: SizeInt; ALen: SizeInt; IgnoreCase: Boolean
  4601. ): Integer; //deprecated 'Use same with TCompareOptions';
  4602. begin
  4603. if IgnoreCase then
  4604. Result:=Compare(A,IndexA,B,IndexB,ALen,[coIgnoreCase])
  4605. else
  4606. Result:=Compare(A,IndexA,B,IndexB,ALen,[])
  4607. end;
  4608. class function TStringHelper.Compare(const A: string; IndexA: SizeInt;
  4609. const B: string; IndexB: SizeInt; ALen: SizeInt; Options: TCompareOptions
  4610. ): Integer;
  4611. Var
  4612. AL,BL : String;
  4613. begin
  4614. AL:=System.Copy(A,IndexA+1,aLen);
  4615. BL:=System.Copy(B,IndexB+1,aLen);
  4616. if (coIgnoreCase in Options) then
  4617. Result:=TJSString(UpperCase(AL)).localeCompare(UpperCase(BL))
  4618. else
  4619. Result:=TJSString(AL).localeCompare(BL)
  4620. end;
  4621. class function TStringHelper.CompareOrdinal(const A: string; const B: string
  4622. ): Integer;
  4623. Var
  4624. L : SizeInt;
  4625. begin
  4626. L:=System.Length(B);
  4627. if L>System.Length(A) then
  4628. L:=System.Length(A);
  4629. Result:=CompareOrdinal(A,0,B,0,L);
  4630. end;
  4631. class function TStringHelper.CompareOrdinal(const A: string; IndexA: SizeInt;
  4632. const B: string; IndexB: SizeInt; ALen: SizeInt): Integer;
  4633. Var
  4634. I,M : integer;
  4635. begin
  4636. M:=System.Length(A)-IndexA;
  4637. If M>(System.Length(B)-IndexB) then
  4638. M:=(System.Length(B)-IndexB);
  4639. if M>aLen then
  4640. M:=aLen;
  4641. I:=0;
  4642. Result:=0;
  4643. While (Result=0) and (I<M) do
  4644. begin
  4645. Result:=TJSString(A).charCodeAt(IndexA+I)-TJSString(B).charCodeAt(IndexB+I);
  4646. Inc(I);
  4647. end;
  4648. end;
  4649. class function TStringHelper.CompareText(const A: string; const B: string
  4650. ): Integer;
  4651. begin
  4652. Result:=Sysutils.CompareText(A,B);
  4653. end;
  4654. class function TStringHelper.Copy(const Str: string): string;
  4655. begin
  4656. Result:=Str;
  4657. end;
  4658. class function TStringHelper.Create(AChar: Char; ACount: SizeInt): string;
  4659. begin
  4660. Result:=StringOfChar(AChar,ACount);
  4661. end;
  4662. class function TStringHelper.Create(const AValue: array of Char): string;
  4663. begin
  4664. Result:=Create(AValue,0,System.Length(AValue));
  4665. end;
  4666. class function TStringHelper.Create(const AValue: array of Char;
  4667. StartIndex: SizeInt; ALen: SizeInt): string;
  4668. Var
  4669. I : Integer;
  4670. begin
  4671. SetLength(Result,ALen);
  4672. For I:=1 to ALen do
  4673. Result[I]:=AValue[StartIndex+I-1];
  4674. end;
  4675. class function TStringHelper.EndsText(const ASubText, AText: string): Boolean;
  4676. begin
  4677. Result:=(ASubText<>'') and (sysutils.CompareText(System.Copy(AText,System.Length(AText)-System.Length(ASubText)+1,System.Length(ASubText)),ASubText)=0);
  4678. end;
  4679. class function TStringHelper.Equals(const a: string; const b: string): Boolean;
  4680. begin
  4681. Result:=A=B;
  4682. end;
  4683. class function TStringHelper.Format(const AFormat: string; const args: array of JSValue): string;
  4684. begin
  4685. Result:=Sysutils.Format(AFormat,Args);
  4686. end;
  4687. class function TStringHelper.IsNullOrEmpty(const AValue: string): Boolean;
  4688. begin
  4689. Result:=system.Length(AValue)=0;
  4690. end;
  4691. class function TStringHelper.IsNullOrWhiteSpace(const AValue: string): Boolean;
  4692. begin
  4693. Result:=system.Length(sysutils.Trim(AValue))=0;
  4694. end;
  4695. class function TStringHelper.Join(const Separator: string; const Values: array of JSValue): string;
  4696. begin
  4697. Result:=TJSArray(Values).Join(Separator);
  4698. end;
  4699. class function TStringHelper.Join(const Separator: string;
  4700. const Values: array of string): string;
  4701. begin
  4702. Result:=TJSArray(Values).Join(Separator);
  4703. end;
  4704. class function TStringHelper.Join(const Separator: string;
  4705. const Values: array of string; StartIndex: SizeInt; ACount: SizeInt): string;
  4706. Var
  4707. VLen : SizeInt;
  4708. begin
  4709. VLen:=High(Values);
  4710. If (ACount<0) or ((StartIndex>0) and (StartIndex>VLen)) then
  4711. raise ERangeError.Create(SRangeError);
  4712. If (ACount=0) or (VLen<0) then
  4713. Result:=''
  4714. else
  4715. Result:=TJSArray(Values).Slice(StartIndex,StartIndex+aCount).Join(Separator);
  4716. end;
  4717. class function TStringHelper.LowerCase(const S: string): string;
  4718. begin
  4719. Result:=sysutils.Lowercase(S);
  4720. end;
  4721. class function TStringHelper.Parse(const AValue: Boolean): string;
  4722. begin
  4723. Result:=BoolToStr(AValue);
  4724. end;
  4725. class function TStringHelper.Parse(const AValue: Extended): string;
  4726. begin
  4727. Result:=FloatToStr(AValue);
  4728. end;
  4729. class function TStringHelper.Parse(const AValue: NativeInt): string;
  4730. begin
  4731. Result:=IntToStr(AValue);
  4732. end;
  4733. class function TStringHelper.Parse(const AValue: Integer): string;
  4734. begin
  4735. Result:=IntToStr(AValue);
  4736. end;
  4737. class function TStringHelper.ToBoolean(const S: string): Boolean;
  4738. begin
  4739. Result:=StrToBool(S);
  4740. end;
  4741. class function TStringHelper.ToDouble(const S: string): Double;
  4742. begin
  4743. Result:=StrToFloat(S);
  4744. end;
  4745. class function TStringHelper.ToExtended(const S: string): Extended;
  4746. begin
  4747. Result:=StrToFloat(S);
  4748. end;
  4749. class function TStringHelper.ToNativeInt(const S: string): NativeInt;
  4750. begin
  4751. Result:=StrToInt64(S);
  4752. end;
  4753. class function TStringHelper.ToInteger(const S: string): Integer;
  4754. begin
  4755. Result:=StrToInt(S);
  4756. end;
  4757. class function TStringHelper.UpperCase(const S: string): string;
  4758. begin
  4759. Result:=sysutils.Uppercase(S);
  4760. end;
  4761. class function TStringHelper.ToCharArray(const S: String): TCharArray;
  4762. Var
  4763. I,Len: integer;
  4764. begin
  4765. Len:=System.Length(S);
  4766. SetLength(Result,Len);
  4767. For I:=1 to Len do
  4768. Result[I-1]:=S[I];
  4769. end;
  4770. function TStringHelper.CompareTo(const B: string): Integer;
  4771. begin
  4772. // Order is important
  4773. Result:=Compare(Self,B);
  4774. end;
  4775. function TStringHelper.Contains(const AValue: string): Boolean;
  4776. begin
  4777. Result:=(AValue<>'') and (Pos(AValue,Self)>0);
  4778. end;
  4779. function TStringHelper.CountChar(const C: Char): SizeInt;
  4780. Var
  4781. S : Char;
  4782. begin
  4783. Result:=0;
  4784. For S in Self do
  4785. if (S=C) then
  4786. Inc(Result);
  4787. end;
  4788. function TStringHelper.DeQuotedString: string;
  4789. begin
  4790. Result:=DeQuotedString('''');
  4791. end;
  4792. function TStringHelper.DeQuotedString(const AQuoteChar: Char): string;
  4793. var
  4794. L,I : SizeInt;
  4795. Res : Array of Char;
  4796. PS,PD : SizeInt;
  4797. IsQuote : Boolean;
  4798. begin
  4799. L:=System.Length(Self);
  4800. if (L<2) or Not ((Self[1]=AQuoteChar) and (Self[L]=AQuoteChar)) then
  4801. Exit(Self);
  4802. SetLength(Res,L);
  4803. IsQuote:=False;
  4804. PS:=2;
  4805. PD:=1;
  4806. For I:=2 to L-1 do
  4807. begin
  4808. if (Self[PS]=AQuoteChar) then
  4809. begin
  4810. IsQuote:=Not IsQuote;
  4811. if Not IsQuote then
  4812. begin
  4813. Result[PD]:=Self[PS];
  4814. Inc(PD);
  4815. end;
  4816. end
  4817. else
  4818. begin
  4819. if IsQuote then
  4820. IsQuote:=false;
  4821. Result[PD]:=Self[PS];
  4822. Inc(PD);
  4823. end;
  4824. Inc(PS);
  4825. end;
  4826. SetLength(Result,PD-1);
  4827. end;
  4828. function TStringHelper.EndsWith(const AValue: string): Boolean;
  4829. begin
  4830. Result:=EndsWith(AValue,False);
  4831. end;
  4832. function TStringHelper.EndsWith(const AValue: string; IgnoreCase: Boolean): Boolean;
  4833. Var
  4834. L : SizeInt;
  4835. S : String;
  4836. begin
  4837. L:=system.Length(AVAlue);
  4838. Result:=L=0;
  4839. if Not Result then
  4840. begin
  4841. S:=system.Copy(Self,Length-L+1,L);
  4842. Result:=system.Length(S)=L;
  4843. if Result then
  4844. if IgnoreCase then
  4845. Result:=CompareText(S,AValue)=0
  4846. else
  4847. Result:=S=AValue;
  4848. end;
  4849. end;
  4850. function TStringHelper.Equals(const AValue: string): Boolean;
  4851. begin
  4852. Result:=(Self=AValue);
  4853. end;
  4854. function TStringHelper.Format(const args: array of jsValue): string;
  4855. begin
  4856. Result:=Sysutils.Format(Self,Args);
  4857. end;
  4858. function TStringHelper.GetHashCode: Integer;
  4859. // Taken from contnrs, fphash
  4860. var
  4861. P,pmax : Integer;
  4862. L : TJSString;
  4863. begin
  4864. {$push}
  4865. {$Q-}
  4866. L:=TJSString(Self);
  4867. Result:=0;
  4868. P:=1;
  4869. pmax:=length+1;
  4870. while (p<pmax) do
  4871. begin
  4872. Result:=LongWord(LongInt(Result shl 5) - LongInt(Result)) xor L.CharCodeAt(P);
  4873. Inc(p);
  4874. end;
  4875. {$pop}
  4876. end;
  4877. function TStringHelper.IndexOf(AValue: Char): SizeInt;
  4878. begin
  4879. Result:=IndexOf(AValue,0,Length);
  4880. end;
  4881. function TStringHelper.IndexOf(const AValue: string): SizeInt;
  4882. begin
  4883. Result:=IndexOf(AValue,0,Length);
  4884. end;
  4885. function TStringHelper.IndexOf(AValue: Char; StartIndex: SizeInt): SizeInt;
  4886. begin
  4887. Result:=IndexOf(AValue,StartIndex,Length);
  4888. end;
  4889. function TStringHelper.IndexOf(const AValue: string; StartIndex: SizeInt
  4890. ): SizeInt;
  4891. begin
  4892. Result:=IndexOf(AValue,StartIndex,Length);
  4893. end;
  4894. function TStringHelper.IndexOf(AValue: Char; StartIndex: SizeInt;
  4895. ACount: SizeInt): SizeInt;
  4896. Var
  4897. S : String;
  4898. begin
  4899. S:=System.Copy(Self,StartIndex+1,ACount);
  4900. Result:=Pos(AValue,S)-1;
  4901. if Result<>-1 then
  4902. Result:=Result+StartIndex;
  4903. end;
  4904. function TStringHelper.IndexOf(const AValue: string; StartIndex: SizeInt;
  4905. ACount: SizeInt): SizeInt;
  4906. Var
  4907. S : String;
  4908. begin
  4909. S:=System.Copy(Self,StartIndex+1,ACount);
  4910. Result:=Pos(AValue,S)-1;
  4911. if Result<>-1 then
  4912. Result:=Result+StartIndex;
  4913. end;
  4914. function TStringHelper.IndexOfUnQuoted(const AValue: string; StartQuote,
  4915. EndQuote: Char; StartIndex: SizeInt = 0): SizeInt;
  4916. Var
  4917. LV : SizeInt;
  4918. S : String;
  4919. Function MatchAt(I : SizeInt) : Boolean ; Inline;
  4920. Var
  4921. J : SizeInt;
  4922. begin
  4923. J:=1;
  4924. Repeat
  4925. Result:=(S[I+J-1]=AValue[j]);
  4926. Inc(J);
  4927. Until (Not Result) or (J>LV);
  4928. end;
  4929. Var
  4930. I,L,Q: SizeInt;
  4931. begin
  4932. S:=Self;
  4933. Result:=-1;
  4934. LV:=system.Length(AValue);
  4935. L:=Length-LV+1;
  4936. if L<0 then
  4937. L:=0;
  4938. I:=StartIndex+1;
  4939. Q:=0;
  4940. if StartQuote=EndQuote then
  4941. begin
  4942. While (Result=-1) and (I<=L) do
  4943. begin
  4944. if (S[I]=StartQuote) then
  4945. Q:=1-Q;
  4946. if (Q=0) and MatchAt(i) then
  4947. Result:=I-1;
  4948. Inc(I);
  4949. end;
  4950. end
  4951. else
  4952. begin
  4953. While (Result=-1) and (I<=L) do
  4954. begin
  4955. if S[I]=StartQuote then
  4956. Inc(Q)
  4957. else if (S[I]=EndQuote) and (Q>0) then
  4958. Dec(Q);
  4959. if (Q=0) and MatchAt(i) then
  4960. Result:=I-1;
  4961. Inc(I);
  4962. end;
  4963. end;
  4964. end;
  4965. function TStringHelper.IndexOfAny(const AnyOf: string): SizeInt;
  4966. begin
  4967. Result:=IndexOfAny(AnyOf.ToCharArray);
  4968. end;
  4969. function TStringHelper.IndexOfAny(const AnyOf: array of Char): SizeInt;
  4970. begin
  4971. Result:=IndexOfAny(AnyOf,0,Length);
  4972. end;
  4973. function TStringHelper.IndexOfAny(const AnyOf: String; StartIndex: SizeInt): SizeInt;
  4974. begin
  4975. Result:=IndexOfAny(AnyOf.ToCharArray,StartIndex);
  4976. end;
  4977. function TStringHelper.IndexOfAny(const AnyOf: array of Char;
  4978. StartIndex: SizeInt): SizeInt;
  4979. begin
  4980. Result:=IndexOfAny(AnyOf,StartIndex,Length);
  4981. end;
  4982. function TStringHelper.IndexOfAny(const AnyOf: String; StartIndex: SizeInt; ACount: SizeInt): SizeInt;
  4983. begin
  4984. Result:=IndexOfAny(AnyOf.ToCharArray,StartIndex,aCount);
  4985. end;
  4986. function TStringHelper.IndexOfAny(const AnyOf: array of Char;
  4987. StartIndex: SizeInt; ACount: SizeInt): SizeInt;
  4988. Var
  4989. i,L : SizeInt;
  4990. begin
  4991. I:=StartIndex+1;
  4992. L:=I+ACount-1;
  4993. If L>Length then
  4994. L:=Length;
  4995. Result:=-1;
  4996. While (Result=-1) and (I<=L) do
  4997. begin
  4998. if HaveChar(Self[i],AnyOf) then
  4999. Result:=I-1;
  5000. Inc(I);
  5001. end;
  5002. end;
  5003. function TStringHelper.IndexOfAny(const AnyOf: array of String): SizeInt;
  5004. begin
  5005. Result:=IndexOfAny(AnyOf,0,Length);
  5006. end;
  5007. function TStringHelper.IndexOfAny(const AnyOf: array of String;
  5008. StartIndex: SizeInt): SizeInt;
  5009. begin
  5010. Result:=IndexOfAny(AnyOf,StartIndex,Length-StartIndex);
  5011. end;
  5012. function TStringHelper.IndexOfAny(const AnyOf: array of String;
  5013. StartIndex: SizeInt; ACount: SizeInt): SizeInt;
  5014. Var
  5015. M : SizeInt;
  5016. begin
  5017. Result:=IndexOfAny(AnyOf,StartIndex,ACount,M);
  5018. end;
  5019. function TStringHelper.IndexOfAny(const AnyOf: array of String;
  5020. StartIndex: SizeInt; ACount: SizeInt; out AMatch: SizeInt): SizeInt;
  5021. Var
  5022. L,I : SizeInt;
  5023. begin
  5024. Result:=-1;
  5025. For I:=0 to System.Length(AnyOf)-1 do
  5026. begin
  5027. L:=IndexOf(AnyOf[i],StartIndex,ACount);
  5028. If (L>=0) and ((Result=-1) or (L<Result)) then
  5029. begin
  5030. Result:=L;
  5031. AMatch:=I;
  5032. end;
  5033. end;
  5034. end;
  5035. function TStringHelper.IndexOfAnyUnquoted(const AnyOf: array of Char;
  5036. StartQuote, EndQuote: Char): SizeInt;
  5037. begin
  5038. Result:=IndexOfAnyUnquoted(AnyOf,StartQuote,EndQuote,0,Length);
  5039. end;
  5040. function TStringHelper.IndexOfAnyUnquoted(const AnyOf: array of Char;
  5041. StartQuote, EndQuote: Char; StartIndex: SizeInt): SizeInt;
  5042. begin
  5043. Result:=IndexOfAnyUnquoted(AnyOf,StartQuote,EndQuote,StartIndex,Length);
  5044. end;
  5045. function TStringHelper.IndexOfAnyUnquoted(const AnyOf: array of Char;
  5046. StartQuote, EndQuote: Char; StartIndex: SizeInt; ACount: SizeInt): SizeInt;
  5047. Var
  5048. I,L : SizeInt;
  5049. Q : SizeInt;
  5050. begin
  5051. Result:=-1;
  5052. L:=StartIndex+ACount-1;
  5053. if L>Length then
  5054. L:=Length;
  5055. I:=StartIndex+1;
  5056. Q:=0;
  5057. if StartQuote=EndQuote then
  5058. begin
  5059. While (Result=-1) and (I<=L) do
  5060. begin
  5061. if (Self[I]=StartQuote) then
  5062. Q:=1-Q;
  5063. if (Q=0) and HaveChar(Self[i],AnyOf) then
  5064. Result:=I-1;
  5065. Inc(I);
  5066. end;
  5067. end
  5068. else
  5069. begin
  5070. While (Result=-1) and (I<=L) do
  5071. begin
  5072. if Self[I]=StartQuote then
  5073. Inc(Q)
  5074. else if (Self[I]=EndQuote) and (Q>0) then
  5075. Dec(Q);
  5076. if (Q=0) and HaveChar(Self[i],AnyOf) then
  5077. Result:=I-1;
  5078. Inc(I);
  5079. end;
  5080. end;
  5081. end;
  5082. function TStringHelper.IndexOfAnyUnquoted(const AnyOf: array of string;
  5083. StartQuote, EndQuote: Char; StartIndex: SizeInt; out Matched: SizeInt
  5084. ): SizeInt;
  5085. Var
  5086. L,I : SizeInt;
  5087. begin
  5088. Result:=-1;
  5089. For I:=0 to System.Length(AnyOf)-1 do
  5090. begin
  5091. L:=IndexOfUnquoted(AnyOf[i],StartQuote,EndQuote,StartIndex);
  5092. If (L>=0) and ((Result=-1) or (L<Result)) then
  5093. begin
  5094. Result:=L;
  5095. Matched:=I;
  5096. end;
  5097. end;
  5098. end;
  5099. function TStringHelper.Insert(StartIndex: SizeInt; const AValue: string
  5100. ): string;
  5101. begin
  5102. system.Insert(AValue,Self,StartIndex+1);
  5103. Result:=Self;
  5104. end;
  5105. function TStringHelper.IsDelimiter(const Delimiters: string; Index: SizeInt
  5106. ): Boolean;
  5107. begin
  5108. Result:=sysutils.IsDelimiter(Delimiters,Self,Index+1);
  5109. end;
  5110. function TStringHelper.IsEmpty: Boolean;
  5111. begin
  5112. Result:=(Length=0)
  5113. end;
  5114. function TStringHelper.LastDelimiter(const Delims: string): SizeInt;
  5115. begin
  5116. Result:=sysutils.LastDelimiter(Delims,Self)-1;
  5117. end;
  5118. function TStringHelper.LastIndexOf(AValue: Char): SizeInt;
  5119. begin
  5120. Result:=LastIndexOf(AValue,Length-1,Length);
  5121. end;
  5122. function TStringHelper.LastIndexOf(const AValue: string): SizeInt;
  5123. begin
  5124. Result:=LastIndexOf(AValue,Length-1,Length);
  5125. end;
  5126. function TStringHelper.LastIndexOf(AValue: Char; AStartIndex: SizeInt): SizeInt;
  5127. begin
  5128. Result:=LastIndexOf(AValue,AStartIndex,Length);
  5129. end;
  5130. function TStringHelper.LastIndexOf(const AValue: string; AStartIndex: SizeInt
  5131. ): SizeInt;
  5132. begin
  5133. Result:=LastIndexOf(AValue,AStartIndex,Length);
  5134. end;
  5135. function TStringHelper.LastIndexOf(AValue: Char; AStartIndex: SizeInt;
  5136. ACount: SizeInt): SizeInt;
  5137. Var
  5138. Min : SizeInt;
  5139. begin
  5140. Result:=AStartIndex+1;
  5141. Min:=Result-ACount+1;
  5142. If Min<1 then
  5143. Min:=1;
  5144. While (Result>=Min) and (Self[Result]<>AValue) do
  5145. Dec(Result);
  5146. if Result<Min then
  5147. Result:=-1
  5148. else
  5149. Result:=Result-1;
  5150. end;
  5151. function TStringHelper.LastIndexOf(const AValue: string; AStartIndex: SizeInt; ACount: SizeInt): SizeInt;
  5152. begin
  5153. Result:=TJSString(Self).lastIndexOf(aValue,aStartIndex);
  5154. if (aStartIndex-Result)>aCount then
  5155. Result:=-1;
  5156. end;
  5157. function TStringHelper.LastIndexOfAny(const AnyOf: array of Char): SizeInt;
  5158. begin
  5159. Result:=LastIndexOfAny(AnyOf,Length-1,Length);
  5160. end;
  5161. function TStringHelper.LastIndexOfAny(const AnyOf: array of Char;
  5162. AStartIndex: SizeInt): SizeInt;
  5163. begin
  5164. Result:=LastIndexOfAny(AnyOf,AStartIndex,Length);
  5165. end;
  5166. function TStringHelper.LastIndexOfAny(const AnyOf: array of Char;
  5167. AStartIndex: SizeInt; ACount: SizeInt): SizeInt;
  5168. Var
  5169. Min : SizeInt;
  5170. begin
  5171. Result:=AStartIndex+1;
  5172. Min:=Result-ACount+1;
  5173. If Min<1 then
  5174. Min:=1;
  5175. While (Result>=Min) and Not HaveChar(Self[Result],AnyOf) do
  5176. Dec(Result);
  5177. if Result<Min then
  5178. Result:=-1
  5179. else
  5180. Result:=Result-1;
  5181. end;
  5182. function TStringHelper.PadLeft(ATotalWidth: SizeInt): string;
  5183. begin
  5184. Result:=PadLeft(ATotalWidth,' ');
  5185. end;
  5186. function TStringHelper.PadLeft(ATotalWidth: SizeInt; PaddingChar: Char): string;
  5187. Var
  5188. L : SizeInt;
  5189. begin
  5190. Result:=Self;
  5191. L:=ATotalWidth-Length;
  5192. If L>0 then
  5193. Result:=StringOfChar(PaddingChar,L)+Result;
  5194. end;
  5195. function TStringHelper.PadRight(ATotalWidth: SizeInt): string;
  5196. begin
  5197. Result:=PadRight(ATotalWidth,' ');
  5198. end;
  5199. function TStringHelper.PadRight(ATotalWidth: SizeInt; PaddingChar: Char
  5200. ): string;
  5201. Var
  5202. L : SizeInt;
  5203. begin
  5204. Result:=Self;
  5205. L:=ATotalWidth-Length;
  5206. If L>0 then
  5207. Result:=Result+StringOfChar(PaddingChar,L);
  5208. end;
  5209. function TStringHelper.QuotedString: string;
  5210. begin
  5211. Result:=QuotedStr(Self);
  5212. end;
  5213. function TStringHelper.QuotedString(const AQuoteChar: Char): string;
  5214. begin
  5215. Result:=QuotedStr(Self,AQuoteChar);
  5216. end;
  5217. function TStringHelper.Remove(StartIndex: SizeInt): string;
  5218. begin
  5219. Result:=Remove(StartIndex,Self.Length-StartIndex);
  5220. end;
  5221. function TStringHelper.Remove(StartIndex: SizeInt; ACount: SizeInt): string;
  5222. begin
  5223. Result:=Self;
  5224. System.Delete(Result,StartIndex+1,ACount);
  5225. end;
  5226. function TStringHelper.Replace(OldChar: Char; NewChar: Char): string;
  5227. begin
  5228. Result:=Replace(OldChar,NewChar,[rfReplaceAll]);
  5229. end;
  5230. function TStringHelper.Replace(OldChar: Char; NewChar: Char;
  5231. ReplaceFlags: TReplaceFlags): string;
  5232. begin
  5233. Result:=StringReplace(Self,OldChar,NewChar,ReplaceFlags);
  5234. end;
  5235. function TStringHelper.Replace(const OldValue: string; const NewValue: string
  5236. ): string;
  5237. begin
  5238. Result:=Replace(OldValue,NewValue,[rfReplaceAll]);
  5239. end;
  5240. function TStringHelper.Replace(const OldValue: string; const NewValue: string;
  5241. ReplaceFlags: TReplaceFlags): string;
  5242. begin
  5243. Result:=StringReplace(Self,OldValue,NewValue,ReplaceFlags);
  5244. end;
  5245. function TStringHelper.Split(const Separators: String): TStringArray;
  5246. begin
  5247. Result:=Split(Separators.ToCharArray);
  5248. end;
  5249. function TStringHelper.Split(const Separators: array of Char): TStringArray;
  5250. begin
  5251. Result:=Split(Separators,#0,#0,Length+1,TStringSplitOptions.None);
  5252. end;
  5253. function TStringHelper.Split(const Separators: string; ACount: SizeInt): TStringArray;
  5254. begin
  5255. Result:=Split(Separators.ToCharArray,aCount);
  5256. end;
  5257. function TStringHelper.Split(const Separators: array of Char; ACount: SizeInt
  5258. ): TStringArray;
  5259. begin
  5260. Result:=Split(Separators,#0,#0,ACount,TStringSplitOptions.None);
  5261. end;
  5262. function TStringHelper.Split(const Separators: string; Options: TStringSplitOptions): TStringArray;
  5263. begin
  5264. Result:=Split(Separators.ToCharArray,Options);
  5265. end;
  5266. function TStringHelper.Split(const Separators: array of Char;
  5267. Options: TStringSplitOptions): TStringArray;
  5268. begin
  5269. Result:=Split(Separators,Length+1,Options);
  5270. end;
  5271. function TStringHelper.Split(const Separators: string; ACount: SizeInt; Options: TStringSplitOptions): TStringArray;
  5272. begin
  5273. Result:=Split(Separators.ToCharArray,aCount,Options);
  5274. end;
  5275. function TStringHelper.Split(const Separators: array of Char; ACount: SizeInt;
  5276. Options: TStringSplitOptions): TStringArray;
  5277. begin
  5278. Result:=Split(Separators,#0,#0,ACount,Options);
  5279. end;
  5280. function TStringHelper.Split(const Separators: array of string): TStringArray;
  5281. begin
  5282. Result:=Split(Separators,Length+1);
  5283. end;
  5284. function TStringHelper.Split(const Separators: array of string; ACount: SizeInt
  5285. ): TStringArray;
  5286. begin
  5287. Result:=Split(Separators,ACount,TStringSplitOptions.None);
  5288. end;
  5289. function TStringHelper.Split(const Separators: array of string;
  5290. Options: TStringSplitOptions): TStringArray;
  5291. begin
  5292. Result:=Split(Separators,Length+1,Options);
  5293. end;
  5294. function TStringHelper.Split(const Separators: array of string;
  5295. ACount: SizeInt; Options: TStringSplitOptions): TStringArray;
  5296. begin
  5297. Result:=Split(Separators,#0,#0,ACount,Options);
  5298. end;
  5299. function TStringHelper.Split(const Separators: String; AQuote: Char): TStringArray;
  5300. begin
  5301. Result:=Split(Separators.ToCharArray,aQuote);
  5302. end;
  5303. function TStringHelper.Split(const Separators: array of Char; AQuote: Char
  5304. ): TStringArray;
  5305. begin
  5306. Result:=Split(Separators,AQuote,AQuote);
  5307. end;
  5308. function TStringHelper.Split(const Separators: String; AQuoteStart, AQuoteEnd: Char): TStringArray;
  5309. begin
  5310. Result:=Split(Separators.ToCharArray,aQuoteStart,aQuoteEnd);
  5311. end;
  5312. function TStringHelper.Split(const Separators: array of Char; AQuoteStart,
  5313. AQuoteEnd: Char): TStringArray;
  5314. begin
  5315. Result:=Split(Separators,AQuoteStart,AQuoteEnd,TStringSplitOptions.None);
  5316. end;
  5317. function TStringHelper.Split(const Separators: string; AQuoteStart, AQuoteEnd: Char; Options: TStringSplitOptions): TStringArray;
  5318. begin
  5319. Result:=Split(Separators.ToCharArray,aQuoteStart,aQuoteEnd,Options);
  5320. end;
  5321. function TStringHelper.Split(const Separators: array of Char; AQuoteStart,
  5322. AQuoteEnd: Char; Options: TStringSplitOptions): TStringArray;
  5323. begin
  5324. Result:=Split(Separators,AQuoteStart,AQuoteEnd,Length+1,Options);
  5325. end;
  5326. function TStringHelper.Split(const Separators: string; AQuoteStart, AQuoteEnd: Char; ACount: SizeInt): TStringArray;
  5327. begin
  5328. Result:=Split(Separators.ToCharArray,aQuoteStart,aQuoteEnd,aCount);
  5329. end;
  5330. function TStringHelper.Split(const Separators: array of Char; AQuoteStart,
  5331. AQuoteEnd: Char; ACount: SizeInt): TStringArray;
  5332. begin
  5333. Result:=Split(Separators,AQuoteStart,AQuoteEnd,ACount,TStringSplitOptions.None);
  5334. end;
  5335. function TStringHelper.Split(const Separators: string; AQuoteStart, AQuoteEnd: Char; ACount: SizeInt; Options: TStringSplitOptions
  5336. ): TStringArray;
  5337. begin
  5338. Result:=Split(Separators.ToCharArray,aQuoteStart,aQuoteEnd,aCount,Options);
  5339. end;
  5340. function TStringHelper.Split(const Separators: array of Char; AQuoteStart,
  5341. AQuoteEnd: Char; ACount: SizeInt; Options: TStringSplitOptions): TStringArray;
  5342. Const
  5343. BlockSize = 10;
  5344. Var
  5345. S : String;
  5346. Function NextSep(StartIndex : SizeInt) : SizeInt;
  5347. begin
  5348. if (AQuoteStart<>#0) then
  5349. Result:=S.IndexOfAnyUnQuoted(Separators,AQuoteStart,AQuoteEnd,StartIndex)
  5350. else
  5351. Result:=S.IndexOfAny(Separators,StartIndex);
  5352. end;
  5353. Procedure MaybeGrow(Curlen : SizeInt);
  5354. begin
  5355. if System.Length(Result)<=CurLen then
  5356. SetLength(Result,System.Length(Result)+BlockSize);
  5357. end;
  5358. Var
  5359. Sep,LastSep,Len : SizeInt;
  5360. T : String;
  5361. begin
  5362. S:=Self;
  5363. SetLength(Result,BlockSize);
  5364. Len:=0;
  5365. LastSep:=0;
  5366. Sep:=NextSep(0);
  5367. While (Sep<>-1) and ((ACount=0) or (Len<ACount)) do
  5368. begin
  5369. T:=SubString(LastSep,Sep-LastSep);
  5370. // Writeln('Examining >',T,'< at pos ',LastSep,', till pos ',Sep);
  5371. If (T<>'') or (not (TStringSplitOptions.ExcludeEmpty=Options)) then
  5372. begin
  5373. MaybeGrow(Len);
  5374. Result[Len]:=T;
  5375. Inc(Len);
  5376. end;
  5377. LastSep:=Sep+1;
  5378. Sep:=NextSep(LastSep);
  5379. end;
  5380. if (LastSep<=Length) and ((ACount=0) or (Len<ACount)) then
  5381. begin
  5382. T:=SubString(LastSep);
  5383. // Writeln('Examining >',T,'< at pos,',LastSep,' till pos ',Sep);
  5384. If (T<>'') or (not (TStringSplitOptions.ExcludeEmpty=Options)) then
  5385. begin
  5386. MaybeGrow(Len);
  5387. Result[Len]:=T;
  5388. Inc(Len);
  5389. end;
  5390. end;
  5391. SetLength(Result,Len);
  5392. end;
  5393. function TStringHelper.Split(const Separators: array of string; AQuote: Char
  5394. ): TStringArray;
  5395. begin
  5396. Result:=SPlit(Separators,AQuote,AQuote);
  5397. end;
  5398. function TStringHelper.Split(const Separators: array of string; AQuoteStart,
  5399. AQuoteEnd: Char): TStringArray;
  5400. begin
  5401. Result:=SPlit(Separators,AQuoteStart,AQuoteEnd,Length+1,TStringSplitOptions.None);
  5402. end;
  5403. function TStringHelper.Split(const Separators: array of string; AQuoteStart,
  5404. AQuoteEnd: Char; Options: TStringSplitOptions): TStringArray;
  5405. begin
  5406. Result:=SPlit(Separators,AQuoteStart,AQuoteEnd,Length+1,Options);
  5407. end;
  5408. function TStringHelper.Split(const Separators: array of string; AQuoteStart,
  5409. AQuoteEnd: Char; ACount: SizeInt): TStringArray;
  5410. begin
  5411. Result:=SPlit(Separators,AQuoteStart,AQuoteEnd,ACount,TStringSplitOptions.None);
  5412. end;
  5413. function TStringHelper.Split(const Separators: array of string; AQuoteStart,
  5414. AQuoteEnd: Char; ACount: SizeInt; Options: TStringSplitOptions): TStringArray;
  5415. Const
  5416. BlockSize = 10;
  5417. Var
  5418. S : String;
  5419. Function NextSep(StartIndex : SizeInt; out Match : SizeInt) : SizeInt;
  5420. begin
  5421. if (AQuoteStart<>#0) then
  5422. Result:=S.IndexOfAnyUnQuoted(Separators,AQuoteStart,AQuoteEnd,StartIndex,Match)
  5423. else
  5424. Result:=S.IndexOfAny(Separators,StartIndex,Length,Match);
  5425. end;
  5426. Procedure MaybeGrow(Curlen : SizeInt);
  5427. begin
  5428. if System.Length(Result)<=CurLen then
  5429. SetLength(Result,System.Length(Result)+BlockSize);
  5430. end;
  5431. Var
  5432. Sep,LastSep,Len,Match : SizeInt;
  5433. T : String;
  5434. begin
  5435. S:=Self;
  5436. SetLength(Result,BlockSize);
  5437. Len:=0;
  5438. LastSep:=0;
  5439. Sep:=NextSep(0,Match);
  5440. While (Sep<>-1) and ((ACount=0) or (Len<ACount)) do
  5441. begin
  5442. T:=SubString(LastSep,Sep-LastSep);
  5443. If (T<>'') or (not (TStringSplitOptions.ExcludeEmpty=Options)) then
  5444. begin
  5445. MaybeGrow(Len);
  5446. Result[Len]:=T;
  5447. Inc(Len);
  5448. end;
  5449. LastSep:=Sep+System.Length(Separators[Match]);
  5450. Sep:=NextSep(LastSep,Match);
  5451. end;
  5452. if (LastSep<=Length) and ((ACount=0) or (Len<ACount)) then
  5453. begin
  5454. T:=SubString(LastSep);
  5455. // Writeln('Examining >',T,'< at pos,',LastSep,' till pos ',Sep);
  5456. If (T<>'') or (not (TStringSplitOptions.ExcludeEmpty=Options)) then
  5457. begin
  5458. MaybeGrow(Len);
  5459. Result[Len]:=T;
  5460. Inc(Len);
  5461. end;
  5462. end;
  5463. SetLength(Result,Len);
  5464. end;
  5465. function TStringHelper.StartsWith(const AValue: string): Boolean;
  5466. begin
  5467. Result:=StartsWith(AValue,False);
  5468. end;
  5469. function TStringHelper.StartsWith(const AValue: string; IgnoreCase: Boolean
  5470. ): Boolean;
  5471. Var
  5472. L : SizeInt;
  5473. S : String;
  5474. begin
  5475. L:=System.Length(AValue);
  5476. Result:=L<=0;
  5477. if not Result then
  5478. begin
  5479. S:=System.Copy(Self,1,L);
  5480. Result:=(System.Length(S)=L);
  5481. if Result then
  5482. if IgnoreCase then
  5483. Result:=SameText(S,aValue)
  5484. else
  5485. Result:=SameStr(S,AValue);
  5486. end;
  5487. end;
  5488. function TStringHelper.Substring(AStartIndex: SizeInt): string;
  5489. begin
  5490. Result:=Self.SubString(AStartIndex,Self.Length-AStartIndex);
  5491. end;
  5492. function TStringHelper.Substring(AStartIndex: SizeInt; ALen: SizeInt): string;
  5493. begin
  5494. Result:=system.Copy(Self,AStartIndex+1,ALen);
  5495. end;
  5496. function TStringHelper.ToBoolean: Boolean;
  5497. begin
  5498. Result:=StrToBool(Self);
  5499. end;
  5500. function TStringHelper.ToInteger: Integer;
  5501. begin
  5502. Result:=StrToInt(Self);
  5503. end;
  5504. function TStringHelper.ToNativeInt: NativeInt;
  5505. begin
  5506. Result:=StrToNativeInt(Self);
  5507. end;
  5508. function TStringHelper.ToDouble: Double;
  5509. begin
  5510. Result:=StrToFLoat(Self);
  5511. end;
  5512. function TStringHelper.ToExtended: Extended;
  5513. begin
  5514. Result:=StrToFLoat(Self);
  5515. end;
  5516. function TStringHelper.ToCharArray: TCharArray;
  5517. begin
  5518. Result:=ToCharArray(0,Self.Length);
  5519. end;
  5520. function TStringHelper.ToCharArray(AStartIndex: SizeInt; ALen: SizeInt
  5521. ): TCharArray;
  5522. Var
  5523. I : SizeInt;
  5524. begin
  5525. SetLength(Result,ALen);
  5526. For I:=0 to ALen-1 do
  5527. Result[I]:=Self[AStartIndex+I+1];
  5528. end;
  5529. function TStringHelper.ToLower: string;
  5530. begin
  5531. Result:=LowerCase(Self);
  5532. end;
  5533. function TStringHelper.ToLowerInvariant: string;
  5534. begin
  5535. Result:=LowerCase(Self);
  5536. end;
  5537. function TStringHelper.ToUpper: string;
  5538. begin
  5539. Result:=UpperCase(Self);
  5540. end;
  5541. function TStringHelper.ToUpperInvariant: string;
  5542. begin
  5543. Result:=UpperCase(Self);
  5544. end;
  5545. function TStringHelper.Trim: string;
  5546. begin
  5547. Result:=SysUtils.Trim(self);
  5548. end;
  5549. function TStringHelper.TrimLeft: string;
  5550. begin
  5551. Result:=SysUtils.TrimLeft(Self);
  5552. end;
  5553. function TStringHelper.TrimRight: string;
  5554. begin
  5555. Result:=SysUtils.TrimRight(Self);
  5556. end;
  5557. function TStringHelper.Trim(const ATrimChars: array of Char): string;
  5558. begin
  5559. Result:=Self.TrimLeft(ATrimChars).TrimRight(ATrimChars);
  5560. end;
  5561. function TStringHelper.TrimLeft(const ATrimChars: array of Char): string;
  5562. Var
  5563. I,Len : SizeInt;
  5564. begin
  5565. I:=1;
  5566. Len:=Self.Length;
  5567. While (I<=Len) and HaveChar(Self[i],ATrimChars) do Inc(I);
  5568. if I=1 then
  5569. Result:=Self
  5570. else if I>Len then
  5571. Result:=''
  5572. else
  5573. Result:=system.Copy(Self,I,Len-I+1);
  5574. end;
  5575. function TStringHelper.TrimRight(const ATrimChars: array of Char): string;
  5576. Var
  5577. I,Len : SizeInt;
  5578. begin
  5579. Len:=Self.Length;
  5580. I:=Len;
  5581. While (I>=1) and HaveChar(Self[i],ATrimChars) do Dec(I);
  5582. if I<1 then
  5583. Result:=''
  5584. else if I=Len then
  5585. Result:=Self
  5586. else
  5587. Result:=system.Copy(Self,1,I);
  5588. end;
  5589. function TStringHelper.TrimEnd(const ATrimChars: array of Char): string;
  5590. begin
  5591. Result:=TrimRight(ATrimChars);
  5592. end;
  5593. function TStringHelper.TrimStart(const ATrimChars: array of Char): string;
  5594. begin
  5595. Result:=TrimLeft(ATrimChars);
  5596. end;
  5597. { ---------------------------------------------------------------------
  5598. TDoubleHelper
  5599. ---------------------------------------------------------------------}
  5600. Class Function TDoubleHelper.IsNan(const AValue: Double): Boolean; overload; inline;
  5601. begin
  5602. Result:=JS.jsIsNaN(AValue);
  5603. end;
  5604. Class Function TDoubleHelper.IsInfinity(const AValue: Double): Boolean; overload; inline;
  5605. begin
  5606. Result:=Not jsIsFinite(aValue);
  5607. end;
  5608. Class Function TDoubleHelper.IsNegativeInfinity(const AValue: Double): Boolean; overload; inline;
  5609. begin
  5610. asm
  5611. return (AValue=Number.NEGATIVE_INFINITY);
  5612. end;
  5613. Result:=aValue=0; // Fool compiler
  5614. end;
  5615. Class Function TDoubleHelper.IsPositiveInfinity(const AValue: Double): Boolean; overload; inline;
  5616. begin
  5617. asm
  5618. return (AValue=Number.POSITIVE_INFINITY);
  5619. end;
  5620. Result:=aValue=0; // Fool compiler.
  5621. end;
  5622. Class Function TDoubleHelper.Parse(const AString: string): Double; overload; inline;
  5623. begin
  5624. Result:=StrToFloat(AString);
  5625. end;
  5626. Class Function TDoubleHelper.ToString(const AValue: Double): string; overload; inline;
  5627. begin
  5628. Result:=FloatToStr(AValue);
  5629. end;
  5630. Class Function TDoubleHelper.ToString(const AValue: Double; const AFormat: TFloatFormat; const APrecision, ADigits: Integer): string; overload; inline;
  5631. begin
  5632. Result:=FloatToStrF(AValue,AFormat,APrecision,ADigits);
  5633. end;
  5634. Class Function TDoubleHelper.TryParse(const AString: string; out AValue: Double): Boolean; overload; inline;
  5635. begin
  5636. Result:=TryStrToFloat(AString,AValue);
  5637. end;
  5638. Function TDoubleHelper.GetB(AIndex: Cardinal): Byte;
  5639. var
  5640. F : TJSFloat64Array;
  5641. B : TJSUInt8array;
  5642. begin
  5643. F:=TJSFloat64Array.New(1);
  5644. B:=TJSUInt8array.New(F.Buffer);
  5645. F[0]:=Self;
  5646. Result:=B[AIndex];
  5647. end;
  5648. Function TDoubleHelper.GetW(AIndex: Cardinal): Word;
  5649. var
  5650. F : TJSFloat64Array;
  5651. W : TJSUInt16array;
  5652. begin
  5653. F:=TJSFloat64Array.New(1);
  5654. W:=TJSUInt16array.New(F.Buffer);
  5655. F[0]:=Self;
  5656. Result:=W[AIndex];
  5657. end;
  5658. Type
  5659. TFloatParts = Record
  5660. sign : boolean;
  5661. exp : integer;
  5662. mantissa : double;
  5663. end;
  5664. // See https://stackoverflow.com/questions/9383593/extracting-the-exponent-and-mantissa-of-a-javascript-number
  5665. Function FloatToParts(aValue : Double) : TFloatParts;
  5666. var
  5667. F : TJSFloat64Array;
  5668. B : TJSUInt8array;
  5669. begin
  5670. F:=TJSFloat64Array.New(1);
  5671. B:=TJSUInt8array.New(F.Buffer);
  5672. F[0]:=aValue;
  5673. Result.Sign:=(B[7] shr 7)=0;
  5674. Result.exp:=(((B[7] and $7f) shl 4) or (B[6] shr 4))- $3ff;
  5675. B[3]:=$3F;
  5676. B[6]:=B[6] or $F0;
  5677. Result.Mantissa:=F[0];
  5678. end;
  5679. Function TDoubleHelper.GetE: NativeUInt; inline;
  5680. begin
  5681. Result:=FloatToParts(Self).Exp;
  5682. end;
  5683. Function TDoubleHelper.GetF: NativeUInt; inline;
  5684. begin
  5685. Result:=0;
  5686. NotImplemented('GetF');
  5687. end;
  5688. Function TDoubleHelper.GetS: Boolean; inline;
  5689. begin
  5690. Result:=FloatToParts(Self).Sign;
  5691. end;
  5692. procedure TDoubleHelper.SetB(AIndex: Cardinal; const AValue: Byte);
  5693. var
  5694. F : TJSFloat64Array;
  5695. B : TJSUInt8array;
  5696. begin
  5697. if (AIndex>=8) then
  5698. raise ERangeError.Create(SRangeError);
  5699. F:=TJSFloat64Array.New(1);
  5700. B:=TJSUInt8array.New(F.Buffer);
  5701. F[0]:=Self;
  5702. B[AIndex]:=aValue;
  5703. Self:=F[0];
  5704. end;
  5705. procedure TDoubleHelper.SetW(AIndex: Cardinal; const AValue: Word);
  5706. Var
  5707. F : TJSFloat64Array;
  5708. W : TJSUInt16array;
  5709. begin
  5710. if (AIndex>=4) then
  5711. raise ERangeError.Create(SRangeError);
  5712. F:=TJSFloat64Array.New(1);
  5713. W:=TJSUInt16array.New(F.Buffer);
  5714. F[0]:=Self;
  5715. W[AIndex]:=aValue;
  5716. Self:=F[0];
  5717. end;
  5718. procedure TDoubleHelper.SetS(AValue: Boolean);
  5719. Var
  5720. F : TJSFloat64Array;
  5721. B : TJSUInt8array;
  5722. begin
  5723. F:=TJSFloat64Array.New(1);
  5724. B:=TJSUInt8array.New(F.Buffer);
  5725. F[0]:=Self;
  5726. if aValue then
  5727. B[7]:=B[7] or (1 shr 7)
  5728. else
  5729. B[7]:=B[7] and not (1 shr 7);
  5730. Self:=F[0];
  5731. end;
  5732. Procedure TDoubleHelper.BuildUp(const ASignFlag: Boolean; const AMantissa: NativeUInt; const AExponent: Integer);
  5733. begin
  5734. NotImplemented('BuildUp');
  5735. // Following statement is just to fool the compiler
  5736. if ASignFlag and (AMantissa>0) and (AExponent<0) then exit;
  5737. // TFloatRec(Self).BuildUp(ASignFlag, AMantissa, AExponent);
  5738. end;
  5739. Function TDoubleHelper.Exponent: Integer;
  5740. begin
  5741. Result:=FloatToParts(Self).Exp;
  5742. end;
  5743. Function TDoubleHelper.Fraction: Extended;
  5744. begin
  5745. Result:=system.Frac(Self);
  5746. end;
  5747. Function TDoubleHelper.IsInfinity: Boolean; overload; inline;
  5748. begin
  5749. Result:=Double.IsInfinity(Self);
  5750. end;
  5751. Function TDoubleHelper.IsNan: Boolean; overload; inline;
  5752. begin
  5753. Result:=Double.IsNan(Self);
  5754. end;
  5755. Function TDoubleHelper.IsNegativeInfinity: Boolean; overload; inline;
  5756. begin
  5757. Result:=Double.IsNegativeInfinity(Self);
  5758. end;
  5759. Function TDoubleHelper.IsPositiveInfinity: Boolean; overload; inline;
  5760. begin
  5761. Result:=Double.IsPositiveInfinity(Self);
  5762. end;
  5763. Function TDoubleHelper.Mantissa: NativeUInt;
  5764. begin
  5765. Result:=Trunc(FloatToParts(Self).mantissa);
  5766. end;
  5767. Function TDoubleHelper.ToString(const AFormat: TFloatFormat; const APrecision, ADigits: Integer): string; overload; inline;
  5768. begin
  5769. Result:=FloatToStrF(Self,AFormat,APrecision,ADigits);
  5770. end;
  5771. Function TDoubleHelper.ToString: string; overload; inline;
  5772. begin
  5773. Result:=FloatToStr(Self);
  5774. end;
  5775. { ---------------------------------------------------------------------
  5776. TByteHelper
  5777. ---------------------------------------------------------------------}
  5778. Class Function TByteHelper.Parse(const AString: string): Byte; inline;
  5779. begin
  5780. Result:=StrToInt(AString);
  5781. end;
  5782. Class Function TByteHelper.Size: Integer; inline;
  5783. begin
  5784. Result:=1;
  5785. end;
  5786. Class Function TByteHelper.ToString(const AValue: Byte): string; overload; inline;
  5787. begin
  5788. Result:=IntToStr(AValue);
  5789. end;
  5790. Class Function TByteHelper.TryParse(const AString: string; out AValue: Byte): Boolean; inline;
  5791. Var
  5792. C : Integer;
  5793. begin
  5794. Val(AString,AValue,C);
  5795. Result:=(C=0);
  5796. end;
  5797. Function TByteHelper.ToBoolean: Boolean; inline;
  5798. begin
  5799. Result:=(Self<>0);
  5800. end;
  5801. Function TByteHelper.ToDouble: Double; inline;
  5802. begin
  5803. Result:=Self;
  5804. end;
  5805. Function TByteHelper.ToExtended: Extended; inline;
  5806. begin
  5807. Result:=Self;
  5808. end;
  5809. Function TByteHelper.ToBinString: string; inline;
  5810. begin
  5811. Result:=BinStr(Self,Size*8);
  5812. end;
  5813. Function TByteHelper.ToHexString(const AMinDigits: Integer): string;
  5814. overload; inline;
  5815. begin
  5816. Result:=IntToHex(Self,AMinDigits);
  5817. end;
  5818. Function TByteHelper.ToHexString: string; overload; inline;
  5819. begin
  5820. Result:=IntToHex(Self,Size*2);
  5821. end;
  5822. Function TByteHelper.ToString: string; overload; inline;
  5823. begin
  5824. Result:=IntToStr(Self);
  5825. end;
  5826. Function TByteHelper.SetBit(const index: TByteBitIndex) : Byte; inline;
  5827. begin
  5828. Self := Self or (Byte(1) shl index);
  5829. Result:=Self;
  5830. end;
  5831. Function TByteHelper.ClearBit(const index: TByteBitIndex) : Byte; inline;
  5832. begin
  5833. Self:=Self and not Byte((Byte(1) shl index));
  5834. Result:=Self;
  5835. end;
  5836. Function TByteHelper.ToggleBit(const index: TByteBitIndex) : Byte; inline;
  5837. begin
  5838. Self := Self xor Byte((Byte(1) shl index));
  5839. Result:=Self;
  5840. end;
  5841. Function TByteHelper.TestBit(const Index: TByteBitIndex):Boolean; inline;
  5842. begin
  5843. Result := (Self and Byte((Byte(1) shl index)))<>0;
  5844. end;
  5845. { ---------------------------------------------------------------------
  5846. TShortintHelper
  5847. ---------------------------------------------------------------------}
  5848. Class Function TShortIntHelper.Parse(const AString: string): ShortInt; inline;
  5849. begin
  5850. Result:=StrToInt(AString);
  5851. end;
  5852. Class Function TShortIntHelper.Size: Integer; inline;
  5853. begin
  5854. Result:=1;
  5855. end;
  5856. Class Function TShortIntHelper.ToString(const AValue: ShortInt): string; overload; inline;
  5857. begin
  5858. Result:=IntToStr(AValue);
  5859. end;
  5860. Class Function TShortIntHelper.TryParse(const AString: string; out AValue: ShortInt): Boolean; inline;
  5861. Var
  5862. C : Integer;
  5863. begin
  5864. Val(AString,AValue,C);
  5865. Result:=(C=0);
  5866. end;
  5867. Function TShortIntHelper.ToBoolean: Boolean; inline;
  5868. begin
  5869. Result:=(Self<>0);
  5870. end;
  5871. Function TShortIntHelper.ToDouble: Double; inline;
  5872. begin
  5873. Result:=Self;
  5874. end;
  5875. Function TShortIntHelper.ToExtended: Extended; inline;
  5876. begin
  5877. Result:=Self;
  5878. end;
  5879. Function TShortIntHelper.ToBinString: string; inline;
  5880. begin
  5881. Result:=BinStr(Self,Size*8);
  5882. end;
  5883. Function TShortIntHelper.ToHexString(const AMinDigits: Integer): string; overload; inline;
  5884. Var
  5885. B : Word;
  5886. U : TJSUInt8Array;
  5887. S : TJSInt8array;
  5888. begin
  5889. if Self>=0 then
  5890. B:=Self
  5891. else
  5892. begin
  5893. S:=TJSInt8Array.New(1);
  5894. S[0]:=Self;
  5895. U:=TJSUInt8Array.New(S);
  5896. B:=U[0];
  5897. if AMinDigits>2 then
  5898. B:=$FF00+B;
  5899. end;
  5900. Result:=IntToHex(B,AMinDigits);
  5901. end;
  5902. Function TShortIntHelper.ToHexString: string; overload; inline;
  5903. begin
  5904. Result:=ToHexString(Size*2);
  5905. end;
  5906. Function TShortIntHelper.ToString: string; overload; inline;
  5907. begin
  5908. Result:=IntToStr(Self);
  5909. end;
  5910. Function TShortIntHelper.SetBit(const index: TShortIntBitIndex) : ShortInt; inline;
  5911. begin
  5912. Self := Self or (ShortInt(1) shl index);
  5913. Result:=Self;
  5914. end;
  5915. Function TShortIntHelper.ClearBit(const index: TShortIntBitIndex) : ShortInt; inline;
  5916. begin
  5917. Self:=Self and not ShortInt((ShortInt(1) shl index));
  5918. Result:=Self;
  5919. end;
  5920. Function TShortIntHelper.ToggleBit(const index: TShortIntBitIndex) : ShortInt; inline;
  5921. begin
  5922. Self := Self xor ShortInt((ShortInt(1) shl index));
  5923. Result:=Self;
  5924. end;
  5925. Function TShortIntHelper.TestBit(const Index: TShortIntBitIndex):Boolean; inline;
  5926. begin
  5927. Result := (Self and ShortInt((ShortInt(1) shl index)))<>0;
  5928. end;
  5929. { ---------------------------------------------------------------------
  5930. TSmallintHelper
  5931. ---------------------------------------------------------------------}
  5932. Class Function TSmallIntHelper.Parse(const AString: string): SmallInt; inline;
  5933. begin
  5934. Result:=StrToInt(AString);
  5935. end;
  5936. Class Function TSmallIntHelper.Size: Integer; inline;
  5937. begin
  5938. Result:=2;
  5939. end;
  5940. Class Function TSmallIntHelper.ToString(const AValue: SmallInt): string; overload; inline;
  5941. begin
  5942. Result:=IntToStr(AValue);
  5943. end;
  5944. Class Function TSmallIntHelper.TryParse(const AString: string; out AValue: SmallInt): Boolean; inline;
  5945. Var
  5946. C : Integer;
  5947. begin
  5948. Val(AString,AValue,C);
  5949. Result:=(C=0);
  5950. end;
  5951. Function TSmallIntHelper.ToBoolean: Boolean; inline;
  5952. begin
  5953. Result:=(Self<>0);
  5954. end;
  5955. Function TSmallIntHelper.ToDouble: Double; inline;
  5956. begin
  5957. Result:=Self;
  5958. end;
  5959. Function TSmallIntHelper.ToExtended: Extended; inline;
  5960. begin
  5961. Result:=Self;
  5962. end;
  5963. Function TSmallIntHelper.ToBinString: string; inline;
  5964. begin
  5965. Result:=BinStr(Self,Size*8);
  5966. end;
  5967. Function TSmallIntHelper.ToHexString(const AMinDigits: Integer): string; overload; inline;
  5968. Var
  5969. B : Cardinal;
  5970. U : TJSUInt16Array;
  5971. S : TJSInt16array;
  5972. begin
  5973. if Self>=0 then
  5974. B:=Self
  5975. else
  5976. begin
  5977. S:=TJSInt16Array.New(1);
  5978. S[0]:=Self;
  5979. U:=TJSUInt16Array.New(S);
  5980. B:=U[0];
  5981. if AMinDigits>6 then
  5982. B:=$FFFF0000+B
  5983. else if AMinDigits>4 then
  5984. B:=$FF0000+B;
  5985. end;
  5986. Result:=IntToHex(B,AMinDigits);
  5987. end;
  5988. Function TSmallIntHelper.ToHexString: string; overload; inline;
  5989. begin
  5990. Result:=ToHexString(Size*2);
  5991. end;
  5992. Function TSmallIntHelper.ToString: string; overload; inline;
  5993. begin
  5994. Result:=IntToStr(Self);
  5995. end;
  5996. Function TSmallIntHelper.SetBit(const index: TSmallIntBitIndex) : SmallInt; inline;
  5997. begin
  5998. Self := Self or (SmallInt(1) shl index);
  5999. Result:=Self;
  6000. end;
  6001. Function TSmallIntHelper.ClearBit(const index: TSmallIntBitIndex) : SmallInt; inline;
  6002. begin
  6003. Self:=Self and not SmallInt((SmallInt(1) shl index));
  6004. Result:=Self;
  6005. end;
  6006. Function TSmallIntHelper.ToggleBit(const index: TSmallIntBitIndex) : SmallInt; inline;
  6007. begin
  6008. Self := Self xor SmallInt((SmallInt(1) shl index));
  6009. Result:=Self;
  6010. end;
  6011. Function TSmallIntHelper.TestBit(const Index: TSmallIntBitIndex):Boolean; inline;
  6012. begin
  6013. Result := (Self and SmallInt((SmallInt(1) shl index)))<>0;
  6014. end;
  6015. { ---------------------------------------------------------------------
  6016. TWordHelper
  6017. ---------------------------------------------------------------------}
  6018. Class Function TWordHelper.Parse(const AString: string): Word; inline;
  6019. begin
  6020. Result:=StrToInt(AString);
  6021. end;
  6022. Class Function TWordHelper.Size: Integer; inline;
  6023. begin
  6024. Result:=2;
  6025. end;
  6026. Class Function TWordHelper.ToString(const AValue: Word): string; overload; inline;
  6027. begin
  6028. Result:=IntToStr(AValue);
  6029. end;
  6030. Class Function TWordHelper.TryParse(const AString: string; out AValue: Word): Boolean; inline;
  6031. Var
  6032. C : Integer;
  6033. begin
  6034. Val(AString,AValue,C);
  6035. Result:=(C=0);
  6036. end;
  6037. Function TWordHelper.ToBoolean: Boolean; inline;
  6038. begin
  6039. Result:=(Self<>0);
  6040. end;
  6041. Function TWordHelper.ToDouble: Double; inline;
  6042. begin
  6043. Result:=Self;
  6044. end;
  6045. Function TWordHelper.ToExtended: Extended; inline;
  6046. begin
  6047. Result:=Self;
  6048. end;
  6049. Function TWordHelper.ToBinString: string; inline;
  6050. begin
  6051. Result:=BinStr(Self,Size*8);
  6052. end;
  6053. Function TWordHelper.ToHexString(const AMinDigits: Integer): string;
  6054. overload; inline;
  6055. begin
  6056. Result:=IntToHex(Self,AMinDigits);
  6057. end;
  6058. Function TWordHelper.ToHexString: string; overload; inline;
  6059. begin
  6060. Result:=IntToHex(Self,Size*2);
  6061. end;
  6062. Function TWordHelper.ToString: string; overload; inline;
  6063. begin
  6064. Result:=IntToStr(Self);
  6065. end;
  6066. Function TWordHelper.SetBit(const index: TWordBitIndex) : Word; inline;
  6067. begin
  6068. Self := Self or (Word(1) shl index);
  6069. Result:=Self;
  6070. end;
  6071. Function TWordHelper.ClearBit(const index: TWordBitIndex) : Word; inline;
  6072. begin
  6073. Self:=Self and not Word((Word(1) shl index));
  6074. Result:=Self;
  6075. end;
  6076. Function TWordHelper.ToggleBit(const index: TWordBitIndex) : Word; inline;
  6077. begin
  6078. Self := Self xor Word((Word(1) shl index));
  6079. Result:=Self;
  6080. end;
  6081. Function TWordHelper.TestBit(const Index: TWordBitIndex):Boolean; inline;
  6082. begin
  6083. Result := (Self and Word((Word(1) shl index)))<>0;
  6084. end;
  6085. { ---------------------------------------------------------------------
  6086. TCardinalHelper
  6087. ---------------------------------------------------------------------}
  6088. Class Function TCardinalHelper.Parse(const AString: string): Cardinal; inline;
  6089. begin
  6090. Result:=StrToInt(AString);
  6091. end;
  6092. Class Function TCardinalHelper.Size: Integer; inline;
  6093. begin
  6094. Result:=4;
  6095. end;
  6096. Class Function TCardinalHelper.ToString(const AValue: Cardinal): string; overload; inline;
  6097. begin
  6098. Result:=IntToStr(AValue);
  6099. end;
  6100. Class Function TCardinalHelper.TryParse(const AString: string; out AValue: Cardinal): Boolean; inline;
  6101. Var
  6102. C : Integer;
  6103. begin
  6104. Val(AString,AValue,C);
  6105. Result:=(C=0);
  6106. end;
  6107. Function TCardinalHelper.ToBoolean: Boolean; inline;
  6108. begin
  6109. Result:=(Self<>0);
  6110. end;
  6111. Function TCardinalHelper.ToDouble: Double; inline;
  6112. begin
  6113. Result:=Self;
  6114. end;
  6115. Function TCardinalHelper.ToExtended: Extended; inline;
  6116. begin
  6117. Result:=Self;
  6118. end;
  6119. Function TCardinalHelper.ToBinString: string; inline;
  6120. begin
  6121. Result:=BinStr(Self,Size*8);
  6122. end;
  6123. Function TCardinalHelper.ToHexString(const AMinDigits: Integer): string;
  6124. overload; inline;
  6125. begin
  6126. Result:=IntToHex(Self,AMinDigits);
  6127. end;
  6128. Function TCardinalHelper.ToHexString: string; overload; inline;
  6129. begin
  6130. Result:=ToHexString(Size*2);
  6131. end;
  6132. Function TCardinalHelper.ToString: string; overload; inline;
  6133. begin
  6134. Result:=IntToStr(Self);
  6135. end;
  6136. Function TCardinalHelper.SetBit(const index: TCardinalBitIndex) : Cardinal; inline;
  6137. begin
  6138. Self := Self or (Cardinal(1) shl index);
  6139. Result:=Self;
  6140. end;
  6141. Function TCardinalHelper.ClearBit(const index: TCardinalBitIndex) : Cardinal; inline;
  6142. begin
  6143. Self:=Self and not Cardinal((Cardinal(1) shl index));
  6144. Result:=Self;
  6145. end;
  6146. Function TCardinalHelper.ToggleBit(const index: TCardinalBitIndex) : Cardinal; inline;
  6147. begin
  6148. Self := Self xor Cardinal((Cardinal(1) shl index));
  6149. Result:=Self;
  6150. end;
  6151. Function TCardinalHelper.TestBit(const Index: TCardinalBitIndex):Boolean; inline;
  6152. begin
  6153. Result := (Self and Cardinal((Cardinal(1) shl index)))<>0;
  6154. end;
  6155. { ---------------------------------------------------------------------
  6156. TIntegerHelper
  6157. ---------------------------------------------------------------------}
  6158. Class Function TIntegerHelper.Parse(const AString: string): Integer; inline;
  6159. begin
  6160. Result:=StrToInt(AString);
  6161. end;
  6162. Class Function TIntegerHelper.Size: Integer; inline;
  6163. begin
  6164. Result:=4;
  6165. end;
  6166. Class Function TIntegerHelper.ToString(const AValue: Integer): string; overload; inline;
  6167. begin
  6168. Result:=IntToStr(AValue);
  6169. end;
  6170. Class Function TIntegerHelper.TryParse(const AString: string; out AValue: Integer): Boolean; inline;
  6171. Var
  6172. C : Integer;
  6173. begin
  6174. Val(AString,AValue,C);
  6175. Result:=(C=0);
  6176. end;
  6177. Function TIntegerHelper.ToBoolean: Boolean; inline;
  6178. begin
  6179. Result:=(Self<>0);
  6180. end;
  6181. Function TIntegerHelper.ToDouble: Double; inline;
  6182. begin
  6183. Result:=Self;
  6184. end;
  6185. Function TIntegerHelper.ToExtended: Extended; inline;
  6186. begin
  6187. Result:=Self;
  6188. end;
  6189. Function TIntegerHelper.ToBinString: string; inline;
  6190. begin
  6191. Result:=BinStr(Self,Size*8);
  6192. end;
  6193. Function TIntegerHelper.ToHexString(const AMinDigits: Integer): string;
  6194. overload; inline;
  6195. Var
  6196. B : Word;
  6197. U : TJSUInt32Array;
  6198. S : TJSInt32array;
  6199. begin
  6200. if Self>=0 then
  6201. B:=Self
  6202. else
  6203. begin
  6204. S:=TJSInt32Array.New(1);
  6205. S[0]:=Self;
  6206. U:=TJSUInt32Array.New(S);
  6207. B:=U[0];
  6208. end;
  6209. Result:=IntToHex(B,AMinDigits);
  6210. end;
  6211. Function TIntegerHelper.ToHexString: string; overload; inline;
  6212. begin
  6213. Result:=ToHexString(Size*2);
  6214. end;
  6215. Function TIntegerHelper.ToString: string; overload; inline;
  6216. begin
  6217. Result:=IntToStr(Self);
  6218. end;
  6219. Function TIntegerHelper.SetBit(const index: TIntegerBitIndex) : Integer; inline;
  6220. begin
  6221. Self := Self or (Integer(1) shl index);
  6222. Result:=Self;
  6223. end;
  6224. Function TIntegerHelper.ClearBit(const index: TIntegerBitIndex) : Integer; inline;
  6225. begin
  6226. Self:=Self and not Integer((Integer(1) shl index));
  6227. Result:=Self;
  6228. end;
  6229. Function TIntegerHelper.ToggleBit(const index: TIntegerBitIndex) : Integer; inline;
  6230. begin
  6231. Self := Self xor Integer((Integer(1) shl index));
  6232. Result:=Self;
  6233. end;
  6234. Function TIntegerHelper.TestBit(const Index: TIntegerBitIndex):Boolean; inline;
  6235. begin
  6236. Result := (Self and Integer((Integer(1) shl index)))<>0;
  6237. end;
  6238. { ---------------------------------------------------------------------
  6239. TNativeIntHelper
  6240. ---------------------------------------------------------------------}
  6241. Class Function TNativeIntHelper.Parse(const AString: string): NativeInt; inline;
  6242. begin
  6243. Result:=StrToInt(AString);
  6244. end;
  6245. Class Function TNativeIntHelper.Size: Integer; inline;
  6246. begin
  6247. Result:=7;
  6248. end;
  6249. Class Function TNativeIntHelper.ToString(const AValue: NativeInt): string; overload; inline;
  6250. begin
  6251. Result:=IntToStr(AValue);
  6252. end;
  6253. Class Function TNativeIntHelper.TryParse(const AString: string; out AValue: NativeInt): Boolean; inline;
  6254. Var
  6255. C : Integer;
  6256. begin
  6257. Val(AString,AValue,C);
  6258. Result:=(C=0);
  6259. end;
  6260. Function TNativeIntHelper.ToBoolean: Boolean; inline;
  6261. begin
  6262. Result:=(Self<>0);
  6263. end;
  6264. Function TNativeIntHelper.ToDouble: Double; inline;
  6265. begin
  6266. Result:=Self;
  6267. end;
  6268. Function TNativeIntHelper.ToExtended: Extended; inline;
  6269. begin
  6270. Result:=Self;
  6271. end;
  6272. Function TNativeIntHelper.ToBinString: string; inline;
  6273. begin
  6274. Result:=BinStr(Self,Size*8);
  6275. end;
  6276. Function TNativeIntHelper.ToHexString(const AMinDigits: Integer): string;
  6277. overload; inline;
  6278. begin
  6279. Result:=IntToHex(Self,AMinDigits);
  6280. end;
  6281. Function TNativeIntHelper.ToHexString: string; overload; inline;
  6282. begin
  6283. Result:=IntToHex(Self,Size*2);
  6284. end;
  6285. Function TNativeIntHelper.ToString: string; overload; inline;
  6286. begin
  6287. Result:=IntToStr(Self);
  6288. end;
  6289. Function TNativeIntHelper.SetBit(const index: TNativeIntBitIndex) : NativeInt; inline;
  6290. begin
  6291. Self := Self or (NativeInt(1) shl index);
  6292. Result:=Self;
  6293. end;
  6294. Function TNativeIntHelper.ClearBit(const index: TNativeIntBitIndex) : NativeInt; inline;
  6295. begin
  6296. Self:=Self and not NativeInt((NativeInt(1) shl index));
  6297. Result:=Self;
  6298. end;
  6299. Function TNativeIntHelper.ToggleBit(const index: TNativeIntBitIndex) : NativeInt; inline;
  6300. begin
  6301. Self := Self xor NativeInt((NativeInt(1) shl index));
  6302. Result:=Self;
  6303. end;
  6304. Function TNativeIntHelper.TestBit(const Index: TNativeIntBitIndex):Boolean; inline;
  6305. begin
  6306. Result := (Self and NativeInt((NativeInt(1) shl index)))<>0;
  6307. end;
  6308. { ---------------------------------------------------------------------
  6309. TNativeUIntHelper
  6310. ---------------------------------------------------------------------}
  6311. Class Function TNativeUIntHelper.Parse(const AString: string): NativeUInt; inline;
  6312. begin
  6313. Result:=StrToInt(AString);
  6314. end;
  6315. Class Function TNativeUIntHelper.Size: Integer; inline;
  6316. begin
  6317. Result:=7;
  6318. end;
  6319. Class Function TNativeUIntHelper.ToString(const AValue: NativeUInt): string; overload; inline;
  6320. begin
  6321. Result:=IntToStr(AValue);
  6322. end;
  6323. Class Function TNativeUIntHelper.TryParse(const AString: string; out AValue: NativeUInt): Boolean; inline;
  6324. Var
  6325. C : Integer;
  6326. begin
  6327. Val(AString,AValue,C);
  6328. Result:=(C=0);
  6329. end;
  6330. Function TNativeUIntHelper.ToBoolean: Boolean; inline;
  6331. begin
  6332. Result:=(Self<>0);
  6333. end;
  6334. Function TNativeUIntHelper.ToDouble: Double; inline;
  6335. begin
  6336. Result:=Self;
  6337. end;
  6338. Function TNativeUIntHelper.ToExtended: Extended; inline;
  6339. begin
  6340. Result:=Self;
  6341. end;
  6342. Function TNativeUIntHelper.ToBinString: string; inline;
  6343. begin
  6344. Result:=BinStr(Self,Size*8);
  6345. end;
  6346. Function TNativeUIntHelper.ToHexString(const AMinDigits: Integer): string;
  6347. overload; inline;
  6348. begin
  6349. Result:=IntToHex(Self,AMinDigits);
  6350. end;
  6351. Function TNativeUIntHelper.ToHexString: string; overload; inline;
  6352. begin
  6353. Result:=IntToHex(Self,Size*2);
  6354. end;
  6355. Function TNativeUIntHelper.ToSingle: Single; inline;
  6356. begin
  6357. Result:=Self;
  6358. end;
  6359. Function TNativeUIntHelper.ToString: string; overload; inline;
  6360. begin
  6361. Result:=IntToStr(Self);
  6362. end;
  6363. Function TNativeUIntHelper.SetBit(const index: TNativeUIntBitIndex) : NativeUInt; inline;
  6364. begin
  6365. Self := Self or (NativeUInt(1) shl index);
  6366. Result:=Self;
  6367. end;
  6368. Function TNativeUIntHelper.ClearBit(const index: TNativeUIntBitIndex) : NativeUInt; inline;
  6369. begin
  6370. Self:=Self and not NativeUInt((NativeUInt(1) shl index));
  6371. Result:=Self;
  6372. end;
  6373. Function TNativeUIntHelper.ToggleBit(const index: TNativeUIntBitIndex) : NativeUInt; inline;
  6374. begin
  6375. Self := Self xor NativeUInt((NativeUInt(1) shl index));
  6376. Result:=Self;
  6377. end;
  6378. Function TNativeUIntHelper.TestBit(const Index: TNativeUIntBitIndex):Boolean; inline;
  6379. begin
  6380. Result := (Self and NativeUInt((NativeUInt(1) shl index)))<>0;
  6381. end;
  6382. { ---------------------------------------------------------------------
  6383. TBooleanHelper
  6384. ---------------------------------------------------------------------}
  6385. Class Function TBooleanHelper.Parse(const S: string): Boolean; inline;
  6386. begin
  6387. Result:=StrToBool(S);
  6388. end;
  6389. Class Function TBooleanHelper.Size: Integer; inline;
  6390. begin
  6391. Result:=1;
  6392. end;
  6393. Class Function TBooleanHelper.ToString(const AValue: Boolean; UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6394. begin
  6395. Result:=BoolToStr(AValue,UseBoolStrs=TUseBoolStrs.True);
  6396. end;
  6397. Class Function TBooleanHelper.TryToParse(const S: string; out AValue: Boolean): Boolean; inline;
  6398. begin
  6399. Result:=TryStrToBool(S,AValue);
  6400. end;
  6401. Function TBooleanHelper.ToInteger: Integer; inline;
  6402. begin
  6403. Result:=Integer(Self);
  6404. end;
  6405. Function TBooleanHelper.ToString(UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6406. begin
  6407. Result:=BoolToStr(Self,UseBoolStrs=TUseBoolStrs.True);
  6408. end;
  6409. { ---------------------------------------------------------------------
  6410. TByteBoolHelper
  6411. ---------------------------------------------------------------------}
  6412. Class Function TByteBoolHelper.Parse(const S: string): Boolean; inline;
  6413. begin
  6414. Result:=StrToBool(S);
  6415. end;
  6416. Class Function TByteBoolHelper.Size: Integer; inline;
  6417. begin
  6418. Result:=1;
  6419. end;
  6420. Class Function TByteBoolHelper.ToString(const AValue: Boolean; UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6421. begin
  6422. Result:=BoolToStr(AValue,UseBoolStrs=TUseBoolStrs.True);
  6423. end;
  6424. Class Function TByteBoolHelper.TryToParse(const S: string; out AValue: Boolean): Boolean; inline;
  6425. begin
  6426. Result:=TryStrToBool(S,AValue);
  6427. end;
  6428. Function TByteBoolHelper.ToInteger: Integer; inline;
  6429. begin
  6430. Result:=Integer(Self);
  6431. end;
  6432. Function TByteBoolHelper.ToString(UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6433. begin
  6434. Result:=BoolToStr(Self,UseBoolStrs=TUseBoolStrs.True);
  6435. end;
  6436. { ---------------------------------------------------------------------
  6437. TWordBoolHelper
  6438. ---------------------------------------------------------------------}
  6439. Class Function TWordBoolHelper.Parse(const S: string): Boolean; inline;
  6440. begin
  6441. Result:=StrToBool(S);
  6442. end;
  6443. Class Function TWordBoolHelper.Size: Integer; inline;
  6444. begin
  6445. Result:=2;
  6446. end;
  6447. Class Function TWordBoolHelper.ToString(const AValue: Boolean; UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6448. begin
  6449. Result:=BoolToStr(AValue,UseBoolStrs=TUseBoolStrs.True);
  6450. end;
  6451. Class Function TWordBoolHelper.TryToParse(const S: string; out AValue: Boolean): Boolean; inline;
  6452. begin
  6453. Result:=TryStrToBool(S,AValue);
  6454. end;
  6455. Function TWordBoolHelper.ToInteger: Integer; inline;
  6456. begin
  6457. Result:=Integer(Self);
  6458. end;
  6459. Function TWordBoolHelper.ToString(UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6460. begin
  6461. Result:=BoolToStr(Self,UseBoolStrs=TUseBoolStrs.True);
  6462. end;
  6463. { ---------------------------------------------------------------------
  6464. TLongBoolHelper
  6465. ---------------------------------------------------------------------}
  6466. Class Function TLongBoolHelper.Parse(const S: string): Boolean; inline;
  6467. begin
  6468. Result:=StrToBool(S);
  6469. end;
  6470. Class Function TLongBoolHelper.Size: Integer; inline;
  6471. begin
  6472. Result:=4;
  6473. end;
  6474. Class Function TLongBoolHelper.ToString(const AValue: Boolean; UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6475. begin
  6476. Result:=BoolToStr(AValue,UseBoolStrs=TUseBoolStrs.True);
  6477. end;
  6478. Class Function TLongBoolHelper.TryToParse(const S: string; out AValue: Boolean): Boolean; inline;
  6479. begin
  6480. Result:=TryStrToBool(S,AValue);
  6481. end;
  6482. Function TLongBoolHelper.ToInteger: Integer; inline;
  6483. begin
  6484. Result:=Integer(Self);
  6485. end;
  6486. Function TLongBoolHelper.ToString(UseBoolStrs: TUseBoolStrs = TUseBoolStrs.False): string; overload; inline;
  6487. begin
  6488. Result:=BoolToStr(Self,UseBoolStrs=TUseBoolStrs.True);
  6489. end;
  6490. end.