# HG changeset patch # User Adam Chlipala # Date 1220802064 14400 # Node ID 0cc956a3216f95e11d702b22a815f6104203c300 # Parent 4260ad920c3668554cac093f6bc60e701c53caeb Parsing strings for floats and bools diff -r 4260ad920c36 -r 0cc956a3216f include/urweb.h --- a/include/urweb.h Sun Sep 07 11:33:13 2008 -0400 +++ b/include/urweb.h Sun Sep 07 11:41:04 2008 -0400 @@ -79,3 +79,5 @@ 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 -r 4260ad920c36 -r 0cc956a3216f lib/basis.urs --- a/lib/basis.urs Sun Sep 07 11:33:13 2008 -0400 +++ b/lib/basis.urs Sun Sep 07 11:41:04 2008 -0400 @@ -31,6 +31,8 @@ val show_bool : show bool val stringToInt : string -> option int +val stringToFloat : string -> option float +val stringToBool : string -> option bool (** SQL *) diff -r 4260ad920c36 -r 0cc956a3216f src/c/urweb.c --- a/src/c/urweb.c Sun Sep 07 11:33:13 2008 -0400 +++ b/src/c/urweb.c Sun Sep 07 11:41:04 2008 -0400 @@ -769,3 +769,27 @@ } 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 -r 4260ad920c36 -r 0cc956a3216f tests/fromString.ur --- a/tests/fromString.ur Sun Sep 07 11:33:13 2008 -0400 +++ b/tests/fromString.ur Sun Sep 07 11:41:04 2008 -0400 @@ -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"))}
-