Skip to content

Commit

Permalink
Fix null convertion in Num::fromString (wren-lang#1131)
Browse files Browse the repository at this point in the history
When `strtod` returns `0.0`, no conversion could have happened. Handle
the error case correctly.
  • Loading branch information
mhermier committed Jan 5, 2023
1 parent c2a75f1 commit fd3fe7f
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/vm/wren_core.c
Original file line number Diff line number Diff line change
Expand Up @@ -618,11 +618,14 @@ DEF_PRIMITIVE(num_fromString)
char* end;
double number = strtod(string->value, &end);

if (errno == ERANGE) RETURN_ERROR("Number literal is too large.");

// Check for no conversion.
if (number == 0.0 && string->value == end) RETURN_NULL;

// Skip past any trailing whitespace.
while (*end != '\0' && isspace((unsigned char)*end)) end++;

if (errno == ERANGE) RETURN_ERROR("Number literal is too large.");

// We must have consumed the entire string. Otherwise, it contains non-number
// characters and we can't parse it.
if (end < string->value + string->length) RETURN_NULL;
Expand Down
1 change: 1 addition & 0 deletions test/core/number/from_string.wren
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ System.print(Num.fromString(" 12 ") == 12) // expect: true
// Test some non-number literals and ensure they return null.
System.print(Num.fromString("test1") == null) // expect: true
System.print(Num.fromString("") == null) // expect: true
System.print(Num.fromString(" ") == null) // expect: true
System.print(Num.fromString("prefix1.2") == null) // expect: true
System.print(Num.fromString("1.2suffix") == null) // expect: true

Expand Down

0 comments on commit fd3fe7f

Please sign in to comment.