aboutsummaryrefslogtreecommitdiffstats
path: root/queue.c
blob: b9e5eecb99da16a928a6db59dbc9d8e71e327341 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
 * queue.c
 * implementation of a generic queue
 *
 * Erik Liodden
 */

#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "structure.h"
#include "misc.h"

static void grow_queue(struct queue *q)
{
	void *middle = (char *)q->elems + q->head * q->elem_size;
	void *end = (char *)q->elems + q->log_length * q->elem_size;
	q->head = 0;
	q->tail = q->log_length;
	q->alloc_length *= 2;
	if (q->head != 0)
		rotate(q->elems, middle, end);
	q->elems = realloc(q->elems, q->alloc_length * q->elem_size);
	assert(q->elems != NULL);
}

void queue_init(struct queue *q, size_t elem_size, void (*freefn)(void *))
{
	q->elem_size = elem_size;
	q->head = 0;
	q->tail = 0;
	q->log_length = 0;
	q->alloc_length = 4;
	q->elems = allocate(q->alloc_length * elem_size);
	q->freefn = freefn;
}

void queue_dispose(struct queue *q)
{
	int i;
	if (q->freefn) {
		for (i = 0; i < q->log_length; i++)
			q->freefn((char *)q->elems + (((q->head + i) %
					q->alloc_length) * q->elem_size));
	}
	free(q->elems);
}

void queue_enqueue(struct queue *q, void *elem_addr)
{
	if (q->log_length == q->alloc_length)
		grow_queue(q);
	void *target = (char *)q->elems + (q->tail * q->elem_size);
	memcpy(target, elem_addr, q->elem_size);
	q->tail = (q->tail + 1) % q->alloc_length;
	q->log_length++;
}

void queue_peek(struct queue *q, void *elem_addr)
{
	assert(q->log_length != 0);
	void *source = (char *)q->elems + (q->head * q->elem_size);
	memcpy(elem_addr, source, q->elem_size);
}

void queue_dequeue(struct queue *q, void *elem_addr)
{
	queue_peek(q, elem_addr);
	q->head = (q->head + 1) % q->alloc_length;
	q->log_length--;
}

int queue_length(struct queue *q)
{
	return q->log_length;
}