xref: /freebsd/contrib/wpa/src/utils/list.h (revision 0b3105a37d7adcadcb720112fed4dc4e8040be99)
1 /*
2  * Doubly-linked list
3  * Copyright (c) 2009, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #ifndef LIST_H
10 #define LIST_H
11 
12 /**
13  * struct dl_list - Doubly-linked list
14  */
15 struct dl_list {
16 	struct dl_list *next;
17 	struct dl_list *prev;
18 };
19 
20 #define DL_LIST_HEAD_INIT(l) { &(l), &(l) }
21 
22 static inline void dl_list_init(struct dl_list *list)
23 {
24 	list->next = list;
25 	list->prev = list;
26 }
27 
28 static inline void dl_list_add(struct dl_list *list, struct dl_list *item)
29 {
30 	item->next = list->next;
31 	item->prev = list;
32 	list->next->prev = item;
33 	list->next = item;
34 }
35 
36 static inline void dl_list_add_tail(struct dl_list *list, struct dl_list *item)
37 {
38 	dl_list_add(list->prev, item);
39 }
40 
41 static inline void dl_list_del(struct dl_list *item)
42 {
43 	item->next->prev = item->prev;
44 	item->prev->next = item->next;
45 	item->next = NULL;
46 	item->prev = NULL;
47 }
48 
49 static inline int dl_list_empty(struct dl_list *list)
50 {
51 	return list->next == list;
52 }
53 
54 static inline unsigned int dl_list_len(struct dl_list *list)
55 {
56 	struct dl_list *item;
57 	int count = 0;
58 	for (item = list->next; item != list; item = item->next)
59 		count++;
60 	return count;
61 }
62 
63 #ifndef offsetof
64 #define offsetof(type, member) ((long) &((type *) 0)->member)
65 #endif
66 
67 #define dl_list_entry(item, type, member) \
68 	((type *) ((char *) item - offsetof(type, member)))
69 
70 #define dl_list_first(list, type, member) \
71 	(dl_list_empty((list)) ? NULL : \
72 	 dl_list_entry((list)->next, type, member))
73 
74 #define dl_list_last(list, type, member) \
75 	(dl_list_empty((list)) ? NULL : \
76 	 dl_list_entry((list)->prev, type, member))
77 
78 #define dl_list_for_each(item, list, type, member) \
79 	for (item = dl_list_entry((list)->next, type, member); \
80 	     &item->member != (list); \
81 	     item = dl_list_entry(item->member.next, type, member))
82 
83 #define dl_list_for_each_safe(item, n, list, type, member) \
84 	for (item = dl_list_entry((list)->next, type, member), \
85 		     n = dl_list_entry(item->member.next, type, member); \
86 	     &item->member != (list); \
87 	     item = n, n = dl_list_entry(n->member.next, type, member))
88 
89 #define dl_list_for_each_reverse(item, list, type, member) \
90 	for (item = dl_list_entry((list)->prev, type, member); \
91 	     &item->member != (list); \
92 	     item = dl_list_entry(item->member.prev, type, member))
93 
94 #define DEFINE_DL_LIST(name) \
95 	struct dl_list name = { &(name), &(name) }
96 
97 #endif /* LIST_H */
98