about summary refs log tree commit diff
path: root/lib/util/nstring.c
diff options
context:
space:
mode:
Diffstat (limited to 'lib/util/nstring.c')
-rw-r--r--lib/util/nstring.c40
1 files changed, 40 insertions, 0 deletions
diff --git a/lib/util/nstring.c b/lib/util/nstring.c
index feb8215e..0fa78c7a 100644
--- a/lib/util/nstring.c
+++ b/lib/util/nstring.c
@@ -915,3 +915,43 @@ strishex(const char * const subject) {
 
     return retval;
 }
+
+
+
+void
+interpret_uint(const char *   const string,
+               unsigned int * const valueP,
+               const char **  const errorP) {
+
+    if (string[0] == '\0')
+        asprintfN(errorP, "Null string.");
+    else {
+        /* strtoul() does a bizarre thing where if the number is out
+           of range, it returns a clamped value but tells you about it
+           by setting errno = ERANGE.  If it is not out of range,
+           strtoul() leaves errno alone.
+        */
+        char * tail;
+        unsigned long ulongValue;
+        
+        errno = 0;  /* So we can tell if strtoul() overflowed */
+
+        ulongValue = strtoul(string, &tail, 10);
+
+        if (tail[0] != '\0')
+            asprintfN(errorP, "Non-digit stuff in string: %s", tail);
+        else if (errno == ERANGE)
+            asprintfN(errorP, "Number too large");
+        else if (ulongValue > UINT_MAX)
+            asprintfN(errorP, "Number too large");
+        else if (string[0] == '-')
+            asprintfN(errorP, "Negative number");
+            /* Sleazy code; string may have leading spaces. */
+        else {
+            *valueP = ulongValue;
+            *errorP = NULL;
+        }
+    }
+}
+
+