Skip to content

Commit bdf80df

Browse files
author
Patrick Soquet
committed
XS: secaudit issue #23
1 parent c8746ea commit bdf80df

File tree

1 file changed

+28
-15
lines changed

1 file changed

+28
-15
lines changed

xs/sources/xsNumber.c

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,6 @@ void fx_Number_prototype_toPrecision(txMachine* the)
408408

409409
void fx_Number_prototype_toString(txMachine* the)
410410
{
411-
char buffer[256];
412411
txInteger radix;
413412
txSlot* slot = fxCheckNumber(the, mxThis);
414413
if (!slot) mxTypeError("this is no number");
@@ -424,11 +423,7 @@ void fx_Number_prototype_toString(txMachine* the)
424423
if (radix == 10)
425424
fxToString(the, mxResult);
426425
else {
427-
static const char gxDigits[] ICACHE_FLASH_ATTR = "0123456789abcdefghijklmnopqrstuvwxyz";
428-
txString string = buffer + sizeof(buffer);
429-
txNumber value;
430-
txBoolean minus;
431-
value = mxResult->value.number;
426+
txNumber value = mxResult->value.number;
432427
switch (c_fpclassify(value)) {
433428
case C_FP_INFINITE:
434429
if (value < 0)
@@ -442,24 +437,42 @@ void fx_Number_prototype_toString(txMachine* the)
442437
case C_FP_ZERO:
443438
fxStringX(the, mxResult, "0");
444439
break;
445-
default:
446-
*(--string) = 0;
440+
default: {
441+
static const char gxDigits[] ICACHE_FLASH_ATTR = "0123456789abcdefghijklmnopqrstuvwxyz";
442+
txInteger minus;
443+
txSize length;
444+
txString string;
445+
txNumber modulo;
447446
if (value < 0) {
448447
minus = 1;
449448
value = -value;
450449
}
451450
else
452451
minus = 0;
453-
do {
454-
if (string == buffer)
455-
fxAbort(the, XS_STACK_OVERFLOW_EXIT);
456-
*(--string) = c_read8(gxDigits + (txInteger)c_fmod(value, radix));
452+
value = c_trunc(value);
453+
length = minus + (txSize)c_floor(c_log(value) / c_log(radix)) + 2;
454+
string = mxResult->value.string = fxNewChunk(the, length);
455+
mxResult->kind = XS_STRING_KIND;
456+
string += length;
457+
*(--string) = 0;
458+
modulo = C_MAX_SAFE_INTEGER * radix;
459+
while (value > modulo) {
460+
*(--string) = '0';
457461
value = value / radix;
462+
}
463+
do {
464+
modulo = c_fmod(value, radix);
465+
*(--string) = c_read8(gxDigits + (txInteger)modulo);
466+
value = (value - modulo) / radix;
458467
} while (value >= 1);
459-
if (minus)
468+
if (minus) {
460469
*(--string) = '-';
461-
fxCopyStringC(the, mxResult, string);
462-
}
470+
}
471+
if (string > mxResult->value.string) {
472+
fprintf(stderr, "oops\n");
473+
c_memmove(mxResult->value.string, string, length - (string - mxResult->value.string));\
474+
}
475+
}}
463476
}
464477
}
465478

0 commit comments

Comments
 (0)