diff options
author | David Härdeman <david@hardeman.nu> | 2020-06-05 14:09:18 +0200 |
---|---|---|
committer | David Härdeman <david@hardeman.nu> | 2020-06-05 14:09:18 +0200 |
commit | db66484c4300f5f0e857eff01d15fd3593002a79 (patch) | |
tree | a787b9f0da1243ae0391d5931ecb9cb0f29d3ee4 /utils.c |
Initial commit
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; +} + |