adding string->number

This commit is contained in:
JeffBezanson 2009-03-23 19:49:08 +00:00
parent 9023705d27
commit 8f93c9dfc6
3 changed files with 27 additions and 6 deletions

View File

@ -141,6 +141,7 @@ value_t compare(value_t a, value_t b); // -1, 0, or 1
value_t equal(value_t a, value_t b); // T or nil value_t equal(value_t a, value_t b); // T or nil
int equal_lispvalue(value_t a, value_t b); int equal_lispvalue(value_t a, value_t b);
uptrint_t hash_lispvalue(value_t a); uptrint_t hash_lispvalue(value_t a);
int isnumtok_base(char *tok, value_t *pval, int base);
/* safe casts */ /* safe casts */
cons_t *tocons(value_t v, char *fname); cons_t *tocons(value_t v, char *fname);

View File

@ -17,7 +17,7 @@ static int symchar(char c)
return (!isspace(c) && !strchr(special, c)); return (!isspace(c) && !strchr(special, c));
} }
static int isnumtok_base(char *tok, value_t *pval, int base) int isnumtok_base(char *tok, value_t *pval, int base)
{ {
char *end; char *end;
int64_t i64; int64_t i64;

View File

@ -290,6 +290,14 @@ value_t fl_string_dec(value_t *args, u_int32_t nargs)
return size_wrap(i); return size_wrap(i);
} }
static ulong get_radix_arg(value_t arg, char *fname)
{
ulong radix = toulong(arg, fname);
if (radix < 2 || radix > 36)
lerror(ArgError, "%s: invalid radix", fname);
return radix;
}
value_t fl_numbertostring(value_t *args, u_int32_t nargs) value_t fl_numbertostring(value_t *args, u_int32_t nargs)
{ {
if (nargs < 1 || nargs > 2) if (nargs < 1 || nargs > 2)
@ -306,11 +314,8 @@ value_t fl_numbertostring(value_t *args, u_int32_t nargs)
neg = 1; neg = 1;
} }
ulong radix = 10; ulong radix = 10;
if (nargs == 2) { if (nargs == 2)
radix = toulong(args[1], "number->string"); radix = get_radix_arg(args[1], "number->string");
if (radix < 2 || radix > 36)
lerror(ArgError, "number->string: invalid radix");
}
char buf[128]; char buf[128];
char *str = uint2str(buf, sizeof(buf), num, radix); char *str = uint2str(buf, sizeof(buf), num, radix);
if (neg && str > &buf[0]) if (neg && str > &buf[0])
@ -318,6 +323,20 @@ value_t fl_numbertostring(value_t *args, u_int32_t nargs)
return string_from_cstr(str); return string_from_cstr(str);
} }
value_t fl_stringtonumber(value_t *args, uint32_t nargs)
{
if (nargs < 1 || nargs > 2)
argcount("string->number", nargs, 2);
char *str = tostring(args[0], "string->number");
value_t n;
ulong radix = 0;
if (nargs == 2)
radix = get_radix_arg(args[1], "string->number");
if (!isnumtok_base(str, &n, (int)radix))
return FL_F;
return n;
}
static builtinspec_t stringfunc_info[] = { static builtinspec_t stringfunc_info[] = {
{ "string", fl_string }, { "string", fl_string },
{ "string?", fl_stringp }, { "string?", fl_stringp },
@ -333,6 +352,7 @@ static builtinspec_t stringfunc_info[] = {
{ "string.decode", fl_string_decode }, { "string.decode", fl_string_decode },
{ "number->string", fl_numbertostring }, { "number->string", fl_numbertostring },
{ "string->number", fl_stringtonumber },
{ NULL, NULL } { NULL, NULL }
}; };