view libnumutil/numstring.c @ 14:78319ed870dc

convert to new ThemWi configure and build system
author Mychaela Falconia <falcon@freecalypso.org>
date Tue, 21 May 2024 00:15:24 +0000
parents 159dd90eeafe
children
line wrap: on
line source

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