* Add enumerator for TStringBuilder. Fix issue #37088

This commit is contained in:
Michaël Van Canneyt 2023-08-12 14:33:10 +02:00
parent 896ca4bb75
commit fd39fd96b3
3 changed files with 85 additions and 0 deletions

View File

@ -37,6 +37,27 @@ begin
Create(aValue,DefaultCapacity);
end;
{ Enumerator }
function TGenericStringBuilder.TCharEnumerator.GetCurrent: SBChar;
begin
Result := FCurrentPosition^;
Inc(FCurrentPosition);
end;
function TGenericStringBuilder.TCharEnumerator.MoveNext: Boolean;
begin
Result := FCurrentPosition < FEndPosition;
end;
function TGenericStringBuilder.GetEnumerator: TCharEnumerator;
var
StartPosition: PSBChar;
begin
StartPosition := @FData[0];
Result.FCurrentPosition := StartPosition;
Result.FEndPosition := StartPosition + Length;
end;
{ Property getter/setter }

View File

@ -6,6 +6,16 @@
private
const
DefaultCapacity = 64;
type
TCharEnumerator = record
private
FCurrentPosition: PSBChar;
FEndPosition: PSBChar;
Function GetCurrent: SBChar; inline;
public
Function MoveNext: Boolean; inline;
property Current: SBChar read GetCurrent;
end;
private
Function GetCapacity: Integer;
Procedure SetCapacity(AValue: Integer);
@ -76,6 +86,8 @@
Function EnsureCapacity(aCapacity: Integer): Integer;
Function Equals(StringBuilder: TGenericStringBuilder): Boolean; reintroduce;
Function GetEnumerator: TCharEnumerator; inline;
Function Insert(Index: Integer; const AValue: Boolean): TGenericStringBuilder;
Function Insert(Index: Integer; const AValue: Byte): TGenericStringBuilder;
Function Insert(Index: Integer; const AValue: SBChar): TGenericStringBuilder;

View File

@ -0,0 +1,52 @@
program strbld_forin_tests;
{$mode Delphi}
uses
SysUtils;
var
c: Char;
sb: TStringBuilder;
i: Integer;
begin
sb := TStringBuilder.Create;
try
sb.Append('Hello');
sb.Append(' ');
sb.Append('World!');
sb.Append(' ');
sb.Append('16052020');
i := 0;
for c in sb do
begin
writeln(c);
if sb[i] <> c then halt(i);
Inc(i);
end;
// test empty
sb.clear;
i := 0;
for c in sb do
begin
writeln(c);
if sb[i] <> c then halt(i);
Inc(i);
end;
sb.Append('A');
i := 0;
for c in sb do
begin
writeln(c);
if sb[i] <> c then halt(i);
Inc(i);
end;
finally
sb.Free;
end;
end.