summaryrefslogtreecommitdiffstats
path: root/libapol/src/queue.c
blob: 1a3de23be8abed82571c4a0e6d1fed639ad1cd04 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/**
 * @file
 *
 * This file is a copy of queue.h from NSA's CVS repository.  It has
 * been modified to follow the setools naming conventions.
 *
 * Author : Stephen Smalley (NSA), <sds@epoch.ncsc.mil>
 *
 * Implementation of the double-ended queue type.
 */

#include <stdlib.h>
#include "queue.h"

apol_queue_t *apol_queue_create(void)
{
	apol_queue_t *q;

	q = (apol_queue_t *) malloc(sizeof(apol_queue_t));
	if (q == NULL)
		return NULL;

	q->head = q->tail = NULL;

	return q;
}

int apol_queue_insert(apol_queue_t * q, void *element)
{
	apol_queue_node_t *newnode;

	if (!q)
		return -1;

	newnode = (apol_queue_node_t *) malloc(sizeof(struct apol_queue_node));
	if (newnode == NULL)
		return -1;

	newnode->element = element;
	newnode->next = NULL;

	if (q->head == NULL) {
		q->head = q->tail = newnode;
	} else {
		q->tail->next = newnode;
		q->tail = newnode;
	}

	return 0;
}

int apol_queue_push(apol_queue_t * q, void *element)
{
	apol_queue_node_t *newnode;

	if (!q)
		return -1;

	newnode = (apol_queue_node_t *) malloc(sizeof(apol_queue_node_t));
	if (newnode == NULL)
		return -1;

	newnode->element = element;
	newnode->next = NULL;

	if (q->head == NULL) {
		q->head = q->tail = newnode;
	} else {
		newnode->next = q->head;
		q->head = newnode;
	}

	return 0;
}

void *apol_queue_remove(apol_queue_t * q)
{
	apol_queue_node_t *node;
	void *element;

	if (!q)
		return NULL;

	if (q->head == NULL)
		return NULL;

	node = q->head;
	q->head = q->head->next;
	if (q->head == NULL)
		q->tail = NULL;

	element = node->element;
	free(node);

	return element;
}

void *apol_queue_head(apol_queue_t * q)
{
	if (!q)
		return NULL;

	if (q->head == NULL)
		return NULL;

	return q->head->element;
}

void apol_queue_destroy(apol_queue_t ** q)
{
	apol_queue_node_t *p, *temp;

	if (!q || *q == NULL)
		return;

	p = (*q)->head;
	while (p != NULL) {
		temp = p;
		p = p->next;
		free(temp);
	}

	free(*q);
	*q = NULL;
}