summaryrefslogtreecommitdiff
path: root/lib/strarg.c
blob: 99635012958cbb36c8a6be18826527b1047daa7c (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
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdlib.h>
#include <error.h>
#include <errno.h>
#include <string.h>
#include "str.h"

char **strarg_new(unsigned int *num)
{
	char **sa = malloc(sizeof(char *));
	if (!sa)
		error(2, errno, "%s", __FUNCTION__);

	*num = 0;
	*sa = NULL;

	return sa;
}

void strarg_free(char **strarg, unsigned int num)
{
	int n;

	if (!strarg)
		goto out;

	for (n = 0; n < num; n++)
		d_string_free(strarg[n]);

	free(strarg);
out:
	strarg = NULL;
}

char **strarg_add(char **strarg, unsigned int *num, const char *s)
{
	if (!strarg)
		strarg = strarg_new(num);

	strarg = realloc(strarg, (*num + 2) * sizeof(char *));
	if (!strarg)
		error(2, errno, "%s", __FUNCTION__);

	strarg[(*num)++] = d_string_new(s);
	strarg[*num] = NULL;

	return strarg;
}

/* Find if a given string exists in the strarg array. Returns 1 for true
 * and 0 for false. */
int strarg_exists(char **strarg, unsigned int num, const char *s)
{
	int n, found = 0;

	if(!strarg)
		goto out;

	for (n = 0; n < num; n++) {
		if (strcmp(s, strarg[n]) == 0) {
			found = 1;
			break;
		}
	}

out:
	return found;
}