diff libnumutil/numstring.c @ 0:159dd90eeafe

beginning, libnumutil compiles
author Mychaela Falconia <falcon@freecalypso.org>
date Tue, 12 Dec 2023 23:52:50 +0000
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libnumutil/numstring.c	Tue Dec 12 23:52:50 2023 +0000
@@ -0,0 +1,52 @@
+/*
+ * Utility functions for number string initial parsing or preening.
+ * grok_number_string() checks whether or not a user-supplied string
+ * argument is fully numeric (with possibility of allowing hyphens),
+ * and returns the number of digits.  dehyphen_number_string() copies
+ * a possibly-hyphenated number string to a new buffer with all hyphens
+ * taken out.
+ */
+
+#include <ctype.h>
+
+#include <themwi/nanp/number_utils.h>
+
+int grok_number_string(const char *str, bool allow_hyphen)
+{
+	const char *cp;
+	int c, n;
+	bool last_hyphen;
+
+	n = 0;
+	last_hyphen = false;
+	for (cp = str; *cp; ) {
+		c = *cp++;
+		if (isdigit(c)) {
+			n++;
+			last_hyphen = false;
+		} else if (c == '-') {
+			if (!allow_hyphen || !n || last_hyphen)
+				return(-1);
+			last_hyphen = true;
+		} else
+			return(-1);
+	}
+	if (last_hyphen)
+		return(-1);
+	return n;
+}
+
+void dehyphen_number_string(const char *src, char *dest)
+{
+	const char *cp;
+	char *dp;
+	int c;
+
+	dp = dest;
+	for (cp = src; *cp; ) {
+		c = *cp++;
+		if (isdigit(c))
+			*dp++ = c;
+	}
+	*dp = '\0';
+}