summaryrefslogtreecommitdiffstats
path: root/src/vector.c
blob: c81e7ce8412c641f8544346f10348266fc7192b1 (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
/*
 * (C) 2006-2008 by Pablo Neira Ayuso <pablo@netfilter.org>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "vector.h"

#include <stdlib.h>
#include <string.h>

struct vector {
	char *data;
	unsigned int cur_elems;
	unsigned int max_elems;
	size_t size;
};

#define DEFAULT_VECTOR_MEMBERS	8
#define DEFAULT_VECTOR_GROWTH	8

struct vector *vector_create(size_t size)
{
	struct vector *v;

	v = calloc(sizeof(struct vector), 1);
	if (v == NULL)
		return NULL;

	v->size = size;
	v->cur_elems = 0;
	v->max_elems = DEFAULT_VECTOR_MEMBERS;

	v->data = calloc(size * DEFAULT_VECTOR_MEMBERS, 1);
	if (v->data == NULL) {
		free(v);
		return NULL;
	}

	return v;
}

void vector_destroy(struct vector *v)
{
	free(v->data);
	free(v);
}

int vector_add(struct vector *v, void *data)
{
	if (v->cur_elems >= v->max_elems) {
		v->max_elems += DEFAULT_VECTOR_GROWTH;
		v->data = realloc(v->data, v->max_elems * v->size);
		if (v->data == NULL) {
			v->max_elems -= DEFAULT_VECTOR_GROWTH;
			return -1;
		}
	}
	memcpy(v->data + (v->size * v->cur_elems), data, v->size);
	v->cur_elems++;
	return 0;
}

int vector_iterate(struct vector *v,
		   const void *data,
		   int (*fcn)(const void *a, const void *b))
{
	unsigned int i;

	for (i=0; i<v->cur_elems; i++) {
		char *ptr = v->data + (v->size * i);
		if (fcn(ptr, data))
			return 1;
	}
	return 0;
}