blob: 7b41fd08c921e1683d4e2f252d254e989bddb7bd [file] [log] [blame]
Rob Landley7aa651a2012-11-13 17:14:08 -06001/* llist.c - Linked list functions
Rob Landley15bdc112006-11-01 22:28:46 -05002 *
3 * Linked list structures have a next pointer as their first element.
4 */
5
6#include "toys.h"
7
Rob Landley9e2b6db2012-07-15 17:22:04 -05008// Call a function (such as free()) on each element of a linked list.
9void llist_traverse(void *list, void (*using)(void *data))
Rob Landley15bdc112006-11-01 22:28:46 -050010{
Rob Landleyfe91e682012-11-22 21:18:09 -060011 void *old = list;
12
Rob Landley7aa651a2012-11-13 17:14:08 -060013 while (list) {
14 void *pop = llist_pop(&list);
15 using(pop);
Rob Landleybdf037f2008-10-23 16:44:30 -050016
Rob Landley7aa651a2012-11-13 17:14:08 -060017 // End doubly linked list too.
Rob Landleyfe91e682012-11-22 21:18:09 -060018 if (old == list) break;
Rob Landley7aa651a2012-11-13 17:14:08 -060019 }
Rob Landley15bdc112006-11-01 22:28:46 -050020}
Rob Landley0a04b3e2006-11-03 00:05:52 -050021
22// Return the first item from the list, advancing the list (which must be called
23// as &list)
24void *llist_pop(void *list)
25{
Rob Landley7aa651a2012-11-13 17:14:08 -060026 // I'd use a void ** for the argument, and even accept the typecast in all
27 // callers as documentation you need the &, except the stupid compiler
28 // would then scream about type-punned pointers. Screw it.
29 void **llist = (void **)list;
30 void **next = (void **)*llist;
31 *llist = *next;
Rob Landley0a04b3e2006-11-03 00:05:52 -050032
Rob Landley7aa651a2012-11-13 17:14:08 -060033 return (void *)next;
Rob Landley0a04b3e2006-11-03 00:05:52 -050034}
Rob Landley6ef04ef2008-01-20 17:34:53 -060035
Rob Landley2c482472012-03-12 00:25:40 -050036void dlist_add_nomalloc(struct double_list **list, struct double_list *new)
37{
Rob Landley7aa651a2012-11-13 17:14:08 -060038 if (*list) {
39 new->next = *list;
40 new->prev = (*list)->prev;
41 (*list)->prev->next = new;
42 (*list)->prev = new;
43 } else *list = new->next = new->prev = new;
Rob Landley2c482472012-03-12 00:25:40 -050044}
45
46
Rob Landley53c75042010-01-05 10:43:36 -060047// Add an entry to the end of a doubly linked list
Rob Landleybdf037f2008-10-23 16:44:30 -050048struct double_list *dlist_add(struct double_list **list, char *data)
Rob Landley6ef04ef2008-01-20 17:34:53 -060049{
Rob Landley7aa651a2012-11-13 17:14:08 -060050 struct double_list *new = xmalloc(sizeof(struct double_list));
Rob Landley6ef04ef2008-01-20 17:34:53 -060051
Rob Landley7aa651a2012-11-13 17:14:08 -060052 new->data = data;
53 dlist_add_nomalloc(list, new);
Rob Landleybdf037f2008-10-23 16:44:30 -050054
Rob Landley7aa651a2012-11-13 17:14:08 -060055 return new;
Rob Landley6ef04ef2008-01-20 17:34:53 -060056}