view libutil/shorthand.c @ 44:0bc89d61fc59

top Makefile: add serial
author Mychaela Falconia <falcon@freecalypso.org>
date Sat, 20 Mar 2021 21:53:31 +0000
parents 34bbb0585cab
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);
}