String.to_float("+") fails (#2021)

* When stripping +/- from the start of a string in String.to_real: only do this if the string length is greater than 1.
* Added a test for the String.to_float("+") bug
This commit is contained in:
Stephen Molloy
2025-03-07 00:02:13 +01:00
committed by GitHub
parent ca87ff066b
commit 1fba9a7993
2 changed files with 31 additions and 8 deletions

View File

@@ -464,13 +464,16 @@ macro String.to_real(chars, $Type) @private
while (chars.len && chars[0] == ' ') chars = chars[1..];
if (!chars.len) return NumberConversion.MALFORMED_FLOAT?;
switch (chars[0])
{
case '-':
sign = -1;
nextcase;
case '+':
chars = chars[1..];
if (chars.len != 1) {
switch (chars[0])
{
case '-':
sign = -1;
nextcase;
case '+':
chars = chars[1..];
}
}
if (chars == "infinity" || chars == "INFINITY") return sign * $Type.inf;
if (chars == "NAN" || chars == "nan") return $Type.nan;

View File

@@ -12,6 +12,16 @@ fn void test_float() @test
assert(String.to_float("-23.545")!! == -23.545f);
assert(String.to_float("1.5555555555555")!! == 1.5555555555555f);
assert(String.to_float("1.5555555555556666")!! == 1.5555555555556666f);
if (catch excuse = String.to_float("+")) {
assert(excuse == NumberConversion.MALFORMED_FLOAT);
} else {
assert(false);
}
if (catch excuse = String.to_float("-")) {
assert(excuse == NumberConversion.MALFORMED_FLOAT);
} else {
assert(false);
}
}
fn void test_double() @test
@@ -26,4 +36,14 @@ fn void test_double() @test
assert(String.to_double("-23.545")!! == -23.545);
assert(String.to_double("1.5555555555555")!! == 1.5555555555555);
assert(String.to_double("1.5555555555556666")!! == 1.5555555555556666);
}
if (catch excuse = String.to_double("+")) {
assert(excuse == NumberConversion.MALFORMED_FLOAT);
} else {
assert(false);
}
if (catch excuse = String.to_double("-")) {
assert(excuse == NumberConversion.MALFORMED_FLOAT);
} else {
assert(false);
}
}