summaryrefslogtreecommitdiff
path: root/utils.c
diff options
context:
space:
mode:
authorDavid Härdeman <david@hardeman.nu>2020-06-05 14:09:18 +0200
committerDavid Härdeman <david@hardeman.nu>2020-06-05 14:09:18 +0200
commitdb66484c4300f5f0e857eff01d15fd3593002a79 (patch)
treea787b9f0da1243ae0391d5931ecb9cb0f29d3ee4 /utils.c
Initial commit
Diffstat (limited to 'utils.c')
-rw-r--r--utils.c37
1 files changed, 37 insertions, 0 deletions
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 <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;
+}
+