EricGrange/DWScript

Issue for dwsHashtables.pas

Opened this issue · 3 comments

There's some code in dwsHashtables.pas.

procedure InitTables;
var
I, K: Char;
Temp: Integer;
begin
for I := #0 to #255 do
begin
HashTable[I] := Ord(I);
InsensitiveHashTable[I] := Ord(AnsiUpperCase(Char(I))[1]);
end;
RandSeed := 111;
for I := #1 to #255 do
begin
repeat
K := Char(Random(255));
until K <> #0;
Temp := HashTable[I];
HashTable[I] := HashTable[K];
HashTable[K] := Temp;
end;
end;

I test the code as follow in Delphi 12. The result shows 63734.

procedure TForm2.FormCreate(Sender: TObject);
var
I: Char;
v: Integer;
begin
v := 0;
for I := #0 to #255 do
begin
Inc(v);
end;
ShowMessage(v.ToString);
end;

I'm not to to follow the relationship between the first code snippet and the second one ?

Though TBH dwsHashtables is legacy, and exposed only through the legacy dwsClassesLibModule, I'm not entirely sure if it works (I never used it). Similar functionality is available and maintain through associative arrays.

The line for I := #1 to #255 do may be more than 255 times cycles.
The I was type Char (WideChar). This value is likely to have implicit conversion according to the local language. In non English systems, this value maybe exceed 255.
Therefore, the appropriate choice should be to use AnsiChar as the loop variable.
And then Ord(AnsiUpperCase(Char(I))[1]); should replace with Ord(System.AnsiStrings.AnsiUpperCase(AnsiChar(I))[1]);

Hmm, there is loop on #1 to #255 in dwsHashTables's InitiTables, it's already "for I := 1 to 255 do"

https://github.com/EricGrange/DWScript/blob/master/Libraries/ClassesLib/dwsHashtables.pas

this was changed a year ago in by this commit

3295c84