feat: add Num.fromString static method to parse decimal string literals

Implements a new `fromString` static method on the `Num` class that attempts to parse a string as a decimal number literal using `strtod`. Returns the parsed `Num` value on success, or `null` if the string does not represent a valid number. Includes runtime validation that the argument is a string, and adds test coverage for positive, negative, zero, and decimal inputs as well as non-numeric strings.
This commit is contained in:
Gavin Schulz
2015-02-23 04:06:17 +00:00
parent 708b883e1f
commit 87cc5fdbae
4 changed files with 34 additions and 2 deletions
+18 -1
View File
@@ -911,6 +911,22 @@ DEF_NATIVE(num_toString)
RETURN_VAL(wrenNewString(vm, buffer, length));
}
DEF_NATIVE(num_fromString)
{
if (!validateString(vm, args, 1, "Argument")) return PRIM_ERROR;
ObjString* candidate = AS_STRING(args[1]);
char* end;
double number = strtod(candidate->value, &end);
// Invalid number literal.
// TODO: Check errno == ERANGE here.
if (end == candidate->value) RETURN_NULL;
RETURN_NUM(number);
}
DEF_NATIVE(num_negate)
{
RETURN_NUM(-AS_NUM(args[0]));
@@ -1447,6 +1463,7 @@ void wrenInitializeCore(WrenVM* vm)
NATIVE(vm->nullClass, "toString", null_toString);
vm->numClass = defineClass(vm, "Num");
NATIVE(vm->numClass->obj.classObj, "fromString ", num_fromString);
NATIVE(vm->numClass, "-", num_negate);
NATIVE(vm->numClass, "- ", num_minus);
NATIVE(vm->numClass, "+ ", num_plus);
@@ -1472,7 +1489,7 @@ void wrenInitializeCore(WrenVM* vm)
NATIVE(vm->numClass, "isNan", num_isNan);
NATIVE(vm->numClass, "sin", num_sin);
NATIVE(vm->numClass, "sqrt", num_sqrt);
NATIVE(vm->numClass, "toString", num_toString)
NATIVE(vm->numClass, "toString", num_toString);
// These are defined just so that 0 and -0 are equal, which is specified by
// IEEE 754 even though they have different bit representations.