chiark / gitweb /
util: add parsers for boolean and integers
authorLennart Poettering <lennart@poettering.net>
Wed, 18 Nov 2009 23:46:47 +0000 (00:46 +0100)
committerLennart Poettering <lennart@poettering.net>
Wed, 18 Nov 2009 23:46:47 +0000 (00:46 +0100)
util.c
util.h

diff --git a/util.c b/util.c
index 3ef190fa2a172faad91439124f0cc10ca576c960..bcb608480f7d54cc0dc6c80f0a36b392d0e21340 100644 (file)
--- a/util.c
+++ b/util.c
@@ -4,6 +4,7 @@
 #include <string.h>
 #include <unistd.h>
 #include <errno.h>
+#include <stdlib.h>
 
 #include "macro.h"
 #include "util.h"
@@ -93,3 +94,54 @@ int nointr_close(int fd) {
                         return r;
         }
 }
+
+int parse_boolean(const char *v) {
+        assert(v);
+
+        if (!strcmp(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
+                return 1;
+        else if (!strcmp(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
+                return 0;
+
+        return -EINVAL;
+}
+
+int safe_atou(const char *s, unsigned *ret_u) {
+        char *x = NULL;
+        unsigned l;
+
+        assert(s);
+        assert(ret_u);
+
+        errno = 0;
+        l = strtoul(s, &x, 0);
+
+        if (!x || *x || errno)
+                return errno ? -errno : -EINVAL;
+
+        if ((unsigned) l != l)
+                return -ERANGE;
+
+        *ret_u = (unsigned) l;
+        return 0;
+}
+
+int safe_atoi(const char *s, int *ret_i) {
+        char *x = NULL;
+        int l;
+
+        assert(s);
+        assert(ret_i);
+
+        errno = 0;
+        l = strtol(s, &x, 0);
+
+        if (!x || *x || errno)
+                return errno ? -errno : -EINVAL;
+
+        if ((int) l != l)
+                return -ERANGE;
+
+        *ret_i = (unsigned) l;
+        return 0;
+}
diff --git a/util.h b/util.h
index 5d9ef39e04ad2e510e49b59742f713ebe8e412e8..2df67b73df5af2934c5b6edcdf17e7772c43151f 100644 (file)
--- a/util.h
+++ b/util.h
@@ -46,4 +46,9 @@ bool startswith(const char *s, const char *prefix);
 
 int nointr_close(int fd);
 
+int parse_boolean(const char *v);
+
+int safe_atou(const char *s, unsigned *ret_u);
+int safe_atoi(const char *s, int *ret_i);
+
 #endif