1 /* $Id: fpm_arrays.h,v 1.2 2008/05/24 17:38:47 anight Exp $ */
2 /* (c) 2007,2008 Andrei Nigmatulin */
3
4 #ifndef FPM_ARRAYS_H
5 #define FPM_ARRAYS_H 1
6
7 #include <stdlib.h>
8 #include <string.h>
9
10 struct fpm_array_s {
11 void *data;
12 size_t sz;
13 size_t used;
14 size_t allocated;
15 };
16
fpm_array_init(struct fpm_array_s * a,unsigned int sz,unsigned int initial_num)17 static inline struct fpm_array_s *fpm_array_init(struct fpm_array_s *a, unsigned int sz, unsigned int initial_num) /* {{{ */
18 {
19 void *allocated = 0;
20
21 if (!a) {
22 a = malloc(sizeof(struct fpm_array_s));
23
24 if (!a) {
25 return 0;
26 }
27
28 allocated = a;
29 }
30
31 a->sz = sz;
32
33 a->data = calloc(sz, initial_num);
34
35 if (!a->data) {
36 free(allocated);
37 return 0;
38 }
39
40 a->allocated = initial_num;
41 a->used = 0;
42
43 return a;
44 }
45 /* }}} */
46
fpm_array_item(struct fpm_array_s * a,unsigned int n)47 static inline void *fpm_array_item(struct fpm_array_s *a, unsigned int n) /* {{{ */
48 {
49 char *ret;
50
51 ret = (char *) a->data + a->sz * n;
52
53 return ret;
54 }
55 /* }}} */
56
fpm_array_item_last(struct fpm_array_s * a)57 static inline void *fpm_array_item_last(struct fpm_array_s *a) /* {{{ */
58 {
59 return fpm_array_item(a, a->used - 1);
60 }
61 /* }}} */
62
fpm_array_item_remove(struct fpm_array_s * a,unsigned int n)63 static inline int fpm_array_item_remove(struct fpm_array_s *a, unsigned int n) /* {{{ */
64 {
65 int ret = -1;
66
67 if (n < a->used - 1) {
68 void *last = fpm_array_item(a, a->used - 1);
69 void *to_remove = fpm_array_item(a, n);
70
71 memcpy(to_remove, last, a->sz);
72
73 ret = n;
74 }
75
76 --a->used;
77
78 return ret;
79 }
80 /* }}} */
81
fpm_array_push(struct fpm_array_s * a)82 static inline void *fpm_array_push(struct fpm_array_s *a) /* {{{ */
83 {
84 void *ret;
85
86 if (a->used == a->allocated) {
87 size_t new_allocated = a->allocated ? a->allocated * 2 : 20;
88 void *new_ptr = realloc(a->data, a->sz * new_allocated);
89
90 if (!new_ptr) {
91 return 0;
92 }
93
94 a->data = new_ptr;
95 a->allocated = new_allocated;
96 }
97
98 ret = fpm_array_item(a, a->used);
99
100 ++a->used;
101
102 return ret;
103 }
104 /* }}} */
105
fpm_array_free(struct fpm_array_s * a)106 static inline void fpm_array_free(struct fpm_array_s *a) /* {{{ */
107 {
108 free(a->data);
109 a->data = 0;
110 a->sz = 0;
111 a->used = a->allocated = 0;
112 }
113 /* }}} */
114
115 #endif
116