diff libutil/shorthand.c @ 160:b86b3f8890ba

libutil: shorthand decimal string parsing implemented
author Mychaela Falconia <falcon@freecalypso.org>
date Fri, 26 Feb 2021 21:04:11 +0000
parents libutil/decimal_str.c@2557012666ea
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libutil/shorthand.c	Fri Feb 26 21:04:11 2021 +0000
@@ -0,0 +1,64 @@
+/*
+ * This module implements the function for parsing shorthand decimal strings.
+ */
+
+#include <sys/types.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <string.h>
+#include <strings.h>
+
+parse_decimal_shorthand(arg, dest, maxdigits)
+	char *arg;
+	u_char *dest;
+	unsigned maxdigits;
+{
+	unsigned n, ntail;
+
+	if (!*arg) {
+		fprintf(stderr,
+			"error: empty argument given for decimal string\n");
+		return(-1);
+	}
+	if (!isdigit(*arg)) {
+		fprintf(stderr,
+		"error: decimal string argument begins with a non-digit\n");
+		return(-1);
+	}
+	for (n = 0; isdigit(*arg); ) {
+		if (n >= maxdigits) {
+toolong:		fprintf(stderr,
+			"error: decimal string exceeds limit of %u digits\n",
+				maxdigits);
+			return(-1);
+		}
+		dest[n++] = *arg++ - '0';
+	}
+	if (!*arg) {
+		if (n != maxdigits) {
+			fprintf(stderr,
+				"error: %u digits required, %u digits given\n",
+				maxdigits, n);
+			return(-1);
+		}
+		return(0);
+	}
+	if (*arg++ != '-') {
+malformed:	fprintf(stderr,
+			"error: malformed shorthand decimal string argument\n");
+		return(-1);
+	}
+	ntail = strlen(arg);
+	if (n + ntail >= maxdigits)
+		goto toolong;
+	while (n < maxdigits - ntail)
+		dest[n++] = 0;
+	if (!isdigit(*arg))
+		goto malformed;
+	while (*arg) {
+		if (!isdigit(*arg))
+			goto malformed;
+		dest[n++] = *arg++ - '0';
+	}
+	return(0);
+}