sysutils.pas 229 KB

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