| 1 |
{ |
| 2 |
Copyright 2000-2024 Michalis Kamburelis. |
| 3 |
|
| 4 |
This file is part of "Castle Game Engine". |
| 5 |
|
| 6 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 7 |
included in this distribution, for details about the copyright. |
| 8 |
|
| 9 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 10 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 12 |
|
| 13 |
---------------------------------------------------------------------------- |
| 14 |
} |
| 15 |
|
| 16 |
{ String utilities. |
| 17 |
Also some operations on Chars and PChars. |
| 18 |
And various conversions strings <-> numbers. |
| 19 |
|
| 20 |
General comments for all procedures that have parameter like IgnoreCase: |
| 21 |
@unorderedList( |
| 22 |
@item( |
| 23 |
If such parameter has some default value, this default value should be |
| 24 |
@definitionList( |
| 25 |
@itemLabel @true |
| 26 |
@item for procedures that only read processed String |
| 27 |
@itemLabel @false |
| 28 |
@item(for procedures that can modify processed String (for safety, |
| 29 |
so that accidental modification should be harder)) |
| 30 |
)) |
| 31 |
|
| 32 |
@item( |
| 33 |
If I don't write in docs for this procedure whether this |
| 34 |
procedure takes current locale into account (as current locale |
| 35 |
can change the meaning of "ignoring case"), then it means it |
| 36 |
@italic(does) take current locale into account.) |
| 37 |
) |
| 38 |
} |
| 39 |
|
| 40 |
unit CastleStringUtils; |
| 41 |
|
| 42 |
{$I castleconf.inc} |
| 43 |
|
| 44 |
interface |
| 45 |
|
| 46 |
uses SysUtils, Classes, Generics.Collections, |
| 47 |
CastleUtils; |
| 48 |
|
| 49 |
type |
| 50 |
TDynamicStringArray = array of String; |
| 51 |
|
| 52 |
TStringsHelper = class helper for TStrings |
| 53 |
{ Convert TStrings to a dynamic String array. } |
| 54 |
function ToArray: TDynamicStringArray; |
| 55 |
|
| 56 |
{ Split the argument into lines (honors any newline convention), |
| 57 |
and add the resulting lines to the list. |
| 58 |
|
| 59 |
If the S doesn't contain any newline, then using AddMultiLine(S) |
| 60 |
is equivalent to trivial Add(S). But when S has some newline characters, |
| 61 |
then AddMultiLine(S) call Add(...) many times. } |
| 62 |
procedure AddMultiLine(const S: String); |
| 63 |
end; |
| 64 |
|
| 65 |
{ List of strings. This is a slightly extended version of standard TStringList. |
| 66 |
The default CaseSensitive value is @true. } |
| 67 |
TCastleStringList = class(TStringList) |
| 68 |
private |
| 69 |
{ Takes Integer, not TListSize -- in FPC, this is also defined as Integer, not TListSize. } |
| 70 |
procedure SetCount(const Value: Integer); |
| 71 |
function GetL(const Index: TListSize): String; |
| 72 |
procedure SetL(const Index: TListSize; const S: String); |
| 73 |
{$ifndef FPC} |
| 74 |
protected |
| 75 |
function DoCompareText(const A, B: String): Integer; |
| 76 |
{$endif} |
| 77 |
public |
| 78 |
constructor Create; |
| 79 |
property Count: Integer read GetCount write SetCount; |
| 80 |
|
| 81 |
{$ifndef FPC} |
| 82 |
procedure AddSubRange(const Source: TStringList; const Index, AddCount: TListSize); |
| 83 |
{$endif} |
| 84 |
|
| 85 |
{ Add strings from Source list. |
| 86 |
Alias for AddStrings, useful for usage with macros, |
| 87 |
since it's consistent with AddRange in other lists. } |
| 88 |
procedure AddRange(const Source: TStrings); overload; |
| 89 |
procedure AddList(const Source: TStrings); deprecated 'use AddRange, consistent with other lists'; |
| 90 |
|
| 91 |
procedure AddRange(const A: array of String); overload; |
| 92 |
procedure AddArray(const A: array of String); deprecated 'use AddRange, consistent with other lists'; |
| 93 |
|
| 94 |
procedure AssignArray(const A: array of String); deprecated 'use Assign'; |
| 95 |
procedure Assign(const A: array of String); {$ifndef FPC} reintroduce; {$endif} overload; |
| 96 |
{$ifndef FPC} |
| 97 |
procedure Assign(const Source: TStringList); reintroduce; overload; |
| 98 |
{$endif} |
| 99 |
|
| 100 |
{ Does another string list have equal length and content. |
| 101 |
|
| 102 |
Any other TStrings descendant may be equal to this instance, |
| 103 |
we don't require it to be a TCastleStringList instance. |
| 104 |
We also don't check all the properties, like Delimiter or such. |
| 105 |
We only compare the contents: count, and actual strings. |
| 106 |
|
| 107 |
The comparison is case-sensitive, or not, depending on the value |
| 108 |
of CaseSensitive property of this list. } |
| 109 |
function Equals(SecondValue: TObject): Boolean; |
| 110 |
// In Delphi, they have non-virtual TStringList.Equals that hides virtual TObject.Equals... |
| 111 |
{$ifdef FPC} override; {$endif} |
| 112 |
overload; |
| 113 |
|
| 114 |
function Equals(const A: array of String): Boolean; overload; |
| 115 |
|
| 116 |
{ Does the SecondValue have equal length and content. |
| 117 |
|
| 118 |
This method does the same thing as @link(Equals). |
| 119 |
It is defined for consistency -- on some lists, like @link(TSingleList), |
| 120 |
there is an important difference between Equals (compares with some |
| 121 |
epsilon tolerance) and PerfectlyEquals. } |
| 122 |
function PerfectlyEquals(const SecondValue: TStringList): Boolean; |
| 123 |
|
| 124 |
{ Reverse the order of items on the array. } |
| 125 |
procedure Reverse; |
| 126 |
|
| 127 |
{ Access strings. This is exactly equivalent to just using standard |
| 128 |
TStringList.Strings property, and is useful only for implementing macros |
| 129 |
that work for both TCastleStringList and TStructList. } |
| 130 |
property L[const Index: TListSize]: String read GetL write SetL; |
| 131 |
end; |
| 132 |
|
| 133 |
{ String-to-string map. Note that in simple cases you can also |
| 134 |
use standard TStringList functionality (see it's properties Names, Values), |
| 135 |
but this is better if your key/values may be multiline. } |
| 136 |
TStringStringMap = class({$ifdef FPC}specialize{$endif} TDictionary<string, string>) |
| 137 |
strict private |
| 138 |
function GetItems(const AKey: String): String; |
| 139 |
procedure SetItems(const AKey: String; const AValue: String); |
| 140 |
public |
| 141 |
{ Set given key value, trying to preserve previous key value too. |
| 142 |
This is useful for safely setting X3D META values. |
| 143 |
|
| 144 |
Compared to normal PutKeyData, this behaves smarter if given Name |
| 145 |
is already set. If it's set with the same Content, we do nothing. |
| 146 |
If the Content is different, we move previous content to a |
| 147 |
@code(Name + '-previous') key. |
| 148 |
This way previous content value is preserved once (but not more, |
| 149 |
to not grow the X3D file indefinitely). } |
| 150 |
procedure PutPreserve(const Name, Content: String); |
| 151 |
|
| 152 |
{ Create another TStringStringMap with exactly the same contents at the beginning. } |
| 153 |
function CreateCopy: TStringStringMap; |
| 154 |
|
| 155 |
{ Assign contents (all keys, values) of another TStringStringMap instance. } |
| 156 |
procedure Assign(const Source: TStringStringMap); |
| 157 |
|
| 158 |
{ Access dictionary items. |
| 159 |
Setting this is allowed regardless if the key previously existed or not, |
| 160 |
in other words: setting this does AddOrSetValue, contrary to the ancestor TDictionary |
| 161 |
that only allows setting when the key already exists. } |
| 162 |
property Items [const AKey: string]: string read GetItems write SetItems; default; |
| 163 |
end; |
| 164 |
|
| 165 |
type |
| 166 |
{ } |
| 167 |
TSearchOptions = set of (soMatchCase, soWholeWord, soBackwards); |
| 168 |
{ A set of Chars. } |
| 169 |
TSetOfChars = SysUtils.TSysCharSet; |
| 170 |
|
| 171 |
const |
| 172 |
AllChars = [Low(AnsiChar) .. High(AnsiChar)]; |
| 173 |
DefaultWordBorders = AllChars - ['a'..'z', 'A'..'Z', '0'..'9', '_']; |
| 174 |
WhiteSpaces = [' ', #9, #10, #13]; |
| 175 |
SimpleAsciiCharacters = [#32 .. #126]; |
| 176 |
|
| 177 |
function RandomString: String; |
| 178 |
|
| 179 |
{ Replace all occurrences of FromPattern string to ToPattern string, |
| 180 |
within another string S. |
| 181 |
|
| 182 |
@code(StringReplaceAllVar(s, from, to)) is actually equivalent to |
| 183 |
simply @code(s := StringReplace(s, from, to, [rfReplaceAll, rfIgnoreCase])). |
| 184 |
So StringReplaceAllVar is just a wrapper for very common use case of |
| 185 |
StringReplace. } |
| 186 |
procedure StringReplaceAllVar(var S: string; |
| 187 |
const FromPattern, ToPattern: string; |
| 188 |
IgnoreCase: boolean = true); overload; |
| 189 |
|
| 190 |
{ Insert newline characters into string S, such that each line |
| 191 |
has at most MaxCol chars. |
| 192 |
|
| 193 |
It tries to insert newline sequence at the last character in AllowedBreakChars but still |
| 194 |
before MaxCol limit, and the character in AllowedBreakChars is deleted in this case. |
| 195 |
In other words, in most typical situation it simply breaks the string |
| 196 |
where the whitespace is, trying to make the line as long as possible within |
| 197 |
MaxCol limit. If no such character in AllowedBreakChars is found (e.g., you |
| 198 |
put a long line of non-white characters), it will still break the string |
| 199 |
at MaxCol position (so in this exceptional case, it will cause a break |
| 200 |
in the middle of the word). |
| 201 |
|
| 202 |
While breaking the string in the middle |
| 203 |
of the word in not nice, this allows us a safe feeling that this |
| 204 |
will always break the string into MaxCol chunks. |
| 205 |
|
| 206 |
This intelligently recognizes already |
| 207 |
existing newline characters (#13, #10, #13#10 or #10#13) in the string, |
| 208 |
so e.g. it will not insert more newline characters when they are not |
| 209 |
necessary. |
| 210 |
|
| 211 |
The Indent is added after every newline. |
| 212 |
This is a bit more powerful than simply specyfing Newline parameter |
| 213 |
as @code(NL + Indent), because this function also adds Indent after existing |
| 214 |
newlines in the input string. } |
| 215 |
function BreakLine(const s: string; const MaxCol: integer; |
| 216 |
const AllowedBreakChars: TSetOfChars = WhiteSpaces): string; overload; |
| 217 |
function BreakLine(const s: string; const MaxCol: integer; |
| 218 |
const AllowedBreakChars: TSetOfChars; |
| 219 |
const Newline: string; const Indent: string): string; overload; |
| 220 |
|
| 221 |
{ Returns S with all chars in ExcludedChars deleted. } |
| 222 |
function SDeleteChars(const s: string; const excludedChars: TSetOfChars): string; |
| 223 |
|
| 224 |
{ Replace all occurrences of characters in FromChars with |
| 225 |
the new string / character. There are three overloaded versions: |
| 226 |
|
| 227 |
@orderedList( |
| 228 |
@item(SReplaceChars(string, string, string) looks in S for characters within |
| 229 |
FromChars, and replaces them with characters on appropriate position |
| 230 |
in ToChars. For example, SReplaceChars(S, 'ab', 'cd') replaces |
| 231 |
all occurrences of 'a' into 'c' and all occurrences of 'b' into 'd'. |
| 232 |
It must always be Length(FromChars) <= Length(ToChars).) |
| 233 |
|
| 234 |
@item(SReplaceChars(string, TSetOfChars, char) replaces all occurrences |
| 235 |
of any character in given set with the one specified character.) |
| 236 |
|
| 237 |
@item(SReplaceChars(string, char, char) simply replaces all occurrences |
| 238 |
of one character into another.)) |
| 239 |
|
| 240 |
@groupBegin |
| 241 |
} |
| 242 |
function SReplaceChars(const s, FromChars, ToChars: string): string; overload; |
| 243 |
function SReplaceChars(const s: string; const FromChars: TSetOfChars; const ToChar: char): string; overload; |
| 244 |
function SReplaceChars(const s: string; const FromChar, ToChar: char): string; overload; |
| 245 |
{ @groupEnd } |
| 246 |
|
| 247 |
{ Pad (fill from the left with character C) string S, until length |
| 248 |
of resulting string is at least Len. |
| 249 |
|
| 250 |
For example, @code(SPad('29', 4, '0')) gives '0029' } |
| 251 |
function SPad(const s: string; len: integer; c: char = ' '): string; overload; |
| 252 |
|
| 253 |
{ Pad (fill from the left) with zeros string S, until length |
| 254 |
of resulting string is at least Len. It's actually just a shortcut for SPad |
| 255 |
with padding character set to '0'. } |
| 256 |
function SZeroPad(const s: string; len: integer): string; |
| 257 |
|
| 258 |
{ Convert uppercase letters to lowercase. Analogous to UpCase. |
| 259 |
Doesn't change other characters. Just like UpCase, this doesn't |
| 260 |
take current locale into account, and works only on English |
| 261 |
A-Z -> a-z letters. } |
| 262 |
function LoCase(const C: Char): Char; |
| 263 |
|
| 264 |
function CharPos(c: char; const s: string; Offset: Integer = 1): integer; |
| 265 |
deprecated 'use SysUtils.Pos or StrUtils.PosEx instead'; |
| 266 |
|
| 267 |
{ Find first occurrence of any character in Chars in string S. |
| 268 |
This is quite like FirstDelimiter but it takes parameter as TSetOfChars |
| 269 |
and has much more sensible name. |
| 270 |
|
| 271 |
BackCharsPos does the same, but from |
| 272 |
the end of the string (i.e. finds the last occurrence). |
| 273 |
|
| 274 |
CharsPosEx searches starting from Offset char. |
| 275 |
|
| 276 |
They all return 0 if not found. |
| 277 |
|
| 278 |
@groupBegin } |
| 279 |
function CharsPos(const Chars: TSetOfChars; const S: string): Integer; |
| 280 |
function CharsPosEx(const Chars: TSetOfChars; const S: string; |
| 281 |
const Offset: Integer): Integer; |
| 282 |
function BackCharsPos(const Chars: TSetOfChars; const s: string): Integer; |
| 283 |
{ @groupEnd } |
| 284 |
|
| 285 |
{ Find @bold(last) occurrence of SubString within S. |
| 286 |
0 if not found. Overloaded version is optimized for searching for |
| 287 |
single character. } |
| 288 |
function BackPos(const SubString, S: string): Integer; overload; |
| 289 |
function BackPos(const SubString: char; const S: string): Integer; overload; |
| 290 |
|
| 291 |
{ Find first occurrence of character in Delimiters. Name is analogous to |
| 292 |
LastDelimiter. Returns 0 if not found. } |
| 293 |
function FirstDelimiter(const Delimiters, S: string): Integer; |
| 294 |
|
| 295 |
{ Returns suffix of S starting from position P. |
| 296 |
Returns '' if P > length(S). |
| 297 |
Yes, this is simply equivalent to Copy(S, P, MaxInt). } |
| 298 |
function SEnding(const s: string; P: integer): string; |
| 299 |
|
| 300 |
function IsPrefix(const Prefix, S: string; |
| 301 |
IgnoreCase: boolean = true): boolean; overload; |
| 302 |
function IsSuffix(const Suffix, S: string; |
| 303 |
IgnoreCase: boolean = true): boolean; overload; |
| 304 |
|
| 305 |
{ Removes the prefix, if it is present. More precisely, if |
| 306 |
IsPrefix(Prefix, S, IgnoreCase) then returns S with this prefix |
| 307 |
removed. Else returns S. } |
| 308 |
function PrefixRemove(const Prefix, S: string; IgnoreCase: boolean): string; |
| 309 |
|
| 310 |
{ Like PrefixRemove, but checks for and removes Suffix. } |
| 311 |
function SuffixRemove(const Suffix, S: string; IgnoreCase: boolean): string; |
| 312 |
|
| 313 |
{ Appends to a string S DataSize bytes from Data. } |
| 314 |
procedure SAppendData(var s: string; const Data; DataSize: integer); deprecated 'this function is not very useful'; |
| 315 |
|
| 316 |
{ A pointer to S[CharNum], that is just @@S[CharNum], |
| 317 |
avoiding range checking. } |
| 318 |
function SChar(const s: string; CharNum: integer): PChar; deprecated 'this function is not very useful'; |
| 319 |
|
| 320 |
{ Check whether S[Index] = C, also checking is Index within S length. |
| 321 |
Return false if S is too short, or the chatacter differs. |
| 322 |
|
| 323 |
@groupBegin } |
| 324 |
function SCharIs(const S: String; const Index: Integer; const C: char): Boolean; overload; |
| 325 |
function SCharIs(const S: String; const Index: Integer; const chars: TSetOfChars): Boolean; overload; |
| 326 |
{ @groupEnd } |
| 327 |
|
| 328 |
{ Replace typically unreadable characters in string S with #number notation. |
| 329 |
Useful for printing strings with some unprintable chars for |
| 330 |
debugging purposes. |
| 331 |
|
| 332 |
Note: In case String may contain Unicode characters, use |
| 333 |
UnicodeCharToReadableString instead, after deconstructing the string |
| 334 |
to Unicode characters using e.g. TCastleStringIterator. } |
| 335 |
function SReadableForm(const S: String): String; overload; |
| 336 |
function SReadableForm(const C: Char): String; overload; |
| 337 |
|
| 338 |
{ Return S[StartPosition..EndPosition]. |
| 339 |
This is similar to standard Copy procedure, |
| 340 |
but last parameter is EndPosition instead of Count, which is more comfortable |
| 341 |
sometimes. } |
| 342 |
function CopyPos(const s: string; StartPosition, EndPosition: integer): string; |
| 343 |
|
| 344 |
{ Delete from S range of characters [StartPosition..EndPosition]. |
| 345 |
Analogous to standard Delete but with EndPosition parameter (while |
| 346 |
standard Delete takes Count). } |
| 347 |
procedure DeletePos(var S: string; StartPosition, EndPosition: Integer); |
| 348 |
|
| 349 |
(*Find next part in the string S separated by delimiters |
| 350 |
TokenDelims. More precisely: search S, starting from position |
| 351 |
SeekPos, for the first character that is @italic(not in TokenDelims). |
| 352 |
Then, all subsequent characters that are not in TokenDelims are |
| 353 |
appended to the Result, until any character @italic(is in TokenDelims) |
| 354 |
is found. In effect, Result contains the whole part that was in TokenDelims. |
| 355 |
|
| 356 |
SeekPos is advanced to the position of the next character, i.e. the character |
| 357 |
right after the ending character that was in TokenDelims. In other words, |
| 358 |
SeekPos points to the position of the next "unprocessed" character in |
| 359 |
string S. Often you will want to make another call to NextToken, passing |
| 360 |
this SeekPos, and this way you can split your string S into parts |
| 361 |
delimited by TokenDelims. |
| 362 |
|
| 363 |
Returns '' if no more tokens available (SeekPos value at the end is |
| 364 |
unspecified). |
| 365 |
|
| 366 |
Typical use scenario (iterate over all tokens in the string) : |
| 367 |
|
| 368 |
@longCode(# |
| 369 |
SeekPos := 1; |
| 370 |
repeat |
| 371 |
Token := NextToken(S, SeekPos); |
| 372 |
if Token = '' then break; |
| 373 |
{ ... process_next_token (Token) ... } |
| 374 |
until false; |
| 375 |
#) |
| 376 |
|
| 377 |
The above example will split the string into parts separated by whitespace. |
| 378 |
|
| 379 |
Note: it's much easier to use CreateTokens instead of this procedure. |
| 380 |
But this procedure gives you quite more flexibility. *) |
| 381 |
function NextToken(const S: string; var SeekPos: Integer; |
| 382 |
const TokenDelims: TSetOfChars = WhiteSpaces): string; |
| 383 |
|
| 384 |
{ Count the amount of tokens in the string } |
| 385 |
function CountTokens(const S: String; |
| 386 |
const TokenDelims: TSetOfChars = WhiteSpaces): Integer; |
| 387 |
|
| 388 |
{ NextTokenOnce works just like NextToken, but doesn't advance the SeekPos |
| 389 |
position. This means that it's quite useless when you're interested |
| 390 |
in @italic(all) tokens inside some string, but it's also more comfortable |
| 391 |
when you're interested in only @italic(one) token inside some string. |
| 392 |
When SeekPos = 1, this is the first token. } |
| 393 |
function NextTokenOnce(const s: string; SeekPos: integer = 1; |
| 394 |
const TokenDelims: TSetOfChars = WhiteSpaces): string; |
| 395 |
overload; |
| 396 |
|
| 397 |
{ Returns TCastleStringList with tokens extracted from S. |
| 398 |
Token is something delimited by TokenDelims. |
| 399 |
TokenDelims are not contained in resulting items. |
| 400 |
E.g. CreateTokens('foo, bar', [' ', ',']) returns TCastleStringList |
| 401 |
with 2 items: 'foo' and 'bar'. } |
| 402 |
function CreateTokens(const s: string; |
| 403 |
const TokenDelims: TSetOfChars = WhiteSpaces): TCastleStringList; |
| 404 |
|
| 405 |
{ Split a string by a character delimiter. |
| 406 |
For example, @code(SplitString('foo|bar', '|')) returns a list with 2 parts: |
| 407 |
@code('foo') and @code('bar'). |
| 408 |
|
| 409 |
The splitting is done "strictly", which means that we always return exactly |
| 410 |
one more part than the occurrences of delimiter in the source string. |
| 411 |
|
| 412 |
In particular, this means that: |
| 413 |
@unorderedList( |
| 414 |
@item(If the Delimiter does not occur in the source string, |
| 415 |
then the result is a list with a single part. This applies |
| 416 |
even if the source string is empty. |
| 417 |
|
| 418 |
@unorderedList( |
| 419 |
@itemSpacing Compact |
| 420 |
@item @code(SplitString('foo', '|') = ['foo']) |
| 421 |
@item @code(SplitString('', '|') = ['']) |
| 422 |
) |
| 423 |
) |
| 424 |
|
| 425 |
@item(If the Delimiter occurs two or more times in a row within the source string, |
| 426 |
then the we will have one or more empty parts in the resulting list. |
| 427 |
|
| 428 |
@unorderedList( |
| 429 |
@itemSpacing Compact |
| 430 |
@item @code(SplitString('foo||bar', '|') = ['foo', '', 'bar]) |
| 431 |
@item @code(SplitString('foo|||bar', '|') = ['foo', '', '', 'bar]) |
| 432 |
) |
| 433 |
) |
| 434 |
|
| 435 |
@item(f the Delimiter occurs at the very end of the source string, |
| 436 |
then the very last part of the resulting list will be an empty string. |
| 437 |
|
| 438 |
@unorderedList( |
| 439 |
@itemSpacing Compact |
| 440 |
@item @code(SplitString('foo||bar|', '|') = ['foo', '', 'bar, '']) |
| 441 |
) |
| 442 |
) |
| 443 |
) |
| 444 |
|
| 445 |
The reverse of this operation is GlueStrings. |
| 446 |
|
| 447 |
See also CreateTokens, for a different way to split, that treats any sequence |
| 448 |
of delimiters like a single delimiter, and is more suitable e.g. to extract |
| 449 |
words separated by whitespace. |
| 450 |
See also standard TStringList.Delimiter feature. } |
| 451 |
function SplitString(const S: string; const Delimiter: char): TCastleStringList; |
| 452 |
|
| 453 |
{ Concatenate the string list with a given Delimiter. |
| 454 |
This is the reverse of SplitString. |
| 455 |
@groupBegin } |
| 456 |
function GlueStrings(const Strings: array of string; const Delimiter: char): string; overload; |
| 457 |
function GlueStrings(const Strings: array of string; const Delimiter: string): string; overload; |
| 458 |
function GlueStrings(const Strings: TStrings; const Delimiter: char): string; overload; |
| 459 |
function GlueStrings(const Strings: TStrings; const Delimiter: string): string; overload; |
| 460 |
{ @groupEnd } |
| 461 |
|
| 462 |
{ Find substring SubText within Text. Returns 0 if not found. |
| 463 |
Similar to a standard Pos function, with some improvements. |
| 464 |
|
| 465 |
@param(StartPosition Starts searching for SubText starting from this position. |
| 466 |
Note that the resulting position is still returned with respect |
| 467 |
to the string beginning. Just like standard PosEx.) |
| 468 |
|
| 469 |
@param(Count Looks only at Count characters from Text. |
| 470 |
You can say that the search is done only within Copy(Text, StartPosition, Count).) |
| 471 |
|
| 472 |
@param(Options Various searching options: |
| 473 |
|
| 474 |
@unorderedList( |
| 475 |
@item(soMatchCase: makes searching case-sensitive (by default, |
| 476 |
case is ignored, taking locale into account).) |
| 477 |
|
| 478 |
@item(soWholeWord: looks only for SubText occurrences surrounded |
| 479 |
by characters from WordBorders (or the beginning/end of Text). |
| 480 |
|
| 481 |
Note that, while the beginning/end of Text is always treated like a word border, |
| 482 |
but the mere beginning/end of the searching range (StartPosition, Count) |
| 483 |
is not a word border. |
| 484 |
For example FindPos('cat', 'foocat dog', 4, MaxInt, [soWholeWord]) |
| 485 |
will answer 0 (not found), because the only 'cat' occurrence is not |
| 486 |
surrounded by default word borders.) |
| 487 |
|
| 488 |
@item(soBackwards: search from the end, that is return rightmost |
| 489 |
found occurrence.) |
| 490 |
) |
| 491 |
) } |
| 492 |
function FindPos(const SubText, Text: string; StartPosition, Count: integer; |
| 493 |
const Options: TSearchOptions; |
| 494 |
const WordBorders: TSetOfChars = DefaultWordBorders): integer; |
| 495 |
deprecated 'use various StrUtils routines to search in string instead of this (slow, not much useful) routine'; |
| 496 |
|
| 497 |
{ Return rightmost RPart characters from S. |
| 498 |
If RPart > Length(S) then returns S. } |
| 499 |
function SRight(const s: string; const rpart: integer): string; |
| 500 |
|
| 501 |
{ If S = '' then returns NextPart, else returns S + PartSeparator + NextPart. } |
| 502 |
function SAppendPart(const s, PartSeparator, NextPart: string): string; |
| 503 |
|
| 504 |
type |
| 505 |
EDeformatError = class(Exception); |
| 506 |
|
| 507 |
{ Parse a string according to the given format, returning the |
| 508 |
values corresponding to placeholders %x in format string. |
| 509 |
|
| 510 |
Format parameter is a sequence of white spaces, placeholders like %d or %f, |
| 511 |
and other characters. More precisely: |
| 512 |
|
| 513 |
@unorderedList( |
| 514 |
@item(If RelaxedWhitespaceChecking = @true (that's the default value) |
| 515 |
then 1 or more white spaces in Format must correspond to 1 or more |
| 516 |
any whitespace characters in Data. I.e., the actual number and kind |
| 517 |
of whitespace in Format and Data doesn't have to match --- it's |
| 518 |
only important that @italic(some whitespace in Format) correspond |
| 519 |
to @italic(some whitespace in Data).) |
| 520 |
|
| 521 |
@item(@code(%d) in Format means an Integer value in Data. |
| 522 |
Args should have a pointer to Integer variable on the appropriate |
| 523 |
position. |
| 524 |
|
| 525 |
Warning: DeFormat cannot detect the type of your arguments, |
| 526 |
or check their validity. Make sure in Args you use a pointer to an Integer |
| 527 |
variable (32-bit, like in FPC ObjFpc or Delphi mode), |
| 528 |
not e.g. ShortInt or Byte. |
| 529 |
) |
| 530 |
|
| 531 |
@item(@code(%f) in Format means a float value (possibly signed, possibly |
| 532 |
with a dot) in Data. Args should have a pointer to Float variable |
| 533 |
on the appropriate position. |
| 534 |
|
| 535 |
Warning: DeFormat cannot detect the type of your arguments, |
| 536 |
or check their validity. Make sure in Args you use a pointer to an Float |
| 537 |
variable (as defined in Math unit), |
| 538 |
not e.g. Single or Double or Extended. |
| 539 |
) |
| 540 |
|
| 541 |
@item(@code(%.single.), @code(%.double.), @code(%.extended.) are like |
| 542 |
@code(%f), but they specify appropriate variable type in Args.) |
| 543 |
|
| 544 |
@item(@code(%.integer.), @code(%.cardinal.), are like |
| 545 |
@code(%d), but they specify appropriate variable type in Args.) |
| 546 |
|
| 547 |
@item(@code(%s) in Format means a string (will end on the first whitespace) |
| 548 |
in Data. Args should contain a pointer to an AnsiString |
| 549 |
on the appropriate position. Note that I mean it --- a pointer |
| 550 |
to an AnsiString, not just a string typecasted into a pointer. |
| 551 |
I.e., if S is AnsiString, Args should contain @@S, not Pointer(S). |
| 552 |
|
| 553 |
Note that a string may be empty in some cases, e.g. Format = '%d %s' |
| 554 |
and Data = '123 ' will result in the empty string as second Args.) |
| 555 |
|
| 556 |
@item(@code(%%) in Format means a one % sign in Data.) |
| 557 |
|
| 558 |
@item(All the other characters (non-white, not %x sequences above) |
| 559 |
should be present in Data exactly like they are specified in Format. |
| 560 |
IgnoreCase controls is the letter case checked. When |
| 561 |
RelaxedWhitespaceChecking = @false then white-space characters |
| 562 |
are treated just like non-white chars: they must match exactly |
| 563 |
between Format and Data.) |
| 564 |
) |
| 565 |
|
| 566 |
Format must always match the whole Data --- in other words, when |
| 567 |
we finished reading the Format, Data should be finished too. |
| 568 |
The exception is at the beginning and end of Data, if |
| 569 |
RelaxedWhitespaceChecking = @true : then at the beginning and end of Data |
| 570 |
any number of white-space is allowed. |
| 571 |
|
| 572 |
For DeFormat, the opposite must also be true: when we finished reading |
| 573 |
Data, Format should be finished too. However, for TryDeFormat, it's |
| 574 |
allowed for Data to end prematurely. TryDeFormat returns how many Args |
| 575 |
were initialized. |
| 576 |
|
| 577 |
Note that while usually you will want RelaxedWhitespaceChecking = @true, |
| 578 |
sometimes it can be needed to set this to @false not only to get |
| 579 |
strickter checking, but also to get some things matching that otherwise |
| 580 |
wouldn't match. For example, consider Data = 'first second apple' |
| 581 |
and Format = 'first %s second %s'. With RelaxedWhitespaceChecking |
| 582 |
these things @italic(do not match) --- because the 1st space character |
| 583 |
in the Format string "consumes" the 1st and 2nd space characters |
| 584 |
in the Data. Then '%s' is matched to the word 'second', and the |
| 585 |
word 'second' is compared with 'apple' and they do not match. |
| 586 |
If you want such Data and Format to match, you must pass |
| 587 |
RelaxedWhitespaceChecking = @true. Then the first '%s' will be matched |
| 588 |
to '' (empty string). |
| 589 |
|
| 590 |
This was written because both JclSscanf and scanf units were buggy. |
| 591 |
(see openGL.testy/nehe10). |
| 592 |
|
| 593 |
@raises(EDeformatError In case of any error --- mismatch between Format |
| 594 |
and Data. Note that in case of error, some of Args may be initialized, |
| 595 |
and some not --- no guarantees here, sorry.) } |
| 596 |
procedure DeFormat(Data: string; const Format: string; |
| 597 |
const args: array of pointer; |
| 598 |
const IgnoreCase: boolean = true; |
| 599 |
const RelaxedWhitespaceChecking: boolean = true); overload; |
| 600 |
function TryDeFormat(Data: string; const Format: string; |
| 601 |
const args: array of pointer; |
| 602 |
const IgnoreCase: boolean = true; |
| 603 |
const RelaxedWhitespaceChecking: boolean = true): integer; overload; |
| 604 |
|
| 605 |
{ Replace all strings in Patterns with corresponding strings in Values. |
| 606 |
This is similar to standard StringReplace, but this does many |
| 607 |
replacements at once. This is just like StrUtils.StringsReplace in FPC. |
| 608 |
|
| 609 |
Patterns and Values arrays must have equal length. |
| 610 |
Patterns[0] will be replaced with Values[0], Patterns[1] with Values[0] etc. |
| 611 |
Patterns are scanned from left to right, that is if two pattern occurrences |
| 612 |
overlap --- we will detect the leftmost one. If both patterns start |
| 613 |
at the same place (this means that one pattern is a prefix of the other), |
| 614 |
we will choose the first pattern in Patterns table. |
| 615 |
|
| 616 |
Using this avoids a common trap at repeated search-replace operations. |
| 617 |
A naive implementation of doing many search-replace over the same string |
| 618 |
is like |
| 619 |
|
| 620 |
@longCode(# |
| 621 |
Result := S; |
| 622 |
Result := StringReplace(Result, Patterns[0], Values[0], [rfReplaceAll]); |
| 623 |
Result := StringReplace(Result, Patterns[1], Values[1], [rfReplaceAll]); |
| 624 |
// etc. |
| 625 |
#) |
| 626 |
|
| 627 |
But the above fails badly when inserting some Values[] creates |
| 628 |
an occurrence of Pattern checked later. For example, when Values[0] |
| 629 |
contains inside whole Patterns[1]. More exotic situations involve |
| 630 |
when some Values[] glues with previous string contents to make |
| 631 |
a pattern detected later. This means that you could replace the same |
| 632 |
content many times, which is usually not what you want. |
| 633 |
|
| 634 |
That's why you should instead use this function for such situations. } |
| 635 |
function SReplacePatterns(const s: string; const patterns, values: array of string; const IgnoreCase: boolean): string; overload; |
| 636 |
function SReplacePatterns(const s: string; const patterns, values: TStrings; const IgnoreCase: boolean): string; overload; |
| 637 |
function SReplacePatterns(const s: string; const Parameters: TStringStringMap; const IgnoreCase: boolean): string; overload; |
| 638 |
|
| 639 |
{$ifndef FPC} |
| 640 |
{ Does InputStr match Wildcards (with * and ?). } |
| 641 |
function IsWild(const InputStr, Wildcards: string; const IgnoreCase: Boolean): Boolean; |
| 642 |
{$endif} |
| 643 |
|
| 644 |
function SCharsCount(const s: string; c: char): Cardinal; overload; |
| 645 |
function SCharsCount(const s: string; const Chars: TSetOfChars): Cardinal; overload; |
| 646 |
|
| 647 |
{ Remove from the string S everything after the first hash "#" character. |
| 648 |
Removes also this very "#" character. |
| 649 |
|
| 650 |
If string doesn't contain hash character, it's simply returned. |
| 651 |
|
| 652 |
Useful for interpreting simple text files when you want to treat |
| 653 |
things after "#" like a comment. } |
| 654 |
function STruncateHash(const s: string): string; |
| 655 |
|
| 656 |
{ Return the value to reproduce exactly string S by Format procedure. |
| 657 |
Saying simply, this doubles the "%" characters inside the string. |
| 658 |
The intention is to make such string that |
| 659 |
@code(Format(SUnformattable(S), []) = S). In other words, "quote" |
| 660 |
any suspicious "%" characters in S for Format. } |
| 661 |
function SUnformattable(const s: string): string; |
| 662 |
|
| 663 |
{ Compare strings, taking into account current locale. |
| 664 |
This simply does AnsiCompareStr or AnsiCompareText, depending on IgnoreCase. |
| 665 |
|
| 666 |
Returns value < 0 when S1 < S2, returns 0 when S1 = S2 and value > 0 |
| 667 |
when S1 > S2. } |
| 668 |
function SAnsiCompare(const s1, s2: string; IgnoreCase: boolean): Integer; |
| 669 |
|
| 670 |
{ Check if strings are equal, taking into account current locale. |
| 671 |
Shortcut for SAnsiCompare(S1, S2) = 0 } |
| 672 |
function SAnsiSame(const s1, s2: string; IgnoreCase: boolean): boolean; |
| 673 |
|
| 674 |
type |
| 675 |
TPercentReplace = record |
| 676 |
{ @noAutoLinkHere } |
| 677 |
c: char; |
| 678 |
{ @noAutoLinkHere } |
| 679 |
s: string; |
| 680 |
end; |
| 681 |
|
| 682 |
EUnknownPercentFormat = class(Exception); |
| 683 |
|
| 684 |
{ Searches for %x patterns and replaces them with specified strings. |
| 685 |
Something like a more generalized Format routine. |
| 686 |
|
| 687 |
More precisely: every two-char sequence that starts with PercentChar |
| 688 |
and then is followed by one of Replaces[I].c characters is replaced |
| 689 |
with appropriate Replaces[i].s. Moreover, a pair of two PercentChar |
| 690 |
characters is replaced with one PercentChar character. |
| 691 |
|
| 692 |
@italic(For example), assume that Replaces contains two items: |
| 693 |
@code((c: 'B'; s: '<bold>'), (c: 'b'; s: '</bold>')). |
| 694 |
Then @code(SPercentReplace('100%% of cats are %Bcute%b', Replaces)) will return |
| 695 |
string @code('100% of cats are <bold>cute</bold>'). |
| 696 |
|
| 697 |
EUnknownPercentFormat is raised if we will see two-char sequence |
| 698 |
that starts with PercentChar and then is followed by character that |
| 699 |
is not any Replaces[i].c and is not PercentChar. Also, a single PercentChar |
| 700 |
at the end of the string is an error. |
| 701 |
|
| 702 |
@italic(For example), assume that Replaces contains the same two items as |
| 703 |
previously. Following calls will result in EUnknownPercentFormat being raised: |
| 704 |
@code(SPercentReplace('Unknown sequence %x', Replaces)), |
| 705 |
@code(SPercentReplace('Unterminated sequence %', Replaces)). |
| 706 |
|
| 707 |
If ErrorOnUnknownPercentFormat is @false, then EUnknownPercentFormat will |
| 708 |
not be raised. Instead, incorrect sequence (like %x or unterminated % in |
| 709 |
examples above) will simply be left in the string. |
| 710 |
|
| 711 |
Of course, replacing is done intelligently. Which means that |
| 712 |
e.g. sequence of four % characters will be correctly transformed into |
| 713 |
two % characters. |
| 714 |
|
| 715 |
Note that IgnoreCase is used to match characters for Replaces[I].c. |
| 716 |
IgnoreCase is not used when it comes to comparing with PercentChar character, |
| 717 |
i.e. even when PercentChar will be set to some letter, it will always |
| 718 |
be compared in case-sensitive manner, regardless of IgnoreCase value. |
| 719 |
|
| 720 |
It is undefined (meaning: don't do it) what happens if Replaces array |
| 721 |
contains more than once the same character C, or if any character C |
| 722 |
in Replaces array is equal to PercentChar. |
| 723 |
|
| 724 |
ReplacementsDone, if passed, will return how many replacements were done. |
| 725 |
Not counting "meaningless" replacements of pair of PercentChar to one |
| 726 |
PercentChar (that is, we count only actual replacements from Replaces |
| 727 |
array). |
| 728 |
|
| 729 |
@raises(EUnknownPercentFormat In case of error in InitialFormat string, |
| 730 |
if ErrorOnUnknownPercentFormat is @true.) |
| 731 |
|
| 732 |
@groupBegin } |
| 733 |
function SPercentReplace(const InitialFormat: string; |
| 734 |
const Replaces: array of TPercentReplace; |
| 735 |
out ReplacementsDone: Cardinal; |
| 736 |
ErrorOnUnknownPercentFormat: boolean = true; |
| 737 |
PercentChar: char ='%'; |
| 738 |
IgnoreCase: boolean = false): string; overload; deprecated 'use standard StrUtils.StringsReplace instead'; |
| 739 |
|
| 740 |
function SPercentReplace(const InitialFormat: string; |
| 741 |
const Replaces: array of TPercentReplace; |
| 742 |
ErrorOnUnknownPercentFormat: boolean = true; |
| 743 |
PercentChar: char ='%'; |
| 744 |
IgnoreCase: boolean = false): string; overload; deprecated 'use standard StrUtils.StringsReplace instead'; |
| 745 |
{ @groupEnd } |
| 746 |
|
| 747 |
{ Replace sequences @code(@@counter(<padding>)) in the NamePattern with Index. |
| 748 |
Any sequence @code(@@counter(<padding>)) is detected (where <padding> is any |
| 749 |
integer >= 0) and replaced with Index padded with zeros (to given <padding> |
| 750 |
length). |
| 751 |
|
| 752 |
If AllowOldPercentSyntax is @true then we also allow older deprecated |
| 753 |
syntax: replace %d in the NamePattern with Index. |
| 754 |
This is used only if @code(@@counter(<padding>)) was not found in NamePattern. |
| 755 |
|
| 756 |
@unorderedList( |
| 757 |
@item(%d is replaced with Index. |
| 758 |
|
| 759 |
You can insert a non-negative number between % and d, to pad |
| 760 |
the counter with zeros to desired length. For example, with Counter = 2, |
| 761 |
%d is replaced with just "2", %2d is replaced with "02", |
| 762 |
%4d is replaced with "0002".) |
| 763 |
|
| 764 |
@item(%% is replaced with single percent char %.) |
| 765 |
|
| 766 |
@item(Everything else is just copied to resulting string. |
| 767 |
Not recognized %-patterns are also just copied. |
| 768 |
The main purpose of this is to specify filenames with optional |
| 769 |
placeholders, so unrecognized stuff should be gracefully ignored.) |
| 770 |
) |
| 771 |
|
| 772 |
The percent syntax was deprecated as it cannot be used with URLs. |
| 773 |
Inside URLs, percent character must always be encodede as @code(%25). |
| 774 |
Sequence like @code(%4d) must mean letter "M" (ASCII 77, which is 4d in |
| 775 |
hexadecimal) inside URL. We could potentially allow syntax like @code(%25d) |
| 776 |
or @code(%254d) (4-digit counter), but that's just ugly, and compatibility |
| 777 |
had to be broken anyway (after Castle Game Engine 4.0.1, you have to fix |
| 778 |
URLs to image sequences anyway, as @code(%4d) must mean letter "M"). |
| 779 |
|
| 780 |
See https://castle-engine.io/x3d_extensions.php#section_ext_movie_from_image_sequence |
| 781 |
for an example when this is useful. |
| 782 |
|
| 783 |
@groupBegin } |
| 784 |
function FormatNameCounter(const NamePattern: string; |
| 785 |
const Index: Integer; const AllowOldPercentSyntax: boolean; |
| 786 |
out ReplacementsDone: Cardinal): string; overload; |
| 787 |
function FormatNameCounter(const NamePattern: string; |
| 788 |
const Index: Integer; const AllowOldPercentSyntax: boolean): string; overload; |
| 789 |
{ @groupEnd } |
| 790 |
|
| 791 |
{ Does this NamePattern contain @code(@@counter) in a format understood |
| 792 |
by @link(FormatNameCounter). When @true, you can be sure @link(FormatNameCounter) |
| 793 |
actually changes the argument by replacing some @code(@@counter). } |
| 794 |
function HasNameCounter(const NamePattern: string; |
| 795 |
const AllowOldPercentSyntax: Boolean = false): Boolean; |
| 796 |
|
| 797 |
{ conversions ------------------------------------------------------------ } |
| 798 |
|
| 799 |
{ Convert digit (like number 0) to character (like '0'). |
| 800 |
Use only for arguments within 0..9 range. } |
| 801 |
function DigitAsChar(const b: byte): char; |
| 802 |
|
| 803 |
{ Convert digit character (like '0') to a number (like 0). |
| 804 |
Use only for characters in '0'...'9' range. } |
| 805 |
function DigitAsByte(const c: char): byte; |
| 806 |
|
| 807 |
{ Convert integer to string, padding string with zeros if needed. } |
| 808 |
function IntToStrZPad(n: integer; const MinLength: integer): string; |
| 809 |
|
| 810 |
{ Convert integer to string, inserting additional Separator to visually delimit |
| 811 |
thousands, milions etc. } |
| 812 |
function IntToStrThousands(const Value: Int64; const Separator: char): string; overload; |
| 813 |
function IntToStrThousands(const Value: Int64; const Separator: string): string; overload; |
| 814 |
|
| 815 |
{ Convert integer to string, in base-Base (like base-16) numeral system. |
| 816 |
For digits above '9', we will use upper letters 'A', 'B'... etc. |
| 817 |
That's also why Base cannot be larger than 'Z'-'A' + 1 + 10 |
| 818 |
(we would not have enough digits then). |
| 819 |
|
| 820 |
Overloaded versions with MinLength pad result with zeros to have |
| 821 |
at least MinLength. |
| 822 |
|
| 823 |
This is similar to the standard StrUtils.Dec2Numb, |
| 824 |
but it can handle negative numbers without any problems (adds a minus |
| 825 |
sign at the beginning then). |
| 826 |
|
| 827 |
@groupBegin } |
| 828 |
function IntToStrBase(const N: Int64; const Base: Byte): string; overload; |
| 829 |
function IntToStrBase( N: QWord; const Base: Byte): string; overload; |
| 830 |
function IntToStrBase(const N: Int64; const Base: Byte; const MinLength: Cardinal): string; overload; |
| 831 |
function IntToStrBase(const N: QWord; const Base: Byte; const MinLength: Cardinal): string; overload; |
| 832 |
{ @groupEnd } |
| 833 |
|
| 834 |
{ Convert integer to binary (base-2 numeral system). |
| 835 |
MinLength means to left-pad result with zeros if necessary. |
| 836 |
|
| 837 |
This is similar to the standard StrUtils.IntToBin function, |
| 838 |
but this works in an obvious way for negative numbers |
| 839 |
(adds a minus sign at the beginning). } |
| 840 |
function IntToStr2(n: Int64; |
| 841 |
const MinLength: Cardinal = 1; |
| 842 |
const ZeroDigit: char = '0'; |
| 843 |
const OneDigit: char = '1'; |
| 844 |
const MinusSign: char = '-'): string; overload; |
| 845 |
|
| 846 |
{ Convert integer to hexadecimal (base-16 numeric system). |
| 847 |
|
| 848 |
This is similar to the standard SysUtils.IntToHex function, |
| 849 |
but this works in an obvious way for negative numbers |
| 850 |
(adds a minus sign at the beginning). |
| 851 |
Contrast this with SysUtils.IntToHex, that instead shows the value |
| 852 |
of negative integer typecasted as unsigned (so it's in 2-completent). |
| 853 |
So IntToHex(-1, 1) = 'FFFFFFFF', while |
| 854 |
IntToStr16(-1) = '-1'. |
| 855 |
|
| 856 |
@groupBegin } |
| 857 |
function IntToStr16(const n: Int64; const MinLength: Cardinal = 1): string; overload; |
| 858 |
function IntToStr16(const n: QWord; const MinLength: Cardinal = 1): string; overload; |
| 859 |
{ @groupEnd } |
| 860 |
|
| 861 |
{ Returns Ptr as 0xXXX... hexadecimal value. "0x" is not a Pascal standard |
| 862 |
for coding hex values, but it's so popular that users are more likely |
| 863 |
to "get" 0x notation. } |
| 864 |
function PointerToStr(const Ptr: Pointer): string; |
| 865 |
|
| 866 |
{ Convert string representing binary number to an integer. |
| 867 |
String must contain only '0', '1' (digits) and start with an optional sign |
| 868 |
(+ or -). |
| 869 |
|
| 870 |
This is similar to the standard StrUtils.Numb2Dec (with Base = 2) function, |
| 871 |
but this reliably raises EConvertError in case of trouble. |
| 872 |
|
| 873 |
@raises EConvertError In case of invalid string. } |
| 874 |
function Str2ToInt(const s: string): integer; |
| 875 |
|
| 876 |
{ Convert string with hexadecimal number to an integer. |
| 877 |
String must contain only digits (0-9, a-z, A-Z), and with an optional |
| 878 |
sign (+ or -). |
| 879 |
|
| 880 |
This is similar to the standard StrUtils.Hex2Dec function, |
| 881 |
but it returns an Int64 value. So this is safer and more consistent |
| 882 |
with standard StrToInt. |
| 883 |
|
| 884 |
@raises EConvertError In case of invalid string. } |
| 885 |
function StrHexToInt(const s: string): Int64; |
| 886 |
|
| 887 |
function StrToFloatDef(const s: string; DefValue: Extended): Extended; |
| 888 |
deprecated 'use StrToFloatDefDot in most cases, to have dot as decimal separator'; |
| 889 |
|
| 890 |
{ Convert a set to a string representation, in somewhat hacky way. |
| 891 |
This assumes that given SetVariable is a set value, and the set type |
| 892 |
is "set of [NumStart .. NumEnd]". |
| 893 |
|
| 894 |
@italic(Implementation is heavily dependent on how the sets are internally |
| 895 |
stored.) |
| 896 |
For now, we depend that a set of [NumStart .. NumEnd] behaves like a set |
| 897 |
of Byte, shifted to the left (i.e., NumStart corresponds to a 0 in set of Byte). |
| 898 |
This is not necessarily true ! For example in Delphi 5 (as far as I remember |
| 899 |
--- I don't have this Delphi now, and I don't remember on which Delphi |
| 900 |
version I observed this) set of 1..16 uses first three bytes, and |
| 901 |
the first bit (that would correspond to 0) is simply wasted. In fact, |
| 902 |
SizeOf such set is still 4, which means that internally sets eat 4 bytes anyway. |
| 903 |
But SizeOf set 200..216 is also 4, which means that the compiler is smart |
| 904 |
and doesn't waste too much space to store only 17 bits. |
| 905 |
|
| 906 |
This all is not a rant on internal set handling by Delphi. On the contrary, |
| 907 |
Delphi does it for speed reasons, and that's very good. This is just |
| 908 |
a warning that SetToStr is not really reliable, and you may need to experiment |
| 909 |
a little with NumStart / NumEnd values to get sensible results. |
| 910 |
Although if your set is like "set of [0 ... something]", this should usually |
| 911 |
work OK. |
| 912 |
|
| 913 |
Still: @italic(this function should be used only for debug purposes. |
| 914 |
Don't depend on it working 100% correctly always --- it can't, because we |
| 915 |
can't depend on how compiler stores sets.) } |
| 916 |
function SetToStr(const SetVariable; NumStart, NumEnd: byte): string; |
| 917 |
|
| 918 |
function CharSetToStr(const SetVariable: TSetOfChars): string; |
| 919 |
|
| 920 |
{ PCharOrNil simply returns a Pointer(S), you can think of it as a NO-OP. |
| 921 |
If string is empty, this returns @nil, otherwise it works just like |
| 922 |
PChar(S): returns a Pointer(S) with appropriate type cast. } |
| 923 |
function PCharOrNil(const s: string): PChar; |
| 924 |
|
| 925 |
{ PWideCharOrNil simply returns a Pointer(S), you can think of it as a NO-OP. |
| 926 |
If string is empty, this returns @nil, otherwise it works just like |
| 927 |
PWideChar(S): returns a Pointer(S) with appropriate type cast. } |
| 928 |
function PWideCharOrNil(const s: WideString): PWideChar; |
| 929 |
|
| 930 |
{ PAnsiCharOrNil simply returns a Pointer(S), you can think of it as a NO-OP. |
| 931 |
If string is empty, this returns @nil, otherwise it works just like |
| 932 |
PAnsiChar(S): returns a Pointer(S) with appropriate type cast. } |
| 933 |
function PAnsiCharOrNil(const s: AnsiString): PAnsiChar; |
| 934 |
|
| 935 |
{ Replace any number of consecutive whitespace (including newlines) |
| 936 |
with a single whitespace. This is nice when you have a string |
| 937 |
(possibly multiline) supplied by user, and you want to use this |
| 938 |
for some UI item (like window's caption or menu item) --- this |
| 939 |
"sanitizes" whitespace inside such string. } |
| 940 |
function SCompressWhiteSpace(const S: string): string; |
| 941 |
|
| 942 |
type |
| 943 |
EInvalidChar = class(Exception); |
| 944 |
|
| 945 |
{ Check that all characters are within a given set. |
| 946 |
Raise exception otherwise (if RaiseExceptionOnError, default) |
| 947 |
or make a warning. |
| 948 |
@raises(EInvalidChar If string contains an invalid character |
| 949 |
and RaiseExceptionOnError = @true. |
| 950 |
The exception string is informative, containing the string value, |
| 951 |
character, character position.) } |
| 952 |
procedure SCheckChars(const S: string; const ValidChars: TSetOfChars; |
| 953 |
const RaiseExceptionOnError: boolean = true); |
| 954 |
|
| 955 |
{ Remove one newline from the end of the string, if any. } |
| 956 |
function TrimEndingNewline(const S: String): String; |
| 957 |
|
| 958 |
{ Format size of file, in bytes / megabytes / and so on, whatever looks nice. } |
| 959 |
function SizeToStr(const Value: Int64): String; |
| 960 |
|
| 961 |
{ Convert String to UTF-16 (UnicodeString). |
| 962 |
On Delphi (more generally: on compilers where String is already UnicodeString, which is UTF-16), |
| 963 |
this does nothing. |
| 964 |
On FPC (more generally: on compilers where String is AnsiString with UTF-8 encoding), |
| 965 |
this converts UTF-8 into UTF-16 UnicodeString. } |
| 966 |
function StringToUtf16(const Src: String): UnicodeString; inline; |
| 967 |
|
| 968 |
{ Convert UTF-16 (UnicodeString) to String. |
| 969 |
On Delphi (more generally: on compilers where String is already UnicodeString, which is UTF-16), |
| 970 |
this does nothing. |
| 971 |
On FPC (more generally: on compilers where String is AnsiString with UTF-8 encoding), |
| 972 |
this converts UTF-16 into UTF-8. } |
| 973 |
function Utf16ToString(const Src: UnicodeString): String; inline; |
| 974 |
|
| 975 |
const |
| 976 |
{ } |
| 977 |
CtrlA = Chr(Ord('a') - Ord('a') + 1); { = #1 } { } |
| 978 |
CtrlB = Chr(Ord('b') - Ord('a') + 1); { = #2 } { } |
| 979 |
CtrlC = Chr(Ord('c') - Ord('a') + 1); { ... etc. } { } |
| 980 |
CtrlD = Chr(Ord('d') - Ord('a') + 1); |
| 981 |
CtrlE = Chr(Ord('e') - Ord('a') + 1); |
| 982 |
CtrlF = Chr(Ord('f') - Ord('a') + 1); |
| 983 |
CtrlG = Chr(Ord('g') - Ord('a') + 1); |
| 984 |
CtrlH = Chr(Ord('h') - Ord('a') + 1); { = CharBackspace } { } |
| 985 |
CtrlI = Chr(Ord('i') - Ord('a') + 1); { = CharTab } { } |
| 986 |
CtrlJ = Chr(Ord('j') - Ord('a') + 1); |
| 987 |
CtrlK = Chr(Ord('k') - Ord('a') + 1); |
| 988 |
CtrlL = Chr(Ord('l') - Ord('a') + 1); |
| 989 |
CtrlM = Chr(Ord('m') - Ord('a') + 1); { = CharEnter } { } |
| 990 |
CtrlN = Chr(Ord('n') - Ord('a') + 1); |
| 991 |
CtrlO = Chr(Ord('o') - Ord('a') + 1); |
| 992 |
CtrlP = Chr(Ord('p') - Ord('a') + 1); |
| 993 |
CtrlQ = Chr(Ord('q') - Ord('a') + 1); |
| 994 |
CtrlR = Chr(Ord('r') - Ord('a') + 1); |
| 995 |
CtrlS = Chr(Ord('s') - Ord('a') + 1); |
| 996 |
CtrlT = Chr(Ord('t') - Ord('a') + 1); |
| 997 |
CtrlU = Chr(Ord('u') - Ord('a') + 1); |
| 998 |
CtrlV = Chr(Ord('v') - Ord('a') + 1); |
| 999 |
CtrlW = Chr(Ord('w') - Ord('a') + 1); |
| 1000 |
CtrlX = Chr(Ord('x') - Ord('a') + 1); |
| 1001 |
CtrlY = Chr(Ord('y') - Ord('a') + 1); |
| 1002 |
CtrlZ = Chr(Ord('z') - Ord('a') + 1); { = #26 } { } |
| 1003 |
|
| 1004 |
CharBackSpace = #8; |
| 1005 |
CharTab = #9; |
| 1006 |
CharEnter = #13; |
| 1007 |
CharEscape = #27; |
| 1008 |
CharDelete = #127; |
| 1009 |
|
| 1010 |
implementation |
| 1011 |
|
| 1012 |
uses {$ifdef FPC} Regexpr {$else} RegularExpressions, Character {$endif}, |
| 1013 |
StrUtils, CastleLog; |
| 1014 |
|
| 1015 |
{ TStringsHelper ------------------------------------------------------------- } |
| 1016 |
|
| 1017 |
function TStringsHelper.ToArray: TDynamicStringArray; |
| 1018 |
var |
| 1019 |
I: Integer; |
| 1020 |
begin |
| 1021 |
SetLength(Result, Count); |
| 1022 |
for I := 0 to Count - 1 do |
| 1023 |
Result[I] := Strings[I]; |
| 1024 |
end; |
| 1025 |
|
| 1026 |
procedure TStringsHelper.AddMultiLine(const S: String); |
| 1027 |
var |
| 1028 |
SList: TStringList; |
| 1029 |
I: Integer; |
| 1030 |
begin |
| 1031 |
if S = '' then |
| 1032 |
Add('') |
| 1033 |
else |
| 1034 |
begin |
| 1035 |
SList := TStringList.Create; |
| 1036 |
try |
| 1037 |
SList.Text := S; |
| 1038 |
for I := 0 to SList.Count - 1 do |
| 1039 |
Add(SList[I]); |
| 1040 |
finally FreeAndNil(SList) end; |
| 1041 |
end; |
| 1042 |
end; |
| 1043 |
|
| 1044 |
{ TCastleStringList ------------------------------------------------------------- } |
| 1045 |
|
| 1046 |
constructor TCastleStringList.Create; |
| 1047 |
begin |
| 1048 |
inherited; |
| 1049 |
CaseSensitive := true; |
| 1050 |
end; |
| 1051 |
|
| 1052 |
procedure TCastleStringList.SetCount(const Value: Integer); |
| 1053 |
var |
| 1054 |
I: TListSize; |
| 1055 |
begin |
| 1056 |
{ Use local variable I, instead of comparing Value = Count for, |
| 1057 |
to possibly speed up a little (GetCount is virtual) } |
| 1058 |
if Value < Count then |
| 1059 |
begin |
| 1060 |
for I := 1 to Count - Value do Delete(Count - 1); |
| 1061 |
end else |
| 1062 |
if Value > Count then |
| 1063 |
begin |
| 1064 |
for I := 1 to Value - Count do Add(''); |
| 1065 |
end; |
| 1066 |
end; |
| 1067 |
|
| 1068 |
{$ifndef FPC} |
| 1069 |
procedure TCastleStringList.AddSubRange(const Source: TStringList; const Index, AddCount: TListSize); |
| 1070 |
var |
| 1071 |
I: TListSize; |
| 1072 |
begin |
| 1073 |
for I := Index to Index + AddCount do |
| 1074 |
begin |
| 1075 |
Add(Source[I]); |
| 1076 |
end; |
| 1077 |
end; |
| 1078 |
{$endif} |
| 1079 |
|
| 1080 |
procedure TCastleStringList.AddRange(const Source: TStrings); |
| 1081 |
begin |
| 1082 |
AddStrings(Source); |
| 1083 |
end; |
| 1084 |
|
| 1085 |
procedure TCastleStringList.AddList(const Source: TStrings); |
| 1086 |
begin |
| 1087 |
AddStrings(Source); |
| 1088 |
end; |
| 1089 |
|
| 1090 |
procedure TCastleStringList.AddRange(const A: array of string); |
| 1091 |
var |
| 1092 |
I: TListSize; |
| 1093 |
begin |
| 1094 |
for I := 0 to High(A) do |
| 1095 |
Add(A[I]); |
| 1096 |
end; |
| 1097 |
|
| 1098 |
procedure TCastleStringList.AddArray(const A: array of string); |
| 1099 |
begin |
| 1100 |
AddRange(A); |
| 1101 |
end; |
| 1102 |
|
| 1103 |
procedure TCastleStringList.AssignArray(const A: array of string); |
| 1104 |
begin |
| 1105 |
Assign(A); |
| 1106 |
end; |
| 1107 |
|
| 1108 |
procedure TCastleStringList.Assign(const A: array of string); |
| 1109 |
begin |
| 1110 |
Clear; |
| 1111 |
AddRange(A); |
| 1112 |
end; |
| 1113 |
|
| 1114 |
{$ifndef FPC} |
| 1115 |
procedure TCastleStringList.Assign(const Source: TStringList); |
| 1116 |
begin |
| 1117 |
Assign(Source.ToStringArray); |
| 1118 |
end; |
| 1119 |
{$endif} |
| 1120 |
|
| 1121 |
procedure TCastleStringList.Reverse; |
| 1122 |
var |
| 1123 |
I: TListSize; |
| 1124 |
begin |
| 1125 |
{ Need to specially check for Count = 0 case, since (0-1) div 2 = -1 div 2 = 0 |
| 1126 |
which means that loop would try invalid Exchange(0, -1). } |
| 1127 |
if Count = 0 then Exit; |
| 1128 |
for I := 0 to (Count - 1) div 2 do |
| 1129 |
Exchange(I, Count - 1 - I); |
| 1130 |
end; |
| 1131 |
|
| 1132 |
{$ifndef FPC} |
| 1133 |
function TCastleStringList.DoCompareText(const A, B: string): Integer; |
| 1134 |
begin |
| 1135 |
if CaseSensitive then |
| 1136 |
Result := AnsiCompareStr(A, B) |
| 1137 |
else |
| 1138 |
Result := AnsiCompareText(A, B); |
| 1139 |
end; |
| 1140 |
{$endif} |
| 1141 |
|
| 1142 |
function TCastleStringList.Equals(SecondValue: TObject): boolean; |
| 1143 |
var |
| 1144 |
I: TListSize; |
| 1145 |
begin |
| 1146 |
Result := SecondValue is TStrings; |
| 1147 |
if Result then |
| 1148 |
begin |
| 1149 |
Result := Count = TStrings(SecondValue).Count; |
| 1150 |
if Result then |
| 1151 |
for I := 0 to Count - 1 do |
| 1152 |
if DoCompareText(Strings[I], TStrings(SecondValue)[I]) <> 0 then |
| 1153 |
begin |
| 1154 |
Result := false; |
| 1155 |
Exit; |
| 1156 |
end; |
| 1157 |
end; |
| 1158 |
end; |
| 1159 |
|
| 1160 |
function TCastleStringList.Equals(const A: array of string): boolean; |
| 1161 |
var |
| 1162 |
I: TListSize; |
| 1163 |
begin |
| 1164 |
if High(A) <> Count - 1 then Exit(false); |
| 1165 |
for I := 0 to Count - 1 do |
| 1166 |
if DoCompareText(A[I], Strings[I]) <> 0 then |
| 1167 |
Exit(false); |
| 1168 |
Result := true; |
| 1169 |
end; |
| 1170 |
|
| 1171 |
function TCastleStringList.PerfectlyEquals(const SecondValue: TStringList): boolean; |
| 1172 |
begin |
| 1173 |
Result := Equals(SecondValue); |
| 1174 |
end; |
| 1175 |
|
| 1176 |
function TCastleStringList.GetL(const Index: TListSize): string; |
| 1177 |
begin |
| 1178 |
Result := Strings[Index]; |
| 1179 |
end; |
| 1180 |
|
| 1181 |
procedure TCastleStringList.SetL(const Index: TListSize; const S: string); |
| 1182 |
begin |
| 1183 |
Strings[Index] := S; |
| 1184 |
end; |
| 1185 |
|
| 1186 |
{ TStringStringMap ----------------------------------------------------------- } |
| 1187 |
|
| 1188 |
procedure TStringStringMap.PutPreserve(const Name, Content: string); |
| 1189 |
var |
| 1190 |
PreviousContent: string; |
| 1191 |
begin |
| 1192 |
if TryGetValue(Name, PreviousContent) and |
| 1193 |
(PreviousContent <> Content) then |
| 1194 |
{ move current content to -previous name } |
| 1195 |
Items[Name + '-previous'] := PreviousContent; |
| 1196 |
|
| 1197 |
{ set new content } |
| 1198 |
Items[Name] := Content; |
| 1199 |
end; |
| 1200 |
|
| 1201 |
function TStringStringMap.CreateCopy: TStringStringMap; |
| 1202 |
begin |
| 1203 |
Result := TStringStringMap.Create; |
| 1204 |
try |
| 1205 |
Result.Assign(Self); |
| 1206 |
except FreeAndNil(Result); raise end; |
| 1207 |
end; |
| 1208 |
|
| 1209 |
procedure TStringStringMap.Assign(const Source: TStringStringMap); |
| 1210 |
var |
| 1211 |
Pair: {$ifdef FPC} TDictionaryPair {$else} TPair<string, string> {$endif}; |
| 1212 |
begin |
| 1213 |
Clear; |
| 1214 |
for Pair in Source do |
| 1215 |
Items[Pair.Key] := Pair.Value; |
| 1216 |
end; |
| 1217 |
|
| 1218 |
function TStringStringMap.GetItems(const AKey: string): string; |
| 1219 |
begin |
| 1220 |
Result := inherited Items[AKey]; |
| 1221 |
end; |
| 1222 |
|
| 1223 |
procedure TStringStringMap.SetItems(const AKey: string; const AValue: String); |
| 1224 |
begin |
| 1225 |
AddOrSetValue(AKey, AValue); |
| 1226 |
end; |
| 1227 |
|
| 1228 |
{ routines ------------------------------------------------------------------- } |
| 1229 |
|
| 1230 |
function RandomString: string; |
| 1231 |
var i: integer; |
| 1232 |
begin |
| 1233 |
result := ''; |
| 1234 |
for i := 1 to random(10) do result := result+char(byte('A')+Random(26)); |
| 1235 |
for i := 1 to 3 do result := result+char(byte('0')+Random(10)); |
| 1236 |
end; |
| 1237 |
|
| 1238 |
procedure StringReplaceAllVar(var S: string; |
| 1239 |
const FromPattern, ToPattern: string; |
| 1240 |
IgnoreCase: boolean); |
| 1241 |
(* |
| 1242 |
{ NAIWNA IMPLEMENTACJA : zawsze szuka w nowym s od subs_orig od poczatku |
| 1243 |
(w rezultacie poczatek stringa przeszukajac wiele razy niepotrzebnie). |
| 1244 |
No i moze sie zapetlic gdy subs_repl zawiera w sobie subs_orig. } |
| 1245 |
var p: integer; |
| 1246 |
begin |
| 1247 |
{assert( Pos(subs_orig, subs_repl) = 0 , 'blad w ReplaceSubstr !');} |
| 1248 |
p := Pos(subs_orig, s); (tutaj powinna byc sterowana IgnoreCase) } |
| 1249 |
while p > 0 do |
| 1250 |
begin |
| 1251 |
Delete(s, p, length(subs_Orig)); |
| 1252 |
Insert(subs_repl, s, p); |
| 1253 |
p := Pos(subs_orig, s); (tutaj powinna byc sterowana IgnoreCase) |
| 1254 |
end; |
| 1255 |
*) |
| 1256 |
begin |
| 1257 |
if IgnoreCase then |
| 1258 |
s := StringReplace(s, FromPattern, ToPattern, [rfReplaceAll, rfIgnoreCase]) else |
| 1259 |
s := StringReplace(s, FromPattern, ToPattern, [rfReplaceAll]); |
| 1260 |
end; |
| 1261 |
|
| 1262 |
function BreakLine(const S: string; const MaxCol: integer; |
| 1263 |
const AllowedBreakChars: TSetOfChars): string; |
| 1264 |
begin |
| 1265 |
Result := BreakLine(S, MaxCol, AllowedBreakChars, NL, ''); |
| 1266 |
end; |
| 1267 |
|
| 1268 |
function BreakLine(const S: string; const MaxCol: integer; |
| 1269 |
const AllowedBreakChars: TSetOfChars; |
| 1270 |
const Newline: string; const Indent: string): string; |
| 1271 |
var |
| 1272 |
done: integer; |
| 1273 |
nowcol, i, brk: integer; |
| 1274 |
BrokenSuccess: boolean; |
| 1275 |
begin |
| 1276 |
// WrapText is not perfect, in looks for AllowedBreakChars after MaxCol. |
| 1277 |
// It also doesn't have Indent that is added to existing newlines. |
| 1278 |
// Result := WrapText(S, Newline, AllowedBreakChars, MaxCol); |
| 1279 |
// Exit; |
| 1280 |
|
| 1281 |
Done := 0; |
| 1282 |
Result := ''; |
| 1283 |
|
| 1284 |
i := 1; |
| 1285 |
while i <= Length(s) do |
| 1286 |
begin |
| 1287 |
if CharInSet(S[i], [#10, #13]) then |
| 1288 |
begin |
| 1289 |
{ let i include whole newline sequence, which may be 2-character #13#10 or #10#13 } |
| 1290 |
case s[i] of |
| 1291 |
#13 : if SCharIs(s, i+1, #10) then Inc(i); |
| 1292 |
#10 : if SCharIs(s, i+1, #13) then Inc(i); |
| 1293 |
end; |
| 1294 |
Result := Result + CopyPos(s, Done+1, i) + Indent; |
| 1295 |
Done := i; |
| 1296 |
end else |
| 1297 |
begin |
| 1298 |
NowCol := i - Done; |
| 1299 |
if NowCol > MaxCol then |
| 1300 |
begin |
| 1301 |
{ we got line s[done+1..i] that we have to break somewhere. } |
| 1302 |
BrokenSuccess := false; |
| 1303 |
for brk := i downto Done + 1 do |
| 1304 |
if CharInSet(s[brk], AllowedBreakChars) then |
| 1305 |
begin |
| 1306 |
Result := Result + CopyPos(s, Done+1, Brk-1) + Newline + Indent; |
| 1307 |
Done := brk; { we left the rest : s[brk+1..i] to be done } |
| 1308 |
BrokenSuccess := true; |
| 1309 |
Break; |
| 1310 |
end; |
| 1311 |
if not BrokenSuccess then |
| 1312 |
begin |
| 1313 |
{ line can't be broken - no AllowedBreakChars found. |
| 1314 |
So we break after done+maxcol position. } |
| 1315 |
Result := Result + Copy(s, Done+1, MaxCol) + Newline + Indent; |
| 1316 |
Done := Done + MaxCol; |
| 1317 |
end; |
| 1318 |
end; |
| 1319 |
end; |
| 1320 |
|
| 1321 |
Inc(i); |
| 1322 |
end; |
| 1323 |
|
| 1324 |
if Done < Length(S) then |
| 1325 |
Result := Result + SEnding(S, Done+1); |
| 1326 |
end; |
| 1327 |
|
| 1328 |
function SDeleteChars(const s: string; const excludedChars: TSetOfChars): string; |
| 1329 |
var |
| 1330 |
i, j: integer; |
| 1331 |
begin |
| 1332 |
SetLength(result, length(s)); |
| 1333 |
j := 1; |
| 1334 |
for i := 1 to length(s) do |
| 1335 |
if not CharInSet(s[i], excludedChars) then |
| 1336 |
begin result[j] := s[i]; Inc(j); end; |
| 1337 |
SetLength(result, j-1); |
| 1338 |
end; |
| 1339 |
|
| 1340 |
function SReplaceChars(const s, FromChars, ToChars: string): string; |
| 1341 |
var |
| 1342 |
i, p: integer; |
| 1343 |
begin |
| 1344 |
Assert(Length(FromChars) = Length(ToChars)); |
| 1345 |
result := s; |
| 1346 |
for i := 1 to Length(result) do |
| 1347 |
begin |
| 1348 |
p := Pos(result[i], FromChars); |
| 1349 |
if p > 0 then result[i] := ToChars[p]; |
| 1350 |
end; |
| 1351 |
end; |
| 1352 |
|
| 1353 |
function SReplaceChars(const s: string; const FromChars: TSetOfChars; const ToChar: char): string; |
| 1354 |
var |
| 1355 |
I: TListSize; |
| 1356 |
begin |
| 1357 |
Result := s; |
| 1358 |
for I := 1 to Length(Result) do |
| 1359 |
if CharInSet(Result[i], FromChars) then |
| 1360 |
Result[i] := ToChar; |
| 1361 |
end; |
| 1362 |
|
| 1363 |
function SReplaceChars(const s: string; const FromChar, ToChar: char): string; |
| 1364 |
var |
| 1365 |
i: TListSize; |
| 1366 |
begin |
| 1367 |
Result := S; |
| 1368 |
for i := 1 to Length(Result) do |
| 1369 |
if Result[i] = FromChar then Result[i] := ToChar; |
| 1370 |
end; |
| 1371 |
|
| 1372 |
function SPad(const s: string; len: integer; c: char): string; |
| 1373 |
var |
| 1374 |
lnow: integer; |
| 1375 |
begin |
| 1376 |
lnow := length(s); |
| 1377 |
if lnow < len then |
| 1378 |
Result := StringOfChar(c, len-lnow) + s else |
| 1379 |
Result := s; |
| 1380 |
end; |
| 1381 |
|
| 1382 |
function SZeroPad(const s: string; len: integer): string; |
| 1383 |
begin result := SPad(s, len, '0') end; |
| 1384 |
|
| 1385 |
function LoCase(const C: Char): Char; |
| 1386 |
begin |
| 1387 |
if CharInSet(C, ['A'..'Z']) then |
| 1388 |
Result := Chr(Ord(C) - Ord('A') + Ord('a')) |
| 1389 |
else |
| 1390 |
Result := C; |
| 1391 |
end; |
| 1392 |
|
| 1393 |
function CharPos(c: char; const s: string; Offset: Integer): integer; |
| 1394 |
var |
| 1395 |
i: integer; |
| 1396 |
begin |
| 1397 |
for i := Offset to length(s) do |
| 1398 |
if s[i] = c then begin result := i; exit end; |
| 1399 |
result := 0; |
| 1400 |
end; |
| 1401 |
|
| 1402 |
function CharsPos(const Chars: TSetOfChars; const S: String): Integer; |
| 1403 |
begin |
| 1404 |
for Result := 1 to Length(S) do |
| 1405 |
if CharInSet(S[result], Chars) then |
| 1406 |
Exit; |
| 1407 |
Result := 0; |
| 1408 |
end; |
| 1409 |
|
| 1410 |
function CharsPosEx(const Chars: TSetOfChars; const S: string; |
| 1411 |
const Offset: Integer): Integer; |
| 1412 |
begin |
| 1413 |
for Result := Offset to Length(S) do |
| 1414 |
if CharInSet(S[Result], Chars) then |
| 1415 |
Exit; |
| 1416 |
Result := 0; |
| 1417 |
end; |
| 1418 |
|
| 1419 |
function BackCharsPos(const chars: TSetOfChars; const s: string): integer; |
| 1420 |
begin |
| 1421 |
for Result := Length(S) downto 1 do |
| 1422 |
if CharInSet(S[Result], Chars) then |
| 1423 |
Exit; |
| 1424 |
Result := 0; |
| 1425 |
end; |
| 1426 |
|
| 1427 |
function BackPos(const SubString, S: string): integer; |
| 1428 |
begin |
| 1429 |
for Result := Length(S) - Length(SubString) + 1 downto 1 do |
| 1430 |
if SubString = Copy(S, Result, Length(SubString)) then Exit; |
| 1431 |
Result := 0; |
| 1432 |
end; |
| 1433 |
|
| 1434 |
function BackPos(const SubString: char; const S: string): Integer; |
| 1435 |
begin |
| 1436 |
for Result := Length(S) downto 1 do |
| 1437 |
if S[Result] = SubString then Exit; |
| 1438 |
Result := 0; |
| 1439 |
end; |
| 1440 |
|
| 1441 |
function FirstDelimiter(const Delimiters, S: string): Integer; |
| 1442 |
begin |
| 1443 |
for result := 1 to Length(s) do |
| 1444 |
if Pos(S[result], Delimiters) <> 0 then exit; |
| 1445 |
result := 0; |
| 1446 |
end; |
| 1447 |
|
| 1448 |
function SEnding(const S: string; P: integer): string; |
| 1449 |
begin |
| 1450 |
result := Copy(S, P, MaxInt) |
| 1451 |
end; |
| 1452 |
|
| 1453 |
function IsPrefix(const Prefix, S: string; IgnoreCase: boolean): boolean; |
| 1454 |
begin |
| 1455 |
if IgnoreCase then |
| 1456 |
Result := AnsiCompareText(Copy(S, 1, Length(Prefix)), Prefix) = 0 else |
| 1457 |
Result := AnsiCompareStr(Copy(S, 1, Length(Prefix)), Prefix) = 0; |
| 1458 |
end; |
| 1459 |
|
| 1460 |
function IsSuffix(const Suffix, S: string; IgnoreCase: boolean): boolean; |
| 1461 |
begin |
| 1462 |
if IgnoreCase then |
| 1463 |
result := AnsiCompareText(SRight(S, Length(Suffix)), Suffix) = 0 else |
| 1464 |
result := AnsiCompareStr(SRight(S, Length(Suffix)), Suffix) = 0; |
| 1465 |
end; |
| 1466 |
|
| 1467 |
function PrefixRemove(const Prefix, S: string; IgnoreCase: boolean): string; |
| 1468 |
begin |
| 1469 |
if IsPrefix(Prefix, S, IgnoreCase) then |
| 1470 |
Result := SEnding(S, Length(Prefix) + 1) else |
| 1471 |
Result := S; |
| 1472 |
end; |
| 1473 |
|
| 1474 |
function SuffixRemove(const Suffix, S: string; IgnoreCase: boolean): string; |
| 1475 |
begin |
| 1476 |
Result := S; |
| 1477 |
if IsSuffix(Suffix, S, IgnoreCase) then |
| 1478 |
begin |
| 1479 |
{ doing assignment and SetLength should be a little faster |
| 1480 |
than doing Result := Copy(S, 1, ...) } |
| 1481 |
SetLength(Result, Length(s) - Length(Suffix)); |
| 1482 |
end; |
| 1483 |
end; |
| 1484 |
|
| 1485 |
procedure SAppendData(var s: string; const Data; DataSize: integer); |
| 1486 |
var |
| 1487 |
OldLen: integer; |
| 1488 |
begin |
| 1489 |
OldLen := Length(s); |
| 1490 |
SetLength(s, OldLen+DataSize); |
| 1491 |
{$warnings off} |
| 1492 |
// using deprecated within deprecated |
| 1493 |
Move(Data, SChar(s, OldLen+1)^ , DataSize); |
| 1494 |
{$warnings on} |
| 1495 |
end; |
| 1496 |
|
| 1497 |
{$Include NoRQCheckBegin.inc} |
| 1498 |
function SChar(const s: string; CharNum: integer): PChar; |
| 1499 |
begin |
| 1500 |
Result := @s[CharNum] |
| 1501 |
end; |
| 1502 |
{$Include NoRQCheckEnd.inc} |
| 1503 |
|
| 1504 |
function SCharIs(const S: String; const Index: Integer; const C: Char): Boolean; |
| 1505 |
begin |
| 1506 |
Result := (Index <= Length(S)) and (S[Index] = C) |
| 1507 |
end; |
| 1508 |
|
| 1509 |
function SCharIs(const S: string; const Index: integer; const Chars: TSetOfChars): Boolean; |
| 1510 |
begin |
| 1511 |
Result := (Index <= Length(S)) and CharInSet(S[Index], chars); |
| 1512 |
end; |
| 1513 |
|
| 1514 |
function SReadableForm(const S: String): String; |
| 1515 |
var |
| 1516 |
I: Integer; |
| 1517 |
begin |
| 1518 |
Result := ''; |
| 1519 |
for I := 1 to Length(S) do |
| 1520 |
Result := Result + SReadableForm(S[I]); |
| 1521 |
end; |
| 1522 |
|
| 1523 |
function SReadableForm(const C: char): string; |
| 1524 |
begin |
| 1525 |
if (Ord(C) < Ord(' ')) or (Ord(C) >= 128) then |
| 1526 |
Result := '#'+IntToStr(Ord(C)) else |
| 1527 |
Result := C; |
| 1528 |
end; |
| 1529 |
|
| 1530 |
function CopyPos(const s: string; StartPosition, EndPosition: integer): string; |
| 1531 |
begin |
| 1532 |
result := Copy(s, StartPosition, EndPosition - StartPosition + 1); |
| 1533 |
end; |
| 1534 |
|
| 1535 |
procedure DeletePos(var S: string; StartPosition, EndPosition: Integer); |
| 1536 |
begin |
| 1537 |
Delete(S, StartPosition, EndPosition - StartPosition + 1); |
| 1538 |
end; |
| 1539 |
|
| 1540 |
function NextToken(const S: string; var SeekPos: Integer; |
| 1541 |
const TokenDelims: TSetOfChars): string; |
| 1542 |
var |
| 1543 |
TokStart: Integer; |
| 1544 |
begin |
| 1545 |
repeat |
| 1546 |
if SeekPos > Length(s) then begin Result := ''; Exit end; |
| 1547 |
if CharInSet(S[SeekPos], TokenDelims) then |
| 1548 |
Inc(SeekPos) |
| 1549 |
else |
| 1550 |
Break; |
| 1551 |
until false; |
| 1552 |
TokStart := SeekPos; { TokStart := first character not in TokenDelims } |
| 1553 |
|
| 1554 |
while (SeekPos <= Length(S)) and |
| 1555 |
not CharInSet(S[SeekPos], TokenDelims) do |
| 1556 |
Inc(SeekPos); |
| 1557 |
|
| 1558 |
{ Calculate result := s[TokStart, ... , SeekPos-1] } |
| 1559 |
result := Copy(s, TokStart, SeekPos-TokStart); |
| 1560 |
|
| 1561 |
{ We don't have to do Inc(seekPos) below. But it's obvious that searching |
| 1562 |
for next token can skip SeekPos, since we know S[SeekPos] is TokenDelim. } |
| 1563 |
Inc(SeekPos); |
| 1564 |
end; |
| 1565 |
|
| 1566 |
function CountTokens(const S: String; const TokenDelims: TSetOfChars): Integer; |
| 1567 |
var |
| 1568 |
I: Integer; |
| 1569 |
IsToken: Boolean; |
| 1570 |
begin |
| 1571 |
Result := 0; |
| 1572 |
IsToken := false; |
| 1573 |
for I := 1 to Length(S) do |
| 1574 |
begin |
| 1575 |
if IsToken then |
| 1576 |
begin |
| 1577 |
{ Inside token? Then detect token end. } |
| 1578 |
if CharInSet(S[I], TokenDelims) then |
| 1579 |
IsToken := false; |
| 1580 |
end else |
| 1581 |
begin |
| 1582 |
{ Not inside token? Then detect token begin. } |
| 1583 |
if not CharInSet(S[I], TokenDelims) then |
| 1584 |
begin |
| 1585 |
IsToken := true; |
| 1586 |
Inc(Result); |
| 1587 |
end; |
| 1588 |
end; |
| 1589 |
end; |
| 1590 |
end; |
| 1591 |
|
| 1592 |
function NextTokenOnce(const s: string; SeekPos: integer; |
| 1593 |
const TokenDelims: TSetOfChars): string; |
| 1594 |
begin |
| 1595 |
result := Nexttoken(S, SeekPos, TokenDelims); |
| 1596 |
end; |
| 1597 |
|
| 1598 |
function CreateTokens(const s: string; |
| 1599 |
const TokenDelims: TSetOfChars): TCastleStringList; |
| 1600 |
var |
| 1601 |
SeekPos: Integer; |
| 1602 |
Token: string; |
| 1603 |
begin |
| 1604 |
Result := TCastleStringList.Create; |
| 1605 |
try |
| 1606 |
SeekPos := 1; |
| 1607 |
repeat |
| 1608 |
Token := NextToken(s, SeekPos, TokenDelims); |
| 1609 |
if Token = '' then break; |
| 1610 |
Result.Add(Token); |
| 1611 |
until false; |
| 1612 |
except Result.Free; raise end; |
| 1613 |
end; |
| 1614 |
|
| 1615 |
function SplitString(const S: string; const Delimiter: char): TCastleStringList; |
| 1616 |
{ Note that implementation doesn't use TStringList.Delimiter. |
| 1617 |
|
| 1618 |
Besides guaranteeing the "strictness", it's also faster than |
| 1619 |
TStringList.Delimiter and DelimitedText, since it's always case-sensitive, |
| 1620 |
and doesn't deal with any TStringList.QuoteChar and TStringList.StrictDelimiter |
| 1621 |
special cases. } |
| 1622 |
var |
| 1623 |
NextChar, NextDelimiter: Integer; |
| 1624 |
begin |
| 1625 |
Result := TCastleStringList.Create; |
| 1626 |
try |
| 1627 |
NextChar := 1; |
| 1628 |
while NextChar <= Length(S) + 1 do |
| 1629 |
begin |
| 1630 |
if NextChar = Length(S) + 1 then |
| 1631 |
begin |
| 1632 |
{ this handles the situation when the delimiter is at the end of S, |
| 1633 |
or when S is empty } |
| 1634 |
Result.Add(''); |
| 1635 |
Break; |
| 1636 |
end else |
| 1637 |
begin |
| 1638 |
NextDelimiter := PosEx(Delimiter, S, NextChar); |
| 1639 |
if NextDelimiter = 0 then |
| 1640 |
begin |
| 1641 |
Result.Add(SEnding(S, NextChar)); |
| 1642 |
Break; |
| 1643 |
end else |
| 1644 |
begin |
| 1645 |
Result.Add(CopyPos(S, NextChar, NextDelimiter - 1)); |
| 1646 |
NextChar := NextDelimiter + 1; |
| 1647 |
end; |
| 1648 |
end; |
| 1649 |
end; |
| 1650 |
except Result.Free; raise end; |
| 1651 |
end; |
| 1652 |
|
| 1653 |
function GlueStrings(const Strings: array of string; const Delimiter: char): string; |
| 1654 |
var |
| 1655 |
I: Integer; |
| 1656 |
begin |
| 1657 |
if High(Strings) = -1 then |
| 1658 |
Exit(''); |
| 1659 |
Result := Strings[0]; |
| 1660 |
for I := 1 to High(Strings) do |
| 1661 |
Result := Result + Delimiter + Strings[I]; |
| 1662 |
end; |
| 1663 |
|
| 1664 |
function GlueStrings(const Strings: array of string; const Delimiter: string): string; |
| 1665 |
var |
| 1666 |
I: Integer; |
| 1667 |
begin |
| 1668 |
if High(Strings) = -1 then |
| 1669 |
Exit(''); |
| 1670 |
Result := Strings[0]; |
| 1671 |
for I := 1 to High(Strings) do |
| 1672 |
Result := Result + Delimiter + Strings[I]; |
| 1673 |
end; |
| 1674 |
|
| 1675 |
function GlueStrings(const Strings: TStrings; const Delimiter: char): string; |
| 1676 |
var |
| 1677 |
I: Integer; |
| 1678 |
begin |
| 1679 |
if Strings.Count = 0 then |
| 1680 |
Exit(''); |
| 1681 |
Result := Strings[0]; |
| 1682 |
for I := 1 to Strings.Count - 1 do |
| 1683 |
Result := Result + Delimiter + Strings[I]; |
| 1684 |
end; |
| 1685 |
|
| 1686 |
function GlueStrings(const Strings: TStrings; const Delimiter: string): string; |
| 1687 |
var |
| 1688 |
I: Integer; |
| 1689 |
begin |
| 1690 |
if Strings.Count = 0 then |
| 1691 |
Exit(''); |
| 1692 |
Result := Strings[0]; |
| 1693 |
for I := 1 to Strings.Count - 1 do |
| 1694 |
Result := Result + Delimiter + Strings[I]; |
| 1695 |
end; |
| 1696 |
|
| 1697 |
function FindPos(const SubText, Text: string; StartPosition, Count: integer; const Options: TSearchOptions; const WordBorders: TSetOfChars): integer; |
| 1698 |
var S, SubS: string; |
| 1699 |
|
| 1700 |
function MatchingPos(i: integer): boolean; |
| 1701 |
{ sprawdz czy i jest dobra Position wystapienia SubS w S. |
| 1702 |
Uwzglednij przy tym czy soWholeWord in Options, zachowuj sie zawsze |
| 1703 |
jakby bylo soMatchCase in Options. } |
| 1704 |
var realI: integer; |
| 1705 |
begin |
| 1706 |
result := false; |
| 1707 |
if Copy(S, i, Length(SubS)) = SubS then |
| 1708 |
begin |
| 1709 |
if soWholeWord in Options then |
| 1710 |
begin |
| 1711 |
realI := i+StartPosition-1; |
| 1712 |
if ( (realI = 1) or CharInSet(Text[realI-1], wordBorders) ) and |
| 1713 |
( (realI+length(subS)-1 = length(Text)) or CharInSet(Text[realI+length(subS)], WordBorders) ) |
| 1714 |
then result := true |
| 1715 |
end else result := true; |
| 1716 |
end; |
| 1717 |
end; |
| 1718 |
|
| 1719 |
var i: integer; |
| 1720 |
begin |
| 1721 |
S := copy(Text, StartPosition, Count); |
| 1722 |
SubS := SubText; |
| 1723 |
if not (soMatchCase in Options) then |
| 1724 |
begin |
| 1725 |
S := AnsiUpperCase(S); |
| 1726 |
SubS := AnsiUpperCase(SubS); |
| 1727 |
end; |
| 1728 |
result := 0; |
| 1729 |
if soBackwards in Options then |
| 1730 |
begin |
| 1731 |
for i := Count-Length(SubS)+1 downto 1 do |
| 1732 |
if MatchingPos(i) then begin result := i; break end; |
| 1733 |
end else |
| 1734 |
begin |
| 1735 |
for i := 1 to Count-Length(SubS)+1 do |
| 1736 |
if MatchingPos(i) then begin result := i; break end; |
| 1737 |
end; |
| 1738 |
if result > 0 then result := result+StartPosition-1; |
| 1739 |
end; |
| 1740 |
|
| 1741 |
function SRight(const s: string; const rpart: integer): string; |
| 1742 |
begin |
| 1743 |
if Length(s) < rpart then |
| 1744 |
result := s else |
| 1745 |
result := Copy(s, Length(s)-rpart+1, rpart); |
| 1746 |
end; |
| 1747 |
|
| 1748 |
function SAppendPart(const s, PartSeparator, NextPart: string): string; |
| 1749 |
begin |
| 1750 |
if s = '' then |
| 1751 |
result := NextPart else |
| 1752 |
result := s+PartSeparator+NextPart; |
| 1753 |
end; |
| 1754 |
|
| 1755 |
procedure DeFormat(Data: string; const Format: string; |
| 1756 |
const args: array of pointer; |
| 1757 |
const IgnoreCase: boolean; |
| 1758 |
const RelaxedWhitespaceChecking: boolean); |
| 1759 |
begin |
| 1760 |
if TryDeFormat(Data, Format, args, IgnoreCase, |
| 1761 |
RelaxedWhitespaceChecking) < High(args)+1 then |
| 1762 |
raise EDeformatError.CreateFmt( |
| 1763 |
'Unexpected end of Data (%s) - format (%s) not fully evaluated', |
| 1764 |
[Data, Format]); |
| 1765 |
end; |
| 1766 |
|
| 1767 |
function TryDeFormat(Data: string; const Format: string; |
| 1768 |
const args: array of pointer; |
| 1769 |
const IgnoreCase: boolean; |
| 1770 |
const RelaxedWhitespaceChecking: boolean): integer; |
| 1771 |
var datapos, formpos: integer; |
| 1772 |
|
| 1773 |
function ReadExtendedData: Extended; |
| 1774 |
var dataposstart: integer; |
| 1775 |
begin |
| 1776 |
{pierwszy znak liczby moze byc + lub -. Potem musza byc same cyfry.} |
| 1777 |
if not CharInSet(data[datapos], ['0'..'9', '+', '-']) then |
| 1778 |
raise EDeformatError.CreateFmt('float not found in data ''%s'' on position %d', [data, datapos]); |
| 1779 |
dataposstart := datapos; |
| 1780 |
Inc(datapos); |
| 1781 |
while (datapos <= Length(data)) and |
| 1782 |
CharInSet(data[datapos], ['0'..'9','.', 'e','E', '-', '+']) do |
| 1783 |
Inc(datapos); |
| 1784 |
{ Note that StrToFloatDot may still raise EConvertError. |
| 1785 |
The argument contains only valid characters, but they may not form a valid number, |
| 1786 |
e.g. '123....456' or 'eee' or '1+2'. } |
| 1787 |
result := StrToFloatDot(CopyPos(data, dataposstart, datapos-1)); |
| 1788 |
end; |
| 1789 |
|
| 1790 |
function ReadInt64Data: Int64; |
| 1791 |
var dataposstart: integer; |
| 1792 |
begin |
| 1793 |
{pierwszy znak integera moze byc + lub -. Potem musza byc same cyfry.} |
| 1794 |
if not CharInSet(data[datapos], ['0'..'9', '+', '-']) then |
| 1795 |
raise EDeformatError.CreateFmt('integer not found in data ''%s'' on position %d', [data, datapos]); |
| 1796 |
dataposstart := datapos; |
| 1797 |
Inc(datapos); |
| 1798 |
while (datapos <= Length(data)) and CharInSet(data[datapos], ['0'..'9']) do |
| 1799 |
Inc(datapos); |
| 1800 |
{ponizszy StrToInt tez moze spowodowac blad jesli np. |
| 1801 |
wyszedl nam string '-' lub '+'} |
| 1802 |
result := StrToInt(CopyPos(data, dataposstart, datapos-1)); |
| 1803 |
end; |
| 1804 |
|
| 1805 |
function ReadStringData: string; |
| 1806 |
var dataposstart: integer; |
| 1807 |
begin |
| 1808 |
dataposstart := datapos; |
| 1809 |
while (datapos <= Length(data)) and |
| 1810 |
(not CharInSet(data[datapos], WhiteSpaces)) do Inc(datapos); |
| 1811 |
result := CopyPos(data, dataposstart, datapos-1); |
| 1812 |
end; |
| 1813 |
|
| 1814 |
function ReadTypeSpecifier: string; |
| 1815 |
{odczytaj type specifier z kropka z format. Przesun formpos} |
| 1816 |
var formposstart: integer; |
| 1817 |
begin |
| 1818 |
formposstart := formpos; |
| 1819 |
repeat |
| 1820 |
if formpos > Length(format) then |
| 1821 |
raise EDeformatError.Create('type specifier incorrect in format '''+format+''''); |
| 1822 |
if format[formpos] = '.' then |
| 1823 |
break else |
| 1824 |
Inc(formpos); |
| 1825 |
until false; |
| 1826 |
result := CopyPos(format, formposstart, formpos-1); |
| 1827 |
Inc(formpos); { omin kropke '.' w format } |
| 1828 |
end; |
| 1829 |
|
| 1830 |
procedure CheckBlackChar(formatchar: char); |
| 1831 |
var BlackCharsCheck: boolean; |
| 1832 |
begin |
| 1833 |
if IgnoreCase then |
| 1834 |
BlackCharsCheck := SameText(Data[datapos], format[formpos]) else |
| 1835 |
BlackCharsCheck := Data[datapos] = format[formpos]; |
| 1836 |
if not BlackCharsCheck then |
| 1837 |
raise EDeformatError.CreateFmt('data (%s) and format (%s) don''t match', [data, format]); |
| 1838 |
end; |
| 1839 |
|
| 1840 |
procedure CheckFormatNotEnd; |
| 1841 |
begin |
| 1842 |
if formpos > Length(format) then |
| 1843 |
raise EDeformatError.Create('Unexpected end of format : "'+format+'"'); |
| 1844 |
end; |
| 1845 |
|
| 1846 |
type |
| 1847 |
{ Define it only locally, remember String = AnsiString or UnicodeString. } |
| 1848 |
PString = ^String; |
| 1849 |
var |
| 1850 |
TypeSpecifier: String; |
| 1851 |
begin |
| 1852 |
datapos := 1; |
| 1853 |
formpos := 1; |
| 1854 |
result := 0; { no args done yet } |
| 1855 |
|
| 1856 |
{ Skip whitespace and the beginning of data } |
| 1857 |
if RelaxedWhitespaceChecking then |
| 1858 |
while SCharIs(Data, DataPos, WhiteSpaces) do Inc(DataPos); |
| 1859 |
|
| 1860 |
while formpos <= Length(Format) do |
| 1861 |
begin |
| 1862 |
{datapos > Length(data) -> means Data has ended but Format not. |
| 1863 |
OK, so we can exit, because we are doing only TryDeFormat. |
| 1864 |
Real DeFormat should check our result if it wishes to check that we parsed |
| 1865 |
whole Format.} |
| 1866 |
if datapos > Length(data) then |
| 1867 |
begin |
| 1868 |
{ Actually, if next thing in format is %s, we can parse it too |
| 1869 |
(string will just be '') } |
| 1870 |
if Format[FormPos] = '%' then |
| 1871 |
begin |
| 1872 |
Inc(formpos); |
| 1873 |
CheckFormatNotEnd; |
| 1874 |
if Format[FormPos] = 's' then |
| 1875 |
begin |
| 1876 |
PString(args[result])^ := ReadStringData; |
| 1877 |
Inc(formpos); |
| 1878 |
Inc(result); |
| 1879 |
end; |
| 1880 |
end; |
| 1881 |
Exit; |
| 1882 |
end; |
| 1883 |
|
| 1884 |
{1 or more whitespace in format means 1 or more whitespaces in data} |
| 1885 |
if RelaxedWhitespaceChecking and CharInSet(format[formpos], WhiteSpaces) then |
| 1886 |
begin |
| 1887 |
if not SCharIs(Data, datapos, WhiteSpaces) then |
| 1888 |
raise EDeformatError.Create('Whitespace not found in data "' + data + |
| 1889 |
'" as requested by format "' + format + '"'); |
| 1890 |
repeat Inc(formpos) until not SCharIs(format, formpos, WhiteSpaces); |
| 1891 |
repeat Inc(datapos) until not SCharIs(data, datapos, WhiteSpaces); |
| 1892 |
end else |
| 1893 |
|
| 1894 |
{%+something means "read this from data", %% means "read %"} |
| 1895 |
if format[formpos] = '%' then |
| 1896 |
begin |
| 1897 |
Inc(formpos); |
| 1898 |
CheckFormatNotEnd; |
| 1899 |
try |
| 1900 |
case format[formpos] of |
| 1901 |
'%':begin |
| 1902 |
CheckBlackChar('%'); |
| 1903 |
Inc(formpos); |
| 1904 |
Inc(datapos); |
| 1905 |
end; |
| 1906 |
's':begin |
| 1907 |
PString(args[result])^:=ReadStringData; |
| 1908 |
Inc(formpos); |
| 1909 |
Inc(result); |
| 1910 |
end; |
| 1911 |
'd':begin |
| 1912 |
PInteger(args[result])^:=ReadInt64Data; |
| 1913 |
Inc(formpos); |
| 1914 |
Inc(result); |
| 1915 |
end; |
| 1916 |
'f':begin |
| 1917 |
PFloat(args[result])^:=ReadExtendedData; |
| 1918 |
Inc(formpos); |
| 1919 |
Inc(result); |
| 1920 |
end; |
| 1921 |
'.':begin |
| 1922 |
Inc(formpos); |
| 1923 |
TypeSpecifier := ReadTypeSpecifier; |
| 1924 |
case ArrayPosStr(TypeSpecifier, |
| 1925 |
['single', 'double', 'extended', 'integer', 'cardinal']) of |
| 1926 |
0: PSingle(args[result])^:=ReadExtendedData; |
| 1927 |
1: PDouble(args[result])^:=ReadExtendedData; |
| 1928 |
2: PExtended(args[result])^:=ReadExtendedData; |
| 1929 |
3: PInteger(args[result])^:=ReadInt64Data; |
| 1930 |
4: PCardinal(args[result])^:=ReadInt64Data; |
| 1931 |
else raise EDeformatError.CreateFmt('Incorrect type specifier "%s"', [TypeSpecifier]); |
| 1932 |
end; |
| 1933 |
Inc(result); |
| 1934 |
end; |
| 1935 |
else raise EDeformatError.Create('incorrect format specifier after "%" sign : '''+format+''''); |
| 1936 |
end; |
| 1937 |
except |
| 1938 |
on E: EConvertError do raise EDeformatError.Create('convert error - '+E.Message) |
| 1939 |
end; |
| 1940 |
end else |
| 1941 |
|
| 1942 |
begin |
| 1943 |
CheckBlackChar(format[formpos]); |
| 1944 |
Inc(datapos); |
| 1945 |
Inc(formpos); |
| 1946 |
end; |
| 1947 |
end; |
| 1948 |
|
| 1949 |
if RelaxedWhitespaceChecking then |
| 1950 |
while SCharIs(Data, DataPos, WhiteSpaces) do Inc(DataPos); |
| 1951 |
|
| 1952 |
if datapos <= Length(data) then |
| 1953 |
raise EDeformatError.CreateFmt( |
| 1954 |
'data ''%s'' too long - unexpected end of format ''%s''', [Data, Format]); |
| 1955 |
end; |
| 1956 |
|
| 1957 |
function SReplacePatterns(const S: string; |
| 1958 |
const Patterns, Values: array of string; const IgnoreCase: boolean): string; |
| 1959 |
begin |
| 1960 |
if IgnoreCase then |
| 1961 |
Result := StringsReplace(S, Patterns, Values, [rfReplaceAll, rfIgnoreCase]) else |
| 1962 |
Result := StringsReplace(S, Patterns, Values, [rfReplaceAll]); |
| 1963 |
end; |
| 1964 |
|
| 1965 |
function SReplacePatterns(const s: string; const Parameters: TStringStringMap; |
| 1966 |
const IgnoreCase: boolean): string; |
| 1967 |
begin |
| 1968 |
Result := SReplacePatterns(S, Parameters.Keys.ToArray, Parameters.Values.ToArray, IgnoreCase); |
| 1969 |
end; |
| 1970 |
|
| 1971 |
function SReplacePatterns(const S: string; |
| 1972 |
const Patterns, Values: TStrings; const IgnoreCase: boolean): string; |
| 1973 |
begin |
| 1974 |
Result := SReplacePatterns(S, Patterns.ToArray, Values.ToArray, IgnoreCase); |
| 1975 |
end; |
| 1976 |
|
| 1977 |
{$ifndef FPC} |
| 1978 |
function IsWild(const InputStr, Wildcards: string; const IgnoreCase: Boolean): Boolean; |
| 1979 |
var |
| 1980 |
Regex: string; |
| 1981 |
RegexOptions: TRegExOptions; |
| 1982 |
begin |
| 1983 |
{ TODO: This is not perfect, as it doesn't handle all the quoting for special |
| 1984 |
characters in InputStr that could mean something special for regex. |
| 1985 |
But it's good enough for now.} |
| 1986 |
Regex := SReplacePatterns(Wildcards, ['.', '*', '?'], ['\.', '.*', '.'], IgnoreCase); |
| 1987 |
if IgnoreCase then |
| 1988 |
RegexOptions := [roIgnoreCase] |
| 1989 |
else |
| 1990 |
RegexOptions := []; |
| 1991 |
Result := TRegEx.IsMatch(InputStr, Regex, RegexOptions); |
| 1992 |
end; |
| 1993 |
{$endif} |
| 1994 |
|
| 1995 |
function SCharsCount(const S: string; C: char): Cardinal; |
| 1996 |
var |
| 1997 |
i: Integer; |
| 1998 |
begin |
| 1999 |
Result := 0; |
| 2000 |
for I := 1 to Length(s) do if S[I] = C then Inc(Result); |
| 2001 |
end; |
| 2002 |
|
| 2003 |
function SCharsCount(const S: string; const Chars: TSetOfChars): Cardinal; |
| 2004 |
var |
| 2005 |
I: Integer; |
| 2006 |
begin |
| 2007 |
Result := 0; |
| 2008 |
for I := 1 to Length(s) do |
| 2009 |
if CharInSet(S[I], Chars) then |
| 2010 |
Inc(Result); |
| 2011 |
end; |
| 2012 |
|
| 2013 |
function STruncateHash(const S: string): string; |
| 2014 |
var |
| 2015 |
p: integer; |
| 2016 |
begin |
| 2017 |
p := Pos('#', s); |
| 2018 |
result := s; |
| 2019 |
if p > 0 then SetLength(result, p-1); |
| 2020 |
end; |
| 2021 |
|
| 2022 |
function SUnformattable(const s: string): string; |
| 2023 |
begin |
| 2024 |
result := StringReplace(s, '%', '%%', [rfReplaceAll]); |
| 2025 |
end; |
| 2026 |
|
| 2027 |
function SAnsiCompare(const s1, s2: string; IgnoreCase: boolean): Integer; |
| 2028 |
begin |
| 2029 |
if IgnoreCase then |
| 2030 |
result := AnsiCompareText(s1, s2) else |
| 2031 |
result := AnsiCompareStr(s1, s2); |
| 2032 |
end; |
| 2033 |
|
| 2034 |
function SAnsiSame(const s1, s2: string; IgnoreCase: boolean): boolean; |
| 2035 |
begin |
| 2036 |
result := SAnsiCompare(s1, s2, IgnoreCase) = 0; |
| 2037 |
end; |
| 2038 |
|
| 2039 |
function SPercentReplace(const InitialFormat: string; |
| 2040 |
const Replaces: array of TPercentReplace; |
| 2041 |
out ReplacementsDone: Cardinal; |
| 2042 |
ErrorOnUnknownPercentFormat: boolean; |
| 2043 |
PercentChar: char; |
| 2044 |
IgnoreCase: boolean): string; |
| 2045 |
|
| 2046 |
function ReplaceWithC(c: char): Integer; |
| 2047 |
var |
| 2048 |
I: Integer; |
| 2049 |
begin |
| 2050 |
if IgnoreCase then |
| 2051 |
begin |
| 2052 |
for i := 0 to High(Replaces) do |
| 2053 |
if AnsiSameText(c, Replaces[i].c) then begin result := i; Exit end; |
| 2054 |
end else |
| 2055 |
begin |
| 2056 |
for i := 0 to High(Replaces) do |
| 2057 |
if c = Replaces[i].c then begin result := i; Exit end; |
| 2058 |
end; |
| 2059 |
result := -1; |
| 2060 |
end; |
| 2061 |
|
| 2062 |
procedure UnknownPercentFormat(const WrongSequence: string); |
| 2063 |
begin |
| 2064 |
raise EUnknownPercentFormat.Create('Unknown format pattern in format "' |
| 2065 |
+InitialFormat+'", wrong sequence is : ' +WrongSequence); |
| 2066 |
end; |
| 2067 |
|
| 2068 |
var |
| 2069 |
P, ReplNum: Integer; |
| 2070 |
Format: string; |
| 2071 |
begin |
| 2072 |
{ Result zawiera czesciowy wynik. Od Format bedziemy odcinac zrobione juz kawalki. |
| 2073 |
Bedziemy caly czas doklejac kolejne wyniki do Result (bedziemy starali sie, |
| 2074 |
dla szybkosci, doklejac mozliwie duze kawalki do Result na raz, np. nie chcemy |
| 2075 |
przepisywac do Result po jednym znaku). } |
| 2076 |
Result := ''; |
| 2077 |
Format := InitialFormat; |
| 2078 |
ReplacementsDone := 0; |
| 2079 |
|
| 2080 |
while Format <> '' do |
| 2081 |
begin |
| 2082 |
P := Pos(PercentChar, Format); |
| 2083 |
if P = 0 then begin Result := Result + Format; Exit end; |
| 2084 |
|
| 2085 |
Result := Result + Copy(Format, 1, P - 1); |
| 2086 |
if P + 1 <= Length(Format) then |
| 2087 |
begin |
| 2088 |
{ zwieksz Result o element wynikajacy z formatu Format[p+1] } |
| 2089 |
if Format[P + 1] = PercentChar then |
| 2090 |
Result := Result + PercentChar else |
| 2091 |
begin |
| 2092 |
ReplNum := ReplaceWithC(Format[P + 1]); |
| 2093 |
if ReplNum = -1 then |
| 2094 |
begin |
| 2095 |
if ErrorOnUnknownPercentFormat then |
| 2096 |
UnknownPercentFormat('"'+PercentChar+Format[P + 1]+'"'); |
| 2097 |
Result := Result + PercentChar + Format[P + 1]; |
| 2098 |
end else |
| 2099 |
begin |
| 2100 |
Result := Result + Replaces[ReplNum].s; |
| 2101 |
Inc(ReplacementsDone); |
| 2102 |
end; |
| 2103 |
end; |
| 2104 |
{ obetnij wykonana czesc z Format } |
| 2105 |
Delete(Format, 1, P + 1); |
| 2106 |
end else |
| 2107 |
begin |
| 2108 |
{ mamy PercentChar na koncu stringa } |
| 2109 |
if ErrorOnUnknownPercentFormat then |
| 2110 |
UnknownPercentFormat(PercentChar+' at the end of the format string'); |
| 2111 |
Result := Result + PercentChar; |
| 2112 |
Exit; |
| 2113 |
end; |
| 2114 |
end; |
| 2115 |
end; |
| 2116 |
|
| 2117 |
function SPercentReplace(const InitialFormat: string; |
| 2118 |
const Replaces: array of TPercentReplace; |
| 2119 |
ErrorOnUnknownPercentFormat: boolean; |
| 2120 |
PercentChar: char; |
| 2121 |
IgnoreCase: boolean): string; |
| 2122 |
var |
| 2123 |
ReplacementsDone: Cardinal; |
| 2124 |
begin |
| 2125 |
{$warnings off} { using deprecated inside deprecated } |
| 2126 |
Result := SPercentReplace(InitialFormat, Replaces, ReplacementsDone, |
| 2127 |
ErrorOnUnknownPercentFormat, PercentChar, IgnoreCase); |
| 2128 |
{ returned ReplacementsDone will simply be ignored } |
| 2129 |
{$warnings on} |
| 2130 |
end; |
| 2131 |
|
| 2132 |
function FormatIndexedName(const NamePattern: string; |
| 2133 |
const Index: Integer; out ReplacementsDone: Cardinal): string; |
| 2134 |
const |
| 2135 |
PercentChar = '%'; |
| 2136 |
var |
| 2137 |
StartP, P, MinLength: Integer; |
| 2138 |
Format: string; |
| 2139 |
begin |
| 2140 |
{ Result zawiera czesciowy wynik. Od Format bedziemy odcinac zrobione juz kawalki. |
| 2141 |
Bedziemy caly czas doklejac kolejne wyniki do Result (bedziemy starali sie, |
| 2142 |
dla szybkosci, doklejac mozliwie duze kawalki do Result na raz, np. nie chcemy |
| 2143 |
przepisywac do Result po jednym znaku). } |
| 2144 |
Result := ''; |
| 2145 |
Format := NamePattern; |
| 2146 |
ReplacementsDone := 0; |
| 2147 |
|
| 2148 |
while Format <> '' do |
| 2149 |
begin |
| 2150 |
P := Pos(PercentChar, Format); |
| 2151 |
if P = 0 then begin Result := Result + Format; Exit end; |
| 2152 |
|
| 2153 |
Result := Result + Copy(Format, 1, P - 1); |
| 2154 |
if P + 1 <= Length(Format) then |
| 2155 |
begin |
| 2156 |
{ zwieksz Result o element wynikajacy z formatu Format[P + 1] } |
| 2157 |
if Format[P + 1] = PercentChar then |
| 2158 |
Result := Result + PercentChar else |
| 2159 |
if Format[P + 1] = 'd' then |
| 2160 |
begin |
| 2161 |
Result := Result + IntToStr(Index); |
| 2162 |
Inc(ReplacementsDone); |
| 2163 |
end else |
| 2164 |
if CharInSet(Format[P + 1], ['0'..'9']) then |
| 2165 |
begin |
| 2166 |
Inc(P); |
| 2167 |
StartP := P; |
| 2168 |
while SCharIs(Format, P, ['0'..'9']) do Inc(P); |
| 2169 |
if SCharIs(Format, P, 'd') then |
| 2170 |
begin |
| 2171 |
{ valid % + number + d sequence, do the replace } |
| 2172 |
MinLength := StrToInt(Copy(Format, StartP, P - StartP)); |
| 2173 |
Result := Result + IntToStrZPad(Index, MinLength); |
| 2174 |
Inc(ReplacementsDone); |
| 2175 |
end else |
| 2176 |
begin |
| 2177 |
{ invalid %-pattern, just copy it (including leading PercentChar |
| 2178 |
and following character <> 'd') } |
| 2179 |
Result := Result + Copy(Format, StartP - 1, P - StartP + 2); |
| 2180 |
end; |
| 2181 |
{ decrement P just so that Delete(Format, ...) below will work Ok } |
| 2182 |
Dec(P); |
| 2183 |
end else |
| 2184 |
begin |
| 2185 |
{ unknown %-pattern, just copy it } |
| 2186 |
Result := Result + PercentChar + Format[P + 1]; |
| 2187 |
end; |
| 2188 |
{ obetnij wykonana czesc z Format } |
| 2189 |
Delete(Format, 1, P + 1); |
| 2190 |
end else |
| 2191 |
begin |
| 2192 |
{ mamy PercentChar na koncu stringa } |
| 2193 |
Result := Result + PercentChar; |
| 2194 |
Exit; |
| 2195 |
end; |
| 2196 |
end; |
| 2197 |
end; |
| 2198 |
|
| 2199 |
type |
| 2200 |
TRegExprString = {$if defined(FPC) and (FPC_FULLVERSION >= 30300)} RegExprString {$else} String {$endif}; |
| 2201 |
|
| 2202 |
TRegExprCounter = class |
| 2203 |
private |
| 2204 |
Index: Integer; |
| 2205 |
ReplacementsDone: Cardinal; |
| 2206 |
function ReplaceCallback( |
| 2207 |
{$ifdef FPC} ARegExpr: TRegExpr {$else} const Match: TMatch {$endif}): TRegExprString; |
| 2208 |
end; |
| 2209 |
|
| 2210 |
function TRegExprCounter.ReplaceCallback( |
| 2211 |
{$ifdef FPC} ARegExpr: TRegExpr {$else} const Match: TMatch {$endif}): TRegExprString; |
| 2212 |
var |
| 2213 |
MatchedText: TRegExprString; |
| 2214 |
begin |
| 2215 |
MatchedText := {$ifdef FPC} ARegExpr.Match[1] {$else} Match.Groups[1].Value {$endif}; |
| 2216 |
Result := IntToStrZPad(Index, StrToInt(MatchedText)); |
| 2217 |
Inc(ReplacementsDone); |
| 2218 |
end; |
| 2219 |
|
| 2220 |
function HasNameCounter(const NamePattern: string; |
| 2221 |
const AllowOldPercentSyntax: Boolean): Boolean; |
| 2222 |
var |
| 2223 |
ReplacementsDone: Cardinal; |
| 2224 |
S: String; |
| 2225 |
begin |
| 2226 |
{ First check by searching for @counter, |
| 2227 |
to eliminate 99% of practical URL cases that will not have @counter. |
| 2228 |
Later check by actually doing FormatNameCounter, |
| 2229 |
in case the @counter is not followed by proper sequence "(123)". |
| 2230 |
This way if HasNameCounter returns @true, we can be sure that |
| 2231 |
FormatNameCounter actually does something, i.e. changes NamePattern, |
| 2232 |
otherwise e.g. LoadNode could loop. } |
| 2233 |
if Pos('@counter', NamePattern) <> 0 then |
| 2234 |
begin |
| 2235 |
S := FormatNameCounter(NamePattern, 0, AllowOldPercentSyntax, ReplacementsDone); |
| 2236 |
if ReplacementsDone <> 0 then |
| 2237 |
begin |
| 2238 |
Assert(NamePattern <> S); |
| 2239 |
Exit(true); |
| 2240 |
end; |
| 2241 |
end; |
| 2242 |
Result := false; |
| 2243 |
end; |
| 2244 |
|
| 2245 |
function FormatNameCounter(const NamePattern: string; |
| 2246 |
const Index: Integer; const AllowOldPercentSyntax: boolean; |
| 2247 |
out ReplacementsDone: Cardinal): string; |
| 2248 |
var |
| 2249 |
R: {$ifdef FPC} TRegExpr {$else} TRegEx {$endif}; |
| 2250 |
C: TRegExprCounter; |
| 2251 |
{$ifndef FPC} |
| 2252 |
P : TMatchEvaluator; |
| 2253 |
{$endif} |
| 2254 |
begin |
| 2255 |
{$ifdef FPC} |
| 2256 |
if NamePattern = '' then |
| 2257 |
Exit(''); // avoid error TRegExpr exec: empty input string |
| 2258 |
R := TRegExpr.Create; |
| 2259 |
R.Expression := '@counter\(([\d]+)\)'; |
| 2260 |
{$else} |
| 2261 |
R := TRegEx.Create('@counter\(([\d]+)\)'); |
| 2262 |
{$endif} |
| 2263 |
try |
| 2264 |
C := TRegExprCounter.Create; |
| 2265 |
try |
| 2266 |
C.Index := Index; |
| 2267 |
{$ifdef FPC} |
| 2268 |
Result := R.Replace(NamePattern, {$ifdef FPC}@{$endif} C.ReplaceCallback); |
| 2269 |
{$else} |
| 2270 |
// Fix for delphi < Tokio, needs an extra Variable for the call |
| 2271 |
P := C.ReplaceCallback; |
| 2272 |
Result := r.Replace(NamePattern, P); |
| 2273 |
{$endif} |
| 2274 |
ReplacementsDone := C.ReplacementsDone; |
| 2275 |
finally FreeAndNil(C) end; |
| 2276 |
finally |
| 2277 |
{$ifdef FPC} // In Delphi, TRegEx is a record |
| 2278 |
FreeAndNil(R); |
| 2279 |
{$endif} |
| 2280 |
end; |
| 2281 |
|
| 2282 |
if (ReplacementsDone = 0) and AllowOldPercentSyntax then |
| 2283 |
Result := FormatIndexedName(NamePattern, Index, ReplacementsDone); |
| 2284 |
end; |
| 2285 |
|
| 2286 |
function FormatNameCounter(const NamePattern: string; |
| 2287 |
const Index: Integer; const AllowOldPercentSyntax: boolean): string; |
| 2288 |
var |
| 2289 |
ReplacementsDone: Cardinal; |
| 2290 |
begin |
| 2291 |
Result := FormatNameCounter(NamePattern, Index, AllowOldPercentSyntax, |
| 2292 |
ReplacementsDone); |
| 2293 |
end; |
| 2294 |
|
| 2295 |
{ conversions ------------------------------------------------------------ } |
| 2296 |
|
| 2297 |
function DigitAsChar(const b: byte): char; |
| 2298 |
begin Result := char(b+byte('0')) end; |
| 2299 |
|
| 2300 |
function DigitAsByte(const c: char): byte; |
| 2301 |
begin Result := byte(c)-byte('0') end; |
| 2302 |
|
| 2303 |
function IntToStrZPad(n: integer; const MinLength: integer): string; |
| 2304 |
begin result := SZeroPad(IntToStr(n), MinLength) end; |
| 2305 |
|
| 2306 |
function IntToStrThousands(const Value: Int64; const Separator: char): string; |
| 2307 |
begin |
| 2308 |
if Value > 1000 then |
| 2309 |
Result := IntToStrThousands(Value div 1000, Separator) + Separator + IntToStrZPad(Value mod 1000, 3) else |
| 2310 |
Result := IntToStr(Value); |
| 2311 |
end; |
| 2312 |
|
| 2313 |
function IntToStrThousands(const Value: Int64; const Separator: string): string; |
| 2314 |
begin |
| 2315 |
if Value > 1000 then |
| 2316 |
Result := IntToStrThousands(Value div 1000, Separator) + Separator + IntToStrZPad(Value mod 1000, 3) else |
| 2317 |
Result := IntToStr(Value); |
| 2318 |
end; |
| 2319 |
|
| 2320 |
function IntToStrBase(N: QWord; const Base: Byte): string; |
| 2321 |
|
| 2322 |
{ Convert Digit (any number < Base) to a character. |
| 2323 |
|
| 2324 |
Digits 0..9 and converted to '0'..'9' naturally, |
| 2325 |
further digits are converted to 'A'..'Z'. |
| 2326 |
In effect Base = 16 is a typical hexadecimal conversion. } |
| 2327 |
function GeneralDigitToChar(const Digit: Byte): Char; |
| 2328 |
begin |
| 2329 |
if Digit < 10 then |
| 2330 |
Result := DigitAsChar(Digit) |
| 2331 |
else |
| 2332 |
Result := Chr( Digit-10+Ord('A') ); {'A'=10 , 'B'=11 etc. } |
| 2333 |
end; |
| 2334 |
|
| 2335 |
begin |
| 2336 |
Assert(Base < 10 + Ord('Z')-Ord('A') +1, 'Too large Base for IntToStrBase'); |
| 2337 |
if N = 0 then |
| 2338 |
Result := '0' |
| 2339 |
else |
| 2340 |
begin |
| 2341 |
Result := ''; |
| 2342 |
while N <> 0 do |
| 2343 |
begin |
| 2344 |
Result := GeneralDigitToChar(N mod Base) + Result; |
| 2345 |
N := N div Base; |
| 2346 |
end; |
| 2347 |
end; |
| 2348 |
end; |
| 2349 |
|
| 2350 |
function IntToStrBase(const N: Int64; const Base: Byte): string; |
| 2351 |
begin |
| 2352 |
if N < 0 then |
| 2353 |
Result := '-' + IntToStrBase(QWord(Abs(N)), Base) |
| 2354 |
else |
| 2355 |
Result := IntToStrBase(QWord(N), Base); |
| 2356 |
end; |
| 2357 |
|
| 2358 |
function IntToStrBase(const N: Int64; const Base: Byte; const MinLength: Cardinal): string; |
| 2359 |
begin |
| 2360 |
{ Call IntToStrBase and (if needed) at zeroes at the beginning } |
| 2361 |
Result := IntToStrBase(n, Base); |
| 2362 |
if N < 0 then |
| 2363 |
Result := '-'+SZeroPad(SEnding(Result, 2), MinLength) |
| 2364 |
else |
| 2365 |
Result := SZeroPad(Result, MinLength); |
| 2366 |
end; |
| 2367 |
|
| 2368 |
function IntToStrBase(const N: QWord; const Base: Byte; const MinLength: Cardinal): string; |
| 2369 |
begin |
| 2370 |
{ Call IntToStrBase and (if needed) at zeroes at the beginning } |
| 2371 |
Result := IntToStrBase(n, Base); |
| 2372 |
Result := SZeroPad(Result, MinLength); |
| 2373 |
end; |
| 2374 |
|
| 2375 |
function IntToStr2(n: Int64; |
| 2376 |
const MinLength: Cardinal; |
| 2377 |
const ZeroDigit: char; |
| 2378 |
const OneDigit: char; |
| 2379 |
const MinusSign: char): string; |
| 2380 |
var |
| 2381 |
Negative: boolean; |
| 2382 |
i: Integer; |
| 2383 |
begin |
| 2384 |
{ Simple implementation : Result := IntToStrBase(n, 2, MinLength) } |
| 2385 |
|
| 2386 |
{ Negative := n < 0, n := Abs(n) } |
| 2387 |
Negative := n < 0; |
| 2388 |
if Negative then n := -n; |
| 2389 |
|
| 2390 |
Result := ''; |
| 2391 |
|
| 2392 |
{ from 0 .. SizeOf(n)*8-1 we have SizeOf(n)*8 values, |
| 2393 |
all possible bits positions. So we're taking SizeOf(n)*8-2, |
| 2394 |
to avoid most significant bit, the sign bit. } |
| 2395 |
for i := SizeOf(n)*8-2 downto 0 do |
| 2396 |
if ((Int64(1) shl i) and n) <> 0 then |
| 2397 |
Result := Result + OneDigit else |
| 2398 |
if Result <> '' then |
| 2399 |
Result := Result + ZeroDigit; |
| 2400 |
|
| 2401 |
if Result = '' then Result := ZeroDigit; |
| 2402 |
|
| 2403 |
Result := SPad(Result, MinLength, ZeroDigit); |
| 2404 |
|
| 2405 |
if Negative then Result := MinusSign + Result; |
| 2406 |
end; |
| 2407 |
|
| 2408 |
function IntToStr16(const n: Int64; const MinLength: Cardinal): string; |
| 2409 |
begin |
| 2410 |
Result := IntToStrBase(n, 16, MinLength) |
| 2411 |
end; |
| 2412 |
|
| 2413 |
function IntToStr16(const n: QWord; const MinLength: Cardinal): string; |
| 2414 |
begin |
| 2415 |
Result := IntToStrBase(n, 16, MinLength) |
| 2416 |
end; |
| 2417 |
|
| 2418 |
function Str2ToInt(const s: string): integer; |
| 2419 |
|
| 2420 |
function BinInt(c: char): integer; |
| 2421 |
begin |
| 2422 |
case c of |
| 2423 |
'0': Result := 0; |
| 2424 |
'1': Result := 1; |
| 2425 |
else raise EConvertError.Create('Invalid Str2ToInt argument, contains invalid chars: ' + s); |
| 2426 |
end; |
| 2427 |
end; |
| 2428 |
|
| 2429 |
var |
| 2430 |
NextChar: integer; |
| 2431 |
begin |
| 2432 |
if s = '' then |
| 2433 |
raise EConvertError.Create('Invalid Str2ToInt argument: empty string'); |
| 2434 |
if s[1] = '-' then |
| 2435 |
begin |
| 2436 |
if Length(s) = 1 then |
| 2437 |
raise EConvertError.Create('Invalid Str2ToInt argument: cannot convert single dash ''-'' to integer.'); |
| 2438 |
Result := -BinInt(s[2]); |
| 2439 |
NextChar := 3; |
| 2440 |
end else |
| 2441 |
begin |
| 2442 |
Result := BinInt(s[1]); |
| 2443 |
NextChar := 2; |
| 2444 |
end; |
| 2445 |
while NextChar <= Length(s) do |
| 2446 |
begin |
| 2447 |
Result := Result * 2 + BinInt(s[NextChar]); |
| 2448 |
Inc(NextChar); |
| 2449 |
end; |
| 2450 |
end; |
| 2451 |
|
| 2452 |
function StrHexToInt(const s: string): Int64; |
| 2453 |
var |
| 2454 |
ScanStart: integer; |
| 2455 |
|
| 2456 |
procedure Scan; |
| 2457 |
var |
| 2458 |
Digit: Int64; |
| 2459 |
i: integer; |
| 2460 |
begin |
| 2461 |
if ScanStart > Length(s) then |
| 2462 |
raise EConvertError.Create('StrHexToInt found unexpected end of string: no digits'); |
| 2463 |
Result := 0; |
| 2464 |
for i := ScanStart to Length(s) do |
| 2465 |
begin |
| 2466 |
case S[I] of |
| 2467 |
'0'..'9':Digit := Ord(S[I])-Ord('0'); |
| 2468 |
'a'..'f':Digit := Ord(S[I])-Ord('a')+10; |
| 2469 |
'A'..'F':Digit := Ord(S[I])-Ord('A')+10; |
| 2470 |
else raise EConvertError.Create('Character "'+S[I]+ |
| 2471 |
'" is not a hexadecimal digit'); |
| 2472 |
end; |
| 2473 |
Result := Result * 16 + Digit; |
| 2474 |
end; |
| 2475 |
end; |
| 2476 |
|
| 2477 |
begin |
| 2478 |
if SCharIs(s, 1, '-') then |
| 2479 |
begin |
| 2480 |
ScanStart := 2; |
| 2481 |
Scan; |
| 2482 |
Result := -Result; |
| 2483 |
end else |
| 2484 |
begin |
| 2485 |
if SCharIs(s, 1, '+') then ScanStart := 2 else ScanStart := 1; |
| 2486 |
Scan; |
| 2487 |
end; |
| 2488 |
end; |
| 2489 |
|
| 2490 |
function PointerToStr(const Ptr: Pointer): string; |
| 2491 |
begin |
| 2492 |
Result := '0x' + IntToStr16(PtrUInt(Ptr), |
| 2493 |
{$ifdef CPU32} 8 {$endif} |
| 2494 |
{$ifdef CPU64} 16 {$endif} ); |
| 2495 |
end; |
| 2496 |
|
| 2497 |
function SetToStr(const SetVariable; NumStart, NumEnd: byte): string; |
| 2498 |
var |
| 2499 |
BSet: set of byte absolute SetVariable; |
| 2500 |
i: byte; |
| 2501 |
begin |
| 2502 |
Result := '['; |
| 2503 |
for i := 0 to NumEnd-NumStart do |
| 2504 |
if i in BSet then |
| 2505 |
if Result = '[' then |
| 2506 |
Result := '[' + IntToStr(i + NumStart) else |
| 2507 |
Result := Result + ',' + IntToStr(i + NumStart); |
| 2508 |
Result := Result + ']'; |
| 2509 |
end; |
| 2510 |
|
| 2511 |
function CharSetToStr(const SetVariable: TSetOfChars): string; |
| 2512 |
var |
| 2513 |
C: char; |
| 2514 |
begin |
| 2515 |
Result := '['; |
| 2516 |
for C := Low(C) to High(C) do |
| 2517 |
if CharInSet(C, SetVariable) then |
| 2518 |
if Result = '[' then |
| 2519 |
Result := '[' + SReadableForm(C) else |
| 2520 |
Result := Result + ',' + SReadableForm(C); |
| 2521 |
Result := Result + ']'; |
| 2522 |
end; |
| 2523 |
|
| 2524 |
function StrToFloatDef(const s: string; DefValue: Extended): Extended; |
| 2525 |
begin |
| 2526 |
try |
| 2527 |
result := StrToFloat(s); |
| 2528 |
except |
| 2529 |
on EConvertError do result := DefValue |
| 2530 |
end; |
| 2531 |
end; |
| 2532 |
|
| 2533 |
function PCharOrNil(const s: string): PChar; |
| 2534 |
begin if s = '' then result := nil else result := PChar(s); end; |
| 2535 |
|
| 2536 |
function PWideCharOrNil(const s: WideString): PWideChar; |
| 2537 |
begin if s = '' then result := nil else result := PWideChar(s); end; |
| 2538 |
|
| 2539 |
function PAnsiCharOrNil(const s: AnsiString): PAnsiChar; |
| 2540 |
begin if s = '' then result := nil else result := PAnsiChar(s); end; |
| 2541 |
|
| 2542 |
function SCompressWhiteSpace(const S: string): string; |
| 2543 |
var |
| 2544 |
SPos: Integer; { this is always next unhandled S position } |
| 2545 |
{$ifdef FPC} |
| 2546 |
ResultPos: Integer; { this is always next free result position } |
| 2547 |
NextSPos: Integer; |
| 2548 |
{$else} |
| 2549 |
StringBuilder: TStringBuilder; |
| 2550 |
SLength: Integer; |
| 2551 |
{$endif} |
| 2552 |
begin |
| 2553 |
{ Move is fast but we can't use it in delphi } |
| 2554 |
{$ifdef FPC} |
| 2555 |
ResultPos := 1; |
| 2556 |
SPos := 1; |
| 2557 |
SetLength(Result, Length(S)); { resulting string is at most as long as S } |
| 2558 |
|
| 2559 |
if SCharIs(S, 1, WhiteSpaces) then |
| 2560 |
begin |
| 2561 |
Result[1] := ' '; |
| 2562 |
Inc(ResultPos); |
| 2563 |
while SCharIs(S, SPos, WhiteSpaces) do Inc(SPos); |
| 2564 |
end; |
| 2565 |
|
| 2566 |
while SPos <= Length(S) do |
| 2567 |
begin |
| 2568 |
Assert(not CharInSet(S[SPos], WhiteSpaces)); |
| 2569 |
|
| 2570 |
{ read next non-white-space chunk } |
| 2571 |
|
| 2572 |
NextSPos := SPos + 1; |
| 2573 |
while (NextSPos <= Length(S)) and |
| 2574 |
not CharInSet(S[NextSPos], WhiteSpaces) do |
| 2575 |
Inc(NextSPos); |
| 2576 |
|
| 2577 |
Move(S[SPos], Result[ResultPos], NextSPos - SPos); |
| 2578 |
|
| 2579 |
ResultPos := ResultPos + NextSPos - SPos; |
| 2580 |
SPos := NextSPos; |
| 2581 |
|
| 2582 |
{ omit next white-space chunk } |
| 2583 |
|
| 2584 |
if SCharIs(S, SPos, WhiteSpaces) then |
| 2585 |
begin |
| 2586 |
Result[ResultPos] := ' '; |
| 2587 |
Inc(ResultPos); |
| 2588 |
while SCharIs(S, SPos, WhiteSpaces) do Inc(SPos); |
| 2589 |
end; |
| 2590 |
end; |
| 2591 |
|
| 2592 |
{ assert we didn't do buffer overflow just now } |
| 2593 |
Assert(ResultPos - 1 <= Length(Result)); |
| 2594 |
|
| 2595 |
SetLength(Result, ResultPos - 1); |
| 2596 |
{$else} |
| 2597 |
SLength := Length(S); |
| 2598 |
|
| 2599 |
if SLength = 0 then |
| 2600 |
Exit(S); |
| 2601 |
|
| 2602 |
StringBuilder := TStringBuilder.Create; |
| 2603 |
try |
| 2604 |
StringBuilder.Capacity := SLength; |
| 2605 |
|
| 2606 |
SPos := 1; |
| 2607 |
while SPos <= SLength do |
| 2608 |
begin |
| 2609 |
if IsSurrogate(S, SPos) then |
| 2610 |
begin |
| 2611 |
StringBuilder.Append(S[SPos]); |
| 2612 |
Inc(SPos); |
| 2613 |
if SPos <= SLength then |
| 2614 |
begin |
| 2615 |
StringBuilder.Append(S[SPos]); |
| 2616 |
Inc(SPos); |
| 2617 |
end; |
| 2618 |
continue; |
| 2619 |
end; |
| 2620 |
|
| 2621 |
if SCharIs(S, SPos, WhiteSpaces) then |
| 2622 |
begin |
| 2623 |
StringBuilder.Append(S[SPos]); |
| 2624 |
while SCharIs(S, SPos, WhiteSpaces) do |
| 2625 |
Inc(SPos); |
| 2626 |
continue; |
| 2627 |
end; |
| 2628 |
|
| 2629 |
StringBuilder.Append(S[SPos]); |
| 2630 |
Inc(SPos); |
| 2631 |
end; |
| 2632 |
|
| 2633 |
Result := StringBuilder.ToString; |
| 2634 |
finally |
| 2635 |
StringBuilder.Free; |
| 2636 |
end; |
| 2637 |
{$endif} |
| 2638 |
end; |
| 2639 |
|
| 2640 |
procedure SCheckChars(const S: string; const ValidChars: TSetOfChars; |
| 2641 |
const RaiseExceptionOnError: boolean); |
| 2642 |
var |
| 2643 |
I: Integer; |
| 2644 |
C: char; |
| 2645 |
|
| 2646 |
procedure ReportInvalid; |
| 2647 |
var |
| 2648 |
SError: string; |
| 2649 |
begin |
| 2650 |
SError := Format('Invalid character "%s" at position %d in string "%s"', [C, I, S]); |
| 2651 |
if RaiseExceptionOnError then |
| 2652 |
raise EInvalidChar.Create(SError) else |
| 2653 |
WritelnWarning('SCheckChars', SError); |
| 2654 |
end; |
| 2655 |
|
| 2656 |
begin |
| 2657 |
for I := 1 to Length(S) do |
| 2658 |
begin |
| 2659 |
C := S[I]; |
| 2660 |
if not CharInSet(C, ValidChars) then |
| 2661 |
ReportInvalid; |
| 2662 |
end; |
| 2663 |
end; |
| 2664 |
|
| 2665 |
function TrimEndingNewline(const S: String): String; |
| 2666 |
begin |
| 2667 |
if IsSuffix(#13#10, S, false) then |
| 2668 |
Result := Copy(S, 1, Length(S) - 2) |
| 2669 |
else |
| 2670 |
if IsSuffix(#10, S, false) then |
| 2671 |
Result := Copy(S, 1, Length(S) - 1) |
| 2672 |
else |
| 2673 |
Result := S; |
| 2674 |
end; |
| 2675 |
|
| 2676 |
function SizeToStr(const Value: Int64): String; |
| 2677 |
begin |
| 2678 |
if Value >= 1024 * 1024 * 1024 then |
| 2679 |
Result := FormatDot('%.2f', [Value / (1024 * 1024 * 1024)]) + ' GB' |
| 2680 |
else |
| 2681 |
if Value >= 1024 * 1024 then |
| 2682 |
Result := FormatDot('%.2f', [Value / (1024 * 1024)]) + ' MB' |
| 2683 |
else |
| 2684 |
if Value >= 1024 then |
| 2685 |
Result := FormatDot('%.2f', [Value / 1024]) + ' KB' |
| 2686 |
else |
| 2687 |
if Value >= 0 then |
| 2688 |
Result := FormatDot('%d', [Value]) + ' bytes' |
| 2689 |
else |
| 2690 |
// display Value like -1 just as "-1", useful e.g. for TCastleDownload.TotalBytes |
| 2691 |
Result := IntToStr(Value); |
| 2692 |
|
| 2693 |
// too verbose |
| 2694 |
//Result += Format(' (%d bytes)', [Value]); |
| 2695 |
end; |
| 2696 |
|
| 2697 |
function StringToUtf16(const Src: String): UnicodeString; |
| 2698 |
begin |
| 2699 |
Result := {$if SizeOf(char) = 2} Src {$else} UTF8Decode(Src) {$ifend}; |
| 2700 |
end; |
| 2701 |
|
| 2702 |
function Utf16ToString(const Src: UnicodeString): String; |
| 2703 |
begin |
| 2704 |
Result := {$if SizeOf(char) = 2} Src {$else} UTF8Encode(Src) {$ifend}; |
| 2705 |
end; |
| 2706 |
|
| 2707 |
end. |