view libutil/numstring.c @ 194:05d01e810217

libutil: add TFO message gen function based on Osmocom crc8gen
author Mychaela Falconia <falcon@freecalypso.org>
date Fri, 17 Mar 2023 16:52:21 -0800
parents d712d518059e
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>

grok_number_string(str, allow_hyphen)
	char *str;
{
	char *cp;
	int c, n, last_hyphen;

	n = 0;
	last_hyphen = 0;
	for (cp = str; *cp; ) {
		c = *cp++;
		if (isdigit(c)) {
			n++;
			last_hyphen = 0;
		} else if (c == '-') {
			if (!allow_hyphen || !n || last_hyphen)
				return(-1);
			last_hyphen = 1;
		} else
			return(-1);
	}
	if (last_hyphen)
		return(-1);
	return n;
}

dehyphen_number_string(src, dest)
	char *src, *dest;
{
	char *cp, *dp;
	int c;

	dp = dest;
	for (cp = src; *cp; ) {
		c = *cp++;
		if (isdigit(c))
			*dp++ = c;
	}
	*dp = '\0';
}