xref: /freebsd/contrib/pkgconf/libpkgconf/iter.h (revision 592efe252472a3385acf36b1f49ecf710a7f3d9c)
1 /*
2  * iter.h
3  * Linked lists and iterators.
4  *
5  * SPDX-License-Identifier: pkgconf
6  *
7  * Copyright (c) 2013 pkgconf authors (see AUTHORS).
8  *
9  * Permission to use, copy, modify, and/or distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * This software is provided 'as is' and without any warranty, express or
14  * implied.  In no event shall the authors be liable for any damages arising
15  * from the use of this software.
16  */
17 
18 #ifndef LIBPKGCONF_ITER_H
19 #define LIBPKGCONF_ITER_H
20 
21 #include <stddef.h>
22 
23 #ifdef __cplusplus
24 extern "C" {
25 #endif
26 
27 typedef struct pkgconf_node_ pkgconf_node_t;
28 
29 struct pkgconf_node_ {
30 	pkgconf_node_t *prev, *next;
31 	void *data;
32 };
33 
34 typedef struct {
35 	pkgconf_node_t *head, *tail;
36 	size_t length;
37 } pkgconf_list_t;
38 
39 #define PKGCONF_LIST_INITIALIZER		{ NULL, NULL, 0 }
40 
41 static inline void
pkgconf_list_zero(pkgconf_list_t * list)42 pkgconf_list_zero(pkgconf_list_t *list)
43 {
44 	list->head = NULL;
45 	list->tail = NULL;
46 	list->length = 0;
47 }
48 
49 static inline void
pkgconf_node_insert(pkgconf_node_t * node,void * data,pkgconf_list_t * list)50 pkgconf_node_insert(pkgconf_node_t *node, void *data, pkgconf_list_t *list)
51 {
52 	pkgconf_node_t *tnode;
53 
54 	node->data = data;
55 
56 	if (list->head == NULL)
57 	{
58 		list->head = node;
59 		list->tail = node;
60 		list->length = 1;
61 		return;
62 	}
63 
64 	tnode = list->head;
65 
66 	node->next = tnode;
67 	tnode->prev = node;
68 
69 	list->head = node;
70 	list->length++;
71 }
72 
73 static inline void
pkgconf_node_insert_tail(pkgconf_node_t * node,void * data,pkgconf_list_t * list)74 pkgconf_node_insert_tail(pkgconf_node_t *node, void *data, pkgconf_list_t *list)
75 {
76 	pkgconf_node_t *tnode;
77 
78 	node->data = data;
79 
80 	if (list->tail == NULL)
81 	{
82 		list->head = node;
83 		list->tail = node;
84 		list->length = 1;
85 		return;
86 	}
87 
88 	tnode = list->tail;
89 
90 	node->prev = tnode;
91 	tnode->next = node;
92 
93 	list->tail = node;
94 	list->length++;
95 }
96 
97 static inline void
pkgconf_node_delete(pkgconf_node_t * node,pkgconf_list_t * list)98 pkgconf_node_delete(pkgconf_node_t *node, pkgconf_list_t *list)
99 {
100 	list->length--;
101 
102 	if (node->prev == NULL)
103 		list->head = node->next;
104 	else
105 		node->prev->next = node->next;
106 
107 	if (node->next == NULL)
108 		list->tail = node->prev;
109 	else
110 		node->next->prev = node->prev;
111 }
112 
113 #ifdef __cplusplus
114 }
115 #endif
116 
117 #endif
118