-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathStrLib.pas
2282 lines (1850 loc) · 62.3 KB
/
StrLib.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit StrLib;
(*
DESCRIPTION: Strings processing
AUTHOR: Alexander Shostak (aka Berserker aka EtherniDee aka BerSoft)
WARNING: The unit uses asserts for meaningfull operations, which will lead to bugs if assertions will be turned off.
Such assertions should probably be replaced with custom exception generating function, not dependent on compiler flags.
*)
(***) interface (***)
uses Windows, Math, SysUtils, Classes, StrUtils, Utils;
const
(* ExplodeEx *)
INCLUDE_DELIM = TRUE;
LIMIT_TOKENS = TRUE;
BINARY_CHARACTERS: set of char = [#0..#8, #11..#12, #14..#31];
CHARACTERS_TILL_SPACE: set of char = [#0..#32];
PATH_DELIMS = ['\', '/'];
(* Windows 7+ *)
// Translate any Unicode characters that do not translate directly to multibyte equivalents to the default character specified by lpDefaultChar
WC_NO_BEST_FIT_CHARS = $00000400;
// Raise error on invalid character for ansi page
WC_ERR_INVALID_CHARS = $80;
FAIL_ON_ERROR = true;
type
(* IMPORT *)
TArrayOfStr = Utils.TArrayOfStr;
TTrimSide = (LEFT_SIDE, RIGHT_SIDE);
TTrimSides = set of LEFT_SIDE..RIGHT_SIDE;
PListItem = ^TListItem;
TListItem = record
Data: array of char;
DataSize: integer;
{On} NextItem: PListItem;
end; // .record TListItem
IStrBuilder = interface
procedure Append (const Str: string);
procedure AppendBuf (BufSize: integer; {n} Buf: pointer);
procedure WriteByte (Value: byte);
procedure WriteWord (Value: word);
procedure WriteInt (Value: integer);
function BuildStr: string;
function BuildBuf: Utils.TArrayOfByte;
procedure BuildTo ({n} Buf: pointer; BufSize: integer);
procedure Clear;
end;
TStrBuilder = class (TInterfacedObject, IStrBuilder)
protected
const
MIN_BLOCK_SIZE = 65000;
var
{On} fRootItem: PListItem;
{Un} fCurrItem: PListItem;
fSize: integer;
public
destructor Destroy; override;
procedure Append (const Str: string);
procedure AppendWide (const Str: WideString);
procedure AppendBuf (BufSize: integer; {n} Buf: pointer);
procedure AppendWithLenField (const Str: string; StrLenFieldSize: integer = sizeof(integer));
procedure WriteByte (Value: byte);
procedure WriteWord (Value: word);
procedure WriteInt (Value: integer);
function BuildStr: string;
function BuildWideStr: WideString;
function BuildBuf: Utils.TArrayOfByte;
procedure BuildTo ({n} Buf: pointer; BufSize: integer);
procedure Clear;
property Size: integer read fSize;
end; // .class TStrBuilder
IByteSource = interface
(* Reads up to specified number of bytes to buffer. Returns number of actually read bytes *)
function Read (Count: integer; {Un} Buf: pointer): integer;
end;
TStrByteSource = class (TInterfacedObject, IByteSource)
protected
fData: string;
fDataLen: integer;
fPos: integer;
public
constructor Create (const Data: string);
function Read (Count: integer; {Un} Buf: pointer): integer;
end; // .TStrByteSource
TBufByteSource = class (TInterfacedObject, IByteSource)
protected
{Un} fBuf: pointer;
fBufSize: integer;
fPos: integer;
public
constructor Create ({Un} Buf: pointer; BufSize: integer);
function Read (Count: integer; {Un} Buf: pointer): integer;
end; // .TBufByteSource
IByteMapper = interface
function GetSource: IByteSource;
procedure ReadToBuf (Count: integer; {n} Buf: pointer);
function ReadByte: byte;
function ReadWord: word;
function ReadInt: integer;
function ReadStr (StrLen: integer): string;
function ReadStrWithLenField (StrLenFieldSize: integer = sizeof(integer)): string;
end;
(* All methods assert reading success *)
TByteMapper = class (TInterfacedObject, IByteMapper)
protected
fByteSource: IByteSource;
public
constructor Create (ByteSource: IByteSource);
function GetSource: IByteSource;
procedure ReadToBuf (Count: integer; {n} Buf: pointer);
function ReadByte: byte;
function ReadWord: word;
function ReadInt: integer;
function ReadStr (StrLen: integer): string;
function ReadStrWithLenField (StrLenFieldSize: integer = sizeof(integer)): string;
end; // .TByteMapper
function MakeStr: IStrBuilder;
function StrAsByteSource (const Str: string): IByteSource;
function BufAsByteSource ({Un} Buf: pointer; BufSize: integer): IByteSource;
function MapBytes (ByteSource: IByteSource): IByteMapper;
function InStrBounds (Pos: integer; const Str: string): boolean;
function BytesToAnsiString (PBytes: pbyte; NumBytes: integer): AnsiString;
function BytesToWideString (PBytes: pbyte; NumBytes: integer): WideString;
function StrLen ({n} Str: pchar): integer;
function FindChar (Ch: char; const Str: string; var {out} CharPos: integer): boolean;
function FindCharEx (Ch: char; const Str: string; StartPos: integer; var {out} CharPos: integer): boolean;
function ReverseFindCharEx (Ch: char; const Str: string; StartPos: integer; var {out} CharPos: integer): boolean;
function ReverseFindChar (Ch: char; const Str: string; var {out} CharPos: integer): boolean;
function FindCharW (Ch: WideChar; const Str: WideString; var {out} CharPos: integer): boolean;
function FindCharExW (Ch: WideChar; const Str: WideString; StartPos: integer; var {out} CharPos: integer): boolean;
function FindCharsetEx (const Charset: Utils.TCharSet; const Str: string; StartPos: integer; var {out} CharPos: integer): boolean;
function SkipCharsetEx (const Charset: Utils.TCharSet; const Str: string; StartPos: integer; var {out} CharPos: integer): boolean;
function FindCharset (const Charset: Utils.TCharSet; const Str: string; var {out} CharPos: integer): boolean;
(* Both FindSubstr routines are wrappers around Delphi Pos function *)
function FindSubstrEx (const Substr, Str: string; StartPos: integer; var {out} SubstrPos: integer): boolean;
function FindSubstr (const Substr, Str: string; var {out} SubstrPos: integer): boolean;
(*
Knuth-Morris-Pratt stable speed fast search algorithm.
F('', Haystack, StartPos in range of Haystack) => true, StartPos
F('', Haystack, StartPos out of range of Haystack) => false
*)
function FindStr (const Needle, Haystack: string; var {out} FoundPos: integer): boolean;
function FindStrEx (const Needle, Haystack: string; Pos: integer; var {out} FoundPos: integer): boolean;
function ReplaceChar (WhatChar, WithChar: char; const Str: string): string;
(* Replaces characters from WhatChars string with correspoding characters in WithChars string in original string *)
function TranslateStr (const WhatChars, WithChars, Str: string): string;
(*
f('') => NIL
f(Str, '') => [Str]
*)
function ExplodeEx (const Str, Delim: string; InclDelim: boolean; LimitTokens: boolean; MaxTokens: integer): TArrayOfStr;
function Explode (const Str: string; const Delim: string): TArrayOfStr;
function Join (const Arr: TArrayOfStr; const Glue: string): string;
(* Returns true if string consists of #0..#32 characters only *)
function IsEmpty (const Str: string): boolean; overload;
function IsEmpty ({n} Buf: pchar): boolean; overload;
(*
TemplArgs - pairs of (ArgName, ArgValue).
Example: f('Hello, ~UserName~. You are ~Years~ years old.', ['Years', '20', 'UserName', 'Bob'], '~') =>
=> 'Hello, Bob. You are 20 years old'.
*)
function BuildStr (const Template: string; const TemplArgs: array of string; TemplChar: char): string;
function CharsetToStr (const Charset: Utils.TCharSet): string;
function IntToRoman (Value: integer): string;
function CharToLower (c: char): char;
function CharToUpper (c: char): char;
function Capitalize (const Str: string): string;
function HexCharToByte (HexChar: char): byte;
function ByteToHexChar (ByteValue: byte): char;
function BinToHex (NumBytes: integer; Bytes: Utils.PEndlessByteArr): string;
function Concat (const Strings: array of string): string; overload;
(* Routine can safely copy two pchars to buffer or concat existing pchar with another one (if Buf = Str1, i.e).
Pass -1 for autodetecting null-terminating string lengths. Returns length of final string without null char *)
function Concat ({n} Buf: pchar; BufSize: integer; {n} Str1: pchar; StrLen1: integer; {n} Str2: pchar; StrLen2: integer = -1): integer; overload;
function TrimEx (const Str: string; const TrimCharSet: Utils.TCharSet; TrimSides: TTrimSides = [LEFT_SIDE, RIGHT_SIDE]): string;
function TrimW (const Str: WideString): WideString;
function TrimExW (const Str: WideString; const TrimCharSet: Utils.TCharSet; TrimSides: TTrimSides = [LEFT_SIDE, RIGHT_SIDE]): WideString;
function ExtractBaseFileName (const FilePath: string): string;
function ExtractExt (const FilePath: string): string;
function Substr ({n} Buf: pchar; StartPos: integer; SubstrLen: integer = -1): string;
function SubstrBeforeChar (const Str: string; Ch: char): string;
function Match (const Str, Pattern: string): boolean;
function MatchW (const Str, Pattern: WideString): boolean;
function ExtractFromPchar (Str: pchar; Count: integer): string;
(* Reads and parses [+-]\d++ value from buffer and returns true, if at least single digit is processed.
BufPos is adjusted to point to next character. Overflows are allowed *)
function ParseIntFromPchar (var BufPos: pchar; var Res: integer): boolean;
(* Consider using SetString (string, pchar, length) *)
function BufToStr ({n} Buf: pointer; BufSize: integer): string;
(*) Detects characters in the BINARY_CHARACTERS set *)
function IsBinaryStr (const Str: string): boolean;
function Utf8ToAnsi (const Str: string): string;
(* Returns empty string on failure *)
function Utf8ToWide (const Str: string; FailOnError: boolean = false): WideString;
(* Returns empty string on failure *)
function WideToUtf8 (const Str: WideString): AnsiString;
function PWideCharToAnsi (const Str: PWideChar; out Res: string; FailOnError: boolean = false): boolean;
(* Converts null-terminated WideString to AnsiString, substituting invalid characters with special character *)
function WideToAnsiSubstitute (const Str: WideString): string;
function WideStringFromBuf ({n} Buf: PWideChar; NumChars: integer = -1): WideString;
function WideStringToBuf (const Str: WideString; Buf: PWideChar): PWideChar;
function WideLowerCase (const Str: WideString): WideString;
function ExcludeLeadingBackslashW (const Str: WideString; {n} HadLeadingBackslash: pboolean = nil): WideString;
function ExcludeTrailingBackslashW (const Str: WideString; {n} HadTrailingBackslash: pboolean = nil): WideString;
function TrimBackslashesW (const Str: WideString): WideString;
function ExtractDirPathW (const Path: WideString): WideString;
function ExtractFileNameW (const Path: WideString): WideString;
function ComparePchars ({n} Str1Ptr, {n} Str2Ptr: pchar): integer;
function CompareWideChars (Str1Ptr, Str2Ptr: PWideChar; Len: integer = -1): integer;
function CompareBinStringsW (const Str1, Str2: WideString): integer;
(***) implementation (***)
destructor TStrBuilder.Destroy;
begin
Self.Clear;
end; // .destructor TStrBuilder.Destroy
procedure TStrBuilder.Append (const Str: string);
begin
Self.AppendBuf(Length(Str), pointer(Str));
end;
procedure TStrBuilder.AppendWithLenField (const Str: string; StrLenFieldSize: integer = sizeof(integer));
var
StrLen: integer;
begin
{!} Assert(StrLenFieldSize in [1, 2, 4, sizeof(integer)]);
StrLen := Length(Str);
Self.AppendBuf(StrLenFieldSize, @StrLen);
Self.AppendBuf(StrLen, pointer(Str));
end;
procedure TStrBuilder.AppendWide (const Str: WideString);
begin
Self.AppendBuf(Length(Str) * sizeof(WideChar), pointer(Str));
end;
procedure TStrBuilder.AppendBuf (BufSize: integer; {n} Buf: pointer);
var
LeftPartSize: integer;
RightPartSize: integer;
begin
{!} Assert(Utils.IsValidBuf(Buf, BufSize));
if BufSize > 0 then begin
if Self.fRootItem = nil then begin
New(Self.fRootItem);
Self.fCurrItem := Self.fRootItem;
SetLength(Self.fCurrItem.Data, Math.Max(BufSize, Self.MIN_BLOCK_SIZE));
Self.fCurrItem.DataSize := 0;
Self.fCurrItem.NextItem := nil;
end;
LeftPartSize := Math.Min(BufSize, Length(Self.fCurrItem.Data) - Self.fCurrItem.DataSize);
RightPartSize := BufSize - LeftPartSize;
if LeftPartSize > 0 then begin
Utils.CopyMem(LeftPartSize, Buf, @Self.fCurrItem.Data[Self.fCurrItem.DataSize]);
end;
Inc(Self.fCurrItem.DataSize, LeftPartSize);
if RightPartSize > 0 then begin
New(Self.fCurrItem.NextItem);
Self.fCurrItem := Self.fCurrItem.NextItem;
SetLength(Self.fCurrItem.Data, Math.Max(RightPartSize, Self.MIN_BLOCK_SIZE));
Self.fCurrItem.DataSize := RightPartSize;
Self.fCurrItem.NextItem := nil;
Utils.CopyMem(RightPartSize, Utils.PtrOfs(Buf, LeftPartSize), @Self.fCurrItem.Data[0]);
end;
Self.fSize := Self.fSize + BufSize;
end; // .if
end; // .procedure TStrBuilder.AppendBuf
procedure TStrBuilder.WriteByte (Value: byte);
begin
Self.AppendBuf(sizeof(Value), @Value);
end;
procedure TStrBuilder.WriteWord (Value: word);
begin
Self.AppendBuf(sizeof(Value), @Value);
end;
procedure TStrBuilder.WriteInt (Value: integer);
begin
Self.AppendBuf(sizeof(Value), @Value);
end;
function TStrBuilder.BuildStr: string;
var
{U} CurrItem: PListItem;
Pos: integer;
begin
CurrItem := Self.fRootItem;
// * * * * * //
SetLength(result, Self.fSize);
Pos := 0;
while CurrItem <> nil do begin
Utils.CopyMem(CurrItem.DataSize, @CurrItem.Data[0], Utils.PtrOfs(pointer(result), Pos));
Pos := Pos + CurrItem.DataSize;
CurrItem := CurrItem.NextItem;
end;
end; // .function TStrBuilder.BuildStr
function TStrBuilder.BuildWideStr: WideString;
var
{U} CurrItem: PListItem;
Pos: integer;
begin
CurrItem := Self.fRootItem;
// * * * * * //
SetLength(result, Ceil(Self.fSize / sizeof(WideChar)));
Pos := 0;
while CurrItem <> nil do begin
Utils.CopyMem(CurrItem.DataSize, @CurrItem.Data[0], Utils.PtrOfs(pointer(result), Pos));
Pos := Pos + CurrItem.DataSize;
CurrItem := CurrItem.NextItem;
end;
end; // .function TStrBuilder.BuildStr
function TStrBuilder.BuildBuf: TArrayOfByte;
var
{U} CurrItem: PListItem;
Pos: integer;
begin
CurrItem := Self.fRootItem;
// * * * * * //
SetLength(result, Self.fSize);
Pos := 0;
while CurrItem <> nil do begin
Utils.CopyMem(CurrItem.DataSize, @CurrItem.Data[0], Utils.PtrOfs(pointer(result), Pos));
Pos := Pos + CurrItem.DataSize;
CurrItem := CurrItem.NextItem;
end;
end; // .function TStrBuilder.BuildBuf
procedure TStrBuilder.BuildTo ({n} Buf: pointer; BufSize: integer);
var
{U} CurrItem: PListItem;
Pos: integer;
begin
{!} Assert(Utils.IsValidBuf(Buf, BufSize));
CurrItem := Self.fRootItem;
// * * * * * //
Pos := 0;
while (CurrItem <> nil) and (Pos < BufSize) do begin
Utils.CopyMem(Math.Min(BufSize - Pos, CurrItem.DataSize), @CurrItem.Data[0], Utils.PtrOfs(pointer(Buf), Pos));
Inc(Pos, CurrItem.DataSize);
CurrItem := CurrItem.NextItem;
end;
end; // .procedure TStrBuilder.BuildTo
procedure TStrBuilder.Clear;
var
{Un} CurrItem: PListItem;
{Un} NextItem: PListItem;
begin
CurrItem := Self.fRootItem;
NextItem := nil;
// * * * * * //
while CurrItem <> nil do begin
NextItem := CurrItem.NextItem;
Dispose(CurrItem);
CurrItem := NextItem;
end;
Self.fRootItem := nil;
Self.fCurrItem := nil;
Self.fSize := 0;
end; // .procedure TStrBuilder.Clear
constructor TStrByteSource.Create (const Data: string);
begin
inherited Create;
fData := Data;
fDataLen := length(Data);
fPos := 0;
end;
function TStrByteSource.Read (Count: integer; {Un} Buf: pointer): integer;
begin
{!} Assert(Utils.IsValidBuf(Buf, Count));
if Count = 0 then begin
result := 0;
end else begin
result := Min(Count, fDataLen - fPos);
if result > 0 then begin
Utils.CopyMem(Count, @fData[fPos + 1], Buf);
inc(fPos, result);
end;
end;
end; // .function TStrByteSource.Read
constructor TBufByteSource.Create ({Un} Buf: pointer; BufSize: integer);
begin
{!} Assert(Utils.IsValidBuf(Buf, BufSize));
inherited Create;
fBuf := Buf;
fBufSize := BufSize;
fPos := 0;
end;
function TBufByteSource.Read (Count: integer; {Un} Buf: pointer): integer;
begin
{!} Assert(Utils.IsValidBuf(Buf, Count));
if Count = 0 then begin
result := 0;
end else begin
result := Min(Count, fBufSize - fPos);
if result > 0 then begin
Utils.CopyMem(Count, Utils.PtrOfs(fBuf, fPos), Buf);
inc(fPos, result);
end;
end;
end; // .function TBufByteSource.Read
constructor TByteMapper.Create (ByteSource: IByteSource);
begin
inherited Create;
fByteSource := ByteSource;
end;
function TByteMapper.GetSource: IByteSource;
begin
result := fByteSource;
end;
procedure TByteMapper.ReadToBuf (Count: integer; {n} Buf: pointer);
begin
{!} Assert(fByteSource.Read(Count, Buf) = Count);
end;
function TByteMapper.ReadByte: byte;
begin
{!} Assert(fByteSource.Read(sizeof(result), @result) = sizeof(result));
end;
function TByteMapper.ReadWord: word;
begin
{!} Assert(fByteSource.Read(sizeof(result), @result) = sizeof(result));
end;
function TByteMapper.ReadInt: integer;
begin
{!} Assert(fByteSource.Read(sizeof(result), @result) = sizeof(result));
end;
function TByteMapper.ReadStr (StrLen: integer): string;
begin
{!} Assert(StrLen >= 0);
SetLength(result, StrLen);
if StrLen > 0 then begin
{!} Assert(fByteSource.Read(StrLen, @result[1]) = StrLen);
end;
end;
function TByteMapper.ReadStrWithLenField (StrLenFieldSize: integer = sizeof(integer)): string;
var
StrLen: integer;
begin
{!} Assert(StrLenFieldSize in [1, 2, 4, sizeof(integer)]);
StrLen := 0;
result := '';
{!} Assert(fByteSource.Read(StrLenFieldSize, @StrLen) = StrLenFieldSize);
{!} Assert(StrLen >= 0);
if StrLen > 0 then begin
SetLength(result, StrLen);
{!} Assert(fByteSource.Read(StrLen, @result[1]) = StrLen);
end;
end;
function MakeStr: IStrBuilder;
begin
result := TStrBuilder.Create;
end;
function StrAsByteSource (const Str: string): IByteSource;
begin
result := TStrByteSource.Create(Str);
end;
function BufAsByteSource ({Un} Buf: pointer; BufSize: integer): IByteSource;
begin
result := TBufByteSource.Create(Buf, BufSize);
end;
function MapBytes (ByteSource: IByteSource): IByteMapper;
begin
result := TByteMapper.Create(ByteSource);
end;
function InStrBounds (Pos: integer; const Str: string): boolean;
begin
result := Math.InRange(Pos, 1, Length(Str));
end;
function StrLen ({n} Str: pchar): integer;
begin
result := 0;
if (Str <> nil) and (Str^ <> #0) then begin
result := Windows.LStrLen(Str);
end;
end;
function BytesToAnsiString (PBytes: PBYTE; NumBytes: integer): AnsiString;
begin
{!} Assert(PBytes <> nil);
{!} Assert(NumBytes >= 0);
SetLength(result, NumBytes);
Utils.CopyMem(NumBytes, PBytes, pointer(result));
end;
function BytesToWideString (PBytes: PBYTE; NumBytes: integer): WideString;
begin
{!} Assert(PBytes <> nil);
{!} Assert(NumBytes >= 0);
{!} Assert(Utils.EVEN(NumBytes));
SetLength(result, NumBytes shr 1);
Utils.CopyMem(NumBytes, PBytes, pointer(result));
end;
function FindCharEx (Ch: char; const Str: string; StartPos: integer; var {out} CharPos: integer): boolean;
var
StrLen: integer;
i: integer;
begin
StrLen := Length(Str);
result := Math.InRange(StartPos, 1, StrLen);
if result then begin
i := StartPos;
while (i <= StrLen) and (Str[i] <> Ch) do begin
Inc(i);
end;
result := i <= StrLen;
if result then begin
CharPos := i;
end;
end;
end; // .function FindCharEx
function ReverseFindCharEx (Ch: char; const Str: string; StartPos: integer; var {out} CharPos: integer): boolean;
var
StrLen: integer;
i: integer;
begin
StrLen := Length(Str);
result := Math.InRange(StartPos, 1, StrLen);
if result then begin
i := StartPos;
while (i >= 1) and (Str[i] <> Ch) do begin
Dec(i);
end;
result := i >= 1;
if result then begin
CharPos := i;
end;
end;
end; // .function ReverseFindCharEx
function FindChar (Ch: char; const Str: string; var {out} CharPos: integer): boolean;
begin
result := FindCharEx(Ch, Str, 1, CharPos);
end;
function ReverseFindChar (Ch: char; const Str: string; var {out} CharPos: integer): boolean;
begin
result := ReverseFindCharEx(Ch, Str, Length(Str), CharPos);
end;
function FindCharExW (Ch: WideChar; const Str: WideString; StartPos: integer; var {out} CharPos: integer): boolean;
var
CharPtr: PWideChar;
StrLen: integer;
begin
CharPtr := nil;
// * * * * * //
StrLen := Length(Str);
result := Math.InRange(StartPos, 1, StrLen);
if result then begin
CharPtr := PWideChar(Str) + (StartPos - 1);
while (CharPtr^ <> #0) and (CharPtr^ <> Ch) do begin
Inc(CharPtr);
end;
result := CharPtr^ <> #0;
if result then begin
CharPos := (CharPtr - PWideChar(Str)) + 1;
end;
end; // .if
end; // .function FindCharExW
function FindCharW (Ch: WideChar; const Str: WideString; var {out} CharPos: integer): boolean;
begin
result := FindCharExW(Ch, Str, 1, CharPos);
end;
function FindCharsetEx (const Charset: Utils.TCharSet; const Str: string; StartPos: integer; var {out} CharPos: integer): boolean;
var
StrLen: integer;
i: integer;
begin
{!} Assert(StartPos >= 1);
StrLen := Length(Str);
result := StartPos <= StrLen;
if result then begin
i := StartPos;
while (i <= StrLen) and not (Str[i] in Charset) do begin
Inc(i);
end;
result := i <= StrLen;
if result then begin
CharPos := i;
end;
end;
end; // .function FindCharsetEx
function FindCharset (const Charset: Utils.TCharSet; const Str: string; var {out} CharPos: integer): boolean;
begin
result := FindCharsetEx(Charset, Str, 1, CharPos);
end;
function SkipCharsetEx (const Charset: Utils.TCharSet; const Str: string; StartPos: integer; var {out} CharPos: integer): boolean;
var
StrLen: integer;
i: integer;
begin
{!} Assert(StartPos >= 1);
StrLen := Length(Str);
result := StartPos <= StrLen;
if result then begin
i := StartPos;
while (i <= StrLen) and (Str[i] in Charset) do begin
Inc(i);
end;
result := i <= StrLen;
if result then begin
CharPos := i;
end;
end;
end; // .function SkipCharsetEx
function FindSubstrEx (const Substr, Str: string; StartPos: integer; var {out} SubstrPos: integer): boolean;
var
Pos: integer;
begin
Pos := StrUtils.PosEx(Substr, Str, StartPos);
if Pos <> 0 then begin
SubstrPos := Pos;
result := true;
end else begin
result := false;
end;
end; // .function FindSubstrEx
function FindSubstr (const Substr, Str: string; var {out} SubstrPos: integer): boolean;
begin
result := FindSubstrEx(Substr, Str, 1, SubstrPos);
end;
function FindStrEx (const Needle, Haystack: string; Pos: integer; var {out} FoundPos: integer): boolean;
const
MAX_STATIC_FALLBACK_TABLE_LEN = 255;
START_STRING_POS = 1;
var
{O} FallbackTableBuf: PEndlessIntArr;
FallbackTableStackStorage: array [0..MAX_STATIC_FALLBACK_TABLE_LEN] of integer;
{U} FallbackTable: PEndlessIntArr;
NeedleLen: integer;
HaystackLen: integer;
FirstNeedleChar: char;
FirstFourNeedleChars: integer;
FarthestStartPos: integer; // Last pos where there is any sense to start searching
FallbackPos: integer;
HaystackPtr: pinteger;
HaystackEndMinusFourPtr: pinteger;
i: integer;
procedure GenerateFallbackTable;
var
k: integer;
begin
// Initialize fallback table pointer to either stack storage or memory buffer
if NeedleLen <= MAX_STATIC_FALLBACK_TABLE_LEN then begin
FallbackTable := @FallbackTableStackStorage[0];
end else begin
GetMem(FallbackTableBuf, (NeedleLen + 1) * sizeof(integer));
FallbackTable := FallbackTableBuf;
end;
// First not matched char always redirect to start, starting analysis from the the second one
FallbackTable[START_STRING_POS] := START_STRING_POS;
k := START_STRING_POS + 1;
while k <= NeedleLen do begin
// Search for the next occurense of needle prefix in the needle itself
repeat
FallbackTable[k] := START_STRING_POS;
Inc(k);
until (k > NeedleLen) or (Needle[k - 1] = FirstNeedleChar);
// First char is already checked, starting from the second one
i := START_STRING_POS + 1;
if k <= NeedleLen then begin
// While characters match needle prefix, fallback offsets grow
// ab[abababab]c[ab]d
// 11[12345678]1[12]1
repeat
FallbackTable[k] := i;
Inc(i);
Inc(k);
until (k > NeedleLen) or (Needle[i] <> Needle[k]);
end;
end; // .while
end; // .procedure GenerateFallbackTable
procedure FindFirstNeedleChars;
begin
if Pos <= FarthestStartPos then begin
HaystackPtr := @Haystack[Pos];
while (cardinal(HaystackPtr) <= cardinal(HaystackEndMinusFourPtr)) and
(HaystackPtr^ <> FirstFourNeedleChars)
do begin
Inc(pbyte(HaystackPtr));
end;
i := START_STRING_POS + sizeof(integer);
if cardinal(HaystackPtr) <= cardinal(HaystackEndMinusFourPtr) then begin
Pos := Pos + (integer(HaystackPtr) - integer(@Haystack[Pos])) + sizeof(integer);
end else begin
Pos := MAXINT;
end;
end; // .if
end; // .procedure FindFirstNeedleChars
begin
FallbackTableBuf := nil;
FallbackTable := nil;
// * * * * * //
if Pos < START_STRING_POS then begin
Pos := START_STRING_POS;
end;
NeedleLen := Length(Needle);
HaystackLen := Length(Haystack);
FarthestStartPos := HaystackLen - NeedleLen + 1;
result := (Pos <= FarthestStartPos) and (HaystackLen > 0);
if result then begin
if NeedleLen = 0 then begin
FoundPos := START_STRING_POS;
end else if NeedleLen <= sizeof(integer) then begin
result := FindSubstrEx(Needle, Haystack, Pos, FoundPos);
end else begin
FirstNeedleChar := Needle[START_STRING_POS];
FirstFourNeedleChars := pinteger(@Needle[START_STRING_POS])^;
HaystackEndMinusFourPtr := @Haystack[HaystackLen - sizeof(integer) + 1];
GenerateFallbackTable;
i := START_STRING_POS;
FindFirstNeedleChars;
while (Pos <= HaystackLen) and (i <= NeedleLen) do begin
if Haystack[Pos] = Needle[i] then begin
Inc(Pos);
Inc(i);
end else begin
FallbackPos := FallbackTable[i];
if FallbackPos = START_STRING_POS then begin
FindFirstNeedleChars;
end else begin
i := FallbackPos;
end;
end; // .else
end; // .while
result := i > NeedleLen;
if result then begin
FoundPos := Pos - NeedleLen;
end;
end; // .else
end; // .if
// * * * * * //
FreeMem(FallbackTableBuf);
end; // .function FindStrEx
function FindStr (const Needle, Haystack: string; var {out} FoundPos: integer): boolean;
begin
result := FindStrEx(Needle, Haystack, 1, FoundPos);
end;
function ReplaceChar (WhatChar, WithChar: char; const Str: string): string;
var
i: integer;
begin
result := Str;
for i := 1 to Length(result) do begin
if result[i] = WhatChar then begin
result[i] := WithChar;
end;
end;
end;
function TranslateStr (const WhatChars, WithChars, Str: string): string;
var
ReplaceCharSet: set of char;
Replacements: array [Low(char)..High(char)] of char;
i: integer;
begin
ReplaceCharSet := [];
for i := 1 to Math.Min(Length(WhatChars), Length(WithChars)) do begin
Include(ReplaceCharSet, WhatChars[i]);
Replacements[chr(i)] := WithChars[i];
end;
result := Str;
for i := 1 to Length(result) do begin
if result[i] in ReplaceCharSet then begin
result[i] := Replacements[chr(i)];
end;
end;
end;
function ExplodeEx (const Str, Delim: string; InclDelim: boolean; LimitTokens: boolean; MaxTokens: integer): TArrayOfStr;
var
(* O *) DelimPosList: Classes.TList {OF INTEGER};
StrLen: integer;
DelimLen: integer;
DelimPos: integer;
DelimsLimit: integer;
NumDelims: integer;
TokenStartPos: integer;
TokenEndPos: integer;
TokenLen: integer;
i: integer;
begin
{!} Assert(not LimitTokens or (MaxTokens > 0));
DelimPosList := Classes.TList.Create;
result := nil;
// * * * * * //
StrLen := Length(Str);
DelimLen := Length(Delim);
if StrLen > 0 then begin
if not LimitTokens then begin
MaxTokens := MAXLONGINT;
end;
if DelimLen = 0 then begin
SetLength(result, 1);
result[0] := Str;
end else begin
DelimsLimit := MaxTokens - 1;
NumDelims := 0;
DelimPos := 1;
while (NumDelims < DelimsLimit) and FindSubstrEx(Delim, Str, DelimPos, DelimPos) do begin
DelimPosList.Add(pointer(DelimPos));
Inc(DelimPos);
Inc(NumDelims);
end;
DelimPosList.Add(pointer(StrLen + 1));
SetLength(result, NumDelims + 1);
TokenStartPos := 1;
for i := 0 to NumDelims do begin
TokenEndPos := integer(DelimPosList[i]);
TokenLen := TokenEndPos - TokenStartPos;
if InclDelim and (i < NumDelims) then begin
TokenLen := TokenLen + DelimLen;
end;
result[i] := Copy(Str, TokenStartPos, TokenLen);
TokenStartPos := TokenStartPos + DelimLen + TokenLen - ord(InclDelim);
end; // .for
end; // .else
end; // .if
// * * * * * //
SysUtils.FreeAndNil(DelimPosList);
end; // .function ExplodeEx
function Explode (const Str: string; const Delim: string): TArrayOfStr;
begin
result := ExplodeEx(Str, Delim, not INCLUDE_DELIM, not LIMIT_TOKENS, 0);
end;
function Join (const Arr: TArrayOfStr; const Glue: string): string;
var
(* U *) Mem: pointer;
ArrLen: integer;