EricGrange / DWScript

Delphi Web Script general purpose scripting engine
175 stars 49 forks source link

Issue for dwsHashtables.pas #14

Open achinastone opened 1 month ago

achinastone commented 1 month ago

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;

EricGrange commented 1 month ago

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.

achinastone commented 1 month ago

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]);

EricGrange commented 1 month ago

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

https://github.com/EricGrange/DWScript/commit/3295c849881fa301cb71647f0a3227ac4e697f8c