2 * Copyright (C) 2012-2015 Thadeu Lima de Souza Cascardo <cascardo@minaslivre.org>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
33 struct list * list_new(void)
37 list = malloc(sizeof(*list) + alen * sizeof(struct item));
42 memset(list->items, 0, alen * sizeof(struct item));
46 static struct list * list_expand(struct list **list)
48 struct list *l = *list;
50 size_t len = l->alen * sizeof(struct item);
51 size_t nlen = len * 2;
52 nlist = realloc(l, sizeof(*nlist) + nlen);
56 memset(&l->items[l->len], 0, len);
57 l->alen = l->alen * 2;
63 int list_add(struct list **list, void *val)
66 struct list *l = *list;
67 l->items[l->len].val = val;
69 if (l->len == l->alen) {
70 l = list_expand(list);
76 l->items[l->len].val = NULL;
80 int list_insert(struct list **list, int pos, void *val)
82 struct list *l = *list;
85 if (l->len + 1 == l->alen) {
86 l = list_expand(list);
91 memmove(&l->items[pos + 1], &l->items[pos],
92 (l->len - pos) * sizeof(struct item));
93 l->items[pos].val = val;
100 int list_insert_ordered(struct list **list, void *val, sort_function_t *fn)
102 struct list *l = *list;
104 for (i = 0; i < l->len; i++)
105 if (fn(l->items[i].val, val) >= 0)
106 return list_insert(list, i, val);
107 return list_add(list, val);
110 void * list_get(struct list *list, int pos)
113 if (pos >= list->len)
115 return list->items[pos].val;
118 void list_free(struct list *list, free_function_t *ifree)
122 for (i = 0; i < list->len; i++)
123 ifree(list->items[i].val);