diff options
Diffstat (limited to 'src/shared')
-rw-r--r-- | src/shared/util.c | 20 | ||||
-rw-r--r-- | src/shared/util.h | 2 |
2 files changed, 22 insertions, 0 deletions
diff --git a/src/shared/util.c b/src/shared/util.c index b1689e651f..d8a75bdc6a 100644 --- a/src/shared/util.c +++ b/src/shared/util.c @@ -332,6 +332,26 @@ int safe_atoi(const char *s, int *ret_i) { return 0; } +int safe_atou8(const char *s, uint8_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) (uint8_t) l != l) + return -ERANGE; + + *ret = (uint8_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 d9d525e8a5..81da59b20c 100644 --- a/src/shared/util.h +++ b/src/shared/util.h @@ -192,6 +192,8 @@ int safe_atolli(const char *s, long long int *ret_i); int safe_atod(const char *s, double *ret_d); +int safe_atou8(const char *s, uint8_t *ret); + #if __WORDSIZE == 32 static inline int safe_atolu(const char *s, unsigned long *ret_u) { assert_cc(sizeof(unsigned long) == sizeof(unsigned)); |