]> git.datanom.net - clib.git/blame - src/queue.c
init
[clib.git] / src / queue.c
CommitLineData
392d65ba
MR
1#include <stdlib.h>
2#include "queue.h"
3
4typedef struct _Queue {
5 void** elems;
6 int size;
7 QueueFreeFunc free;
8} Queue;
9
10static void free_elem(Queue* queue) {
11 if (queue->free) {
12 for (int i = 0; i < queue->size; i++)
13 queue->free(queue->elems[i]);
14 }
15 free(queue->elems);
16}
17
18Queue* queue_new() {
19 Queue* q = malloc(sizeof(Queue));
20 q->size = 0;
21 q->elems = NULL;
22 q->free = NULL;
23 return q;
24}
25
26Queue* queue_new_full(QueueFreeFunc free){
27 Queue* q = malloc(sizeof(Queue));
28 q->size = 0;
29 q->elems = NULL;
30 q->free = free;
31 return q;
32}
33
34void queue_destroy(Queue* queue) {
35 free_elem(queue);
36 free(queue);
37}
38
39/*
40static void extend(Queue* queue, void* elem) {
41 while (int i = queue->size - 1; i > 0; i--) {
42 queue->elems[i] = queue->elems[i - 1]
43 }
44 queue->elems[0] elem;
45}
46*/
47void* queue_dequeue(Queue* queue) {
48 if (queue_empty(queue))
49 return NULL;
50 queue->size -= 1;
51 void* elem = queue->elems[queue->size];
52 queue->elems[queue->size] = NULL;
53 queue->elems = realloc(queue->elems, queue->size * sizeof(void*));
54
55 return elem;
56}
57
58void queue_enqueue(Queue* queue, void* elem) {
59 if (queue == NULL)
60 return;
61
62 queue->size += 1;
63 queue->elems = realloc(queue->elems, queue->size * sizeof(void*));
64 for (int i = queue->size - 1; i > 0; i--) {
65 queue->elems[i] = queue->elems[i - 1];
66 }
67 queue->elems[0] = elem;
68}
69
70void* queue_front(Queue* queue) {
71 if (queue_empty(queue))
72 return NULL;
73 return queue->elems[0];
74}
75
76void* queue_back(Queue* queue) {
77 if (queue_empty(queue))
78 return NULL;
79 return queue->elems[queue->size - 1];
80}
81
82bool queue_empty(Queue* queue) {
83 return (queue == NULL || queue->size == 0);
84}
85
86void queue_clear(Queue* queue) {
87 if (queue == NULL)
88 return;
89
90 free_elem(queue);
91 queue->size = 0;
92 queue->elems = NULL;
93}
94
95int queue_size(Queue* queue) {
96 if (queue_empty(queue))
97 return 0;
98 return queue->size;
99}
This page took 0.058358 seconds and 5 git commands to generate.