]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/queue.c
Merge from branch-2-1
[netatalk.git] / libatalk / util / queue.c
1 /*
2   $Id: queue.c,v 1.1.2.1 2010-02-01 10:56:08 franklahm Exp $
3   Copyright (c) 2010 Frank Lahm <franklahm@gmail.com>
4
5   This program is free software; you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation; either version 2 of the License, or
8   (at your option) any later version.
9
10   This program is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14 */
15
16 /*!
17  * @file
18  * Netatalk utility functions: queue
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif /* HAVE_CONFIG_H */
24
25 #include <stdlib.h>
26
27 #include <atalk/queue.h>
28
29 static qnode_t *alloc_init_node(void *data)
30 {
31     qnode_t *node;
32     if ((node = malloc(sizeof(qnode_t))) == NULL)
33         return NULL;
34     node->data = data;
35
36     return node;
37 }
38
39 /********************************************************************************
40  * Interface
41  *******************************************************************************/
42
43 q_t *queue_init(void)
44 {
45     q_t *queue;
46
47     if ((queue = alloc_init_node(NULL)) == NULL)
48         return NULL;
49
50     queue->prev = queue->next = queue;
51     return queue;
52 }
53
54 qnode_t *enqueue(q_t *q, void *data)
55 {
56     qnode_t *node;
57
58     if ((node = alloc_init_node(data)) == NULL)
59         return NULL;
60
61     /* insert at tail */
62     node->next = q;
63     node->prev = q->prev;
64     q->prev->next = node;
65     q->prev = node;
66
67     return node;
68 }
69
70 void *dequeue(q_t *q)
71 {
72     qnode_t *node;
73     void *data;
74
75     if (q == NULL || q->next == q)
76         return NULL;
77
78     /* take first node from head */
79     node = q->next;
80     data = node->data;
81     q->next = node->next;
82     node->next->prev = node->prev;
83     free(node);
84
85     return data;    
86 }
87
88 void queue_destroy(q_t *q, void (*callback)(void *))
89 {
90     void *p;
91
92     while ((p = dequeue(q)) != NULL)
93         callback(p);
94
95     free(q);
96     q = NULL;
97 }
98