Haka
vector.h
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 #ifndef HAKA_CONTAINER_VECTOR_H
6 #define HAKA_CONTAINER_VECTOR_H
7 
8 #include <haka/compiler.h>
9 #include <haka/types.h>
10 #include <stddef.h>
11 
12 
13 struct vector {
14  size_t element_size;
15  size_t count;
16  size_t allocated_count;
17  void *data;
18  void (*destruct)(void *elem);
19 };
20 
21 #define VECTOR_INIT(type, destruct) {sizeof(type), 0, 0, NULL, destruct}
22 
23 #define vector_create(v, type, destruct) _vector_create((v), sizeof(type), 0, (destruct))
24 #define vector_create_reserve(v, type, count, destruct) _vector_create((v), sizeof(type), (count), (destruct))
25 #define vector_getvalue(v, type, index) (*(type*)_vector_get((v), sizeof(type), (index)))
26 #define vector_get(v, type, index) ((type*)_vector_get((v), sizeof(type), (index)))
27 #define vector_set(v, type, index, value) (*(type*)_vector_get((v), sizeof(type), (index)) = (value))
28 #define vector_push(v, type) ((type*)_vector_push((v), sizeof(type)))
29 #define vector_last(v, type) ((type*)_vector_get((v), sizeof(type), vector_count(v)-))
30 #define vector_first(v, type) ((type*)_vector_get((v), sizeof(type), 0))
31 
32 INLINE size_t vector_count(struct vector *v) { return v->count; }
33 INLINE bool vector_isempty(struct vector *v) { return v->count == 0; }
34 void vector_destroy(struct vector *v);
35 void vector_pop(struct vector *v);
36 bool vector_resize(struct vector *v, size_t count);
37 bool vector_reserve(struct vector *v, size_t count);
38 void vector_swap(struct vector *a, struct vector *b);
39 
40 bool _vector_create(struct vector *v, size_t elemsize, size_t reservecount, void (*destruct)(void *elem));
41 void *_vector_get(struct vector *v, size_t elemsize, int index);
42 void *_vector_push(struct vector *v, size_t elemsize);
43 
44 #endif /* HAKA_CONTAINER_VECTOR_H */