-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerics.h
More file actions
89 lines (79 loc) · 2.03 KB
/
generics.h
File metadata and controls
89 lines (79 loc) · 2.03 KB
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
#ifndef GENERICS_H_
#define GENERICS_H_
#include <stdlib.h>
#define def_array(T) \
typedef struct { \
T* ptr; \
int max; \
} array_##T;
#define def_alloc_memory(T) \
array_##T* alloc_memory_##T(int len) { \
array_##T* obj = malloc(sizeof(array_##T)); \
if (obj != NULL) { \
obj->max = len; \
obj->ptr = malloc(len * sizeof(T)); \
} \
return obj; \
}
#define def_realloc_memory(T) \
int realloc_memory_##T(array_##T* obj, int len) { \
if (obj == NULL) { \
return 0; \
} else { \
if (obj->max == len) { \
return 1; \
} else { \
obj->ptr = (T*)realloc(obj->ptr, len * sizeof(T)); \
if (obj->ptr == NULL) { \
return 0; \
} else { \
obj->max = len; \
return 1; \
} \
} \
} \
}
#define def_get(T) \
T get_##T(array_##T* obj, int pos, int* status) { \
if (obj != NULL) { \
if (pos >= obj->max || pos < 0) { \
printf("get out of bound -> len:%i, pos:%i\n", obj->max, pos); \
*status = 0; \
return 0; \
} else { \
*status = 1; \
return obj->ptr[pos]; \
} \
} else { \
printf("your obj is NULL.\n"); \
*status = 0; \
return 0; \
} \
}
#define def_set(T) \
int set_##T(array_##T* obj, int pos, T value) { \
if (obj != NULL) { \
if (pos >= obj->max && pos < 0) { \
printf("set out of bound -> len:%i, pos:%i\n", obj->max, pos); \
return 0; \
} else { \
obj->ptr[pos] = value; \
return 1; \
} \
} else { \
printf("your obj is NULL.\n"); \
return 0; \
} \
}
#define def_free_array(T) \
void free_array_##T(array_##T* obj) { \
free(obj->ptr); \
}
#define def_all(T) \
def_array(T) \
def_alloc_memory(T) \
def_realloc_memory(T) \
def_get(T) \
def_set(T) \
def_free_array(T)
#endif