Skip to content

Commit 7f069c0

Browse files
committed
Fixed overflow detection in new StrToInt overload + updated test
1 parent 3be6a49 commit 7f069c0

File tree

3 files changed

+44
-29
lines changed

3 files changed

+44
-29
lines changed

Source/dwsUtils.pas

Lines changed: 35 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2006,41 +2006,47 @@ function TryStrToIntBase(const s : UnicodeString; base : Integer; var value : In
20062006

20072007
p := Pointer(s);
20082008

2009-
neg := False;
2010-
case p^ of
2011-
'+' : Inc(p);
2012-
'-' : begin
2013-
neg := True;
2014-
Inc(p);
2015-
end;
2016-
'0' : begin
2017-
while p[1] = '0' do
2009+
try
2010+
neg := False;
2011+
case p^ of
2012+
'+' : Inc(p);
2013+
'-' : begin
2014+
neg := True;
20182015
Inc(p);
2016+
end;
2017+
'0' : begin
2018+
while p[1] = '0' do
2019+
Inc(p);
2020+
end;
20192021
end;
2020-
end;
20212022

2022-
temp := 0;
2023+
temp := 0;
20232024

2024-
while True do begin
2025-
case p^ of
2026-
#0 : Break;
2027-
'0'..'9' : d := Ord(p^) - Ord('0');
2028-
'a'..'z' : d := Ord(p^) + (10 - Ord('a'));
2029-
'A'..'Z' : d := Ord(p^) + (10 - Ord('A'));
2030-
else
2031-
Exit;
2025+
while True do begin
2026+
case p^ of
2027+
#0 : Break;
2028+
'0'..'9' : d := Ord(p^) - Ord('0');
2029+
'a'..'z' : d := Ord(p^) + (10 - Ord('a'));
2030+
'A'..'Z' : d := Ord(p^) + (10 - Ord('A'));
2031+
else
2032+
Exit;
2033+
end;
2034+
if d >= base then
2035+
Exit;
2036+
{$Q+}
2037+
temp := temp * base + d;
2038+
{$Q-}
2039+
Inc(p);
20322040
end;
2033-
if d >= base then
2034-
Exit;
2035-
temp := temp * base + d;
2036-
if temp < 0 then
2037-
exit;
2038-
Inc(p);
2041+
if neg then
2042+
value := -temp
2043+
else value := temp;
2044+
Result := True;
2045+
except
2046+
on E: EIntOverflow do
2047+
Exit(False);
2048+
else raise;
20392049
end;
2040-
if neg then
2041-
value := -temp
2042-
else value := temp;
2043-
Result := True;
20442050
end;
20452051

20462052
// FastStringReplace

Test/FunctionsString/strtoint_base.pas

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,10 @@
4040
except
4141
on E: Exception do PrintLn(E.Message);
4242
end;
43+
44+
try
45+
PrintLn(StrToInt('4444444444444444', base+6));
46+
PrintLn(StrToInt('44444444444444444', base+6));
47+
except
48+
on E: Exception do PrintLn(E.Message);
49+
end;

Test/FunctionsString/strtoint_base.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,5 @@ Invalid base for string to integer conversion (1) [line: 18, column: 12]
4141
9223372036854775807
4242
-9223372036854775807
4343
"zzzZzzzZzzzzzz" is not a valid 64bit integer value in base 36 [line: 39, column: 12]
44+
4919131752989213764
45+
"44444444444444444" is not a valid 64bit integer value in base 16 [line: 46, column: 12]

0 commit comments

Comments
 (0)