2 * array.h - useful array handling header
4 * Copyright © 2008 Pierre Habouzit <madcoder@debian.org>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #ifndef AWESOME_COMMON_ARRAY_H
23 #define AWESOME_COMMON_ARRAY_H
26 #include "common/util.h"
28 #define ARRAY_TYPE(type_t, pfx) \
29 typedef struct pfx##_array_t { \
34 #define ARRAY_FUNCS(type_t, pfx, dtor) \
35 static inline pfx##_array_t * pfx##_array_new(void) { \
36 return p_new(pfx##_array_t, 1); \
38 static inline void pfx##_array_init(pfx##_array_t *arr) { \
41 static inline void pfx##_array_wipe(pfx##_array_t *arr) { \
42 for (int i = 0; i < arr->len; i++) { \
45 p_delete(&arr->tab); \
47 static inline void pfx##_array_delete(pfx##_array_t **arrp) { \
49 pfx##_array_wipe(*arrp); \
54 static inline void pfx##_array_grow(pfx##_array_t *arr, int newlen) { \
55 p_grow(&arr->tab, newlen, &arr->size); \
58 pfx##_array_splice(pfx##_array_t *arr, int pos, int len, \
59 type_t items[], int count) \
61 assert (pos >= 0 && len >= 0 && count >= 0); \
62 assert (pos <= arr->len && pos + len <= arr->len); \
64 pfx##_array_grow(arr, arr->len + count - len); \
65 memmove(arr->tab + pos + count, arr->tab + pos + len, \
66 (arr->len - pos - len) * sizeof(*items)); \
67 arr->len += count - len; \
69 memcpy(arr->tab + pos, items, count * sizeof(*items)); \
71 static inline type_t pfx##_array_take(pfx##_array_t *arr, int pos) { \
72 type_t res = arr->tab[pos]; \
73 pfx##_array_splice(arr, pos, 1, NULL, 0); \
76 static inline void pfx##_array_append(pfx##_array_t *arr, type_t e) { \
77 pfx##_array_splice(arr, arr->len, 0, &e, 1); \
80 #define DO_ARRAY(type_t, pfx, dtor) \
81 ARRAY_TYPE(type_t, pfx) \
82 ARRAY_FUNCS(type_t, pfx, dtor)
85 // vim: filetype=c:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=80