2 list.c -- functions to deal with double linked lists
3 Copyright (C) 2000-2005 Ivo Timmermans
4 2000-2006 Guus Sliepen <guus@tinc-vpn.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.
26 /* (De)constructors */
28 list_t *list_alloc(list_action_t delete) {
31 list = xmalloc_and_zero(sizeof(list_t));
32 list->delete = delete;
37 void list_free(list_t *list) {
41 list_node_t *list_alloc_node(void) {
42 return xmalloc_and_zero(sizeof(list_node_t));
45 void list_free_node(list_t *list, list_node_t *node) {
46 if(node->data && list->delete)
47 list->delete(node->data);
52 /* Insertion and deletion */
54 list_node_t *list_insert_head(list_t *list, void *data) {
57 node = list_alloc_node();
61 node->next = list->head;
65 node->next->prev = node;
74 list_node_t *list_insert_tail(list_t *list, void *data) {
77 node = list_alloc_node();
81 node->prev = list->tail;
85 node->prev->next = node;
94 list_node_t *list_insert_after(list_t *list, list_node_t *after, void *data) {
97 node = list_alloc_node();
100 node->next = after->next;
105 node->next->prev = node;
114 void list_unlink_node(list_t *list, list_node_t *node) {
116 node->prev->next = node->next;
118 list->head = node->next;
121 node->next->prev = node->prev;
123 list->tail = node->prev;
128 void list_delete_node(list_t *list, list_node_t *node) {
129 list_unlink_node(list, node);
130 list_free_node(list, node);
133 void list_delete_head(list_t *list) {
134 list_delete_node(list, list->head);
137 void list_delete_tail(list_t *list) {
138 list_delete_node(list, list->tail);
141 /* Head/tail lookup */
143 void *list_get_head(list_t *list) {
145 return list->head->data;
150 void *list_get_tail(list_t *list) {
152 return list->tail->data;
157 /* Fast list deletion */
159 void list_delete_list(list_t *list) {
160 list_node_t *node, *next;
162 for(node = list->head; node; node = next) {
164 list_free_node(list, node);
172 void list_foreach_node(list_t *list, list_action_node_t action) {
173 list_node_t *node, *next;
175 for(node = list->head; node; node = next) {
181 void list_foreach(list_t *list, list_action_t action) {
182 list_node_t *node, *next;
184 for(node = list->head; node; node = next) {