]> mj.ucw.cz Git - libucw.git/blobdiff - ucw/xtypes-basic.c
xtypes: added first shot on unit parser
[libucw.git] / ucw / xtypes-basic.c
index 2d365078ecdbdb904eefe3cc96678fe9a6589f8d..2792cd19109dd32aca0f785d81d0d4d2ba663908 100644 (file)
@@ -55,12 +55,12 @@ static const char *xt_double_format(void *src, u32 fmt, struct mempool *pool)
 
   switch(fmt) {
   case XTYPE_FMT_RAW:
-    return mp_printf(pool, "%.10lf", *(double *)src);
+    return mp_printf(pool, "%.15lg", *(double *)src);
   case XTYPE_FMT_PRETTY:
     return mp_printf(pool, "%.2lf", *(double *)src);
   case XTYPE_FMT_DEFAULT:
   default:
-    return mp_printf(pool, "%.5lf", *(double *)src);
+    return mp_printf(pool, "%.6lg", *(double *)src);
   }
 }
 
@@ -69,24 +69,43 @@ static const char *xt_double_parse(const char *str, void *dest, struct mempool *
   char *endptr = NULL;
   errno = 0;
   double result = strtod(str, &endptr);
-  if(*endptr != 0 || endptr == str) return "Could not parse double.";
-  if(errno == ERANGE) return "Could not parse double.";
+  if(*endptr != 0 || endptr == str) return "Could not parse floating point number.";
+  if(errno == ERANGE) return "Could not parse floating point number.";
 
   *((double *) dest) = result;
 
   return NULL;
 }
 
-XTYPE_NUM_STRUCT(double, double)
+static const char * xt_double_fmt_parse(const char *str, u32 *dest, struct mempool *pool)
+{
+  uint precision = 0;
+  const char *tmp_err = str_to_uint(&precision, str, NULL, 0);
+  if(tmp_err) {
+    return mp_printf(pool, "An error occured while parsing precision: %s.", tmp_err);
+  }
+
+  *dest = XTYPE_FMT_DBL_FIXED_PREC(precision);
+
+  return NULL;
+}
+
+const struct xtype xt_double = {
+  .size = sizeof(double),
+  .name = "double",
+  .parse = xt_double_parse,
+  .format = xt_double_format,
+  .parse_fmt = xt_double_fmt_parse
+};
 
 /* bool */
 
 static const char *xt_bool_format(void *src, u32 fmt UNUSED, struct mempool *pool)
 {
   switch(fmt) {
-    case XTYPE_FMT_DEFAULT:
     case XTYPE_FMT_PRETTY:
       return mp_printf(pool, "%s", *((bool *)src) ? "true" : "false");
+    case XTYPE_FMT_DEFAULT:
     case XTYPE_FMT_RAW:
       return mp_printf(pool, "%s", *((bool *)src) ? "1" : "0");
     default:
@@ -99,7 +118,7 @@ static const char *xt_bool_parse(const char *str, void *dest, struct mempool *po
   if(!str) return "Cannot parse bool: string is NULL.";
 
   if(str[1] == 0) {
-    if(str[0] == '1') {
+    if(str[0] == '0') {
       *((bool *)dest) = false;
       return NULL;
     }