vfs: check userland buffers before reading them.
[haiku.git] / src / system / kernel / util / queue.cpp
blob617ace27e318933fe31efb6b8aa344bf338a5438
1 /* Standard queue */
3 /*
4 ** Copyright 2001, Travis Geiselbrecht. All rights reserved.
5 ** Distributed under the terms of the NewOS License.
6 */
8 #include <kernel.h>
9 #include <queue.h>
10 #include <malloc.h>
11 #include <errno.h>
13 typedef struct queue_element {
14 void *next;
15 } queue_element;
17 typedef struct queue_typed {
18 queue_element *head;
19 queue_element *tail;
20 int count;
21 } queue_typed;
24 int
25 queue_init(queue *q)
27 q->head = q->tail = NULL;
28 q->count = 0;
29 return 0;
33 int
34 queue_remove_item(queue *_q, void *e)
36 queue_typed *q = (queue_typed *)_q;
37 queue_element *elem = (queue_element *)e;
38 queue_element *temp, *last = NULL;
40 temp = (queue_element *)q->head;
41 while (temp) {
42 if (temp == elem) {
43 if (last)
44 last->next = temp->next;
45 else
46 q->head = (queue_element*)temp->next;
48 if (q->tail == temp)
49 q->tail = last;
50 q->count--;
51 return 0;
53 last = temp;
54 temp = (queue_element*)temp->next;
57 return -1;
61 int
62 queue_enqueue(queue *_q, void *e)
64 queue_typed *q = (queue_typed *)_q;
65 queue_element *elem = (queue_element *)e;
67 if (q->tail == NULL) {
68 q->tail = elem;
69 q->head = elem;
70 } else {
71 q->tail->next = elem;
72 q->tail = elem;
74 elem->next = NULL;
75 q->count++;
76 return 0;
80 void *
81 queue_dequeue(queue *_q)
83 queue_typed *q = (queue_typed *)_q;
84 queue_element *elem;
86 elem = q->head;
87 if (q->head != NULL)
88 q->head = (queue_element*)q->head->next;
89 if (q->tail == elem)
90 q->tail = NULL;
92 if (elem != NULL)
93 q->count--;
95 return elem;
99 void *
100 queue_peek(queue *q)
102 return q->head;
106 // #pragma mark -
107 /* fixed queue stuff */
111 fixed_queue_init(fixed_queue *q, int size)
113 if (size <= 0)
114 return EINVAL;
116 q->table = (void**)malloc(size * sizeof(void *));
117 if (!q->table)
118 return ENOMEM;
119 q->head = 0;
120 q->tail = 0;
121 q->count = 0;
122 q->size = size;
124 return 0;
128 void
129 fixed_queue_destroy(fixed_queue *q)
131 free(q->table);
136 fixed_queue_enqueue(fixed_queue *q, void *e)
138 if (q->count == q->size)
139 return ENOMEM;
141 q->table[q->head++] = e;
142 if (q->head >= q->size)
143 q->head = 0;
144 q->count++;
146 return 0;
150 void *
151 fixed_queue_dequeue(fixed_queue *q)
153 void *e;
155 if (q->count <= 0)
156 return NULL;
158 e = q->table[q->tail++];
159 if (q->tail >= q->size)
160 q->tail = 0;
161 q->count--;
163 return e;
167 void *
168 fixed_queue_peek(fixed_queue *q)
170 if (q->count <= 0)
171 return NULL;
173 return q->table[q->tail];