From 9ae8932c978ab9c12f683745b47b3e0898581635 Mon Sep 17 00:00:00 2001 From: Adam Chlipala Date: Sun, 7 Sep 2008 11:41:04 -0400 Subject: Parsing strings for floats and bools --- include/urweb.h | 2 ++ lib/basis.urs | 2 ++ src/c/urweb.c | 24 ++++++++++++++++++++++++ tests/fromString.ur | 24 ++++++++++++++++++++---- 4 files changed, 48 insertions(+), 4 deletions(-) diff --git a/include/urweb.h b/include/urweb.h index 84cc6719..83039520 100644 --- a/include/urweb.h +++ b/include/urweb.h @@ -79,3 +79,5 @@ lw_Basis_string lw_Basis_floatToString(lw_context, lw_Basis_float); lw_Basis_string lw_Basis_boolToString(lw_context, lw_Basis_bool); lw_Basis_int *lw_Basis_stringToInt(lw_context, lw_Basis_string); +lw_Basis_float *lw_Basis_stringToFloat(lw_context, lw_Basis_string); +lw_Basis_bool *lw_Basis_stringToBool(lw_context, lw_Basis_string); diff --git a/lib/basis.urs b/lib/basis.urs index e6072690..4275e195 100644 --- a/lib/basis.urs +++ b/lib/basis.urs @@ -31,6 +31,8 @@ val show_string : show string val show_bool : show bool val stringToInt : string -> option int +val stringToFloat : string -> option float +val stringToBool : string -> option bool (** SQL *) diff --git a/src/c/urweb.c b/src/c/urweb.c index dce33bf1..bf697340 100644 --- a/src/c/urweb.c +++ b/src/c/urweb.c @@ -769,3 +769,27 @@ lw_Basis_int *lw_Basis_stringToInt(lw_context ctx, lw_Basis_string s) { } else return NULL; } + +lw_Basis_float *lw_Basis_stringToFloat(lw_context ctx, lw_Basis_string s) { + char *endptr; + lw_Basis_float n = strtod(s, &endptr); + + if (*s != '\0' && *endptr == '\0') { + lw_Basis_float *r = lw_malloc(ctx, sizeof(lw_Basis_float)); + *r = n; + return r; + } else + return NULL; +} + +lw_Basis_bool *lw_Basis_stringToBool(lw_context ctx, lw_Basis_string s) { + static lw_Basis_bool true = lw_Basis_True; + static lw_Basis_bool false = lw_Basis_False; + + if (!strcasecmp (s, "True")) + return &true; + else if (!strcasecmp (s, "False")) + return &false; + else + return NULL; +} diff --git a/tests/fromString.ur b/tests/fromString.ur index d9a087e4..673503ae 100644 --- a/tests/fromString.ur +++ b/tests/fromString.ur @@ -1,10 +1,26 @@ -fun i2s s = +fun s2i s = case stringToInt s of None => 0 | Some n => n +fun s2f s = + case stringToFloat s of + None => 0.0 + | Some n => n + +fun s2b s = + case stringToBool s of + None => False + | Some b => b + fun main () : transaction page = return - Error = {cdata (show _ (i2s "Error"))}
- 3 = {cdata (show _ (i2s "+3"))}
+ Error = {cdata (show _ (s2i "Error"))}
+ 3 = {cdata (show _ (s2i "+3"))}
+
+ Error = {cdata (show _ (s2f "Error"))}
+ 98.76 = {cdata (show _ (s2f "98.76"))}
+
+ Error = {cdata (show _ (s2b "Error"))}
+ False = {cdata (show _ (s2b "false"))}
+ True = {cdata (show _ (s2b "trUE"))}
- -- cgit v1.2.3