changeset 160:b86b3f8890ba

libutil: shorthand decimal string parsing implemented
author Mychaela Falconia <falcon@freecalypso.org>
date Fri, 26 Feb 2021 21:04:11 +0000
parents 2557012666ea
children 884b93362449
files libutil/Makefile libutil/shorthand.c
diffstat 2 files changed, 65 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/libutil/Makefile	Fri Feb 26 20:45:17 2021 +0000
+++ b/libutil/Makefile	Fri Feb 26 21:04:11 2021 +0000
@@ -3,7 +3,7 @@
 OBJS=	alpha_decode.o alpha_fromfile.o alpha_valid.o decimal_str.o \
 	filesearch.o gsm7_decode.o gsm7_encode.o gsm7_encode_table.o \
 	gsm7_unpack.o hexdigits.o hexread.o hexstr.o number_decode.o \
-	number_encode.o pinentry.o plmncodes.o revnibbles.o
+	number_encode.o pinentry.o plmncodes.o revnibbles.o shorthand.o
 LIB=	libutil.a
 
 all:	${LIB}
--- /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);
+}