X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~ianmdlvl/git?p=elogind.git;a=blobdiff_plain;f=util.c;h=4bec220f7a1dbfad1c1868d8228d973bb77863df;hp=3ef190fa2a172faad91439124f0cc10ca576c960;hb=a41e8209be729cd8de34d715135fe84920e8016c;hpb=6091827530d6dd43479d6709fb6e9f745c11e900;ds=inline diff --git a/util.c b/util.c index 3ef190fa2..4bec220f7 100644 --- a/util.c +++ b/util.c @@ -4,6 +4,7 @@ #include #include #include +#include #include "macro.h" #include "util.h" @@ -93,3 +94,73 @@ 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; +} + +/* What is interpreted as whitespace? */ +#define WHITESPACE " \t\n" + +/* Split a string into words. */ +char *split_spaces(const char *c, size_t *l, char **state) { + char *current; + + current = *state ? *state : (char*) c; + + if (!*current || *c == 0) + return NULL; + + current += strspn(current, WHITESPACE); + *l = strcspn(current, WHITESPACE); + *state = current+*l; + + return (char*) current; +}