summaryrefslogtreecommitdiff
path: root/vector.c
blob: 8ff637cae7fd7bbd7da1a1cd27ad562ba6ce1908 (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
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>

#include "vector.h"

#define VECTOR_TOOBIG(alloc,elemsize,arrayoff)    ((SIZE_MAX - (arrayoff)) / (alloc) < (elemsize))
#define VECTOR_ALLOCSIZE(alloc,elemsize,arrayoff) ((arrayoff) + (alloc) * (elemsize))

void *vector_init(size_t alloc, size_t elemsize, size_t arrayoff)
{
	if (VECTOR_TOOBIG(alloc, elemsize, arrayoff)) return NULL;
	struct vector *v = malloc(VECTOR_ALLOCSIZE(alloc, elemsize, arrayoff));
	if (!v) return NULL;

	*v = (struct vector) {
		.alloc    = alloc,
		.elemsize = elemsize,
		.arrayoff = arrayoff,
	};
	return v;
}

void *vector_append(struct vector **vp)
{
	struct vector *v = *vp;
	if (v->count >= v->alloc) {
		size_t alloc = 2 * v->alloc;
		if (VECTOR_TOOBIG(alloc, v->elemsize, v->arrayoff)) return NULL;
		v = realloc(v, VECTOR_ALLOCSIZE(alloc, v->elemsize, v->arrayoff));
		if (!v) return NULL;
		v->alloc = alloc;
		*vp = v;
	}
	return (char*)v + v->arrayoff + v->count++ * v->elemsize;
}

void vector_sort(struct vector *v, int (*cmp)(const void *, const void *))
{
	qsort((char*)v + v->arrayoff, v->count, v->elemsize, cmp);
}

void *vector_search(struct vector *v, const void *key, int (*cmp)(const void *, const void *))
{
	return bsearch(key, (char*)v + v->arrayoff, v->count, v->elemsize, cmp);
}