sysutils.pas 204 KB

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