From db66484c4300f5f0e857eff01d15fd3593002a79 Mon Sep 17 00:00:00 2001 From: David Härdeman Date: Fri, 5 Jun 2020 14:09:18 +0200 Subject: Initial commit --- utils.c | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 utils.c (limited to 'utils.c') diff --git a/utils.c b/utils.c new file mode 100644 index 0000000..a84f63b --- /dev/null +++ b/utils.c @@ -0,0 +1,37 @@ +#include +#include +#include +#include + +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; +} + -- cgit v1.2.3