summaryrefslogtreecommitdiff
path: root/sapi/fpm/fpm/fpm_arrays.h
blob: 82c7cbc09e1e0da8a03cdb1766b03f9c66262b1e (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
102
103
104
105
106
107
108
109
110
111
112
113
114
	/* (c) 2007,2008 Andrei Nigmatulin */

#ifndef FPM_ARRAYS_H
#define FPM_ARRAYS_H 1

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

struct fpm_array_s {
	void *data;
	size_t sz;
	size_t used;
	size_t allocated;
};

static inline struct fpm_array_s *fpm_array_init(struct fpm_array_s *a, unsigned int sz, unsigned int initial_num) /* {{{ */
{
	void *allocated = 0;

	if (!a) {
		a = malloc(sizeof(struct fpm_array_s));

		if (!a) {
			return 0;
		}

		allocated = a;
	}

	a->sz = sz;

	a->data = calloc(sz, initial_num);

	if (!a->data) {
		free(allocated);
		return 0;
	}

	a->allocated = initial_num;
	a->used = 0;

	return a;
}
/* }}} */

static inline void *fpm_array_item(struct fpm_array_s *a, unsigned int n) /* {{{ */
{
	char *ret;

	ret = (char *) a->data + a->sz * n;

	return ret;
}
/* }}} */

static inline void *fpm_array_item_last(struct fpm_array_s *a) /* {{{ */
{
	return fpm_array_item(a, a->used - 1);
}
/* }}} */

static inline int fpm_array_item_remove(struct fpm_array_s *a, unsigned int n) /* {{{ */
{
	int ret = -1;

	if (n < a->used - 1) {
		void *last = fpm_array_item(a, a->used - 1);
		void *to_remove = fpm_array_item(a, n);

		memcpy(to_remove, last, a->sz);

		ret = n;
	}

	--a->used;

	return ret;
}
/* }}} */

static inline void *fpm_array_push(struct fpm_array_s *a) /* {{{ */
{
	void *ret;

	if (a->used == a->allocated) {
		size_t new_allocated = a->allocated ? a->allocated * 2 : 20;
		void *new_ptr = realloc(a->data, a->sz * new_allocated);

		if (!new_ptr) {
			return 0;
		}

		a->data = new_ptr;
		a->allocated = new_allocated;
	}

	ret = fpm_array_item(a, a->used);

	++a->used;

	return ret;
}
/* }}} */

static inline void fpm_array_free(struct fpm_array_s *a) /* {{{ */
{
	free(a->data);
	a->data = 0;
	a->sz = 0;
	a->used = a->allocated = 0;
}
/* }}} */

#endif