2547b47341ccbb29577dd7842420e0dec6b96ace
[profile/ivi/libxkbcommon.git] / src / darray.h
1 /*
2  * Copyright (C) 2011 Joseph Adams <joeyadams3.14159@gmail.com>
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files (the "Software"), to deal
6  * in the Software without restriction, including without limitation the rights
7  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8  * copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20  * THE SOFTWARE.
21  */
22
23 #ifndef CCAN_DARRAY_H
24 #define CCAN_DARRAY_H
25
26 #include <stdlib.h>
27 #include <string.h>
28 #include "config.h"
29
30 /*
31  * SYNOPSIS
32  *
33  * Life cycle of a darray (dynamically-allocated array):
34  *
35  *     darray(int) a = darray_new();
36  *     darray_free(a);
37  *
38  *     struct {darray(int) a;} foo;
39  *     darray_init(foo.a);
40  *     darray_free(foo.a);
41  *
42  *     const struct {
43  *         darray(int) a;
44  *      } foo = {
45  *         .a = darray_lit({1, 2, 3})
46  *      };
47  *
48  * Typedefs for darrays of common types:
49  *
50  *     darray_char, darray_schar, darray_uchar
51  *     darray_short, darray_int, darray_long
52  *     darray_ushort, darray_uint, darray_ulong
53  *
54  * Access:
55  *
56  *     T      darray_item(darray(T) arr, size_t index);
57  *     size_t darray_size(darray(T) arr);
58  *     size_t darray_alloc(darray(T) arr);
59  *     bool   darray_empty(darray(T) arr);
60  *
61  * Insertion (single item):
62  *
63  *     void   darray_append(darray(T) arr, T item);
64  *     void   darray_prepend(darray(T) arr, T item);
65  *     void   darray_push(darray(T) arr, T item); // same as darray_append
66  *
67  * Insertion (multiple items):
68  *
69  *     void   darray_append_items(darray(T) arr, T *items, size_t count);
70  *     void   darray_prepend_items(darray(T) arr, T *items, size_t count);
71  *
72  *     void   darray_appends(darray(T) arr, [T item, [...]]);
73  *     void   darray_prepends(darray(T) arr, [T item, [...]]);
74  *
75  *     // Same functionality as above, but does not require typeof.
76  *     void   darray_appends_t(darray(T) arr, #T, [T item, [...]]);
77  *     void   darray_prepends_t(darray(T) arr, #T, [T item, [...]]);
78  *
79  * Removal:
80  *
81  *     T      darray_pop(darray(T) arr | darray_size(arr) != 0);
82  *     T*     darray_pop_check(darray(T*) arr);
83  *
84  * Replacement:
85  *
86  *     void   darray_from_items(darray(T) arr, T *items, size_t count);
87  *     void   darray_from_c(darray(T) arr, T c_array[N]);
88  *
89  * String buffer:
90  *
91  *     void   darray_append_string(darray(char) arr, const char *str);
92  *     void   darray_append_lit(darray(char) arr, char stringLiteral[N+1]);
93  *
94  *     void   darray_prepend_string(darray(char) arr, const char *str);
95  *     void   darray_prepend_lit(darray(char) arr, char stringLiteral[N+1]);
96  *
97  *     void   darray_from_string(darray(T) arr, const char *str);
98  *     void   darray_from_lit(darray(char) arr, char stringLiteral[N+1]);
99  *
100  * Size management:
101  *
102  *     void   darray_resize(darray(T) arr, size_t newSize);
103  *     void   darray_resize0(darray(T) arr, size_t newSize);
104  *
105  *     void   darray_realloc(darray(T) arr, size_t newAlloc);
106  *     void   darray_growalloc(darray(T) arr, size_t newAlloc);
107  *
108  *     void   darray_make_room(darray(T) arr, size_t room);
109  *
110  * Traversal:
111  *
112  *     darray_foreach(T *&i, darray(T) arr) {...}
113  *     darray_foreach_reverse(T *&i, darray(T) arr) {...}
114  *
115  * Except for darray_foreach and darray_foreach_reverse,
116  * all macros evaluate their non-darray arguments only once.
117  */
118
119 /*** Life cycle ***/
120
121 #define darray(type) struct {type *item; size_t size; size_t alloc;}
122
123 #define darray_new() {0,0,0}
124 #define darray_lit(c_array) {(c_array), sizeof(c_array) / sizeof(*(c_array)), 0}
125 #define darray_init(arr) do {(arr).item=0; (arr).size=0; (arr).alloc=0;} while(0)
126 #define darray_free(arr) do {free((arr).item);} while(0)
127
128
129 /*
130  * Typedefs for darrays of common types.  These are useful
131  * when you want to pass a pointer to an darray(T) around.
132  *
133  * The following will produce an incompatible pointer warning:
134  *
135  *     void foo(darray(int) *arr);
136  *     darray(int) arr = darray_new();
137  *     foo(&arr);
138  *
139  * The workaround:
140  *
141  *     void foo(darray_int *arr);
142  *     darray_int arr = darray_new();
143  *     foo(&arr);
144  */
145
146 typedef darray(char)           darray_char;
147 typedef darray(signed char)    darray_schar;
148 typedef darray(unsigned char)  darray_uchar;
149
150 typedef darray(short)          darray_short;
151 typedef darray(int)            darray_int;
152 typedef darray(long)           darray_long;
153
154 typedef darray(unsigned short) darray_ushort;
155 typedef darray(unsigned int)   darray_uint;
156 typedef darray(unsigned long)  darray_ulong;
157
158
159 /*** Access ***/
160
161 #define darray_item(arr, i) ((arr).item[i])
162 #define darray_size(arr)    ((arr).size)
163 #define darray_alloc(arr)   ((arr).alloc)
164 #define darray_empty(arr)   ((arr).size == 0)
165
166
167 /*** Insertion (single item) ***/
168
169 #define darray_append(arr, ...) do { \
170                 darray_resize(arr, (arr).size+1); \
171                 (arr).item[(arr).size-1] = (__VA_ARGS__); \
172         } while(0)
173 #define darray_prepend(arr, ...) do { \
174                 darray_resize(arr, (arr).size+1); \
175                 memmove((arr).item+1, (arr).item, ((arr).size-1)*sizeof(*(arr).item)); \
176                 (arr).item[0] = (__VA_ARGS__); \
177         } while(0)
178 #define darray_push(arr, ...) darray_append(arr, __VA_ARGS__)
179
180
181 /*** Insertion (multiple items) ***/
182
183 #define darray_append_items(arr, items, count) do { \
184                 size_t __count = (count), __oldSize = (arr).size; \
185                 darray_resize(arr, __oldSize + __count); \
186                 memcpy((arr).item + __oldSize, items, __count * sizeof(*(arr).item)); \
187         } while(0)
188
189 #define darray_prepend_items(arr, items, count) do { \
190                 size_t __count = (count), __oldSize = (arr).size; \
191                 darray_resize(arr, __count + __oldSize); \
192                 memmove((arr).item + __count, (arr).item, __oldSize * sizeof(*(arr).item)); \
193                 memcpy((arr).item, items, __count * sizeof(*(arr).item)); \
194         } while(0)
195
196 #define darray_append_items_nullterminate(arr, items, count) do { \
197                 size_t __count = (count), __oldSize = (arr).size; \
198                 darray_resize(arr, __oldSize + __count + 1); \
199                 memcpy((arr).item + __oldSize, items, __count * sizeof(*(arr).item)); \
200                 (arr).item[--(arr).size] = 0; \
201         } while(0)
202
203 #define darray_prepend_items_nullterminate(arr, items, count) do { \
204                 size_t __count = (count), __oldSize = (arr).size; \
205                 darray_resize(arr, __count + __oldSize + 1); \
206                 memmove((arr).item + __count, (arr).item, __oldSize * sizeof(*(arr).item)); \
207                 memcpy((arr).item, items, __count * sizeof(*(arr).item)); \
208                 (arr).item[--(arr).size] = 0; \
209         } while(0)
210
211 #if HAVE_TYPEOF
212 #define darray_appends(arr, ...) darray_appends_t(arr, typeof((*(arr).item)), __VA_ARGS__)
213 #define darray_prepends(arr, ...) darray_prepends_t(arr, typeof((*(arr).item)), __VA_ARGS__)
214 #endif
215
216 #define darray_appends_t(arr, type, ...) do { \
217                 type __src[] = {__VA_ARGS__}; \
218                 darray_append_items(arr, __src, sizeof(__src)/sizeof(*__src)); \
219         } while(0)
220 #define darray_prepends_t(arr, type, ...) do { \
221                 type __src[] = {__VA_ARGS__}; \
222                 darray_prepend_items(arr, __src, sizeof(__src)/sizeof(*__src)); \
223         } while(0)
224
225
226 /*** Removal ***/
227
228 /* Warning: Do not call darray_pop on an empty darray. */
229 #define darray_pop(arr) ((arr).item[--(arr).size])
230 #define darray_pop_check(arr) ((arr).size ? darray_pop(arr) : NULL)
231
232
233 /*** Replacement ***/
234
235 #define darray_from_items(arr, items, count) do {size_t __count = (count); darray_resize(arr, __count); memcpy((arr).item, items, __count*sizeof(*(arr).item));} while(0)
236 #define darray_from_c(arr, c_array) darray_from_items(arr, c_array, sizeof(c_array)/sizeof(*(c_array)))
237
238
239 /*** String buffer ***/
240
241 #define darray_append_string(arr, str) do {const char *__str = (str); darray_append_items(arr, __str, strlen(__str)+1); (arr).size--;} while(0)
242 #define darray_append_lit(arr, stringLiteral) do {darray_append_items(arr, stringLiteral, sizeof(stringLiteral)); (arr).size--;} while(0)
243
244 #define darray_prepend_string(arr, str) do { \
245                 const char *__str = (str); \
246                 darray_prepend_items_nullterminate(arr, __str, strlen(__str)); \
247         } while(0)
248 #define darray_prepend_lit(arr, stringLiteral) \
249         darray_prepend_items_nullterminate(arr, stringLiteral, sizeof(stringLiteral) - 1)
250
251 #define darray_from_string(arr, str) do {const char *__str = (str); darray_from_items(arr, __str, strlen(__str)+1); (arr).size--;} while(0)
252 #define darray_from_lit(arr, stringLiteral) do {darray_from_items(arr, stringLiteral, sizeof(stringLiteral)); (arr).size--;} while(0)
253
254
255 /*** Size management ***/
256
257 #define darray_resize(arr, newSize) darray_growalloc(arr, (arr).size = (newSize))
258 #define darray_resize0(arr, newSize) do { \
259                 size_t __oldSize = (arr).size, __newSize = (newSize); \
260                 (arr).size = __newSize; \
261                 if (__newSize > __oldSize) { \
262                         darray_growalloc(arr, __newSize); \
263                         memset(&(arr).item[__oldSize], 0, (__newSize - __oldSize) * sizeof(*(arr).item)); \
264                 } \
265         } while(0)
266
267 #define darray_realloc(arr, newAlloc) do { \
268                 (arr).item = realloc((arr).item, ((arr).alloc = (newAlloc)) * sizeof(*(arr).item)); \
269         } while(0)
270 #define darray_growalloc(arr, need) do { \
271                 size_t __need = (need); \
272                 if (__need > (arr).alloc) \
273                         darray_realloc(arr, darray_next_alloc((arr).alloc, __need)); \
274         } while(0)
275
276 #if HAVE_STATEMENT_EXPR==1
277 #define darray_make_room(arr, room) ({size_t newAlloc = (arr).size+(room); if ((arr).alloc<newAlloc) darray_realloc(arr, newAlloc); (arr).item+(arr).size; })
278 #endif
279
280 static inline size_t darray_next_alloc(size_t alloc, size_t need)
281 {
282         if (alloc == 0)
283                 alloc = 4;
284         while (alloc < need)
285                 alloc *= 2;
286         return alloc;
287 }
288
289
290 /*** Traversal ***/
291
292 /*
293  * darray_foreach(T *&i, darray(T) arr) {...}
294  *
295  * Traverse a darray.  `i` must be declared in advance as a pointer to an item.
296  */
297 #define darray_foreach(i, arr) \
298         for ((i) = &(arr).item[0]; (i) < &(arr).item[(arr).size]; (i)++)
299
300 /*
301  * darray_foreach_reverse(T *&i, darray(T) arr) {...}
302  *
303  * Like darray_foreach, but traverse in reverse order.
304  */
305 #define darray_foreach_reverse(i, arr) \
306         for ((i) = &(arr).item[(arr).size]; (i)-- > &(arr).item[0]; )
307
308
309 #endif /* CCAN_DARRAY_H */
310
311 /*
312
313 darray_growalloc(arr, newAlloc) sees if the darray can currently hold newAlloc items;
314         if not, it increases the alloc to satisfy this requirement, allocating slack
315         space to avoid having to reallocate for every size increment.
316
317 darray_from_string(arr, str) copies a string to an darray_char.
318
319 darray_push(arr, item) pushes an item to the end of the darray.
320 darray_pop(arr) pops it back out.  Be sure there is at least one item in the darray before calling.
321 darray_pop_check(arr) does the same as darray_pop, but returns NULL if there are no more items left in the darray.
322
323 darray_make_room(arr, room) ensures there's 'room' elements of space after the end of the darray, and it returns a pointer to this space.
324 Currently requires HAVE_STATEMENT_EXPR, but I plan to remove this dependency by creating an inline function.
325
326 The following require HAVE_TYPEOF==1 :
327
328 darray_appends(arr, item0, item1...) appends a collection of comma-delimited items to the darray.
329 darray_prepends(arr, item0, item1...) prepends a collection of comma-delimited items to the darray.\
330
331
332 Examples:
333
334         darray(int)  arr;
335         int        *i;
336         
337         darray_appends(arr, 0,1,2,3,4);
338         darray_appends(arr, -5,-4,-3,-2,-1);
339         darray_foreach(i, arr)
340                 printf("%d ", *i);
341         printf("\n");
342         
343         darray_free(arr);
344         
345
346         typedef struct {int n,d;} Fraction;
347         darray(Fraction) fractions;
348         Fraction        *i;
349         
350         darray_appends(fractions, {3,4}, {3,5}, {2,1});
351         darray_foreach(i, fractions)
352                 printf("%d/%d\n", i->n, i->d);
353         
354         darray_free(fractions);
355 */