view libutil/shorthand.c @ 175:eb660497f888

scripts/grcard2-read-all added to collection
author Mychaela Falconia <falcon@freecalypso.org>
date Tue, 02 Mar 2021 04:46:21 +0000
parents b86b3f8890ba
children
line wrap: on
line source

/*
 * 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);
}