1 /* list.c -- doubly linked list routines for vlock,
2 * the VT locking program for linux
4 * This program is copyright (C) 2007 Frank Benkstein, and is free
5 * software which is freely distributable under the terms of the
6 * GNU General Public License version 2, included as the file COPYING in this
7 * distribution. It is NOT public domain software, and any
8 * redistribution not permitted by the GNU General Public License is
9 * expressly forbidden without prior written permission from
21 /* Create a new, empty list. */
22 struct list
*list_new(void)
24 struct list
*l
= ensure_malloc(sizeof *l
);
30 /* Create a (shallow) copy of the given list. */
31 struct list
*list_copy(struct list
*l
)
33 struct list
*new_list
= list_new();
35 list_for_each(l
, item
)
36 list_append(new_list
, item
->data
);
41 /* Deallocate the given list and all items. */
42 void list_free(struct list
*l
)
44 list_for_each_manual(l
, item
) {
45 struct list_item
*tmp
= item
->next
;
53 /* Calculate the number of items in the given list. */
54 size_t list_length(struct list
*l
)
58 list_for_each(l
, item
)
64 /* Create a new list item with the given data and add it to the end of the
66 void list_append(struct list
*l
, void *data
)
68 struct list_item
*item
= ensure_malloc(sizeof *item
);
71 item
->previous
= l
->last
;
83 /* Remove the given item from the list. Returns the item following the deleted
84 * one or NULL if the given item was the last. */
85 struct list_item
*list_delete_item(struct list
*l
, struct list_item
*item
)
87 struct list_item
*next
= item
->next
;
89 if (item
->previous
!= NULL
)
90 item
->previous
->next
= item
->next
;
92 if (item
->next
!= NULL
)
93 item
->next
->previous
= item
->previous
;
96 l
->first
= item
->next
;
99 l
->last
= item
->previous
;
106 /* Remove the first item with the given data. Does nothing if no item has this
108 void list_delete(struct list
*l
, void *data
)
110 struct list_item
*item
= list_find(l
, data
);
113 (void) list_delete_item(l
, item
);
116 /* Find the first item with the given data. Returns NULL if no item has this
118 struct list_item
*list_find(struct list
*l
, void *data
)
120 list_for_each(l
, item
)
121 if (item
->data
== data
)