diff options
Diffstat (limited to 'src/shared')
-rw-r--r-- | src/shared/util.c | 40 | ||||
-rw-r--r-- | src/shared/util.h | 3 |
2 files changed, 43 insertions, 0 deletions
diff --git a/src/shared/util.c b/src/shared/util.c index 2f4fa237dd..eeced4769a 100644 --- a/src/shared/util.c +++ b/src/shared/util.c @@ -363,6 +363,46 @@ int safe_atou8(const char *s, uint8_t *ret) { return 0; } +int safe_atou16(const char *s, uint16_t *ret) { + char *x = NULL; + unsigned long l; + + assert(s); + assert(ret); + + errno = 0; + l = strtoul(s, &x, 0); + + if (!x || x == s || *x || errno) + return errno > 0 ? -errno : -EINVAL; + + if ((unsigned long) (uint16_t) l != l) + return -ERANGE; + + *ret = (uint16_t) l; + return 0; +} + +int safe_atoi16(const char *s, int16_t *ret) { + char *x = NULL; + long l; + + assert(s); + assert(ret); + + errno = 0; + l = strtol(s, &x, 0); + + if (!x || x == s || *x || errno) + return errno > 0 ? -errno : -EINVAL; + + if ((long) (int16_t) l != l) + return -ERANGE; + + *ret = (int16_t) l; + return 0; +} + int safe_atollu(const char *s, long long unsigned *ret_llu) { char *x = NULL; unsigned long long l; diff --git a/src/shared/util.h b/src/shared/util.h index 04f2d8a564..835fee496d 100644 --- a/src/shared/util.h +++ b/src/shared/util.h @@ -245,6 +245,9 @@ static inline int safe_atoi64(const char *s, int64_t *ret_i) { return safe_atolli(s, (long long int*) ret_i); } +int safe_atou16(const char *s, uint16_t *ret); +int safe_atoi16(const char *s, int16_t *ret); + const char* split(const char **state, size_t *l, const char *separator, bool quoted); #define FOREACH_WORD(word, length, s, state) \ |