Skip to content

Commit 00e5752

Browse files
committed
More resilient parseInt behaviour
1 parent 1aa7647 commit 00e5752

3 files changed

Lines changed: 13 additions & 1 deletion

File tree

ChangeLog

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
Add Math.tan()
44
Ensure Double/Integer have Number as a prototype (fixes: Number.prototype.n=function();(5.0).n() )
55
||/&& now doesn't use booleans (fix #251)
6+
More resilient parseInt behaviour
67

78
1v54 : Add 4x6 font (instead of 8x8)
89
Fix occasional instability with Waveform read/write

src/jsutils.c

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,12 @@ const char *escapeCharacter(char ch) {
5858

5959
/* convert a number in the given radix to an int. if radix=0, autodetect */
6060
JsVarInt stringToIntWithRadix(const char *s, int forceRadix, bool *hasError) {
61+
62+
// skip whitespace (strange parseInt behaviour)
63+
while (isWhitespace(*s)) s++;
64+
65+
const char *numberStart = s;
66+
6167
bool isNegated = false;
6268
JsVarInt v = 0;
6369
JsVarInt radix = 10;
@@ -110,7 +116,8 @@ JsVarInt stringToIntWithRadix(const char *s, int forceRadix, bool *hasError) {
110116
s++;
111117
}
112118

113-
if (hasError) *hasError = *s!=0; // we're ok if we reached the end of the string
119+
if (hasError)
120+
*hasError = s==numberStart; // we had an error if we didn't manage to parse any chars at all
114121

115122
if (isNegated) return -v;
116123
return v;

src/jswrap_functions.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,10 @@ JsVar *jswrap_parseInt(JsVar *v, JsVar *radixVar) {
8282
if (jsvIsNumeric(radixVar))
8383
radix = (int)jsvGetInteger(radixVar);
8484

85+
// shortcut for values that are already numbers
86+
if ((radix==0 || radix==10) && jsvIsNumeric(v))
87+
return jsvNewFromInteger(jsvGetInteger(v));
88+
// otherwise convert to string
8589
char buffer[JS_NUMBER_BUFFER_SIZE];
8690
jsvGetString(v, buffer, JS_NUMBER_BUFFER_SIZE);
8791
bool hasError;

0 commit comments

Comments
 (0)