sysutils.pas 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062
  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. interface
  13. uses
  14. RTLConsts, js;
  15. procedure FreeAndNil(var Obj);
  16. type
  17. TProcedure = procedure;
  18. {*****************************************************************************
  19. Various types
  20. *****************************************************************************}
  21. type
  22. { TFloatRec }
  23. TFloatRec = Record
  24. Exponent: Integer;
  25. Negative: Boolean;
  26. Digits: Array[0..18] Of Char;
  27. End;
  28. TEndian = (Little,Big);
  29. TFileName = String;
  30. TByteArray = array [0..32767] of Byte;
  31. TWordArray = array [0..16383] of Word;
  32. TBytes = Array of byte;
  33. TStringArray = array of string;
  34. TMonthNameArray = array [1..12] of string;
  35. TDayTable = array [1..12] of Word;
  36. TWeekNameArray = array [1..7] of string;
  37. TMonthNames = TMonthNameArray;
  38. TDayNames = array[0..6] of string;
  39. {*****************************************************************************
  40. Exception handling
  41. *****************************************************************************}
  42. { Exception }
  43. Exception = class(TObject)
  44. private
  45. fMessage: String;
  46. fHelpContext: Integer;
  47. public
  48. constructor Create(const Msg: String); reintroduce;
  49. constructor CreateFmt(const Msg: string; const Args: array of jsvalue);
  50. constructor CreateHelp(const Msg: String; AHelpContext: Integer);
  51. constructor CreateFmtHelp(const Msg: string; const Args: array of jsvalue; AHelpContext: Integer);
  52. function ToString: String; override;
  53. property HelpContext: Integer read fHelpContext write fHelpContext;
  54. property Message: String read fMessage write fMessage;
  55. end;
  56. ExceptClass = class of Exception;
  57. EExternal = class(Exception);
  58. { General math errors }
  59. EMathError = class(EExternal);
  60. EInvalidOp = class(EMathError);
  61. EZeroDivide = class(EMathError);
  62. EOverflow = class(EMathError);
  63. EUnderflow = class(EMathError);
  64. EAbort = class(Exception);
  65. EInvalidCast = class(Exception);
  66. EAssertionFailed = class(Exception);
  67. EObjectCheck = class(Exception);
  68. { String conversion errors }
  69. EConvertError = class(Exception);
  70. EFormatError = class(Exception);
  71. { integer math exceptions }
  72. EIntError = Class(EExternal);
  73. EDivByZero = Class(EIntError);
  74. ERangeError = Class(EIntError);
  75. EIntOverflow = Class(EIntError);
  76. { General math errors }
  77. { Run-time and I/O Errors }
  78. EInOutError = class(Exception)
  79. public
  80. ErrorCode : Integer;
  81. end;
  82. EHeapMemoryError = class(Exception);
  83. EHeapException = EHeapMemoryError;
  84. EExternalException = class(EExternal);
  85. EInvalidPointer = Class(EHeapMemoryError);
  86. EOutOfMemory = Class(EHeapMemoryError);
  87. { EVariantError }
  88. EVariantError = Class(Exception)
  89. ErrCode : longint;
  90. Constructor CreateCode(Code : Longint);
  91. end;
  92. EAccessViolation = Class(EExternal);
  93. EBusError = Class(EAccessViolation);
  94. EPrivilege = class(EExternal);
  95. EStackOverflow = class(EExternal);
  96. EControlC = class(EExternal);
  97. { String conversion errors }
  98. { Other errors }
  99. EAbstractError = Class(Exception);
  100. EPropReadOnly = class(Exception);
  101. EPropWriteOnly = class(Exception);
  102. EIntfCastError = class(Exception);
  103. EInvalidContainer = class(Exception);
  104. EInvalidInsert = class(Exception);
  105. EPackageError = class(Exception);
  106. EOSError = class(Exception)
  107. public
  108. ErrorCode: Longint;
  109. end;
  110. ESafecallException = class(Exception);
  111. ENoThreadSupport = Class(Exception);
  112. ENoWideStringSupport = Class(Exception);
  113. ENotImplemented = class(Exception);
  114. EArgumentException = class(Exception);
  115. EArgumentOutOfRangeException = class(EArgumentException);
  116. EArgumentNilException = class(EArgumentException);
  117. EPathTooLongException = class(Exception);
  118. ENotSupportedException = class(Exception);
  119. EDirectoryNotFoundException = class(Exception);
  120. EFileNotFoundException = class(Exception);
  121. EPathNotFoundException = class(Exception);
  122. ENoConstructException = class(Exception);
  123. //function GetTickCount: Integer;
  124. {*****************************************************************************
  125. String function
  126. *****************************************************************************}
  127. Const
  128. EmptyStr = '';
  129. EmptyWideStr = ''; // No difference here.
  130. HexDisplayPrefix: string = '$';
  131. LeadBytes = [] unimplemented;
  132. Function CharInSet(Ch: Char;Const CSet : array of char) : Boolean;
  133. function LeftStr(const S: string; Count: Integer): String; assembler;
  134. function RightStr(const S: string; Count: Integer): String; assembler;
  135. function Trim(const S: String): String; assembler;
  136. function TrimLeft(const S: String): String; assembler;
  137. function TrimRight(const S: String): String; assembler;
  138. function UpperCase(const s: String): String; assembler; overload;
  139. function LowerCase(const s: String): String; assembler; overload;
  140. function CompareStr(const s1, s2: String): Integer; assembler;
  141. function SameStr(const s1, s2: String): Boolean; assembler;
  142. function CompareText(const s1, s2: String): Integer; assembler;
  143. function SameText(const s1, s2: String): Boolean; assembler;
  144. function AnsiCompareText(const s1, s2: String): Integer; assembler;
  145. function AnsiSameText(const s1, s2: String): Boolean; assembler;
  146. function AnsiCompareStr(const s1, s2: String): Integer;
  147. procedure AppendStr(var Dest: String; const S: string);
  148. function Format(const Fmt: String; const Args: array of JSValue): String;
  149. // JavaScript built-in functions
  150. function LocaleCompare(const s1, s2, locales: String): Boolean; assembler; overload;
  151. function NormalizeStr(const S: String; const Norm: String = 'NFC'): String; assembler; overload; // not in IE
  152. function IsValidIdent(const Ident: string; AllowDots: Boolean = False; StrictDots: Boolean = False): Boolean;
  153. Type
  154. TStringReplaceFlag = (rfReplaceAll, rfIgnoreCase);
  155. TReplaceFlag = TStringReplaceFlag;
  156. TStringReplaceFlags = set of TStringReplaceFlag;
  157. TReplaceFlags = TStringReplaceFlags;
  158. function StringReplace(aOriginal, aSearch, aReplace: string; Flags: TStringReplaceFlags): String;
  159. function QuoteString(aOriginal: String; AQuote: Char): String;
  160. function QuotedStr(const s: string; QuoteChar: Char = ''''): string;
  161. function DeQuoteString(aQuoted: String; AQuote: Char): String;
  162. function IsDelimiter(const Delimiters, S: string; Index: Integer): Boolean;
  163. function AdjustLineBreaks(const S: string): string;
  164. function AdjustLineBreaks(const S: string; Style: TTextLineBreakStyle): string;
  165. function WrapText(const Line, BreakStr: string; const BreakChars: Array of char; MaxCol: Integer): string;
  166. function WrapText(const Line: string; MaxCol: Integer): string;
  167. { *****************************************************************************
  168. Integer conversions
  169. *****************************************************************************}
  170. function IntToStr(const Value: Integer): string;
  171. Function TryStrToInt(const S : String; Out res : Integer) : Boolean;
  172. Function TryStrToInt(const S : String; Out res : NativeInt) : Boolean;
  173. Function StrToIntDef(const S : String; Const aDef : Integer) : Integer;
  174. Function StrToIntDef(const S : String; Const aDef : NativeInt) : NativeInt;
  175. Function StrToInt(const S : String) : Integer;
  176. Function StrToNativeInt(const S : String) : NativeInt;
  177. // For compatibility
  178. Function StrToInt64(const S : String) : NativeLargeInt;
  179. Function StrToInt64Def(const S : String; ADefault : NativeLargeInt) : NativeLargeInt;
  180. Function TryStrToInt64(const S : String; Out res : NativeLargeInt) : Boolean;
  181. Function StrToQWord(const S : String) : NativeLargeUInt;
  182. Function StrToQWordDef(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  183. Function TryStrToQWord(const S : String; Out res : NativeLargeUInt) : Boolean;
  184. Function StrToUInt64(const S : String) : NativeLargeUInt;
  185. Function StrToUInt64Def(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  186. Function TryStrToUInt64(const S : String; Out res : NativeLargeUInt) : Boolean;
  187. Function StrToDWord(const S : String) : DWord;
  188. Function StrToDWordDef(const S : String; ADefault : DWord) : DWord;
  189. Function TryStrToDWord(const S : String; Out res : DWord) : Boolean;
  190. function IntToHex(Value: NativeInt; Digits: integer): string;
  191. { *****************************************************************************
  192. Float conversions
  193. *****************************************************************************}
  194. const
  195. // Note: Currency is internally a double, multiplied by 10000 and truncated.
  196. // The below values are the safe limits, within every step exists.
  197. // Since currency is a double it can take much larger values, but the result
  198. // may differ from Delphi/FPC
  199. MaxCurrency: Currency = 450359962737.0495; // fpc: 922337203685477.5807;
  200. MinCurrency: Currency = -450359962737.0496; // fpc: -922337203685477.5808;
  201. Type
  202. TFloatFormat = (ffFixed,ffGeneral,ffExponent,ffNumber,ffCurrency);
  203. Function FloatToDecimal(Value : double; Precision, Decimals : integer) : TFloatRec;
  204. Function FloatToStr(Value: Double): String;
  205. Function FloatToStrF(const Value : double; format: TFloatFormat; Precision, Digits: Integer): String;
  206. Function TryStrToFloat(const S : String; Out res : Double) : Boolean;
  207. Function StrToFloatDef(const S : String; Const aDef : Double) : Double;
  208. Function StrToFloat(const S : String) : Double;
  209. Function FormatFloat (Fmt : String; aValue : Double) : String;
  210. { *****************************************************************************
  211. Boolean conversions
  212. *****************************************************************************}
  213. Var
  214. TrueBoolStrs, FalseBoolStrs : Array of String;
  215. function StrToBool(const S: String): Boolean;
  216. function BoolToStr(B: Boolean; UseBoolStrs:Boolean=False): string;
  217. function BoolToStr(B: Boolean; const TrueS, FalseS: String): string;
  218. function StrToBoolDef(const S: String; Default: Boolean): Boolean;
  219. function TryStrToBool(const S: String; out Value: Boolean): Boolean;
  220. {*****************************************************************************
  221. OS/Environment
  222. *****************************************************************************}
  223. Const
  224. ConfigExtension : String = '.cfg';
  225. SysConfigDir : String = '';
  226. type
  227. TOnGetEnvironmentVariable = function(Const EnvVar: String): String;
  228. TOnGetEnvironmentString = function(Index: Integer): String;
  229. TOnGetEnvironmentVariableCount = function: Integer;
  230. var
  231. OnGetEnvironmentVariable: TOnGetEnvironmentVariable;
  232. OnGetEnvironmentString: TOnGetEnvironmentString;
  233. OnGetEnvironmentVariableCount: TOnGetEnvironmentVariableCount;
  234. function GetEnvironmentVariable(Const EnvVar: String): String;
  235. function GetEnvironmentVariableCount: Integer;
  236. function GetEnvironmentString(Index: Integer): String;
  237. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  238. Procedure Abort;
  239. {*****************************************************************************
  240. Events
  241. *****************************************************************************}
  242. Type
  243. TEventType = (etCustom,etInfo,etWarning,etError,etDebug);
  244. TEventTypes = Set of TEventType;
  245. {*****************************************************************************
  246. Date and time
  247. *****************************************************************************}
  248. Type
  249. TSystemTime = record
  250. Year, Month, Day, DayOfWeek: word;
  251. Hour, Minute, Second, MilliSecond: word;
  252. end ;
  253. TTimeStamp = record
  254. Time: longint; { Number of milliseconds since midnight }
  255. Date: longint; { One plus number of days since 1/1/0001 }
  256. end ;
  257. Var
  258. TimeSeparator : char = ':';
  259. DateSeparator : char = '-';
  260. ShortDateFormat : string = 'yyyy-mm-dd';
  261. LongDateFormat : string = 'ddd, yyyy-mm-dd';
  262. ShortTimeFormat : string = 'hh:nn';
  263. LongTimeFormat : string = 'hh:nn:ss';
  264. DecimalSeparator : string = '.';
  265. ThousandSeparator : string;
  266. TimeAMString : string = 'AM';
  267. TimePMString : string = 'PM';
  268. const
  269. HoursPerDay = 24;
  270. MinsPerHour = 60;
  271. SecsPerMin = 60;
  272. MSecsPerSec = 1000;
  273. MinsPerDay = HoursPerDay * MinsPerHour;
  274. SecsPerDay = MinsPerDay * SecsPerMin;
  275. MSecsPerDay = SecsPerDay * MSecsPerSec;
  276. MaxDateTime: TDateTime = 2958465.99999999;
  277. MinDateTime: TDateTime = -693593.99999999;
  278. JulianEpoch = TDateTime(-2415018.5);
  279. UnixEpoch = JulianEpoch + TDateTime(2440587.5);
  280. DateDelta = 693594; // Days between 1/1/0001 and 12/31/1899
  281. UnixDateDelta = 25569;
  282. { True=Leapyear }
  283. Var
  284. MonthDays : array [Boolean] of TDayTable =
  285. ((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
  286. (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31));
  287. ShortMonthNames : TMonthNames = (
  288. 'Jan',
  289. 'Feb',
  290. 'Mar',
  291. 'Apr',
  292. 'May',
  293. 'Jun',
  294. 'Jul',
  295. 'Aug',
  296. 'Sep',
  297. 'Oct',
  298. 'Nov',
  299. 'Dec');
  300. LongMonthNames : TMonthNames = (
  301. 'January',
  302. 'February',
  303. 'March',
  304. 'April',
  305. 'May',
  306. 'June',
  307. 'July',
  308. 'August',
  309. 'September',
  310. 'October',
  311. 'November',
  312. 'December');
  313. ShortDayNames : TDayNames = (
  314. 'Sun',
  315. 'Mon',
  316. 'Tue',
  317. 'Wed',
  318. 'Thu',
  319. 'Fri',
  320. 'Sat');
  321. LongDayNames : TDayNames = (
  322. 'Sunday',
  323. 'Monday',
  324. 'Tuesday',
  325. 'Wednesday',
  326. 'Thursday',
  327. 'Friday',
  328. 'Saturday');
  329. type
  330. // Stub, for easier porting of FPC/Delphi code.
  331. // Reading/Writing the properties will actually set the global variables
  332. { TFormatSettings }
  333. TFormatSettings = class(TObject)
  334. private
  335. function GetCurrencyDecimals: Byte;
  336. function GetCurrencyFormat: Byte;
  337. function GetCurrencyString: String;
  338. function GetDateSeparator: char;
  339. function GetDecimalSeparator: string;
  340. function GetLongDateFormat: string;
  341. function GetLongDayNames: TDayNames;
  342. function GetLongMonthNames: TMonthNames;
  343. function GetLongTimeFormat: string;
  344. function GetNegCurrFormat: Byte;
  345. function GetShortDateFormat: string;
  346. function GetShortDayNames: TDayNames;
  347. function GetShortMonthNames: TMonthNames;
  348. function GetShortTimeFormat: string;
  349. function GetThousandSeparator: string;
  350. function GetTimeAMString: string;
  351. function GetTimePMString: string;
  352. function GetTimeSeparator: char;
  353. procedure SetCurrencyFormat(AValue: Byte);
  354. procedure SetCurrencyString(AValue: String);
  355. procedure SetDateSeparator(const Value: char);
  356. procedure SetDecimalSeparator(const Value: string);
  357. procedure SetLongDateFormat(const Value: string);
  358. procedure SetLongDayNames(AValue: TDayNames);
  359. procedure SetLongMonthNames(AValue: TMonthNames);
  360. procedure SetLongTimeFormat(const Value: string);
  361. procedure SetNegCurrFormat(AValue: Byte);
  362. procedure SetShortDateFormat(const Value: string);
  363. procedure SetShortDayNames(AValue: TDayNames);
  364. procedure SetShortMonthNames(AValue: TMonthNames);
  365. procedure SetShortTimeFormat(const Value: string);
  366. procedure SetCurrencyDecimals(AValue: Byte);
  367. procedure SetThousandSeparator(const Value: string);
  368. procedure SetTimeAMString(const Value: string);
  369. procedure SetTimePMString(const Value: string);
  370. procedure SetTimeSeparator(const Value: char);
  371. public
  372. Property ShortMonthNames : TMonthNames Read GetShortMonthNames Write SetShortMonthNames;
  373. Property LongMonthNames : TMonthNames Read GetLongMonthNames Write SetLongMonthNames;
  374. Property ShortDayNames : TDayNames Read GetShortDayNames Write SetShortDayNames;
  375. Property LongDayNames : TDayNames Read GetLongDayNames Write SetLongDayNames;
  376. property TimeSeparator : char read GetTimeSeparator write SetTimeSeparator;
  377. property DateSeparator : char read GetDateSeparator write SetDateSeparator;
  378. property ShortDateFormat : string read GetShortDateFormat write SetShortDateFormat;
  379. property LongDateFormat : string read GetLongDateFormat write SetLongDateFormat;
  380. property ShortTimeFormat : string read GetShortTimeFormat write SetShortTimeFormat;
  381. property LongTimeFormat : string read GetLongTimeFormat write SetLongTimeFormat;
  382. property DecimalSeparator : string read GetDecimalSeparator write SetDecimalSeparator;
  383. property ThousandSeparator : string read GetThousandSeparator write SetThousandSeparator;
  384. property TimeAMString : string read GetTimeAMString write SetTimeAMString;
  385. property TimePMString : string read GetTimePMString write SetTimePMString;
  386. Property CurrencyFormat : Byte read GetCurrencyFormat Write SetCurrencyFormat;
  387. Property NegCurrFormat : Byte read GetNegCurrFormat Write SetNegCurrFormat;
  388. Property CurrencyDecimals : Byte Read GetCurrencyDecimals Write SetCurrencyDecimals;
  389. Property CurrencyString : String Read GetCurrencyString Write SetCurrencyString;
  390. end;
  391. Var
  392. FormatSettings: TFormatSettings;
  393. TwoDigitYearCenturyWindow : word = 50;
  394. { Threshold to be subtracted from year before age-detection.}
  395. function DateTimeToJSDate(aDateTime : TDateTime) : TJSDate;
  396. function JSDateToDateTime(aDate : TJSDate) : TDateTime;
  397. function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp;
  398. function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
  399. function MSecsToTimeStamp(MSecs: NativeInt): TTimeStamp;
  400. function TimeStampToMSecs(const TimeStamp: TTimeStamp): NativeInt;
  401. function TryEncodeDate(Year, Month, Day: Word; out Date: TDateTime): Boolean;
  402. function TryEncodeTime(Hour, Min, Sec, MSec: Word; out Time: TDateTime): Boolean;
  403. function EncodeDate(Year, Month, Day :word): TDateTime;
  404. function EncodeTime(Hour, Minute, Second, MilliSecond:word): TDateTime;
  405. function ComposeDateTime(Date,Time : TDateTime) : TDateTime;
  406. procedure DecodeDate(Date: TDateTime; out Year, Month, Day: word);
  407. function DecodeDateFully(const DateTime: TDateTime; out Year, Month, Day, DOW: Word): Boolean;
  408. procedure DecodeTime(Time: TDateTime; out Hour, Minute, Second, MilliSecond: word);
  409. procedure DateTimeToSystemTime(DateTime: TDateTime; out SystemTime: TSystemTime);
  410. function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
  411. function DayOfWeek(DateTime: TDateTime): integer;
  412. function Date: TDateTime;
  413. function Time: TDateTime;
  414. function Now: TDateTime;
  415. function IncMonth(const DateTime: TDateTime; NumberOfMonths: integer = 1 ): TDateTime;
  416. procedure IncAMonth(var Year, Month, Day: Word; NumberOfMonths: Integer = 1);
  417. function IsLeapYear(Year: Word): boolean;
  418. function DateToStr(Date: TDateTime): string;
  419. // function DateToStr(Date: TDateTime; const FormatSettings: TFormatSettings): string;
  420. function TimeToStr(Time: TDateTime): string;
  421. // function TimeToStr(Time: TDateTime; const FormatSettings: TFormatSettings): string;
  422. function DateTimeToStr(DateTime: TDateTime; ForceTimeIfZero : Boolean = False): string;
  423. // function DateTimeToStr(DateTime: TDateTime; const FormatSettings: TFormatSettings; ForceTimeIfZero : Boolean = False): string;
  424. function StrToDate(const S: String): TDateTime;
  425. function StrToDate(const S: String; separator : char): TDateTime;
  426. function StrToDate(const S: String; const useformat : string; separator : char): TDateTime;
  427. //function StrToDate(const S: string; FormatSettings : TFormatSettings): TDateTime;
  428. function StrToTime(const S: String): TDateTime;
  429. function StrToTime(const S: String; separator : char): TDateTime;
  430. // function StrToTime(const S: string; FormatSettings : TFormatSettings): TDateTime;
  431. function StrToDateTime(const S: String): TDateTime;
  432. //function StrToDateTime(const s: ShortString; const FormatSettings : TFormatSettings): TDateTime;
  433. function FormatDateTime(const FormatStr: string; const DateTime: TDateTime): string;
  434. // function FormatDateTime(const FormatStr: string; DateTime: TDateTime; const FormatSettings: TFormatSettings; Options : TFormatDateTimeOptions = []): string;
  435. function TryStrToDate(const S: String; out Value: TDateTime): Boolean;
  436. function TryStrToDate(const S: String; out Value: TDateTime; separator : char): Boolean;
  437. function TryStrToDate(const S: String; out Value: TDateTime; const useformat : string; separator : char): Boolean;
  438. // function TryStrToDate(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  439. function TryStrToTime(const S: String; out Value: TDateTime): Boolean;
  440. function TryStrToTime(const S: String; out Value: TDateTime; separator : char): Boolean;
  441. function TryStrToDateTime(const S: String; out Value: TDateTime): Boolean;
  442. // function TryStrToTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  443. // function TryStrToDateTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  444. function StrToDateDef(const S: String; const Defvalue : TDateTime): TDateTime;
  445. function StrToDateDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  446. function StrToTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  447. function StrToTimeDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  448. function StrToDateTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  449. function CurrentYear:Word;
  450. procedure ReplaceTime(var dati: TDateTime; NewTime : TDateTime);
  451. procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime);
  452. Function FloatToDateTime (Const Value : Extended) : TDateTime;
  453. { *****************************************************************************
  454. Currency support
  455. *****************************************************************************}
  456. Var
  457. CurrencyFormat : Byte = 0;
  458. NegCurrFormat : Byte = 0;
  459. CurrencyDecimals : Byte = 2;
  460. CurrencyString : String = '$';
  461. Function FloattoCurr (Const Value : Extended) : Currency;
  462. function TryFloatToCurr(const Value: Extended; var AResult: Currency): Boolean;
  463. Function CurrToStr(Value: Currency): string;
  464. //Function CurrToStr(Value: Currency; Const FormatSettings: TFormatSettings): string;
  465. function StrToCurr(const S: string): Currency;
  466. //function StrToCurr(const S: string; Const FormatSettings: TFormatSettings): Currency;
  467. function TryStrToCurr(const S: string;Out Value : Currency): Boolean;
  468. //function TryStrToCurr(const S: string;Out Value : Currency; Const FormatSettings: TFormatSettings): Boolean;
  469. function StrToCurrDef(const S: string; Default : Currency): Currency;
  470. //function StrToCurrDef(const S: string; Default : Currency; Const FormatSettings: TFormatSettings): Currency;
  471. {*****************************************************************************
  472. File Paths
  473. *****************************************************************************}
  474. type
  475. PathStr = String;
  476. //function ExtractFilePath(const FileName: PathStr): PathStr;
  477. {*****************************************************************************
  478. Interfaces
  479. *****************************************************************************}
  480. const
  481. GUID_NULL: TGuid = '{00000000-0000-0000-0000-000000000000}';
  482. function Supports(const Instance: IInterface; const AClass: TClass; out Obj): Boolean; overload;
  483. function Supports(const Instance: IInterface; const IID: TGuid; out Intf): Boolean; overload;
  484. function Supports(const Instance: TObject; const IID: TGuid; out Intf): Boolean; overload;
  485. function Supports(const Instance: TObject; const IID: TGuidString; out Intf): Boolean; overload;
  486. function Supports(const Instance: IInterface; const AClass: TClass): Boolean; overload;
  487. function Supports(const Instance: IInterface; const IID: TGuid): Boolean; overload;
  488. function Supports(const Instance: TObject; const IID: TGuid): Boolean; overload;
  489. function Supports(const Instance: TObject; const IID: TGuidString): Boolean; overload;
  490. function Supports(const AClass: TClass; const IID: TGuid): Boolean; overload;
  491. function Supports(const AClass: TClass; const IID: TGuidString): Boolean; overload;
  492. function TryStringToGUID(const s: string; out Guid: TGuid): Boolean;
  493. function StringToGUID(const S: string): TGuid;
  494. function GUIDToString(const guid: TGuid): string;
  495. function IsEqualGUID(const guid1, guid2: TGuid): Boolean;
  496. function GuidCase(const guid: TGuid; const List: array of TGuid): Integer;
  497. implementation
  498. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  499. Var
  500. S : String;
  501. begin
  502. S:='Application raised an exception '+ExceptObject.ClassName;
  503. if ExceptObject is Exception then
  504. S:=S+' : '+Exception(ExceptObject).Message;
  505. {$IFDEF BROWSER}
  506. asm
  507. window.alert(S);
  508. end;
  509. {$ENDIF}
  510. {$IFDEF NODEJS}
  511. Writeln(S);
  512. {$ENDIF}
  513. if ExceptAddr=nil then;
  514. end;
  515. Const
  516. SAbortError = 'Operation aborted';
  517. procedure Abort;
  518. begin
  519. Raise EAbort.Create(SAbortError);
  520. end;
  521. Function CharInSet(Ch: Char;Const CSet : array of char) : Boolean;
  522. Var
  523. I : integer;
  524. begin
  525. Result:=False;
  526. I:=Length(CSet)-1;
  527. While (Not Result) and (I>=0) do
  528. begin
  529. Result:=(Ch=CSet[i]);
  530. Dec(I);
  531. end;
  532. end;
  533. function LeftStr(const S: string; Count: Integer): String; assembler;
  534. asm
  535. return (Count>0) ? S.substr(0,Count) : "";
  536. end;
  537. function RightStr(const S: string; Count: Integer): String; assembler;
  538. asm
  539. var l = S.length;
  540. return (Count<1) ? "" : ( Count>=l ? S : S.substr(l-Count));
  541. end;
  542. function Trim(const S: String): String; assembler;
  543. asm
  544. return S.trim();
  545. end;
  546. function TrimLeft(const S: String): String; assembler;
  547. asm
  548. return S.replace(/^[\s\uFEFF\xA0\x00-\x1f]+/,'');
  549. end;
  550. function TrimRight(const S: String): String; assembler;
  551. asm
  552. return S.replace(/[\s\uFEFF\xA0\x00-\x1f]+$/,'');
  553. end;
  554. function IntToStr(const Value: Integer): string;
  555. begin
  556. Result:=str(Value);
  557. end;
  558. Function FloatToDecimal(Value : double; Precision, Decimals : integer) : TFloatRec;
  559. Const
  560. Rounds = '1234567890';
  561. var
  562. Buffer: String; //Though str func returns only 25 chars, this might change in the future
  563. InfNan: string;
  564. OutPos,Error, N, L, Start, C: Integer;
  565. GotNonZeroBeforeDot, BeforeDot : boolean;
  566. begin
  567. if Value=0 then
  568. exit;
  569. asm
  570. Buffer=Value.toPrecision(21); // Double precision
  571. end;
  572. // Writeln('Buffer :',Buffer);
  573. N := 1;
  574. L := Length(Buffer);
  575. while Buffer[N]=' ' do
  576. Inc(N);
  577. Result.Negative := (Buffer[N] = '-');
  578. if Result.Negative then
  579. Inc(N)
  580. else if (Buffer[N] = '+') then
  581. inc(N);
  582. { special cases for Inf and Nan }
  583. if (L>=N+2) then
  584. begin
  585. InfNan:=copy(Buffer,N,3);
  586. if (InfNan='Inf') then
  587. begin
  588. Result.Digits[0]:=#0;
  589. Result.Exponent:=32767;
  590. exit
  591. end;
  592. if (InfNan='Nan') then
  593. begin
  594. Result.Digits[0]:=#0;
  595. Result.Exponent:=-32768;
  596. exit
  597. end;
  598. end;
  599. Start := N; //Start of digits
  600. Outpos:=0;
  601. Result.Exponent := 0; BeforeDot := true;
  602. GotNonZeroBeforeDot := false;
  603. while (L>=N) and (Buffer[N]<>'E') do
  604. begin
  605. // Writeln('Examining : ',Buffer[N],'( output pos: ',outPos,')');
  606. if Buffer[N]='.' then
  607. BeforeDot := false
  608. else
  609. begin
  610. if BeforeDot then
  611. begin // Currently this is always 1 char
  612. Inc(Result.Exponent);
  613. Result.Digits[Outpos] := Buffer[N];
  614. if Buffer[N] <> '0' then
  615. GotNonZeroBeforeDot := true;
  616. end
  617. else
  618. Result.Digits[Outpos] := Buffer[N];
  619. Inc(outpos);
  620. end;
  621. Inc(N);
  622. end;
  623. Inc(N); // Pass through 'E'
  624. if N<=L then
  625. begin
  626. Val(Copy(Buffer, N, L-N+1), C, Error); // Get exponent after 'E'
  627. Inc(Result.Exponent, C);
  628. end;
  629. // Calculate number of digits we have from str
  630. N:=OutPos;
  631. // Writeln('Number of digits: ',N,' requested precision : ',Precision);
  632. L:=Length(Result.Digits);
  633. While N<L do
  634. begin
  635. Result.Digits[N]:='0'; //Zero remaining space
  636. Inc(N);
  637. end;
  638. if Decimals + Result.Exponent < Precision Then //After this it is the same as in FloatToDecimal
  639. N := Decimals + Result.Exponent
  640. Else
  641. N := Precision;
  642. if N >= L Then
  643. N := L-1;
  644. // Writeln('Rounding on digit : ',N);
  645. if N = 0 Then
  646. begin
  647. if Result.Digits[0] >= '5' Then
  648. begin
  649. Result.Digits[0] := '1';
  650. Result.Digits[1] := #0;
  651. Inc(Result.Exponent);
  652. end
  653. Else
  654. Result.Digits[0] := #0;
  655. end //N=0
  656. Else if N > 0 Then
  657. begin
  658. if Result.Digits[N] >= '5' Then
  659. begin
  660. Repeat
  661. Result.Digits[N] := #0;
  662. Dec(N);
  663. // Writeln(N,': ',Result.Digits[N],', Rounding to : ',Rounds[StrToInt(Result.Digits[N])]);
  664. Result.Digits[N]:=Rounds[StrToInt(Result.Digits[N])+1];
  665. Until (N = 0) Or (Result.Digits[N] < ':');
  666. If Result.Digits[0] = '0' Then
  667. begin
  668. Result.Digits[0] := '1';
  669. Inc(Result.Exponent);
  670. end;
  671. end
  672. Else
  673. begin
  674. Result.Digits[N] := '0';
  675. While (N > -1) And (Result.Digits[N] = '0') Do
  676. begin
  677. Result.Digits[N] := #0;
  678. Dec(N);
  679. end;
  680. end;
  681. end //N>0
  682. Else
  683. Result.Digits[0] := #0;
  684. if (Result.Digits[0] = #0) and
  685. not GotNonZeroBeforeDot then
  686. begin
  687. Result.Exponent := 0;
  688. Result.Negative := False;
  689. end;
  690. end;
  691. function FloatToStr(Value: Double): String;
  692. begin
  693. Result:=FloatToStrF(Value,ffGeneral,15,0);
  694. end;
  695. Function TryStrToFloat(const S : String; Out res : Double) : Boolean;
  696. Var
  697. J : JSValue;
  698. N : String;
  699. begin
  700. N:=S;
  701. // Delocalize
  702. if (ThousandSeparator <>'') then
  703. N:=StringReplace(N,ThousandSeparator,'',[rfReplaceAll]);
  704. if (DecimalSeparator<>'.') then
  705. N:=StringReplace(N,DecimalSeparator,'.',[]);
  706. J:=parseFloat(N);
  707. Result:=Not jsIsNaN(J);
  708. if Result then
  709. Res:=Double(J);
  710. end;
  711. Function StrToFloatDef(const S : String; Const aDef : Double) : Double;
  712. begin
  713. if not TryStrToFloat(S,Result) then
  714. Result:=aDef;
  715. end;
  716. Function StrToFloat(const S : String) : Double;
  717. begin
  718. if not TryStrToFloat(S,Result) then
  719. Raise EConvertError.CreateFmt(SErrInvalidFloat,[S]);
  720. end;
  721. function FormatFloat(Fmt: String; aValue: Double): String;
  722. Type
  723. TPosArray = Array of Integer;
  724. const
  725. MaxPrecision = 18; // Extended precision
  726. var
  727. // Input in usable format
  728. E : Extended; // Value as extended.
  729. FV: TFloatRec; // Value as floatrec.
  730. Section : String; // Format can contain 3 sections, semicolon separated: Pos;Neg;Zero. This is the one to use.
  731. SectionLength : Integer; // Length of section.
  732. // Calculated based on section. Static during output
  733. ThousandSep: Boolean; // Thousands separator detected in format ?
  734. IsScientific: Boolean; // Use Scientific notation ? (E detected in format)
  735. DecimalPos: Integer; // Position of decimal point in pattern.
  736. FirstDigit: Integer; // First actual digit in input (# or 0), relative to decimal point
  737. LastDigit: Integer; // Last required (0) digit, relative to decimal point
  738. RequestedDigits: Integer; // Number of requested digits, # and 0 alike
  739. ExpSize : Integer; // Number of digits in exponent
  740. Available: Integer; // Available digits in FV.
  741. // These change during output loop
  742. Current: Integer; // Current digit in available digits
  743. PadZeroes: Integer; // Difference in requested digits before comma and exponent, needs to be padded with zeroes.
  744. DistToDecimal: Integer; // Place of current digit, relative to decimal point taking in account PadZeroes!
  745. Procedure InitVars;
  746. begin
  747. E:=aValue;
  748. Section:='';
  749. SectionLength:=0;
  750. ThousandSep:=false;
  751. IsScientific:=false;
  752. DecimalPos:=0;
  753. FirstDigit:=MaxInt;
  754. LastDigit:=0;
  755. RequestedDigits:=0;
  756. ExpSize:=0;
  757. Available:=-1;
  758. end;
  759. procedure ToResult(const AChar: Char);
  760. begin
  761. Result:=Result+AChar;
  762. end;
  763. procedure AddToResult(const AStr: String);
  764. begin
  765. Result:=Result+AStr;
  766. end;
  767. procedure WriteDigit(ADigit: Char);
  768. // Write a digit to result, prepend with decimalseparator or append with 1000 separator
  769. begin
  770. if ADigit=#0 then exit;
  771. // Writeln('WriteDigit: ',ADigit,', DistToDecimal: ',DistToDecimal);
  772. Dec(DistToDecimal);
  773. // -1 -> we've arrived behind the decimal
  774. if (DistToDecimal=-1) then
  775. begin
  776. AddToResult(DecimalSeparator);
  777. ToResult(ADigit);
  778. end
  779. else
  780. begin
  781. // We're still before the decimal.
  782. ToResult(ADigit);
  783. if ThousandSep and ((DistToDecimal mod 3)=0) and (DistToDecimal>1) then
  784. AddToResult(ThousandSeparator);
  785. end;
  786. end;
  787. Function GetDigit : Char;
  788. // Return next digit from available digits.
  789. // May return #0 if none available.
  790. // Will return '0' if applicable.
  791. begin
  792. // Writeln(' DistToDecimal <= LastDigit : ',DistToDecimal,' <= ',LastDigit,' have digit: ',Current<=Available, ' (',Current,')');
  793. Result:=#0;
  794. if (Current<=Available) then
  795. begin
  796. Result:=FV.Digits[Current];
  797. Inc(Current);
  798. end
  799. else if (DistToDecimal <= LastDigit) then
  800. Dec(DistToDecimal)
  801. else
  802. Result:='0';
  803. // Writeln('GetDigit ->: ',Result);
  804. end;
  805. procedure CopyDigit;
  806. // Copy a digit (#, 0) to the output with the correct value
  807. begin
  808. // Writeln('CopyDigit ');
  809. if (PadZeroes=0) then
  810. WriteDigit(GetDigit) // No shift needed, just copy what is available.
  811. else if (PadZeroes<0) then
  812. begin
  813. // We must prepend zeroes
  814. Inc(PadZeroes);
  815. if (DistToDecimal<=FirstDigit) then
  816. WriteDigit('0')
  817. else
  818. Dec(DistToDecimal);
  819. end
  820. else
  821. begin
  822. // We must append zeroes
  823. while PadZeroes > 0 do
  824. begin
  825. WriteDigit(GetDigit);
  826. Dec(PadZeroes);
  827. end;
  828. WriteDigit(GetDigit);
  829. end;
  830. end;
  831. Function GetSections(Var SP : TPosArray) : Integer;
  832. var
  833. FL : Integer;
  834. i : Integer;
  835. C,Q : Char;
  836. inQuote : Boolean;
  837. begin
  838. Result:=1;
  839. SP[1]:=-1;
  840. SP[2]:=-1;
  841. SP[3]:=-1;
  842. inQuote:=False;
  843. Q:=#0;
  844. I:=1;
  845. FL:=Length(Fmt);
  846. while (I<=FL) do
  847. begin
  848. C:=Fmt[I];
  849. case C of
  850. ';':
  851. begin
  852. if not InQuote then
  853. begin
  854. if Result>3 then
  855. Raise Exception.Create('Invalid float format');
  856. SP[Result]:=I+1;
  857. Inc(Result);
  858. end;
  859. end;
  860. '"','''':
  861. begin
  862. if InQuote then
  863. InQuote:=C<>Q
  864. else
  865. begin
  866. InQuote:=True;
  867. Q:=C;
  868. end;
  869. end;
  870. end;
  871. Inc(I);
  872. end;
  873. if SP[Result]=-1 then
  874. SP[Result]:=FL+1;
  875. end;
  876. Procedure AnalyzeFormat;
  877. var
  878. I,Len: Integer;
  879. Q,C: Char;
  880. InQuote : Boolean;
  881. begin
  882. Len:=Length(Section);
  883. I:=1;
  884. InQuote:=False;
  885. Q:=#0;
  886. while (I<=Len) do
  887. begin
  888. C:=Section[i];
  889. if C in ['"',''''] then
  890. begin
  891. if InQuote then
  892. InQuote:=C<>Q
  893. else
  894. begin
  895. InQuote:=True;
  896. Q:=C;
  897. end;
  898. end
  899. else if not InQuote then
  900. case C of
  901. '.':
  902. if (DecimalPos=0) then
  903. DecimalPos:=RequestedDigits+1;
  904. ',':
  905. ThousandSep:=ThousandSeparator<>#0;
  906. 'e', 'E':
  907. begin
  908. Inc(I);
  909. if (I<Len) then
  910. begin
  911. C:=Section[i];
  912. IsScientific:=C in ['-','+'];
  913. if IsScientific then
  914. while (I<Len) and (Section[i+1]='0') do
  915. begin
  916. Inc(ExpSize);
  917. Inc(I);
  918. end;
  919. if ExpSize>4 then
  920. ExpSize:=4;
  921. end;
  922. end;
  923. '#':
  924. Inc(RequestedDigits);
  925. '0':
  926. begin
  927. if RequestedDigits<FirstDigit then
  928. FirstDigit:=RequestedDigits+1;
  929. Inc(RequestedDigits);
  930. LastDigit:=RequestedDigits+1;
  931. end;
  932. end;
  933. Inc(I);
  934. end;
  935. if DecimalPos=0 then
  936. DecimalPos:=RequestedDigits+1;
  937. // Writeln('LastDigit: ',DecimalPos,'-',LastDigit);
  938. LastDigit:=DecimalPos-LastDigit;
  939. if LastDigit>0 then
  940. LastDigit:=0;
  941. // Writeln('FirstDigit: ',DecimalPos,'-',FirstDigit);
  942. FirstDigit:=DecimalPos-FirstDigit;
  943. if FirstDigit<0 then
  944. FirstDigit:=0;
  945. end;
  946. Function ValueOutSideScope : Boolean;
  947. begin
  948. With FV do
  949. Result:=((Exponent >= 18) and (not IsScientific)) or (Exponent = $7FF) or (Exponent = $800)
  950. end;
  951. Procedure CalcRunVars;
  952. Var
  953. D,P: Integer;
  954. begin
  955. if IsScientific then
  956. begin
  957. P:=RequestedDigits;
  958. D:=9999;
  959. end
  960. else
  961. begin
  962. P:=MaxPrecision;
  963. D:=RequestedDigits-DecimalPos+1;
  964. end;
  965. FV:=FloatToDecimal(aValue,P,D);
  966. // Writeln('Number of digits available : ',Length(FV.Digits));
  967. // For p:=0 to Length(FV.Digits)-1 do
  968. // writeln(P,': ',FV.Digits[p]);
  969. DistToDecimal:=DecimalPos-1;
  970. if IsScientific then
  971. PadZeroes:=0 // No padding.
  972. else
  973. begin
  974. PadZeroes:=FV.Exponent-(DecimalPos-1);
  975. if (PadZeroes>=0) then
  976. DistToDecimal:=FV.Exponent
  977. end;
  978. // Writeln('PadZeroes : ',PadZeroes, ', DistToDecimal : ',DistToDecimal);
  979. Available:=-1;
  980. while (Available<High(FV.Digits)) and (FV.Digits[Available+1]<>#0) do
  981. Inc(Available);
  982. // Writeln('Available: ',Available);
  983. end;
  984. Function FormatExponent(ASign: Char; aExponent: Integer) : String;
  985. begin
  986. Result:=IntToStr(aExponent);
  987. Result:=StringOfChar('0',ExpSize-Length(Result))+Result;
  988. if (aExponent<0) then
  989. Result:='-'+Result
  990. else if (aExponent>0) and (aSign='+') then
  991. Result:=aSign+Result;
  992. end;
  993. var
  994. I,S : Integer;
  995. C,Q : Char;
  996. PA : TPosArray;
  997. InLiteral : Boolean;
  998. begin
  999. SetLength(PA,4);
  1000. Result:='';
  1001. Initvars;
  1002. // What section to use ?
  1003. if (E>0) then
  1004. S:=1
  1005. else if (E<0) then
  1006. S:=2
  1007. else
  1008. S:=3;
  1009. PA[0]:=0;
  1010. I:=GetSections(PA);
  1011. if (I<S) or (PA[S]-PA[S-1]=0) then
  1012. S:=1;
  1013. // Extract correct section
  1014. SectionLength:=PA[S]-PA[S-1]-1;
  1015. Section:=Copy(Fmt,PA[S-1]+1,SectionLength);
  1016. SetLength(Section,SectionLength);
  1017. // Writeln('Section ',I,' : "',Section,'" ',SectionLength);
  1018. AnalyzeFormat;
  1019. // Writeln('RequestedDigits: ',RequestedDigits,', DecimalPos : ',DecimalPos,', LastDigit: ',LastDigit,', FirstDigit: ',FirstDigit);
  1020. CalcRunVars;
  1021. // If we cannot process value using current settings, fallback
  1022. if (SectionLength=0) or ValueOutSideScope then
  1023. begin
  1024. asm
  1025. Section=E.toPrecision(15);
  1026. end;
  1027. Result:=Section;
  1028. end;
  1029. // Get Started
  1030. I:=1;
  1031. Current:=0;
  1032. Q:=' ';
  1033. InLiteral:=False;
  1034. if (FV.Negative) and (S=1) then
  1035. ToResult('-');
  1036. while (I<=SectionLength) do
  1037. begin
  1038. C:=Section[i];
  1039. // Writeln('Analyzing pos ',I,': "',C,'"');
  1040. If (C in ['"', '''']) then
  1041. begin
  1042. if InLiteral then
  1043. InLiteral:=C<>Q
  1044. else
  1045. begin
  1046. inLiteral:=True;
  1047. Q:=C;
  1048. end;
  1049. end
  1050. else if InLiteral then
  1051. ToResult(C)
  1052. else
  1053. case C of
  1054. '0', '#':
  1055. CopyDigit;
  1056. '.', ',':
  1057. ; // Do nothing, handled by CopyDigit
  1058. 'e', 'E':
  1059. begin
  1060. ToResult(C); // Always needed
  1061. Inc(I);
  1062. if I<=Length(Section) then
  1063. begin
  1064. C:=Section[I];
  1065. if (C in ['+','-']) then
  1066. begin
  1067. AddToResult(FormatExponent(C,FV.Exponent-DecimalPos+1));
  1068. // Skip rest
  1069. while (I<SectionLength) and (Section[i+1]='0') do
  1070. Inc(I);
  1071. end;
  1072. end;
  1073. end;
  1074. else
  1075. ToResult(C);
  1076. end;
  1077. Inc(i);
  1078. end;
  1079. end;
  1080. function StrToBool(const S: String): Boolean;
  1081. begin
  1082. if not(TryStrToBool(S,Result)) then
  1083. raise EConvertError.CreateFmt(SInvalidBoolean,[S]);
  1084. end;
  1085. procedure CheckBoolStrs;
  1086. begin
  1087. if Length(TrueBoolStrs)=0 then
  1088. begin
  1089. SetLength(TrueBoolStrs,1);
  1090. TrueBoolStrs[0]:='True';
  1091. end;
  1092. if Length(FalseBoolStrs)=0 then
  1093. begin
  1094. SetLength(FalseBoolStrs,1);
  1095. FalseBoolStrs[0]:='False';
  1096. end;
  1097. end;
  1098. function BoolToStr(B: Boolean; UseBoolStrs: Boolean): string;
  1099. begin
  1100. if UseBoolStrs Then
  1101. begin
  1102. CheckBoolStrs;
  1103. if B then
  1104. Result:=TrueBoolStrs[0]
  1105. else
  1106. Result:=FalseBoolStrs[0];
  1107. end else
  1108. if B then
  1109. Result:='-1'
  1110. else
  1111. Result:='0';
  1112. end;
  1113. function BoolToStr(B: Boolean; const TrueS, FalseS: String): string;
  1114. begin
  1115. if B then Result:=TrueS else Result:=FalseS;
  1116. end;
  1117. function StrToBoolDef(const S: String; Default: Boolean): Boolean;
  1118. begin
  1119. if not TryStrToBool(S,Result) then
  1120. Result:=Default;
  1121. end;
  1122. function TryStrToBool(const S: String; out Value: Boolean): Boolean;
  1123. Var
  1124. Temp : String;
  1125. I : Longint;
  1126. D : Double;
  1127. Code: integer;
  1128. begin
  1129. Temp:=uppercase(S);
  1130. Val(Temp,D,code);
  1131. Result:=true;
  1132. If Code=0 then
  1133. Value:=(D<>0.0)
  1134. else
  1135. begin
  1136. CheckBoolStrs;
  1137. for I:=low(TrueBoolStrs) to High(TrueBoolStrs) do
  1138. if Temp=uppercase(TrueBoolStrs[I]) then
  1139. begin
  1140. Value:=true;
  1141. exit;
  1142. end;
  1143. for I:=low(FalseBoolStrs) to High(FalseBoolStrs) do
  1144. if Temp=uppercase(FalseBoolStrs[I]) then
  1145. begin
  1146. Value:=false;
  1147. exit;
  1148. end;
  1149. Result:=false;
  1150. end;
  1151. end;
  1152. function UpperCase(const s: String): String; assembler;
  1153. asm
  1154. return s.toUpperCase();
  1155. end;
  1156. function LowerCase(const s: String): String; assembler;
  1157. asm
  1158. return s.toLowerCase();
  1159. end;
  1160. function CompareStr(const s1, s2: String): Integer; assembler;
  1161. asm
  1162. var l1 = s1.length;
  1163. var l2 = s2.length;
  1164. if (l1<=l2){
  1165. var s = s2.substr(0,l1);
  1166. if (s1<s){ return -1;
  1167. } else if (s1>s){ return 1;
  1168. } else { return l1<l2 ? -1 : 0; };
  1169. } else {
  1170. var s = s1.substr(0,l2);
  1171. if (s<s2){ return -1;
  1172. } else { return 1; };
  1173. };
  1174. end;
  1175. function SameStr(const s1, s2: String): Boolean; assembler;
  1176. asm
  1177. return s1 == s2;
  1178. end;
  1179. function CompareText(const s1, s2: String): Integer; assembler;
  1180. asm
  1181. var l1 = s1.toLowerCase();
  1182. var l2 = s2.toLowerCase();
  1183. if (l1>l2){ return 1;
  1184. } else if (l1<l2){ return -1;
  1185. } else { return 0; }
  1186. end;
  1187. function SameText(const s1, s2: String): Boolean; assembler;
  1188. asm
  1189. return s1.toLowerCase() == s2.toLowerCase();
  1190. end;
  1191. function AnsiCompareText(const s1, s2: String): Integer; assembler;
  1192. asm
  1193. return s1.localeCompare(s2);
  1194. end;
  1195. function AnsiSameText(const s1, s2: String): Boolean; assembler;
  1196. asm
  1197. return s1.localeCompare(s2) == 0;
  1198. end;
  1199. function AnsiCompareStr(const s1, s2: String): Integer;
  1200. begin
  1201. {$IFDEF ECMAScript6}
  1202. Result:=CompareText(TJSString(s1).normalize(),TJSString(s1).normalize());
  1203. {$ELSE}
  1204. Result:=CompareText(s1,s2);
  1205. {$ENDIF}
  1206. end;
  1207. procedure AppendStr(var Dest: String; const S: string);
  1208. begin
  1209. Dest:=Dest+S;
  1210. end;
  1211. Const
  1212. feInvalidFormat = 1;
  1213. feMissingArgument = 2;
  1214. feInvalidArgIndex = 3;
  1215. Procedure DoFormatError (ErrCode : Longint;const fmt: String);
  1216. begin
  1217. //!! must be changed to contain format string...
  1218. Case ErrCode of
  1219. feInvalidFormat : raise EConvertError.Createfmt(SInvalidFormat,[Fmt]);
  1220. feMissingArgument : raise EConvertError.Createfmt(SArgumentMissing,[Fmt]);
  1221. feInvalidArgIndex : raise EConvertError.Createfmt(SInvalidArgIndex,[Fmt]);
  1222. end;
  1223. end;
  1224. Const
  1225. maxdigits = 15;
  1226. Function ReplaceDecimalSep(S: String; Const DS : string) : string;
  1227. Var
  1228. P : Integer;
  1229. begin
  1230. P:=Pos('.',S);
  1231. if P>0 then
  1232. Result:=Copy(S,1,P-1)+DS+Copy(S,P+1,Length(S)-P)
  1233. else
  1234. Result:=S;
  1235. end;
  1236. function FormatGeneralFloat(Value : double; Precision : Integer; DS : String) : string;
  1237. Var
  1238. P, PE, Q, Exponent: Integer;
  1239. Begin
  1240. If (Precision = -1) Or (Precision > maxdigits) Then
  1241. Precision := maxdigits;
  1242. { First convert to scientific format, with correct precision }
  1243. Str(Value:precision+7, Result);
  1244. { Delete leading spaces }
  1245. Result:=TrimLeft(Result);
  1246. P:=Pos('.',Result);
  1247. if P=0 then
  1248. exit;
  1249. { Consider removing exponent }
  1250. PE:=Pos('E',Result);
  1251. if PE=0 then
  1252. begin
  1253. Result:=ReplaceDecimalSep(Result,DS);
  1254. exit;
  1255. end;
  1256. { Read exponent }
  1257. Q:=PE+2;
  1258. Exponent := 0;
  1259. while (Q <= Length(Result)) do
  1260. begin
  1261. Exponent := Exponent*10 + Ord(Result[Q])-Ord('0');
  1262. Inc(Q);
  1263. end;
  1264. if Result[PE+1] = '-' then
  1265. Exponent := -Exponent;
  1266. if (P+Exponent < PE) and (Exponent > -6) then
  1267. begin
  1268. { OK to remove exponent }
  1269. SetLength(Result,PE-1); { Trim exponent }
  1270. if Exponent >= 0 then
  1271. begin
  1272. { Shift point to right }
  1273. for Q := 0 to Exponent-1 do
  1274. begin
  1275. Result[P] := Result[P+1];
  1276. Inc(P);
  1277. end;
  1278. Result[P] := '.';
  1279. P := 1;
  1280. if Result[P] = '-' then
  1281. Inc(P);
  1282. while (Result[P] = '0') and (P < Length(Result)) and (Copy(Result,P+1,Length(DS))<>DS) do
  1283. { Trim leading zeros; conversion above should not give any, but occasionally does
  1284. because of rounding }
  1285. System.Delete(Result,P,1);
  1286. end
  1287. else
  1288. begin
  1289. { Add zeros at start }
  1290. Insert(Copy('00000',1,-Exponent),Result,P-1);
  1291. Result[P-Exponent] := Result[P-Exponent-1]; { Copy leading digit }
  1292. Result[P] := '.';
  1293. if Exponent <> -1 then
  1294. Result[P-Exponent-1] := '0';
  1295. end;
  1296. { Remove trailing zeros }
  1297. Q := Length(Result);
  1298. while (Q > 0) and (Result[Q] = '0') do
  1299. Dec(Q);
  1300. if Result[Q] = '.' then
  1301. Dec(Q); { Remove trailing decimal point }
  1302. if (Q = 0) or ((Q=1) and (Result[1] = '-')) then
  1303. Result := '0'
  1304. else
  1305. SetLength(Result,Q);
  1306. end
  1307. else
  1308. begin
  1309. { Need exponent, but remove superfluous characters }
  1310. { Delete trailing zeros }
  1311. while Result[PE-1] = '0' do
  1312. begin
  1313. System.Delete(Result,PE-1,1);
  1314. Dec(PE);
  1315. end;
  1316. { If number ends in decimal point, remove it }
  1317. if Result[PE-1] = DS then
  1318. begin
  1319. System.Delete(Result,PE-1,1);
  1320. Dec(PE);
  1321. end;
  1322. { delete superfluous + in exponent }
  1323. if Result[PE+1]='+' then
  1324. System.Delete(Result,PE+1,1)
  1325. else
  1326. Inc(PE);
  1327. while Result[PE+1] = '0' do
  1328. { Delete leading zeros in exponent }
  1329. System.Delete(Result,PE+1,1)
  1330. end;
  1331. Result:=ReplaceDecimalSep(Result,DS)
  1332. end;
  1333. function FormatExponentFloat(Value : double; Precision,Digits : Integer;DS : String) : string;
  1334. Var
  1335. P: Integer;
  1336. Begin
  1337. DS:=DecimalSeparator;
  1338. If (Precision = -1) Or (Precision > maxdigits) Then
  1339. Precision := maxdigits;
  1340. Str(Value:Precision+7, Result);
  1341. { Delete leading spaces }
  1342. while Result[1] = ' ' do
  1343. System.Delete(Result, 1, 1);
  1344. P:=Pos('E',Result);
  1345. if P=0 then
  1346. begin
  1347. Result:=ReplaceDecimalSep(Result,DS);
  1348. exit;
  1349. end;
  1350. Inc(P, 2);
  1351. if Digits > 4 then
  1352. Digits:=4;
  1353. Digits:=Length(Result) - P - Digits + 1;
  1354. if Digits < 0 then
  1355. insert(copy('0000',1,-Digits),Result,P)
  1356. else
  1357. while (Digits > 0) and (Result[P] = '0') do
  1358. begin
  1359. System.Delete(Result, P, 1);
  1360. if P > Length(Result) then
  1361. begin
  1362. System.Delete(Result, P - 2, 2);
  1363. break;
  1364. end;
  1365. Dec(Digits);
  1366. end;
  1367. Result:=ReplaceDecimalSep(Result,DS);
  1368. End;
  1369. function FormatFixedFloat(Value : double; Digits : Integer; DS : String) : string;
  1370. Begin
  1371. If Digits = -1 Then
  1372. Digits := 2
  1373. Else If Digits > 18 Then
  1374. Digits := 18;
  1375. Str(Value:0:Digits, Result);
  1376. if (Result<>'') and (Result[1]=' ') then
  1377. Delete(Result,1,1);
  1378. Result:=ReplaceDecimalSep(Result,DS);
  1379. end;
  1380. function FormatNumberFloat(Value : double; Digits : Integer; DS,TS : String) : string;
  1381. Var
  1382. P : integer;
  1383. Begin
  1384. If Digits = -1 Then
  1385. Digits := 2
  1386. else If Digits > maxdigits Then
  1387. Digits := maxdigits;
  1388. Str(Value:0:Digits, Result);
  1389. if (Result<>'') and (Result[1]=' ') then
  1390. Delete(Result,1,1);
  1391. P:=Pos('.',Result);
  1392. Result:=ReplaceDecimalSep(Result,DS);
  1393. Dec(P,3);
  1394. if (TS<>'') and (TS<>#0) then
  1395. While (P>1) Do
  1396. Begin
  1397. If (Result[P-1] <> '-') Then
  1398. Insert(TS, Result, P);
  1399. Dec(P, 3);
  1400. End;
  1401. End;
  1402. function RemoveLeadingNegativeSign(var AValue: String; DS : String): Boolean;
  1403. // removes negative sign in case when result is zero eg. -0.00
  1404. var
  1405. i: PtrInt;
  1406. TS: String;
  1407. StartPos: PtrInt;
  1408. begin
  1409. Result:=False;
  1410. StartPos := 2;
  1411. TS := ThousandSeparator;
  1412. for i :=StartPos to length(AValue) do
  1413. begin
  1414. Result := (AValue[i] in ['0', DS, 'E', '+']) or (aValue=TS);
  1415. if not Result then
  1416. break;
  1417. end;
  1418. if (Result) then
  1419. Delete(AValue, 1, 1);
  1420. end;
  1421. Function FormatNumberCurrency(const Value : Currency; Digits : Integer; DS,TS : String) : string;
  1422. Var
  1423. Negative: Boolean;
  1424. P : Integer;
  1425. Begin
  1426. If Digits = -1 Then
  1427. Digits := CurrencyDecimals
  1428. Else If Digits > 18 Then
  1429. Digits := 18;
  1430. Str(Value:0:Digits, Result);
  1431. Negative:=Result[1] = '-';
  1432. if Negative then
  1433. System.Delete(Result, 1, 1);
  1434. P := Pos('.', Result);
  1435. If P <> 0 Then
  1436. Result:=ReplaceDecimalSep(Result,DS)
  1437. else
  1438. P := Length(Result)+1;
  1439. Dec(P, 3);
  1440. While (P > 1) Do
  1441. Begin
  1442. If ThousandSeparator<>#0 Then
  1443. Insert(FormatSettings.ThousandSeparator, Result, P);
  1444. Dec(P, 3);
  1445. End;
  1446. if (length(Result) > 1) and Negative then
  1447. Negative := not RemoveLeadingNegativeSign(Result,DS);
  1448. If Not Negative Then
  1449. Case CurrencyFormat Of
  1450. 0: Result := CurrencyString + Result;
  1451. 1: Result := Result + CurrencyString;
  1452. 2: Result := CurrencyString + ' ' + Result;
  1453. 3: Result := Result + ' ' + CurrencyString;
  1454. end
  1455. else
  1456. Case NegCurrFormat Of
  1457. 0: Result := '(' + CurrencyString + Result + ')';
  1458. 1: Result := '-' + CurrencyString + Result;
  1459. 2: Result := CurrencyString + '-' + Result;
  1460. 3: Result := CurrencyString + Result + '-';
  1461. 4: Result := '(' + Result + CurrencyString + ')';
  1462. 5: Result := '-' + Result + CurrencyString;
  1463. 6: Result := Result + '-' + CurrencyString;
  1464. 7: Result := Result + CurrencyString + '-';
  1465. 8: Result := '-' + Result + ' ' + CurrencyString;
  1466. 9: Result := '-' + CurrencyString + ' ' + Result;
  1467. 10: Result := Result + ' ' + CurrencyString + '-';
  1468. 11: Result := CurrencyString + ' ' + Result + '-';
  1469. 12: Result := CurrencyString + ' ' + '-' + Result;
  1470. 13: Result := Result + '-' + ' ' + CurrencyString;
  1471. 14: Result := '(' + CurrencyString + ' ' + Result + ')';
  1472. 15: Result := '(' + Result + ' ' + CurrencyString + ')';
  1473. end;
  1474. if TS='' then ;
  1475. end;
  1476. Function FloatToStrF(const Value : double; format: TFloatFormat; Precision, Digits: Integer): String;
  1477. Var
  1478. DS: string;
  1479. Begin
  1480. DS:=DecimalSeparator;
  1481. Case format Of
  1482. ffGeneral:
  1483. Result:=FormatGeneralFloat(Value,Precision,DS);
  1484. ffExponent:
  1485. Result:=FormatExponentFloat(Value,Precision,Digits,DS);
  1486. ffFixed:
  1487. Result:=FormatFixedFloat(Value,Digits,DS);
  1488. ffNumber:
  1489. Result:=FormatNumberFloat(Value,Digits,DS,ThousandSeparator);
  1490. ffCurrency:
  1491. Result:=FormatNumberCurrency(Value,Digits,DS,ThousandSeparator);
  1492. end;
  1493. if (Format<>ffCurrency) and (length(Result)>1) and (Result[1]='-') then
  1494. RemoveLeadingNegativeSign(Result,DS);
  1495. end;
  1496. function Format (const Fmt: String; const Args: array of jsvalue): String;
  1497. Var ChPos,OldPos,ArgPos,DoArg,Len : SizeInt;
  1498. Hs,ToAdd : String;
  1499. Index : SizeInt;
  1500. Width,Prec : Longint;
  1501. Left : Boolean;
  1502. Fchar : char;
  1503. vq : nativeint;
  1504. {
  1505. ReadFormat reads the format string. It returns the type character in
  1506. uppercase, and sets index, Width, Prec to their correct values,
  1507. or -1 if not set. It sets Left to true if left alignment was requested.
  1508. In case of an error, DoFormatError is called.
  1509. }
  1510. Function ReadFormat : Char;
  1511. Var Value : NativeInt;
  1512. Procedure ReadInteger;
  1513. var
  1514. Code: integer;
  1515. ArgN: SizeInt;
  1516. begin
  1517. If Value<>-1 then exit; // Was already read.
  1518. OldPos:=ChPos;
  1519. While (ChPos<=Len) and
  1520. (Fmt[ChPos]<='9') and (Fmt[ChPos]>='0') do inc(ChPos);
  1521. If ChPos>len then
  1522. DoFormatError(feInvalidFormat,Fmt);
  1523. If Fmt[ChPos]='*' then
  1524. begin
  1525. if Index=-1 then
  1526. ArgN:=Argpos
  1527. else
  1528. begin
  1529. ArgN:=Index;
  1530. Inc(Index);
  1531. end;
  1532. If (ChPos>OldPos) or (ArgN>High(Args)) then
  1533. DoFormatError(feInvalidFormat,Fmt);
  1534. ArgPos:=ArgN+1;
  1535. if IsNumber(Args[ArgN]) and IsInteger(Args[ArgN]) then
  1536. Value:=Integer(Args[ArgN])
  1537. else
  1538. DoFormatError(feInvalidFormat,Fmt);
  1539. Inc(ChPos);
  1540. end
  1541. else
  1542. begin
  1543. If (OldPos<ChPos) Then
  1544. begin
  1545. Val (Copy(Fmt,OldPos,ChPos-OldPos),value,code);
  1546. // This should never happen !!
  1547. If Code>0 then DoFormatError (feInvalidFormat,Fmt);
  1548. end
  1549. else
  1550. Value:=-1;
  1551. end;
  1552. end;
  1553. Procedure ReadIndex;
  1554. begin
  1555. If Fmt[ChPos]<>':' then
  1556. ReadInteger
  1557. else
  1558. value:=0; // Delphi undocumented behaviour, assume 0, #11099
  1559. If Fmt[ChPos]=':' then
  1560. begin
  1561. If Value=-1 then DoFormatError(feMissingArgument,Fmt);
  1562. Index:=Value;
  1563. Value:=-1;
  1564. Inc(ChPos);
  1565. end;
  1566. end;
  1567. Procedure ReadLeft;
  1568. begin
  1569. If Fmt[ChPos]='-' then
  1570. begin
  1571. left:=True;
  1572. Inc(ChPos);
  1573. end
  1574. else
  1575. Left:=False;
  1576. end;
  1577. Procedure ReadWidth;
  1578. begin
  1579. ReadInteger;
  1580. If Value<>-1 then
  1581. begin
  1582. Width:=Value;
  1583. Value:=-1;
  1584. end;
  1585. end;
  1586. Procedure ReadPrec;
  1587. begin
  1588. If Fmt[ChPos]='.' then
  1589. begin
  1590. inc(ChPos);
  1591. ReadInteger;
  1592. If Value=-1 then
  1593. Value:=0;
  1594. prec:=Value;
  1595. end;
  1596. end;
  1597. begin
  1598. Index:=-1;
  1599. Width:=-1;
  1600. Prec:=-1;
  1601. Value:=-1;
  1602. inc(ChPos);
  1603. If Fmt[ChPos]='%' then
  1604. begin
  1605. Result:='%';
  1606. exit; // VP fix
  1607. end;
  1608. ReadIndex;
  1609. ReadLeft;
  1610. ReadWidth;
  1611. ReadPrec;
  1612. Result:=Upcase(Fmt[ChPos]);
  1613. end;
  1614. function Checkarg (AT : TJSValueType; err:boolean):boolean;
  1615. {
  1616. Check if argument INDEX is of correct type (AT)
  1617. If Index=-1, ArgPos is used, and argpos is augmented with 1
  1618. DoArg is set to the argument that must be used.
  1619. }
  1620. begin
  1621. result:=false;
  1622. if Index=-1 then
  1623. DoArg:=Argpos
  1624. else
  1625. DoArg:=Index;
  1626. ArgPos:=DoArg+1;
  1627. If (Doarg>High(Args)) or (GetValueTYpe(Args[Doarg])<>AT) then
  1628. begin
  1629. if err then
  1630. DoFormatError(feInvalidArgindex,Fmt);
  1631. dec(ArgPos);
  1632. exit;
  1633. end;
  1634. result:=true;
  1635. end;
  1636. begin
  1637. Result:='';
  1638. Len:=Length(Fmt);
  1639. ChPos:=1;
  1640. OldPos:=1;
  1641. ArgPos:=0;
  1642. While ChPos<=len do
  1643. begin
  1644. While (ChPos<=Len) and (Fmt[ChPos]<>'%') do
  1645. inc(ChPos);
  1646. If ChPos>OldPos Then
  1647. Result:=Result+Copy(Fmt,OldPos,ChPos-Oldpos);
  1648. If ChPos<Len then
  1649. begin
  1650. FChar:=ReadFormat;
  1651. {$ifdef fmtdebug}
  1652. DumpFormat(FCHar);
  1653. {$endif}
  1654. Case FChar of
  1655. 'D' : begin
  1656. Checkarg(jvtinteger,true);
  1657. toAdd:=IntToStr(NativeInt(Args[DoArg]));
  1658. Width:=Abs(width);
  1659. Index:=Prec-Length(ToAdd);
  1660. If ToAdd[1]<>'-' then
  1661. ToAdd:=StringOfChar('0',Index)+ToAdd
  1662. else
  1663. // + 1 to accomodate for - sign in length !!
  1664. Insert(StringOfChar('0',Index+1),toadd,2);
  1665. end;
  1666. 'U' : begin
  1667. Checkarg(jvtinteger,True);
  1668. if NativeInt(Args[Doarg])<0 then
  1669. DoFormatError(feInvalidArgindex,Fmt);
  1670. Toadd:=IntToStr(NativeInt(Args[Doarg]));
  1671. Width:=Abs(width);
  1672. Index:=Prec-Length(ToAdd);
  1673. ToAdd:=StringOfChar('0',Index)+ToAdd
  1674. end;
  1675. 'E' : begin
  1676. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1677. ToAdd:=FloatToStrF(Double(Args[doarg]),ffFixed,9999,Prec);
  1678. end;
  1679. 'F' : begin
  1680. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1681. ToAdd:=FloatToStrF(Double(Args[doarg]),ffFixed,9999,Prec);
  1682. end;
  1683. 'G' : begin
  1684. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1685. ToAdd:=FloatToStrF(Double(Args[doarg]),ffGeneral,Prec,3);
  1686. end;
  1687. 'N' : begin
  1688. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1689. ToAdd:=FloatToStrF(Double(Args[doarg]),ffNumber,9999,Prec);
  1690. end;
  1691. 'M' : begin
  1692. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1693. ToAdd:=FloatToStrF(Double(Args[doarg]),ffCurrency,9999,Prec);
  1694. end;
  1695. 'S' : begin
  1696. CheckArg(jvtString,true);
  1697. hs:=String(Args[doarg]);
  1698. Index:=Length(hs);
  1699. If (Prec<>-1) and (Index>Prec) then
  1700. Index:=Prec;
  1701. ToAdd:=Copy(hs,1,Index);
  1702. end;
  1703. 'P' : Begin
  1704. CheckArg(jvtInteger,true);
  1705. ToAdd:=IntToHex(NativeInt(Args[DoArg]),31);
  1706. end;
  1707. 'X' : begin
  1708. Checkarg(jvtinteger,true);
  1709. vq:=nativeInt(Args[Doarg]);
  1710. index:=31; // May need to adjust to NativeInt
  1711. If Prec>index then
  1712. ToAdd:=IntToHex(vq,index)
  1713. else
  1714. begin
  1715. // determine minimum needed number of hex digits.
  1716. Index:=1;
  1717. While (NativeInt(1) shl (Index*4)<=vq) and (index<16) do
  1718. inc(Index);
  1719. If Index>Prec then
  1720. Prec:=Index;
  1721. ToAdd:=IntToHex(vq,Prec);
  1722. end;
  1723. end;
  1724. '%': ToAdd:='%';
  1725. end;
  1726. If Width<>-1 then
  1727. If Length(ToAdd)<Width then
  1728. If not Left then
  1729. ToAdd:=StringOfChar(' ',Width-Length(ToAdd))+ToAdd
  1730. else
  1731. ToAdd:=ToAdd+StringOfChar(' ',Width-Length(ToAdd));
  1732. Result:=Result+ToAdd;
  1733. end;
  1734. inc(ChPos);
  1735. Oldpos:=ChPos;
  1736. end;
  1737. end;
  1738. function LocaleCompare(const s1, s2, locales: String): Boolean; assembler;
  1739. asm
  1740. return s1.localeCompare(s2,locales) == 0;
  1741. end;
  1742. function NormalizeStr(const S: String; const Norm: String): String; assembler;
  1743. asm
  1744. return S.normalize(Norm);
  1745. end;
  1746. function IsValidIdent(const Ident: string; AllowDots: Boolean = False; StrictDots: Boolean = False): Boolean;
  1747. const
  1748. Alpha = ['A'..'Z', 'a'..'z', '_'];
  1749. AlphaNum = Alpha + ['0'..'9'];
  1750. Dot = '.';
  1751. var
  1752. First: Boolean;
  1753. I, Len: Integer;
  1754. begin
  1755. Len := Length(Ident);
  1756. if Len < 1 then
  1757. Exit(False);
  1758. First := True;
  1759. Result:=false;
  1760. I:=1;
  1761. While I<=len do
  1762. begin
  1763. if First then
  1764. begin
  1765. if not (Ident[I] in Alpha) then exit;
  1766. First := False;
  1767. end
  1768. else if AllowDots and (Ident[I] = Dot) then
  1769. begin
  1770. if StrictDots then
  1771. begin
  1772. if I >= Len then exit;
  1773. First := True;
  1774. end;
  1775. end
  1776. else
  1777. if not (Ident[I] in AlphaNum) then exit;
  1778. I:=I+1;
  1779. end;
  1780. Result:=true;
  1781. end;
  1782. procedure FreeAndNil(var Obj);
  1783. var
  1784. o: TObject;
  1785. begin
  1786. o:=TObject(Obj);
  1787. if o=nil then exit;
  1788. TObject(Obj):=nil;
  1789. o.Destroy;
  1790. end;
  1791. { EVariantError }
  1792. constructor EVariantError.CreateCode(Code: Longint);
  1793. begin
  1794. ErrCode:=Code;
  1795. end;
  1796. { Exception }
  1797. constructor Exception.Create(const Msg: String);
  1798. begin
  1799. fMessage:=Msg;
  1800. end;
  1801. constructor Exception.CreateFmt(const Msg: string; const Args: array of JSValue);
  1802. begin
  1803. //writeln('Exception.CreateFmt START ',ClassName,' "',Msg,'" Args=',Args);
  1804. fMessage:=Format(Msg,Args);
  1805. //writeln('Exception.CreateFmt END ',ClassName,' "',Msg,'" fMessage=',fMessage);
  1806. end;
  1807. constructor Exception.CreateHelp(const Msg: String; AHelpContext: Integer);
  1808. begin
  1809. fMessage:=Msg;
  1810. fHelpContext:=AHelpContext;
  1811. end;
  1812. constructor Exception.CreateFmtHelp(const Msg: string;
  1813. const Args: array of JSValue; AHelpContext: Integer);
  1814. begin
  1815. fMessage:=Format(Msg,Args);
  1816. fHelpContext:=AHelpContext;
  1817. end;
  1818. function Exception.ToString: String;
  1819. begin
  1820. Result:=ClassName+': '+Message;
  1821. end;
  1822. Const
  1823. RESpecials = '([\[\]\(\)\\\.\*])';
  1824. Function StringReplace(aOriginal, aSearch, aReplace : string; Flags : TStringReplaceFlags) : String;
  1825. Var
  1826. REFlags : String;
  1827. REString : String;
  1828. begin
  1829. REFlags:='';
  1830. if rfReplaceAll in flags then
  1831. ReFlags:='g';
  1832. if rfIgnoreCase in flags then
  1833. ReFlags:=ReFlags+'i';
  1834. REString:=TJSString(aSearch).replace(TJSRegexp.new(RESpecials,'g'),'\$1');
  1835. Result:=TJSString(aOriginal).replace(TJSRegexp.new(REString,REFlags),aReplace);
  1836. end;
  1837. Function QuoteString(aOriginal : String; AQuote : Char) : String;
  1838. begin
  1839. Result:=AQuote+StringReplace(aOriginal,aQuote,aQuote+aQuote,[rfReplaceAll])+AQuote;
  1840. end;
  1841. function QuotedStr(const s: string; QuoteChar : Char = ''''): string;
  1842. begin
  1843. Result:=QuoteString(S,QuoteChar);
  1844. end;
  1845. function DeQuoteString(aQuoted: String; AQuote: Char): String;
  1846. var
  1847. i: Integer;
  1848. begin
  1849. Result:=aQuoted;
  1850. if TJSString(Result).substr(0,1)<>AQuote then exit;
  1851. Result:=TJSString(Result).slice(1);
  1852. i:=1;
  1853. while i<=length(Result) do
  1854. begin
  1855. if Result[i]=AQuote then
  1856. begin
  1857. if (i=length(Result)) or (Result[i+1]<>AQuote) then
  1858. begin
  1859. Result:=TJSString(Result).slice(0,i-1);
  1860. exit;
  1861. end
  1862. else
  1863. Result:=TJSString(Result).slice(0,i-1)+TJSString(Result).slice(i);
  1864. end
  1865. else
  1866. inc(i);
  1867. end;
  1868. end;
  1869. function IsDelimiter(const Delimiters, S: string; Index: Integer): Boolean;
  1870. begin
  1871. Result:=False;
  1872. if (Index>0) and (Index<=Length(S)) then
  1873. Result:=Pos(S[Index],Delimiters)<>0; // Note we don't do MBCS yet
  1874. end;
  1875. function AdjustLineBreaks(const S: string): string;
  1876. begin
  1877. Result:=AdjustLineBreaks(S,DefaultTextLineBreakStyle);
  1878. end;
  1879. function AdjustLineBreaks(const S: string; Style: TTextLineBreakStyle): string;
  1880. var
  1881. I,L: Longint;
  1882. Res : String;
  1883. Procedure Add(C : Char);
  1884. begin
  1885. Res:=Res+C;
  1886. end;
  1887. begin
  1888. I:=0;
  1889. L:=Length(S);
  1890. Result:='';
  1891. While (I<=L) do
  1892. case S[I] of
  1893. #10: begin
  1894. if Style in [tlbsCRLF,tlbsCR] then
  1895. Add(#13);
  1896. if Style=tlbsCRLF then
  1897. Add(#10);
  1898. Inc(I);
  1899. end;
  1900. #13: begin
  1901. if Style=tlbsCRLF then
  1902. Add(#13);
  1903. Add(#10);
  1904. Inc(I);
  1905. if S[I]=#10 then
  1906. Inc(I);
  1907. end;
  1908. else
  1909. Add(S[i]);
  1910. Inc(I);
  1911. end;
  1912. Result:=Res;
  1913. end;
  1914. function WrapText(const Line, BreakStr: string; const BreakChars: Array of char; MaxCol: Integer): string;
  1915. const
  1916. Quotes = ['''', '"'];
  1917. Var
  1918. L : String;
  1919. C,LQ,BC : Char;
  1920. P,BLen,Len : Integer;
  1921. HB,IBC : Boolean;
  1922. begin
  1923. Result:='';
  1924. L:=Line;
  1925. Blen:=Length(BreakStr);
  1926. If (BLen>0) then
  1927. BC:=BreakStr[1]
  1928. else
  1929. BC:=#0;
  1930. Len:=Length(L);
  1931. While (Len>0) do
  1932. begin
  1933. P:=1;
  1934. LQ:=#0;
  1935. HB:=False;
  1936. IBC:=False;
  1937. While ((P<=Len) and ((P<=MaxCol) or not IBC)) and ((LQ<>#0) or Not HB) do
  1938. begin
  1939. C:=L[P];
  1940. If (C=LQ) then
  1941. LQ:=#0
  1942. else If (C in Quotes) then
  1943. LQ:=C;
  1944. If (LQ<>#0) then
  1945. Inc(P)
  1946. else
  1947. begin
  1948. HB:=((C=BC) and (BreakStr=Copy(L,P,BLen)));
  1949. If HB then
  1950. Inc(P,Blen)
  1951. else
  1952. begin
  1953. If (P>=MaxCol) then
  1954. IBC:=CharInSet(C,BreakChars);
  1955. Inc(P);
  1956. end;
  1957. end;
  1958. // Writeln('"',C,'" : IBC : ',IBC,' HB : ',HB,' LQ : ',LQ,' P>MaxCol : ',P>MaxCol);
  1959. end;
  1960. Result:=Result+Copy(L,1,P-1);
  1961. Delete(L,1,P-1);
  1962. Len:=Length(L);
  1963. If (Len>0) and Not HB then
  1964. Result:=Result+BreakStr;
  1965. end;
  1966. end;
  1967. function WrapText(const Line: string; MaxCol: Integer): string;
  1968. begin
  1969. Result:=WrapText(Line,sLineBreak, [' ', '-', #9], MaxCol);
  1970. end;
  1971. function GetEnvironmentVariable(const EnvVar: String): String;
  1972. begin
  1973. if Assigned(OnGetEnvironmentVariable) then
  1974. Result:=OnGetEnvironmentVariable(EnvVar)
  1975. else
  1976. Result:='';
  1977. end;
  1978. function GetEnvironmentVariableCount: Integer;
  1979. begin
  1980. if Assigned(OnGetEnvironmentVariableCount) then
  1981. Result:=OnGetEnvironmentVariableCount()
  1982. else
  1983. Result:=0;
  1984. end;
  1985. function GetEnvironmentString(Index: Integer): String;
  1986. begin
  1987. if Assigned(OnGetEnvironmentString) then
  1988. Result:=OnGetEnvironmentString(Index)
  1989. else
  1990. Result:='';
  1991. end;
  1992. { Date/Time routines}
  1993. Function DoEncodeDate(Year, Month, Day: Word): longint;
  1994. Var
  1995. D : TDateTime;
  1996. begin
  1997. If TryEncodeDate(Year,Month,Day,D) then
  1998. Result:=Trunc(D)
  1999. else
  2000. Result:=0;
  2001. end;
  2002. function DoEncodeTime(Hour, Minute, Second, MilliSecond: word): TDateTime;
  2003. begin
  2004. If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then
  2005. Result:=0;
  2006. end;
  2007. Function DateTimeToJSDate(aDateTime : TDateTime) : TJSDate;
  2008. Var
  2009. Y,M,D,h,n,s,z : Word;
  2010. begin
  2011. DecodeDate(Trunc(aDateTime),Y,M,D);
  2012. DecodeTime(Frac(aDateTime),H,N,S,Z);
  2013. Result:=TJSDate.New(Y,M,D,h,n,s,z);
  2014. end;
  2015. Function JSDatetoDateTime(ADate: TJSDate) : TDateTime;
  2016. begin
  2017. Result:=EncodeDate(ADate.FullYear,ADate.Month+1,ADate.Date) +
  2018. EncodeTime(ADate.Hours,ADate.Minutes,ADate.Seconds,ADate.Milliseconds);
  2019. end;
  2020. { ComposeDateTime converts a Date and a Time into one TDateTime }
  2021. function ComposeDateTime(Date,Time : TDateTime) : TDateTime;
  2022. begin
  2023. if Date < 0 then
  2024. Result := trunc(Date) - Abs(frac(Time))
  2025. else
  2026. Result := trunc(Date) + Abs(frac(Time));
  2027. end;
  2028. Function TryEncodeDate(Year,Month,Day : Word; Out Date : TDateTime) : Boolean;
  2029. var
  2030. c, ya: LongWord;
  2031. begin
  2032. Result:=(Year>0) and (Year<10000) and
  2033. (Month >= 1) and (Month<=12) and
  2034. (Day>0) and (Day<=MonthDays[IsleapYear(Year),Month]);
  2035. If Result then
  2036. begin
  2037. if month > 2 then
  2038. Dec(Month,3)
  2039. else
  2040. begin
  2041. Inc(Month,9);
  2042. Dec(Year);
  2043. end;
  2044. c:= Year DIV 100;
  2045. ya:= Year - 100*c;
  2046. Date := (146097*c) SHR 2 + (1461*ya) SHR 2 + (153*LongWord(Month)+2) DIV 5 + LongWord(Day);
  2047. // Note that this line can't be part of the line above, since TDateTime is
  2048. // signed and c and ya are not
  2049. Date := Date - 693900;
  2050. end
  2051. end;
  2052. function TryEncodeTime(Hour, Min, Sec, MSec:word; Out Time : TDateTime) : boolean;
  2053. begin
  2054. Result:=(Hour<24) and (Min<60) and (Sec<60) and (MSec<1000);
  2055. If Result then
  2056. Time:=TDateTime(LongWord(Hour)*3600000+LongWord(Min)*60000+LongWord(Sec)*1000+MSec)/MSecsPerDay;
  2057. end;
  2058. { EncodeDate packs three variables Year, Month and Day into a
  2059. TDateTime value the result is the number of days since 12/30/1899 }
  2060. function EncodeDate(Year, Month, Day: word): TDateTime;
  2061. begin
  2062. If Not TryEncodeDate(Year,Month,Day,Result) then
  2063. Raise EConvertError.CreateFmt('%s-%s-%s is not a valid date specification',
  2064. [IntToStr(Year),IntToStr(Month),IntToStr(Day)]);
  2065. end;
  2066. { EncodeTime packs four variables Hour, Minute, Second and MilliSecond into
  2067. a TDateTime value }
  2068. function EncodeTime(Hour, Minute, Second, MilliSecond:word):TDateTime;
  2069. begin
  2070. If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then
  2071. Raise EConvertError.CreateFmt('%s:%s:%s.%s is not a valid time specification',
  2072. [IntToStr(Hour),IntToStr(Minute),IntToStr(Second),IntToStr(MilliSecond)]);
  2073. end;
  2074. { DecodeDate unpacks the value Date into three values:
  2075. Year, Month and Day }
  2076. procedure DecodeDate(Date: TDateTime; out Year, Month, Day: word);
  2077. var
  2078. ly,ld,lm,j : LongWord;
  2079. begin
  2080. if Date <= -datedelta then // If Date is before 1-1-1 then return 0-0-0
  2081. begin
  2082. Year := 0;
  2083. Month := 0;
  2084. Day := 0;
  2085. end
  2086. else
  2087. begin
  2088. if Date>0 then
  2089. Date:=(Date+(1/(msecsperday*2)))
  2090. else
  2091. Date:=Date-(1/(msecsperday*2));
  2092. if Date>MaxDateTime then
  2093. Date:=MaxDateTime;
  2094. // Raise EConvertError.CreateFmt('%f is not a valid TDatetime encoding, maximum value is %f.',[Date,MaxDateTime]);
  2095. j := ((Trunc(Date) + 693900) SHL 2)-1;
  2096. ly:= j DIV 146097;
  2097. j:= j - 146097 * LongWord(ly);
  2098. ld := j SHR 2;
  2099. j:=(ld SHL 2 + 3) DIV 1461;
  2100. ld:= ((ld SHL 2) + 7 - 1461*j) SHR 2;
  2101. lm:=(5 * ld-3) DIV 153;
  2102. ld:= (5 * ld +2 - 153*lm) DIV 5;
  2103. ly:= 100 * LongWord(ly) + j;
  2104. if lm < 10 then
  2105. inc(lm,3)
  2106. else
  2107. begin
  2108. dec(lm,9);
  2109. inc(ly);
  2110. end;
  2111. year:=ly;
  2112. month:=lm;
  2113. day:=ld;
  2114. end;
  2115. end;
  2116. function DecodeDateFully(const DateTime: TDateTime; out Year, Month, Day, DOW: Word): Boolean;
  2117. begin
  2118. DecodeDate(DateTime,Year,Month,Day);
  2119. DOW:=DayOfWeek(DateTime);
  2120. Result:=IsLeapYear(Year);
  2121. end;
  2122. { DateTimeToTimeStamp converts DateTime to a TTimeStamp }
  2123. function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp;
  2124. Var
  2125. D : Double;
  2126. begin
  2127. D:=DateTime * Double(MSecsPerDay);
  2128. if D<0 then
  2129. D:=D-0.5
  2130. else
  2131. D:=D+0.5;
  2132. result.Time := Trunc(Abs(Trunc(D)) Mod MSecsPerDay);
  2133. result.Date := DateDelta + (Trunc(D) div MSecsPerDay);
  2134. end;
  2135. { TimeStampToDateTime converts TimeStamp to a TDateTime value }
  2136. function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
  2137. begin
  2138. Result := ComposeDateTime(TimeStamp.Date - DateDelta,TimeStamp.Time/MSecsPerDay)
  2139. end;
  2140. { MSecsToTimeStamp }
  2141. function MSecsToTimeStamp(MSecs: NativeInt): TTimeStamp;
  2142. begin
  2143. result.Date := Trunc(msecs/msecsperday);
  2144. msecs:= msecs-NativeInt(result.date)*msecsperday;
  2145. result.Time := Round(MSecs);
  2146. end;
  2147. function TimeStampToMSecs(const TimeStamp: TTimeStamp): NativeInt;
  2148. begin
  2149. result := TimeStamp.Time + (timestamp.date*msecsperday);
  2150. end ;
  2151. { DecodeTime unpacks Time into four values:
  2152. Hour, Minute, Second and MilliSecond }
  2153. procedure DecodeTime(Time: TDateTime; out Hour, Minute, Second, MilliSecond: word);
  2154. Var
  2155. l : LongWord;
  2156. begin
  2157. l := DateTimeToTimeStamp(Time).Time;
  2158. Hour := l div 3600000;
  2159. l := l mod 3600000;
  2160. Minute := l div 60000;
  2161. l := l mod 60000;
  2162. Second := l div 1000;
  2163. l := l mod 1000;
  2164. MilliSecond := l;
  2165. end;
  2166. { DateTimeToSystemTime converts DateTime value to SystemTime }
  2167. procedure DateTimeToSystemTime(DateTime: TDateTime; out SystemTime: TSystemTime);
  2168. begin
  2169. DecodeDateFully(DateTime, SystemTime.Year, SystemTime.Month, SystemTime.Day,SystemTime.DayOfWeek);
  2170. DecodeTime(DateTime, SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond);
  2171. Dec(SystemTime.DayOfWeek);
  2172. end ;
  2173. { SystemTimeToDateTime converts SystemTime to a TDateTime value }
  2174. function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
  2175. begin
  2176. result := ComposeDateTime(DoEncodeDate(SystemTime.Year, SystemTime.Month, SystemTime.Day),
  2177. DoEncodeTime(SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond));
  2178. end ;
  2179. function DayOfWeek(DateTime: TDateTime): integer;
  2180. begin
  2181. Result := 1 + ((Trunc(DateTime) - 1) mod 7);
  2182. If (Result<=0) then
  2183. Inc(Result,7);
  2184. end;
  2185. function Now: TDateTime;
  2186. begin
  2187. Result:=JSDateToDateTime(TJSDate.New());
  2188. end;
  2189. function Date: TDateTime;
  2190. begin
  2191. Result:=Trunc(Now);
  2192. end;
  2193. function Time: TDateTime;
  2194. begin
  2195. Result:=Now-Date;
  2196. end ;
  2197. { IncMonth increments DateTime with NumberOfMonths months,
  2198. NumberOfMonths can be less than zero }
  2199. function IncMonth(const DateTime: TDateTime; NumberOfMonths: integer = 1 ): TDateTime;
  2200. var
  2201. Year, Month, Day : word;
  2202. begin
  2203. DecodeDate(DateTime, Year, Month, Day);
  2204. IncAMonth(Year, Month, Day, NumberOfMonths);
  2205. result := ComposeDateTime(DoEncodeDate(Year, Month, Day), DateTime);
  2206. end ;
  2207. { IncAMonth is the same as IncMonth, but operates on decoded date }
  2208. procedure IncAMonth(var Year, Month, Day: Word; NumberOfMonths: Integer = 1);
  2209. var
  2210. TempMonth, S: Integer;
  2211. begin
  2212. If NumberOfMonths>=0 then
  2213. s:=1
  2214. else
  2215. s:=-1;
  2216. inc(Year,(NumberOfMonths div 12));
  2217. TempMonth:=Month+(NumberOfMonths mod 12)-1;
  2218. if (TempMonth>11) or
  2219. (TempMonth<0) then
  2220. begin
  2221. Dec(TempMonth, S*12);
  2222. Inc(Year, S);
  2223. end;
  2224. Month:=TempMonth+1; { Months from 1 to 12 }
  2225. If (Day>MonthDays[IsLeapYear(Year)][Month]) then
  2226. Day:=MonthDays[IsLeapYear(Year)][Month];
  2227. end;
  2228. { IsLeapYear returns true if Year is a leap year }
  2229. function IsLeapYear(Year: Word): boolean;
  2230. begin
  2231. Result := (Year mod 4 = 0) and ((Year mod 100 <> 0) or (Year mod 400 = 0));
  2232. end;
  2233. { DateToStr returns a string representation of Date using ShortDateFormat }
  2234. function DateToStr(Date: TDateTime): string;
  2235. begin
  2236. Result:=FormatDateTime('ddddd', Date);
  2237. end ;
  2238. { TimeToStr returns a string representation of Time using LongTimeFormat }
  2239. function TimeToStr(Time: TDateTime): string;
  2240. begin
  2241. Result:=FormatDateTime('tt',Time);
  2242. end ;
  2243. { DateTimeToStr returns a string representation of DateTime using LongDateTimeFormat }
  2244. Var
  2245. DateTimeToStrFormat : Array[Boolean] of string = ('c','f');
  2246. function DateTimeToStr(DateTime: TDateTime; ForceTimeIfZero : Boolean = False): string;
  2247. begin
  2248. Result:=FormatDateTime(DateTimeToStrFormat[ForceTimeIfZero], DateTime)
  2249. end ;
  2250. { StrToDate converts the string S to a TDateTime value
  2251. if S does not represent a valid date value
  2252. an EConvertError will be raised }
  2253. function IntStrToDate(Out ErrorMsg : String; const S: String; const useformat : string; separator : char): TDateTime;
  2254. Const
  2255. WhiteSpace = ' '#8#9#10#12#13;
  2256. Digits = '0123456789';
  2257. procedure FixErrorMsg(const errmarg : String);
  2258. begin
  2259. ErrorMsg:=Format(SInvalidDateFormat,[errmarg]);
  2260. end;
  2261. var
  2262. df:string;
  2263. d,m,y,ly,ld,lm:word;
  2264. n,i,len:longint;
  2265. c: integer;
  2266. dp,mp,yp,which : Byte;
  2267. s1:string;
  2268. values: array of integer;
  2269. YearMoreThenTwoDigits : boolean;
  2270. begin
  2271. SetLength(values,4);
  2272. Result:=0;
  2273. Len:=Length(S);
  2274. ErrorMsg:='';
  2275. While (Len>0) and (Pos(S[Len],WhiteSpace)>0) do
  2276. Dec(len);
  2277. if (Len=0) then
  2278. begin
  2279. FixErrorMsg(S);
  2280. exit;
  2281. end;
  2282. YearMoreThenTwoDigits := False;
  2283. if separator = #0 then
  2284. if (DateSeparator<>#0) then
  2285. separator := DateSeparator
  2286. else
  2287. separator:='-';
  2288. // Writeln('Separator: ',Separator);
  2289. df := UpperCase(useFormat);
  2290. { Determine order of D,M,Y }
  2291. yp:=0;
  2292. mp:=0;
  2293. dp:=0;
  2294. Which:=0;
  2295. i:=0;
  2296. while (i<Length(df)) and (Which<3) do
  2297. begin
  2298. inc(i);
  2299. Case df[i] of
  2300. 'Y' :
  2301. if yp=0 then
  2302. begin
  2303. Inc(Which);
  2304. yp:=which;
  2305. end;
  2306. 'M' :
  2307. if mp=0 then
  2308. begin
  2309. Inc(Which);
  2310. mp:=which;
  2311. end;
  2312. 'D' :
  2313. if dp=0 then
  2314. begin
  2315. Inc(Which);
  2316. dp:=which;
  2317. end;
  2318. end;
  2319. end;
  2320. // Writeln('YP: ',Yp,', MP: ',Mp,', DP: ',DP);
  2321. for i := 1 to 3 do
  2322. values[i] := 0;
  2323. s1 := '';
  2324. n := 0;
  2325. for i := 1 to len do
  2326. begin
  2327. if Pos(s[i],Digits)>0 then
  2328. s1 := s1 + s[i];
  2329. { space can be part of the shortdateformat, and is defaultly in slovak
  2330. windows, therefor it shouldn't be taken as separator (unless so specified)
  2331. and ignored }
  2332. if (Separator <> ' ') and (s[i] = ' ') then
  2333. Continue;
  2334. if (s[i] = separator) or ((i = len) and (Pos(s[i],Digits)>0)) then
  2335. begin
  2336. inc(n);
  2337. if n>3 then
  2338. begin
  2339. // Writeln('More than 3 separators');
  2340. FixErrorMsg(S);
  2341. exit;
  2342. end;
  2343. // Check if the year has more then two digits (if n=yp, then we are evaluating the year.)
  2344. if (n=yp) and (length(s1)>2) then YearMoreThenTwoDigits := True;
  2345. val(s1, values[n], c);
  2346. if c<>0 then
  2347. begin
  2348. // Writeln('S1 not a number ',S1);
  2349. FixErrorMsg(s);
  2350. Exit;
  2351. end;
  2352. s1 := '';
  2353. end
  2354. else if (Pos(s[i],Digits)=0) then
  2355. begin
  2356. // Writeln('Not a number at pos ',I,' ',S[i]);
  2357. FixErrorMsg(s);
  2358. Exit;
  2359. end;
  2360. end ;
  2361. // Writeln('Which : ',Which,' N : ',N);
  2362. if (Which<3) and (N>Which) then
  2363. begin
  2364. FixErrorMsg(s);
  2365. Exit;
  2366. end;
  2367. // Fill in values.
  2368. DecodeDate(Date,Ly,LM,LD);
  2369. If N=3 then
  2370. begin
  2371. y:=values[yp];
  2372. m:=values[mp];
  2373. d:=values[dp];
  2374. end
  2375. Else
  2376. begin
  2377. Y:=ly;
  2378. If n<2 then
  2379. begin
  2380. d:=values[1];
  2381. m := LM;
  2382. end
  2383. else
  2384. If dp<mp then
  2385. begin
  2386. d:=values[1];
  2387. m:=values[2];
  2388. end
  2389. else
  2390. begin
  2391. d:=values[2];
  2392. m:=values[1];
  2393. end;
  2394. end;
  2395. if (y >= 0) and (y < 100) and not YearMoreThenTwoDigits then
  2396. begin
  2397. ly := ly - TwoDigitYearCenturyWindow;
  2398. Inc(Y, ly div 100 * 100);
  2399. if (TwoDigitYearCenturyWindow > 0) and (Y < ly) then
  2400. Inc(Y, 100);
  2401. end;
  2402. if not TryEncodeDate(y, m, d, result) then
  2403. errormsg:=SErrInvalidDate;
  2404. end;
  2405. function StrToDate(const S: String; const useformat : string; separator : char): TDateTime;
  2406. Var
  2407. MSg : String;
  2408. begin
  2409. Result:=IntStrToDate(Msg,S,useFormat,Separator);
  2410. If (Msg<>'') then
  2411. Raise EConvertError.Create(Msg);
  2412. end;
  2413. function StrToDate(const S: String; separator : char): TDateTime;
  2414. begin
  2415. result := StrToDate(S,ShortDateFormat,separator)
  2416. end;
  2417. function StrToDate(const S: String): TDateTime;
  2418. begin
  2419. result := StrToDate(S,ShortDateFormat,#0);
  2420. end;
  2421. { StrToTime converts the string S to a TDateTime value
  2422. if S does not represent a valid time value an
  2423. EConvertError will be raised }
  2424. function IntStrToTime(Out ErrorMsg : String; const S: String; Len : integer; separator : char): TDateTime;
  2425. const
  2426. AMPM_None = 0;
  2427. AMPM_AM = 1;
  2428. AMPM_PM = 2;
  2429. tiHour = 0;
  2430. tiMin = 1;
  2431. tiSec = 2;
  2432. tiMSec = 3;
  2433. type
  2434. TTimeValues = array of Word;
  2435. var
  2436. AmPm: integer;
  2437. TimeValues: TTimeValues;
  2438. function SplitElements(out TimeValues: TTimeValues; out AmPm: Integer): Boolean;
  2439. //Strict version. It does not allow #32 as Separator, it will treat it as whitespace always
  2440. const
  2441. Digits = '0123456789';
  2442. var
  2443. Cur, Offset, ElemLen, Err, TimeIndex, FirstSignificantDigit: Integer;
  2444. Value: Integer;
  2445. DigitPending, MSecPending: Boolean;
  2446. AmPmStr: String;
  2447. CurChar: Char;
  2448. I : Integer;
  2449. allowedchars : string;
  2450. begin
  2451. Result := False;
  2452. AmPm := AMPM_None; //No Am or PM in string found yet
  2453. MSecPending := False;
  2454. TimeIndex := 0; //indicating which TTimeValue must be filled next
  2455. For I:=tiHour to tiMSec do
  2456. TimeValues[i]:=0;
  2457. Cur := 1;
  2458. //skip leading blanks
  2459. While (Cur < Len) and (S[Cur] =#32) do Inc(Cur);
  2460. Offset := Cur;
  2461. //First non-blank cannot be Separator or DecimalSeparator
  2462. if (Cur > Len - 1) or (S[Cur] = Separator) or (S[Cur] = Decimalseparator) then
  2463. begin
  2464. // Writeln('Error in sep S[Cur]',S[Cur],' ',separator,' ',GetDecimalSeparator);
  2465. Exit;
  2466. end;
  2467. DigitPending := (Pos(S[Cur],Digits)>0);
  2468. While (Cur <= Len) do
  2469. begin
  2470. //writeln;
  2471. // writeln('Main While loop: Cur = ',Cur,' S[Cur] = "',S[Cur],'" Len = ',Len,' separator : ',Separator);
  2472. CurChar := S[Cur];
  2473. if Pos(CurChar,Digits)>0 then
  2474. begin//Digits
  2475. //HH, MM, SS, or Msec?
  2476. // writeln('Digit: ', CurChar);
  2477. //Digits are only allowed after starting Am/PM or at beginning of string or after Separator
  2478. //and TimeIndex must be <= tiMSec
  2479. //Uncomment "or (#32 = Separator)" and it will allllow #32 as separator
  2480. if (not (DigitPending {or (#32 = Separator)})) or (TimeIndex > tiMSec) then
  2481. begin
  2482. // Writeln('DigitPending',ElemLen);
  2483. Exit;
  2484. end;
  2485. OffSet := Cur;
  2486. if (CurChar <> '0') then FirstSignificantDigit := OffSet else FirstSignificantDigit := -1;
  2487. while (Cur < Len) and (Pos(S[Cur + 1],Digits)>0) do
  2488. begin
  2489. //Mark first Digit that is not '0'
  2490. if (FirstSignificantDigit = -1) and (S[Cur] <> '0') then FirstSignificantDigit := Cur;
  2491. Inc(Cur);
  2492. end;
  2493. if (FirstSignificantDigit = -1) then FirstSignificantDigit := Cur;
  2494. ElemLen := 1+ Cur - FirstSignificantDigit;
  2495. // writeln(' S[FirstSignificantDigit] = ',S[FirstSignificantDigit], ' S[Cur] = ',S[Cur],' ElemLen = ',ElemLen,' -> ', S[Offset], ElemLen);
  2496. // writeln(' Cur = ',Cur);
  2497. //this way we know that Val() will never overflow Value !
  2498. if (ElemLen <= 2) or ((ElemLen <= 3) and (TimeIndex = tiMSec) ) then
  2499. begin
  2500. Val(Copy(S,FirstSignificantDigit, ElemLen), Value, Err);
  2501. // writeln(' Value = ',Value,' HH = ',TimeValues[0],' MM = ',TimeValues[1],' SS = ',TimeValues[2],' MSec = ',Timevalues[3]);
  2502. //This is safe now, because we know Value < High(Word)
  2503. TimeValues[TimeIndex] := Value;
  2504. Inc(TimeIndex);
  2505. DigitPending := False;
  2506. end
  2507. else
  2508. begin
  2509. // Writeln('Wrong elemlen: ',ElemLen, ' timeIndex: ',timeindex);
  2510. Exit; //Value to big, so it must be a wrong timestring
  2511. end;
  2512. end//Digits
  2513. else if (CurChar = #32) then
  2514. begin
  2515. //writeln('#32');
  2516. //just skip, but we must adress this, or it will be parsed by either AM/PM or Separator
  2517. end
  2518. else if (CurChar = Separator) then
  2519. begin
  2520. // writeln('Separator ',Separator);
  2521. if DigitPending or (TimeIndex > tiSec) then
  2522. begin
  2523. // Writeln ('DigitPending ',DigitPending,' or (TimeIndex',Timeindex,' > tiSec,', tiSec,')');
  2524. Exit;
  2525. end;
  2526. DigitPending := True;
  2527. MSecPending := False;
  2528. end
  2529. else if (CurChar = DecimalSeparator) then
  2530. begin
  2531. //writeln('DecimalSeparator');
  2532. if DigitPending or MSecPending or (TimeIndex <> tiMSec) then
  2533. begin
  2534. // Writeln('DigitPending ',DigitPending,' or MSecPending ',MSecPending,' (',TimeIndex,',Timeindex, >', tiMSec,' tiSec)');
  2535. Exit;
  2536. end;
  2537. DigitPending := True;
  2538. MSecPending := True;
  2539. end
  2540. else
  2541. begin//AM/PM?
  2542. //None of the above, so this char _must_ be the start of AM/PM string
  2543. //If we already have found AM/PM or we expect a digit then then timestring must be wrong at this point
  2544. //writeln('AM/PM?');
  2545. if (AmPm <> AMPM_None) or DigitPending then
  2546. begin
  2547. // Writeln('AmPm <> AMPM_None) or DigitPending');
  2548. Exit;
  2549. end;
  2550. OffSet := Cur;
  2551. allowedchars:=DecimalSeparator+' ';
  2552. if Separator<>#0 then
  2553. allowedchars:=allowedchars+Separator;
  2554. while (Cur < Len -1) and (Pos(S[Cur + 1],AllowedChars)=0)
  2555. and (Pos(S[Cur + 1],Digits)=0) do Inc(Cur);
  2556. ElemLen := 1 + Cur - OffSet;
  2557. // writeln(' S[Offset] = ',S[1+Offset], ' S[Cur] = ',S[Cur],' ElemLen = ',ElemLen,' -> ', S[1+Offset], ElemLen);
  2558. // writeln(' Cur = ',Cur, 'S =',S);
  2559. AmPmStr := Copy(S,1+OffSet, ElemLen);
  2560. // writeln('AmPmStr = ',ampmstr,' (',length(ampmstr),')');
  2561. //We must compare to TimeAMString before hardcoded 'AM' for delphi compatibility
  2562. //Also it is perfectly legal, though insane to have TimeAMString = 'PM' and vice versa
  2563. if (CompareText(AmPmStr, TimeAMString) = 0) then AmPm := AMPM_AM
  2564. else if (CompareText(AmPmStr, TimePMString) = 0) then AmPm := AMPM_PM
  2565. else if (CompareText(AmPmStr, 'AM') = 0) then AmPm := AMPM_AM
  2566. else if (CompareText(AmPmStr, 'PM') = 0) then AmPm := AMPM_PM
  2567. else
  2568. begin
  2569. // Writeln('No timestring ',AmPmStr);
  2570. Exit; //If text does not match any of these, timestring must be wrong;
  2571. end;
  2572. //if AM/PM is at beginning of string, then a digit is mandatory after it
  2573. if (TimeIndex = tiHour) then
  2574. begin
  2575. DigitPending := True;
  2576. end
  2577. //otherwise, no more TimeValues allowed after this
  2578. else
  2579. begin
  2580. TimeIndex := tiMSec + 1;
  2581. DigitPending := False;
  2582. end;
  2583. end;//AM/PM
  2584. Inc(Cur)
  2585. end;//while
  2586. //If we arrive here, parsing the elements has been successfull
  2587. //if not at least Hours specified then input is not valid
  2588. //when am/pm is specified Hour must be <= 12 and not 0
  2589. if (TimeIndex = tiHour) or ((AmPm <> AMPM_None) and ((TimeValues[tiHour] > 12) or (TimeValues[tiHour] = 0))) or DigitPending then
  2590. Exit;
  2591. Result := True;
  2592. end;
  2593. begin
  2594. setlength(timevalues,4);
  2595. if separator = #0 then
  2596. if (TimeSeparator<>#0) then
  2597. separator := TimeSeparator
  2598. else
  2599. separator:=':';
  2600. AmPm := AMPM_None;
  2601. if not SplitElements(TimeValues, AmPm) then
  2602. begin
  2603. ErrorMsg:=Format(SErrInvalidTimeFormat,[S]);
  2604. Exit;
  2605. end;
  2606. if (AmPm=AMPM_PM) and (TimeValues[tiHour]<>12) then Inc(TimeValues[tiHour], 12)
  2607. else if (AmPm=AMPM_AM) and (TimeValues[tiHour]=12) then TimeValues[tiHour]:=0;
  2608. // Writeln( TimeValues[tiHour], TimeValues[tiMin], TimeValues[tiSec], TimeValues[tiMSec]);
  2609. if not TryEncodeTime(TimeValues[tiHour], TimeValues[tiMin], TimeValues[tiSec], TimeValues[tiMSec], result) Then
  2610. ErrorMsg:=Format(SErrInvalidTimeFormat,[S]);
  2611. end ;
  2612. function StrToTime(const s: String; separator : char): TDateTime;
  2613. Var
  2614. Msg : String;
  2615. begin
  2616. Result:=IntStrToTime(Msg,S,Length(S),Separator);
  2617. If (Msg<>'') then
  2618. Raise EConvertError.Create(Msg);
  2619. end;
  2620. function StrToTime(const s: String): TDateTime;
  2621. begin
  2622. result:= StrToTime(s, TimeSeparator);
  2623. end;
  2624. { StrToDateTime converts the string S to a TDateTime value
  2625. if S does not represent a valid date and/or time value
  2626. an EConvertError will be raised }
  2627. function SplitDateTimeStr(DateTimeStr: String; out DateStr, TimeStr: String): Integer;
  2628. { Helper function for StrToDateTime
  2629. Pre-condition
  2630. Date is before Time
  2631. If either Date or Time is omitted then see what fits best, a time or a date (issue #0020522)
  2632. Date and Time are separated by whitespace (space Tab, Linefeed or carriage return)
  2633. FS.DateSeparator can be the same as FS.TimeSeparator (issue #0020522)
  2634. If they are both #32 and TrimWhite(DateTimeStr) contains a #32 a date is assumed.
  2635. Post-condition
  2636. DateStr holds date as string or is empty
  2637. TimeStr holds time as string or is empty
  2638. Result = number of strings returned, 0 = error
  2639. }
  2640. const
  2641. WhiteSpace = #9#10#13#32;
  2642. var
  2643. p: Integer;
  2644. DummyDT: TDateTime;
  2645. begin
  2646. Result := 0;
  2647. DateStr := '';
  2648. TimeStr := '';
  2649. DateTimeStr := Trim(DateTimeStr);
  2650. if Length(DateTimeStr) = 0 then exit;
  2651. if (DateSeparator = #32) and (TimeSeparator = #32) and (Pos(#32, DateTimeStr) > 0) then
  2652. begin
  2653. DateStr:=DateTimeStr;
  2654. {
  2655. Assume a date: dd [mm [yy]].
  2656. Really fancy would be counting the number of whitespace occurrences and decide
  2657. and split accordingly
  2658. }
  2659. Exit(1);
  2660. end;
  2661. p:=1;
  2662. //find separator
  2663. if (DateSeparator<>#32) then
  2664. begin
  2665. while (p<Length(DateTimeStr)) and (not (Pos(DateTimeStr[p+1],WhiteSpace)>0)) do
  2666. Inc(p);
  2667. end
  2668. else
  2669. begin
  2670. p:=Pos(TimeSeparator, DateTimeStr);
  2671. if (p<>0) then
  2672. repeat
  2673. Dec(p);
  2674. until (p=0) or (Pos(DateTimeStr[p],WhiteSpace)>0);
  2675. end;
  2676. //Always fill DateStr, it eases the algorithm later
  2677. if (p=0) then
  2678. p:=Length(DateTimeStr);
  2679. DateStr:=Copy(DateTimeStr,1,p);
  2680. TimeStr:=Trim(Copy(DateTimeStr,p+1,100));
  2681. if (Length(TimeStr)<>0) then
  2682. Result:=2
  2683. else
  2684. begin
  2685. Result:=1; //found 1 string
  2686. // 2 cases when DateTimeStr only contains a time:
  2687. // Date/time separator differ, and string contains a timeseparator
  2688. // Date/time separators are equal, but transformation to date fails.
  2689. if ((DateSeparator<>TimeSeparator) and (Pos(TimeSeparator,DateStr) > 0))
  2690. or ((DateSeparator=TimeSeparator) and (not TryStrToDate(DateStr, DummyDT))) then
  2691. begin
  2692. TimeStr := DateStr;
  2693. DateStr := '';
  2694. end;
  2695. end;
  2696. end;
  2697. function StrToDateTime(const s: String): TDateTime;
  2698. var
  2699. TimeStr, DateStr: String;
  2700. PartsFound: Integer;
  2701. begin
  2702. PartsFound := SplitDateTimeStr(S, DateStr, TimeStr);
  2703. case PartsFound of
  2704. 0: Result:=StrToDate('');
  2705. 1: if (Length(DateStr) > 0) then
  2706. Result := StrToDate(DateStr,ShortDateFormat,DateSeparator)
  2707. else
  2708. Result := StrToTime(TimeStr);
  2709. 2: Result := ComposeDateTime(StrTodate(DateStr,ShortDateFormat,DateSeparator),
  2710. StrToTime(TimeStr));
  2711. end;
  2712. end;
  2713. Function FormatDateTime(const FormatStr: string; const DateTime: TDateTime) : String;
  2714. procedure StoreStr(APos,Len: Integer);
  2715. begin
  2716. // Writeln('StoreStr: ',Result,'+',Copy(FormatStr,APos,Len));
  2717. Result:=Result+Copy(FormatStr,APos,Len);
  2718. end;
  2719. procedure StoreString(const AStr: string);
  2720. begin
  2721. // Writeln('StoreString: ',Result,'+',AStr);
  2722. Result:=Result+AStr;
  2723. end;
  2724. procedure StoreInt(Value, Digits: Integer);
  2725. var
  2726. S: string;
  2727. begin
  2728. S:=IntToStr(Value);
  2729. While (Length(S)<Digits) do
  2730. S:='0'+S;
  2731. StoreString(S);
  2732. end;
  2733. var
  2734. Year, Month, Day, DayOfWeek, Hour, Minute, Second, MilliSecond: word;
  2735. procedure StoreFormat(const FormatStr: string; Nesting: Integer; TimeFlag: Boolean);
  2736. var
  2737. Token, lastformattoken, prevlasttoken: char;
  2738. Count: integer;
  2739. Clock12: boolean;
  2740. tmp: integer;
  2741. isInterval: Boolean;
  2742. P,FormatCurrent,FormatEnd : Integer;
  2743. begin
  2744. if Nesting > 1 then // 0 is original string, 1 is included FormatString
  2745. Exit;
  2746. FormatCurrent := 1;
  2747. FormatEnd := Length(FormatStr);
  2748. Clock12 := false;
  2749. isInterval := false;
  2750. // look for unquoted 12-hour clock token
  2751. P:=1;
  2752. while P<=FormatEnd do
  2753. begin
  2754. Token := FormatStr[P];
  2755. case Token of
  2756. '''', '"':
  2757. begin
  2758. Inc(P);
  2759. while (P < FormatEnd) and (FormatStr[P]<>Token) do
  2760. Inc(P);
  2761. end;
  2762. 'A', 'a':
  2763. begin
  2764. if (CompareText(Copy(FormatStr,P,3),'A/P')=0) or
  2765. (CompareText(Copy(FormatStr,P,4),'AMPM')=0) or
  2766. (CompareText(Copy(FormatStr,P,5),'AM/PM')=0) then
  2767. begin
  2768. Clock12 := true;
  2769. break;
  2770. end;
  2771. end;
  2772. end; // case
  2773. Inc(P);
  2774. end ;
  2775. token := #255;
  2776. lastformattoken := ' ';
  2777. prevlasttoken := 'H';
  2778. while FormatCurrent <= FormatEnd do
  2779. begin
  2780. Token := UpperCase(FormatStr[FormatCurrent])[1];
  2781. // Writeln('Treating token at pos ',FormatCurrent,', : ',Token,' (',FormatStr,')');
  2782. Count := 1;
  2783. P := FormatCurrent + 1;
  2784. case Token of
  2785. '''', '"':
  2786. begin
  2787. while (P < FormatEnd) and (FormatStr[P]<>Token) do
  2788. Inc(P);
  2789. Inc(P);
  2790. Count := P - FormatCurrent;
  2791. StoreStr(FormatCurrent + 1, Count - 2);
  2792. end ;
  2793. 'A':
  2794. begin
  2795. if CompareText(Copy(FormatStr,FormatCurrent,4), 'AMPM') = 0 then
  2796. begin
  2797. Count := 4;
  2798. if Hour < 12 then
  2799. StoreString(TimeAMString)
  2800. else
  2801. StoreString(TimePMString);
  2802. end
  2803. else if CompareText(Copy(FormatStr,FormatCurrent,5), 'AM/PM') = 0 then
  2804. begin
  2805. Count := 5;
  2806. if Hour < 12 then StoreStr(FormatCurrent, 2)
  2807. else StoreStr(FormatCurrent+3, 2);
  2808. end
  2809. else if CompareText(Copy(FormatStr,FormatCurrent,3), 'A/P') = 0 then
  2810. begin
  2811. Count := 3;
  2812. if Hour < 12 then StoreStr(FormatCurrent, 1)
  2813. else StoreStr(FormatCurrent+2, 1);
  2814. end
  2815. else
  2816. raise EConvertError.Create('Illegal character in format string');
  2817. end ;
  2818. '/':
  2819. begin
  2820. // Writeln('Detected date separator');
  2821. StoreString(DateSeparator);
  2822. end;
  2823. ':': StoreString(TimeSeparator);
  2824. ' ', 'C', 'D', 'H', 'M', 'N', 'S', 'T', 'Y', 'Z', 'F' :
  2825. begin
  2826. // Writeln(FormatCurrent,' Special Token: ',Token,', Count: ',Count,', P: ',P);
  2827. while (P <= FormatEnd) and (UpperCase(FormatStr[P]) = Token) do
  2828. Inc(P);
  2829. Count := P - FormatCurrent;
  2830. // Writeln(FormatCurrent,' Special Token: ',Token,', Count: ',Count,', P: ',P);
  2831. case Token of
  2832. ' ': StoreStr(FormatCurrent, Count);
  2833. 'Y': begin
  2834. if Count > 2 then
  2835. StoreInt(Year, 4)
  2836. else
  2837. StoreInt(Year mod 100, 2);
  2838. end;
  2839. 'M': begin
  2840. if isInterval and ((prevlasttoken = 'H') or TimeFlag) then
  2841. StoreInt(Minute + (Hour + trunc(abs(DateTime))*24)*60, 0)
  2842. else
  2843. if (lastformattoken = 'H') or TimeFlag then
  2844. begin
  2845. if Count = 1 then
  2846. StoreInt(Minute, 0)
  2847. else
  2848. StoreInt(Minute, 2);
  2849. end
  2850. else
  2851. begin
  2852. case Count of
  2853. 1: StoreInt(Month, 0);
  2854. 2: StoreInt(Month, 2);
  2855. 3: StoreString(ShortMonthNames[Month]);
  2856. else
  2857. StoreString(LongMonthNames[Month]);
  2858. end;
  2859. end;
  2860. end;
  2861. 'D': begin
  2862. case Count of
  2863. 1: StoreInt(Day, 0);
  2864. 2: StoreInt(Day, 2);
  2865. 3: StoreString(ShortDayNames[DayOfWeek]);
  2866. 4: StoreString(LongDayNames[DayOfWeek]);
  2867. 5: StoreFormat(ShortDateFormat, Nesting+1, False);
  2868. else
  2869. StoreFormat(LongDateFormat, Nesting+1, False);
  2870. end ;
  2871. end ;
  2872. 'H':
  2873. if isInterval then
  2874. StoreInt(Hour + trunc(abs(DateTime))*24, 0)
  2875. else
  2876. if Clock12 then
  2877. begin
  2878. tmp := hour mod 12;
  2879. if tmp=0 then tmp:=12;
  2880. if Count = 1 then
  2881. StoreInt(tmp, 0)
  2882. else
  2883. StoreInt(tmp, 2);
  2884. end
  2885. else begin
  2886. if Count = 1 then
  2887. StoreInt(Hour, 0)
  2888. else
  2889. StoreInt(Hour, 2);
  2890. end;
  2891. 'N': if isInterval then
  2892. StoreInt(Minute + (Hour + trunc(abs(DateTime))*24)*60, 0)
  2893. else
  2894. if Count = 1 then
  2895. StoreInt(Minute, 0)
  2896. else
  2897. StoreInt(Minute, 2);
  2898. 'S': if isInterval then
  2899. StoreInt(Second + (Minute + (Hour + trunc(abs(DateTime))*24)*60)*60, 0)
  2900. else
  2901. if Count = 1 then
  2902. StoreInt(Second, 0)
  2903. else
  2904. StoreInt(Second, 2);
  2905. 'Z': if Count = 1 then
  2906. StoreInt(MilliSecond, 0)
  2907. else
  2908. StoreInt(MilliSecond, 3);
  2909. 'T': if Count = 1 then
  2910. StoreFormat(ShortTimeFormat, Nesting+1, True)
  2911. else
  2912. StoreFormat(LongTimeFormat, Nesting+1, True);
  2913. 'C': begin
  2914. StoreFormat(ShortDateFormat, Nesting+1, False);
  2915. if (Hour<>0) or (Minute<>0) or (Second<>0) then
  2916. begin
  2917. StoreString(' ');
  2918. StoreFormat(LongTimeFormat, Nesting+1, True);
  2919. end;
  2920. end;
  2921. 'F': begin
  2922. StoreFormat(ShortDateFormat, Nesting+1, False);
  2923. StoreString(' ');
  2924. StoreFormat(LongTimeFormat, Nesting+1, True);
  2925. end;
  2926. end;
  2927. prevlasttoken := lastformattoken;
  2928. lastformattoken := token;
  2929. end;
  2930. else
  2931. StoreString(Token);
  2932. end ;
  2933. Inc(FormatCurrent, Count);
  2934. end;
  2935. end;
  2936. begin
  2937. DecodeDateFully(DateTime, Year, Month, Day, DayOfWeek);
  2938. DecodeTime(DateTime, Hour, Minute, Second, MilliSecond);
  2939. // Writeln(DateTime,'->',Year,',', Month, ',',Day, ',',DayOfWeek,',',Hour, ',',Minute, ',',Second, ',',MilliSecond);
  2940. if FormatStr <> '' then
  2941. StoreFormat(FormatStr, 0, False)
  2942. else
  2943. StoreFormat('C', 0, False);
  2944. end ;
  2945. function CurrentYear: Word;
  2946. begin
  2947. Result:=TJSDate.New().FullYear;
  2948. end;
  2949. function TryStrToDate(const S: String; out Value: TDateTime): Boolean;
  2950. begin
  2951. Result:=TryStrToDate(S,Value,ShortDateFormat,#0);
  2952. end;
  2953. function TryStrToDate(const S: String; out Value: TDateTime; separator : char): Boolean;
  2954. begin
  2955. Result:=TryStrToDate(S,Value,ShortDateFormat,Separator);
  2956. end;
  2957. function TryStrToDate(const S: String; out Value: TDateTime;
  2958. const useformat : string; separator : char = #0): Boolean;
  2959. Var
  2960. Msg : String;
  2961. begin
  2962. Result:=Length(S)<>0;
  2963. If Result then
  2964. begin
  2965. Value:=IntStrToDate(Msg,S,useformat,Separator);
  2966. Result:=(Msg='');
  2967. end;
  2968. end;
  2969. function TryStrToTime(const S: String; out Value: TDateTime; separator : char): Boolean;
  2970. Var
  2971. Msg : String;
  2972. begin
  2973. Result:=Length(S)<>0;
  2974. If Result then
  2975. begin
  2976. Value:=IntStrToTime(Msg,S,Length(S),Separator);
  2977. Result:=(Msg='');
  2978. end;
  2979. end;
  2980. function TryStrToTime(const S: String; out Value: TDateTime): Boolean;
  2981. begin
  2982. result:=TryStrToTime(S,Value,#0);
  2983. end;
  2984. function TryStrToDateTime(const S: String; out Value: TDateTime): Boolean;
  2985. var
  2986. I: integer;
  2987. dtdate, dttime :TDateTime;
  2988. begin
  2989. result:=false;
  2990. I:=Pos(TimeSeparator,S);
  2991. If (I>0) then
  2992. begin
  2993. While (I>0) and (S[I]<>' ') do
  2994. Dec(I);
  2995. If I>0 then
  2996. begin
  2997. if not TryStrToDate(Copy(S,1,I-1),dtdate) then
  2998. exit;
  2999. if not TryStrToTime(Copy(S,i+1, Length(S)-i),dttime) then
  3000. exit;
  3001. Value:=ComposeDateTime(dtdate,dttime);
  3002. result:=true;
  3003. end
  3004. else
  3005. result:=TryStrToTime(s,Value);
  3006. end
  3007. else
  3008. result:=TryStrToDate(s,Value);
  3009. end;
  3010. function StrToDateDef(const S: String; const Defvalue : TDateTime): TDateTime;
  3011. begin
  3012. result := StrToDateDef(S,DefValue,#0);
  3013. end;
  3014. function StrToTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  3015. begin
  3016. result := StrToTimeDef(S,DefValue,#0);
  3017. end;
  3018. function StrToDateTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  3019. begin
  3020. if not TryStrToDateTime(s,Result) Then
  3021. result:=defvalue;
  3022. end;
  3023. function StrToDateDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  3024. begin
  3025. if not TryStrToDate(s,Result, separator) Then
  3026. result:=defvalue;
  3027. end;
  3028. function StrToTimeDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  3029. begin
  3030. if not TryStrToTime(s,Result, separator) Then
  3031. result:=defvalue;
  3032. end;
  3033. procedure ReplaceTime(var dati:TDateTime; NewTime : TDateTime);
  3034. begin
  3035. dati:= ComposeDateTime(dati, newtime);
  3036. end;
  3037. procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime);
  3038. var
  3039. tmp : TDateTime;
  3040. begin
  3041. tmp:=NewDate;
  3042. ReplaceTime(tmp,DateTime);
  3043. DateTime:=tmp;
  3044. end;
  3045. Function FloatToDateTime (Const Value : Extended) : TDateTime;
  3046. begin
  3047. If (Value<MinDateTime) or (Value>MaxDateTime) then
  3048. Raise EConvertError.CreateFmt (SInvalidDateTime,[FloatToStr(Value)]);
  3049. Result:=Value;
  3050. end;
  3051. function FloattoCurr(const Value: Extended): Currency;
  3052. begin
  3053. if not TryFloatToCurr(Value, Result) then
  3054. Raise EConvertError.CreateFmt(SInvalidCurrency, [FloatToStr(Value)]);
  3055. end;
  3056. function TryFloatToCurr(const Value: Extended; var AResult: Currency): Boolean;
  3057. begin
  3058. Result:=(Value>=MinCurrency) and (Value<=MaxCurrency);
  3059. if Result then
  3060. AResult := Value;
  3061. end;
  3062. function CurrToStr(Value: Currency): string;
  3063. begin
  3064. Result:=FloatToStrF(Value,ffGeneral,-1,0);
  3065. end;
  3066. (*
  3067. function CurrToStr(Value: Currency; const FormatSettings: TFormatSettings): string;
  3068. begin
  3069. end;
  3070. *)
  3071. function StrToCurr(const S: string): Currency;
  3072. begin
  3073. if not TryStrToCurr(S,Result) then
  3074. Raise EConvertError.createfmt(SInvalidCurrency,[S]);
  3075. end;
  3076. (*
  3077. function StrToCurr(const S: string; const FormatSettings: TFormatSettings): Currency;
  3078. begin
  3079. end;
  3080. *)
  3081. function TryStrToCurr(const S: string; out Value: Currency): Boolean;
  3082. Var
  3083. D : Double;
  3084. begin
  3085. Result:=TryStrToFloat(S,D);
  3086. if Result then
  3087. Value:=D;
  3088. end;
  3089. (*
  3090. function TryStrToCurr(const S: string; out Value: Currency; const FormatSettings: TFormatSettings): Boolean;
  3091. begin
  3092. end;
  3093. *)
  3094. function StrToCurrDef(const S: string; Default: Currency): Currency;
  3095. Var
  3096. R : Currency;
  3097. begin
  3098. if TryStrToCurr(S,R) then
  3099. Result:=R
  3100. else
  3101. Result:=Default;
  3102. end;
  3103. (*
  3104. function StrToCurrDef(const S: string; Default: Currency; const FormatSettings: TFormatSettings): Currency;
  3105. begin
  3106. end;
  3107. *)
  3108. { ---------------------------------------------------------------------
  3109. Interface related
  3110. ---------------------------------------------------------------------}
  3111. function Supports(const Instance: IInterface; const AClass: TClass; out Obj
  3112. ): Boolean;
  3113. begin
  3114. Result := (Instance<>nil) and (Instance.QueryInterface(IObjectInstance,Obj)=S_OK)
  3115. and (TObject(Obj).InheritsFrom(AClass));
  3116. end;
  3117. function Supports(const Instance: IInterface; const IID: TGUID; out Intf
  3118. ): Boolean;
  3119. begin
  3120. Result:=(Instance<>nil) and (Instance.QueryInterface(IID,Intf)=S_OK);
  3121. end;
  3122. function Supports(const Instance: TObject; const IID: TGUID; out Intf
  3123. ): Boolean;
  3124. begin
  3125. Result:=(Instance<>nil) and Instance.GetInterface(IID,Intf);
  3126. end;
  3127. function Supports(const Instance: TObject; const IID: TGuidString; out Intf
  3128. ): Boolean;
  3129. begin
  3130. Result:=(Instance<>nil) and Instance.GetInterfaceByStr(IID,Intf);
  3131. end;
  3132. function Supports(const Instance: IInterface; const AClass: TClass): Boolean;
  3133. var
  3134. Temp: TObject;
  3135. begin
  3136. Result:=Supports(Instance,AClass,Temp);
  3137. end;
  3138. function Supports(const Instance: IInterface; const IID: TGUID): Boolean;
  3139. var
  3140. Temp: IInterface;
  3141. begin
  3142. Result:=Supports(Instance,IID,Temp);
  3143. end;
  3144. function Supports(const Instance: TObject; const IID: TGUID): Boolean;
  3145. var
  3146. Temp: TJSObject;
  3147. begin
  3148. Result:=Supports(Instance,IID,Temp);
  3149. asm
  3150. if (Temp && Temp.$kind==='com') Temp._Release();
  3151. end;
  3152. end;
  3153. function Supports(const Instance: TObject; const IID: TGuidString): Boolean;
  3154. var
  3155. Temp: TJSObject;
  3156. begin
  3157. Result:=Supports(Instance,IID,Temp);
  3158. asm
  3159. if (Temp && Temp.$kind==='com') Temp._Release();
  3160. end;
  3161. end;
  3162. function Supports(const AClass: TClass; const IID: TGUID): Boolean;
  3163. var
  3164. maps: JSValue;
  3165. begin
  3166. if AClass=nil then exit(false);
  3167. maps := TJSObject(AClass)['$intfmaps'];
  3168. if not maps then exit(false);
  3169. if TJSObject(maps)[GUIDToString(IID)] then exit(true);
  3170. Result:=false;
  3171. end;
  3172. function Supports(const AClass: TClass; const IID: TGuidString): Boolean;
  3173. var
  3174. maps: JSValue;
  3175. begin
  3176. if AClass=nil then exit(false);
  3177. maps := TJSObject(AClass)['$intfmaps'];
  3178. if not maps then exit(false);
  3179. if TJSObject(maps)[uppercase(IID)] then exit(true);
  3180. Result:=false;
  3181. end;
  3182. function TryStringToGUID(const s: string; out Guid: TGUID): Boolean;
  3183. var
  3184. re: TJSRegexp;
  3185. begin
  3186. if Length(s)<>38 then Exit(False);
  3187. 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}\}$');
  3188. Result:=re.test(s);
  3189. if not Result then
  3190. begin
  3191. Guid.D1:=0;
  3192. exit;
  3193. end;
  3194. asm
  3195. rtl.strToGUIDR(s,Guid.get());
  3196. end;
  3197. Result:=true;
  3198. end;
  3199. function StringToGUID(const S: string): TGUID;
  3200. begin
  3201. if not TryStringToGUID(S, Result) then
  3202. raise EConvertError.CreateFmt(SInvalidGUID, [S]);
  3203. end;
  3204. function GUIDToString(const guid: TGUID): string;
  3205. begin
  3206. Result:=System.GUIDToString(guid);
  3207. end;
  3208. function IsEqualGUID(const guid1, guid2: TGUID): Boolean;
  3209. var
  3210. i: integer;
  3211. begin
  3212. if (guid1.D1<>guid2.D1) or (guid1.D2<>guid2.D2) or (guid1.D3<>guid2.D3) then
  3213. exit(false);
  3214. for i:=0 to 7 do if guid1.D4[i]<>guid2.D4[i] then exit(false);
  3215. Result:=true;
  3216. end;
  3217. function GuidCase(const guid: TGUID; const List: array of TGuid): Integer;
  3218. begin
  3219. for Result := High(List) downto 0 do
  3220. if IsEqualGUID(guid, List[Result]) then
  3221. Exit;
  3222. Result := -1;
  3223. end;
  3224. { ---------------------------------------------------------------------
  3225. Integer/Ordinal related
  3226. ---------------------------------------------------------------------}
  3227. Function TryStrToInt(const S : String; Out res : Integer) : Boolean;
  3228. Var
  3229. NI : NativeInt;
  3230. begin
  3231. Result:=TryStrToInt(S,NI);
  3232. if Result then
  3233. res:=NI;
  3234. end;
  3235. Function TryStrToInt(const S : String; Out res : NativeInt) : Boolean;
  3236. Var
  3237. Radix : Integer = 10;
  3238. F,N : String;
  3239. J : JSValue;
  3240. begin
  3241. N:=S;
  3242. F:=Copy(N,1,1);
  3243. if (F='$') then
  3244. Radix:=16
  3245. else if (F='&') then
  3246. Radix:=8
  3247. else if (F='%') then
  3248. Radix:=2;
  3249. If Radix<>10 then
  3250. Delete(N,1,1);
  3251. J:=parseInt(N,Radix);
  3252. Result:=Not jsIsNan(j);
  3253. if Result then
  3254. res:=NativeInt(J);
  3255. end;
  3256. Function StrToIntDef(const S : String; Const aDef : Integer) : Integer;
  3257. Var
  3258. R : NativeInt;
  3259. begin
  3260. if TryStrToInt(S,R) then
  3261. Result:=R
  3262. else
  3263. Result:=aDef;
  3264. end;
  3265. Function StrToIntDef(const S : String; Const aDef : NativeInt) : NativeInt;
  3266. Var
  3267. R : NativeInt;
  3268. begin
  3269. if TryStrToInt(S,R) then
  3270. Result:=R
  3271. else
  3272. Result:=aDef;
  3273. end;
  3274. Function StrToInt(const S : String) : Integer;
  3275. Var
  3276. R : NativeInt;
  3277. begin
  3278. if not TryStrToInt(S,R) then
  3279. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3280. Result:=R;
  3281. end;
  3282. Function StrToNativeInt(const S : String) : NativeInt;
  3283. begin
  3284. if not TryStrToInt(S,Result) then
  3285. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3286. end;
  3287. Function StrToInt64(const S : String) : NativeLargeInt;
  3288. Var
  3289. N : NativeInt;
  3290. begin
  3291. if not TryStrToInt(S,N) then
  3292. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3293. Result:=N;
  3294. end;
  3295. Function TryStrToInt64(const S : String; Out res : NativeLargeInt) : Boolean;
  3296. Var
  3297. R : nativeint;
  3298. begin
  3299. Result:=TryStrToInt(S,R);
  3300. If Result then
  3301. Res:=R;
  3302. end;
  3303. Function StrToInt64Def(const S : String; ADefault : NativeLargeInt) : NativeLargeInt;
  3304. begin
  3305. if TryStrToInt64(S,Result) then
  3306. Result:=ADefault;
  3307. end;
  3308. Function StrToQWord(const S : String) : NativeLargeUInt;
  3309. Var
  3310. N : NativeInt;
  3311. begin
  3312. if (not TryStrToInt(S,N)) or (N<0) then
  3313. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3314. Result:=N;
  3315. end;
  3316. Function TryStrToQWord(const S : String; Out res : NativeLargeUInt) : Boolean;
  3317. Var
  3318. R : nativeint;
  3319. begin
  3320. Result:=TryStrToInt(S,R) and (R>=0);
  3321. If Result then
  3322. Res:=R;
  3323. end;
  3324. Function StrToQWordDef(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  3325. begin
  3326. if Not TryStrToQword(S,Result) then
  3327. Result:=ADefault;
  3328. end;
  3329. Function StrToUInt64(const S : String) : NativeLargeUInt;
  3330. Var
  3331. N : NativeInt;
  3332. begin
  3333. if (not TryStrToInt(S,N)) or (N<0) then
  3334. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3335. Result:=N;
  3336. end;
  3337. Function TryStrToUInt64(const S : String; Out res : NativeLargeUInt) : Boolean;
  3338. Var
  3339. R : nativeint;
  3340. begin
  3341. Result:=TryStrToInt(S,R) and (R>=0);
  3342. If Result then
  3343. Res:=R;
  3344. end;
  3345. Function StrToUInt64Def(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  3346. begin
  3347. if Not TryStrToUInt64(S,Result) then
  3348. Result:=ADefault;
  3349. end;
  3350. Function TryStrToDWord(const S : String; Out res : DWord) : Boolean;
  3351. Var
  3352. R : nativeint;
  3353. begin
  3354. Result:=TryStrToInt(S,R) and (R>=0) and (R<=DWord($FFFFFFFF));
  3355. If Result then
  3356. Res:=R;
  3357. end;
  3358. Function StrToDWord(const S : String) : DWord;
  3359. begin
  3360. if not TryStrToDWord(S,Result) then
  3361. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3362. end;
  3363. Function StrToDWordDef(const S : String; ADefault : DWord) : DWord;
  3364. begin
  3365. if Not TryStrToDWord(S,Result) then
  3366. Result:=ADefault;
  3367. end;
  3368. function IntToHex(Value: NativeInt; Digits: integer): string;
  3369. const
  3370. HexDigits = '0123456789ABCDEF';
  3371. begin
  3372. If Digits=0 then
  3373. Digits:=1;
  3374. Result:='';
  3375. While Value>0 do
  3376. begin
  3377. result:=HexDigits[(value and 15)+1]+Result;
  3378. value := value shr 4;
  3379. end ;
  3380. while (Length(Result)<Digits) do
  3381. Result:='0'+Result;
  3382. end;
  3383. { TFormatSettings }
  3384. function TFormatSettings.GetCurrencyDecimals: Byte;
  3385. begin
  3386. Result:=Sysutils.CurrencyDecimals;
  3387. end;
  3388. function TFormatSettings.GetCurrencyFormat: Byte;
  3389. begin
  3390. Result:=Sysutils.CurrencyFormat;
  3391. end;
  3392. function TFormatSettings.GetCurrencyString: String;
  3393. begin
  3394. Result:=Sysutils.CurrencyString;
  3395. end;
  3396. function TFormatSettings.GetDateSeparator: char;
  3397. begin
  3398. Result := SysUtils.DateSeparator;
  3399. end;
  3400. function TFormatSettings.GetDecimalSeparator: string;
  3401. begin
  3402. Result := SysUtils.DecimalSeparator;
  3403. end;
  3404. function TFormatSettings.GetLongDateFormat: string;
  3405. begin
  3406. Result := SysUtils.LongDateFormat;
  3407. end;
  3408. function TFormatSettings.GetLongDayNames: TDayNames;
  3409. begin
  3410. Result:=Sysutils.LongDayNames;
  3411. end;
  3412. function TFormatSettings.GetLongMonthNames: TMonthNames;
  3413. begin
  3414. Result:=Sysutils.LongMonthNames;
  3415. end;
  3416. function TFormatSettings.GetLongTimeFormat: string;
  3417. begin
  3418. Result := SysUtils.LongTimeFormat;
  3419. end;
  3420. function TFormatSettings.GetNegCurrFormat: Byte;
  3421. begin
  3422. Result:=Sysutils.NegCurrFormat;
  3423. end;
  3424. function TFormatSettings.GetShortDateFormat: string;
  3425. begin
  3426. Result := SysUtils.ShortDateFormat;
  3427. end;
  3428. function TFormatSettings.GetShortDayNames: TDayNames;
  3429. begin
  3430. Result:=Sysutils.ShortDayNames;
  3431. end;
  3432. function TFormatSettings.GetShortMonthNames: TMonthNames;
  3433. begin
  3434. Result:=Sysutils.ShortMonthNames;
  3435. end;
  3436. function TFormatSettings.GetShortTimeFormat: string;
  3437. begin
  3438. Result := SysUtils.ShortTimeFormat;
  3439. end;
  3440. function TFormatSettings.GetThousandSeparator: string;
  3441. begin
  3442. Result := SysUtils.ThousandSeparator;
  3443. end;
  3444. function TFormatSettings.GetTimeAMString: string;
  3445. begin
  3446. Result := SysUtils.TimeAMString;
  3447. end;
  3448. function TFormatSettings.GetTimePMString: string;
  3449. begin
  3450. Result := SysUtils.TimePMString;
  3451. end;
  3452. function TFormatSettings.GetTimeSeparator: char;
  3453. begin
  3454. Result := SysUtils.TimeSeparator;
  3455. end;
  3456. procedure TFormatSettings.SetCurrencyFormat(AValue: Byte);
  3457. begin
  3458. Sysutils.CurrencyFormat:=AValue;
  3459. end;
  3460. procedure TFormatSettings.SetCurrencyString(AValue: String);
  3461. begin
  3462. Sysutils.CurrencyString:=AValue;
  3463. end;
  3464. procedure TFormatSettings.SetDateSeparator(const Value: char);
  3465. begin
  3466. SysUtils.DateSeparator := Value;
  3467. end;
  3468. procedure TFormatSettings.SetDecimalSeparator(const Value: string);
  3469. begin
  3470. SysUtils.DecimalSeparator := Value;
  3471. end;
  3472. procedure TFormatSettings.SetLongDateFormat(const Value: string);
  3473. begin
  3474. SysUtils.LongDateFormat := Value;
  3475. end;
  3476. procedure TFormatSettings.SetLongDayNames(AValue: TDayNames);
  3477. begin
  3478. SysUtils.LongDayNames:=AValue;
  3479. end;
  3480. procedure TFormatSettings.SetLongMonthNames(AValue: TMonthNames);
  3481. begin
  3482. SysUtils.LongMonthNames:=AValue;
  3483. end;
  3484. procedure TFormatSettings.SetLongTimeFormat(const Value: string);
  3485. begin
  3486. SysUtils.LongTimeFormat := Value;
  3487. end;
  3488. procedure TFormatSettings.SetNegCurrFormat(AValue: Byte);
  3489. begin
  3490. Sysutils.NegCurrFormat:=AValue;
  3491. end;
  3492. procedure TFormatSettings.SetShortDateFormat(const Value: string);
  3493. begin
  3494. SysUtils.ShortDateFormat := Value;
  3495. end;
  3496. procedure TFormatSettings.SetShortDayNames(AValue: TDayNames);
  3497. begin
  3498. SysUtils.ShortDayNames:=AValue;
  3499. end;
  3500. procedure TFormatSettings.SetShortMonthNames(AValue: TMonthNames);
  3501. begin
  3502. SysUtils.ShortMonthNames:=AValue;
  3503. end;
  3504. procedure TFormatSettings.SetShortTimeFormat(const Value: string);
  3505. begin
  3506. SysUtils.ShortTimeFormat := Value;
  3507. end;
  3508. procedure TFormatSettings.SetCurrencyDecimals(AValue: Byte);
  3509. begin
  3510. Sysutils.CurrencyDecimals:=aValue;
  3511. end;
  3512. procedure TFormatSettings.SetThousandSeparator(const Value: string);
  3513. begin
  3514. SysUtils.ThousandSeparator := Value;
  3515. end;
  3516. procedure TFormatSettings.SetTimeAMString(const Value: string);
  3517. begin
  3518. SysUtils.TimeAMString := Value;
  3519. end;
  3520. procedure TFormatSettings.SetTimePMString(const Value: string);
  3521. begin
  3522. SysUtils.TimePMString := Value;
  3523. end;
  3524. procedure TFormatSettings.SetTimeSeparator(const Value: char);
  3525. begin
  3526. SysUtils.TimeSeparator := Value;
  3527. end;
  3528. initialization
  3529. FormatSettings := TFormatSettings.Create;
  3530. end.