From 8f93c9dfc67de6759f713809d7faa37c5cb7a30c Mon Sep 17 00:00:00 2001 From: JeffBezanson Date: Mon, 23 Mar 2009 19:49:08 +0000 Subject: [PATCH] adding string->number --- femtolisp/flisp.h | 1 + femtolisp/read.c | 2 +- femtolisp/string.c | 30 +++++++++++++++++++++++++----- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/femtolisp/flisp.h b/femtolisp/flisp.h index 19ccdd6..452f833 100644 --- a/femtolisp/flisp.h +++ b/femtolisp/flisp.h @@ -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 int equal_lispvalue(value_t a, value_t b); uptrint_t hash_lispvalue(value_t a); +int isnumtok_base(char *tok, value_t *pval, int base); /* safe casts */ cons_t *tocons(value_t v, char *fname); diff --git a/femtolisp/read.c b/femtolisp/read.c index d13f6e2..cfeed3c 100644 --- a/femtolisp/read.c +++ b/femtolisp/read.c @@ -17,7 +17,7 @@ static int symchar(char 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; int64_t i64; diff --git a/femtolisp/string.c b/femtolisp/string.c index 7f2edd1..2269c0f 100644 --- a/femtolisp/string.c +++ b/femtolisp/string.c @@ -290,6 +290,14 @@ value_t fl_string_dec(value_t *args, u_int32_t nargs) 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) { if (nargs < 1 || nargs > 2) @@ -306,11 +314,8 @@ value_t fl_numbertostring(value_t *args, u_int32_t nargs) neg = 1; } ulong radix = 10; - if (nargs == 2) { - radix = toulong(args[1], "number->string"); - if (radix < 2 || radix > 36) - lerror(ArgError, "number->string: invalid radix"); - } + if (nargs == 2) + radix = get_radix_arg(args[1], "number->string"); char buf[128]; char *str = uint2str(buf, sizeof(buf), num, radix); 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); } +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[] = { { "string", fl_string }, { "string?", fl_stringp }, @@ -333,6 +352,7 @@ static builtinspec_t stringfunc_info[] = { { "string.decode", fl_string_decode }, { "number->string", fl_numbertostring }, + { "string->number", fl_stringtonumber }, { NULL, NULL } };