-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.h
96 lines (88 loc) · 2.57 KB
/
vector.h
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
#include <stdlib.h>
#include <stddef.h>
#include <assert.h>
#define VECT_START_LENGTH 5
#define vector_init(type) ({ \
struct __vector_ { \
type *vect; \
size_t length; \
long max; \
}; \
struct __vector_ *t = malloc(sizeof(*t)); \
t->vect = malloc(sizeof(type) * VECT_START_LENGTH); \
t->length = VECT_START_LENGTH; \
t->max = -1; \
t; \
})
/* Let's use this hacky gnu99 extension to return a value from the macro!
* Unfortunately, I didn't find a way to do it without the container..
*/
#define vector_get(vec, pos, container) ({ \
assert(vec && \
"vector might no be NULL pointer"); \
struct __vector_{ \
typeof(container) *vect; \
size_t length; \
size_t max; \
}; \
struct __vector_ *__tmp = (void *)vec; \
container = __tmp->vect[pos]; \
})
//#define vector_set(vec, pos, val) do { \
// assert(vec && \
// "vector might no be NULL pointer"); \
// struct __vector_ { \
// typeof(val) *vect; \
// size_t length; \
// size_t max; \
// }; \
// struct __vector_ *__tmp = (void *)vec; \
// if (__tmp->max >= __tmp->length - 1) { \
// __tmp->length *= 2; \
// __tmp->vect = realloc(__tmp->vect, \
// sizeof(*__tmp->vect) * __tmp->length);\
// } \
// if (pos > __tmp->max) \
// __tmp->max = pos; \
// \
// __tmp->vect[pos] = val; \
//} while(0)
#define vector_append(vec, val) do { \
assert(vec && \
"vector might no be NULL pointer"); \
struct __vector__ { \
typeof(val) *vect; \
size_t length; \
size_t max; \
}; \
struct __vector__ *__tmp = (void *)vec; \
if (__tmp->max >= __tmp->length - 1) { \
__tmp->length *= 2; \
__tmp->vect = realloc(__tmp->vect, \
sizeof(*__tmp->vect) * __tmp->length);\
} \
__tmp->max++; \
__tmp->vect[__tmp->max] = val; \
} while (0)
static inline void vector_destroy(void *vec)
{
assert(vec && "vector might no be NULL pointer");
struct __vector_ {
void *vect;
size_t length;
size_t max;
};
struct __vector_ *__tmp = (void *)vec;
free(__tmp->vect);
free(__tmp);
}
static inline size_t vector_size(void *vec)
{
struct __vector__ {
void *vect;
size_t length;
size_t max;
};
struct __vector__ *tmp = vec;
return tmp->max + 1;
}