summaryrefslogtreecommitdiffstats
path: root/mandoc.c
diff options
context:
space:
mode:
Diffstat (limited to 'mandoc.c')
-rw-r--r--mandoc.c34
1 files changed, 34 insertions, 0 deletions
diff --git a/mandoc.c b/mandoc.c
index 9f9f6918..08710780 100644
--- a/mandoc.c
+++ b/mandoc.c
@@ -23,6 +23,8 @@
#include <assert.h>
#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
@@ -686,3 +688,35 @@ mandoc_getcontrol(const char *cp, int *ppos)
*ppos = pos;
return(1);
}
+
+/*
+ * Convert a string to a long that may not be <0.
+ * If the string is invalid, or is less than 0, return -1.
+ */
+int
+mandoc_strntou(const char *p, size_t sz, int base)
+{
+ char buf[32];
+ char *ep;
+ long v;
+
+ if (sz > 31)
+ return(-1);
+
+ memcpy(buf, p, sz);
+ buf[sz] = '\0';
+
+ errno = 0;
+ v = strtol(buf, &ep, base);
+
+ if (buf[0] == '\0' || *ep != '\0')
+ return(-1);
+
+ if ((errno == ERANGE &&
+ (v == LONG_MAX || v == LONG_MIN)) ||
+ (v > INT_MAX || v < 0))
+ return(-1);
+
+ return((int)v);
+}
+