aboutsummaryrefslogtreecommitdiffstats
path: root/service/src/util.c
blob: ef29c92db7941925514e5aade07f42f69a87dc3c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "util.h"

int
is_numstr(const char *str)
{
	int i;

	if (!*str) return 0;

	for (i = 0; str[i]; i++) {
		if (str[i] < '0' || str[i] > '9')
			return 0;
	}

	return 1;
}

char*
randstr(int n)
{
	const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
		"abcdefghijklmnopqrstuvwxyz0123456789";
	char *msg;
	int i;

	srand(time(NULL));

	msg = malloc(n + 1);
	ASSERT(msg != NULL);

	for (i = 0; i < n; i++)
		msg[i] = alphabet[rand() % (ARRSIZE(alphabet)-1)];
	msg[n] = '\0';

	return msg;
}

void
assert(int res, const char *fmtstr, ...)
{
	va_list ap;

	if (!res) {
		va_start(ap, fmtstr);
		vfprintf(stderr, fmtstr, ap);
		va_end(ap);
		exit(1);
	}
}

char*
ask(const char *fmtstr, ...)
{
	static char buf[2048];
	va_list ap;
	char *tok;

	va_start(ap, fmtstr);
	vprintf(fmtstr, ap);
	va_end(ap);

	if (fgets(buf, ARRSIZE(buf), stdin)) {
		tok = strchr(buf, '\n');
		if (tok) *tok = '\0';
	} else {
		*buf = '\0';
	}

	return buf;
}