summaryrefslogtreecommitdiff
path: root/libwmii_hack/util.c
blob: 32988e48e7e5f83698a64914462475249faee153 (plain)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <ctype.h>
#include <stdio.h>
#include <string.h>

#define strbcmp(str, const) (strncmp((str), (const), sizeof(const)-1))	
static int
getbase(const char **s) {
	const char *p;

	p = *s;
	if(!strbcmp(p, "0x")) {
		*s += 2;
		return 16;
	}
	if(isdigit(p[0])) {
		if(p[1] == 'r') {
			*s += 2;
			return p[0] - '0';
		}
		if(isdigit(p[1]) && p[2] == 'r') {
			*s += 3;
			return 10*(p[0]-'0') + (p[1]-'0');
		}
	}
	if(p[0] == '0') {
		*s += 1;
		return 8;
	}
	return 10;
}

static int
getlong(const char *s, long *ret) {
	const char *end;
	char *rend;
	int base;

	end = s+strlen(s);
	base = getbase(&s);

	*ret = strtol(s, &rend, base);
	return (end == rend);
}

static uint
tokenize(char *res[], uint reslen, char *str, char delim) {
	char *s;
	uint i;

	i = 0;
	s = str;
	while(i < reslen && *s) {
		while(*s == delim)
			*(s++) = '\0';
		if(*s)
			res[i++] = s;
		while(*s && *s != delim)
			s++;
	}
	return i;
}

static char*
vsmprint(const char *fmt, va_list ap) {
	va_list al;
	char *buf = "";
	int n;

	va_copy(al, ap);
	n = vsnprintf(buf, 0, fmt, al);
	va_end(al);

	buf = malloc(++n);
	if(buf)
		vsnprintf(buf, n, fmt, ap);
	return buf;
}

static char*
smprint(const char *fmt, ...) {
	va_list ap;
	char *ret;

	va_start(ap, fmt);
	ret = vsmprint(fmt, ap);
	va_end(ap);
	return ret;
}

static char*
strdup(const char *s) {
	char *ret;
	int len;

	len = strlen(s)+1;
	ret = malloc(len);
	if(ret)
		memcpy(ret, s, len);
	return ret;
}