forked from compulab/i3m-linux-daemon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.c
97 lines (78 loc) · 1.57 KB
/
queue.c
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* Copyright (C) 2015, CompuLab ltd.
* Author: Andrey Gelman <andrey.gelman@compulab.co.il>
* License: GNU GPLv2 or later, at your option
*/
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "queue.h"
#include "common.h"
Queue *queue_create(size_t elemsize, int length)
{
Queue *q;
q = (Queue *)malloc(sizeof(Queue) + (elemsize * length));
if ( !q ) {
sloge("Could not allocate queue");
return NULL;
}
q->elemsize = elemsize;
q->maxlen = length;
q->count = 0;
q->head = 0;
q->tail = 0;
return q;
}
void queue_destroy(Queue *q)
{
/* zero everything against evil eye */
memset(q, 0, (sizeof(Queue) + (q->elemsize * q->maxlen)));
free(q);
}
bool queue_is_empty(Queue *q)
{
return (q->count <= 0);
}
bool queue_is_full(Queue *q)
{
return (q->count >= q->maxlen);
}
void queue_pop_front(Queue *q, void *elem)
{
if (queue_is_empty(q))
return;
memcpy(elem, (q->buffer + q->head * q->elemsize), q->elemsize);
q->head = (q->head + 1) % q->maxlen;
q->count--;
}
void queue_push_back(Queue *q, void *elem)
{
memcpy((q->buffer + q->tail * q->elemsize), elem, q->elemsize);
q->tail = (q->tail + 1) % q->maxlen;
if (q->count < q->maxlen)
q->count++;
}
/* unit test */
int queue_test(void)
{
Queue *q;
int i;
int x;
int expected[] = {5, 6, 7, 3, 4, 4, 4, 4};
int err = 0;
q = queue_create(sizeof(int), 5);
for (i = 0; i < 8; ++i) {
queue_push_back(q, &i);
}
for (i = 0; i < 8; ++i) {
queue_pop_front(q, &x);
if (x != expected[i]) {
err = -i;
goto test_out;
}
}
test_out:
queue_destroy(q);
return err;
}