1 |
#include <stdlib.h> |
2 |
|
3 |
typedef void (*vector_init_function)(void *item); |
4 |
typedef void (*vector_destroy_function)(void *item); |
5 |
|
6 |
typedef struct { |
7 |
size_t item_size; |
8 |
int used_count; |
9 |
int alloc_count; |
10 |
int block_size; |
11 |
vector_init_function init_fn; |
12 |
vector_destroy_function destroy_fn; |
13 |
} vector_header; |
14 |
|
15 |
int statgrab_vector_resize(void **vector, vector_header *h, int count); |
16 |
|
17 |
/* Declare a vector. Specify the init/destroy functions as NULL if you don't |
18 |
* need them. The block size is how many items to allocate at once. */ |
19 |
#define VECTOR_DECLARE(name, item_type, block_size, init_fn, destroy_fn) \ |
20 |
item_type * name = NULL; \ |
21 |
vector_header name##_header = { \ |
22 |
sizeof(item_type), \ |
23 |
0, \ |
24 |
0, \ |
25 |
block_size, \ |
26 |
(vector_init_function) init_fn, \ |
27 |
(vector_destroy_function) destroy_fn \ |
28 |
} |
29 |
|
30 |
/* Return the current size of a vector. */ |
31 |
#define VECTOR_SIZE(name) \ |
32 |
name##_header.used_count |
33 |
|
34 |
/* Resize a vector. Returns 0 on success, -1 on out-of-memory. On |
35 |
* out-of-memory, the old contents of the vector will be destroyed and the old |
36 |
* vector will be freed. */ |
37 |
#define VECTOR_RESIZE(name, num_items) \ |
38 |
statgrab_vector_resize((void **) &name, &name##_header, num_items) |
39 |
|
40 |
/* Free a vector, destroying its contents. */ |
41 |
#define VECTOR_FREE(name) \ |
42 |
VECTOR_RESIZE(name, 0) |
43 |
|
44 |
|