diff options
Diffstat (limited to 'utils.c')
-rw-r--r-- | utils.c | 37 |
1 files changed, 37 insertions, 0 deletions
@@ -0,0 +1,37 @@ +#include <stdlib.h> +#include <errno.h> +#include <stdint.h> +#include <limits.h> + +int +strtou16_strict(const char *str, uint16_t *result) +{ + char *end; + long val; + + if (!str) + return -EINVAL; + + errno = 0; + val = strtol(str, &end, 10); + + if (errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) + return -EINVAL; + + if (errno != 0 && val == 0) + return -EINVAL; + + if (end == str) + return -EINVAL; + + if (*end != '\0') + return -EINVAL; + + if (val < 1 || val > UINT16_MAX) + return -EINVAL; + + if (result) + *result = val; + return 0; +} + |