Parcourir la source

* Add enumerator for TStringBuilder. Fix issue #37088

Michaël Van Canneyt il y a 2 ans
Parent
commit
fd39fd96b3

+ 21 - 0
rtl/objpas/sysutils/syssb.inc

@@ -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 }
 

+ 12 - 0
rtl/objpas/sysutils/syssbh.inc

@@ -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;

+ 52 - 0
tests/test/units/sysutils/tsrbldfi.pp

@@ -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.