This source file includes following definitions.
- _sir_queue_node_create
- _sir_queue_node_destroy
- _sir_queue_create
- _sir_queue_destroy
- _sir_queue_size
- _sir_queue_isempty
- _sir_queue_push
- _sir_queue_pop
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 #include "sir/queue.h"
33 #include "sir/helpers.h"
34 #include "sir/errors.h"
35
36 sir_queue_node* _sir_queue_node_create(void* data) {
37 sir_queue_node* retval = calloc(1, sizeof(sir_queue_node));
38 if (!retval)
39 (void)_sir_handleerr(errno);
40 else
41 retval->data = data;
42
43 return retval;
44 }
45
46 bool _sir_queue_node_destroy(sir_queue_node** node, void** data) {
47 bool valid = _sir_validptrptr(node) && _sir_validptr(*node);
48
49 if (valid) {
50 if (data)
51 *data = (*node)->data;
52
53 _sir_safefree(node);
54 }
55
56 return valid;
57 }
58
59 bool _sir_queue_create(sir_queue** q) {
60 bool valid = _sir_validptrptr(q);
61
62 if (valid) {
63 *q = calloc(1, sizeof(sir_queue));
64 if (!_sir_validptrnofail(*q))
65 (void)_sir_handleerr(errno);
66 }
67
68 return valid && _sir_validptrnofail(*q);
69 }
70
71 bool _sir_queue_destroy(sir_queue** q) {
72 bool valid = _sir_validptrptr(q) && _sir_validptr(*q);
73
74 if (valid) {
75 sir_queue_node* next = (*q)->head;
76 while (next) {
77 sir_queue_node* this_node = next;
78 void* data = NULL;
79 next = this_node->next;
80
81 if (_sir_queue_node_destroy(&this_node, &data))
82 _sir_safefree(&data);
83 }
84
85 _sir_safefree(q);
86 }
87
88 return valid;
89 }
90
91 size_t _sir_queue_size(sir_queue* q) {
92 if (_sir_queue_isempty(q))
93 return 0;
94
95 sir_queue_node* next = q->head->next;
96 size_t idx = 1;
97 while (next) {
98 idx++;
99 next = next->next;
100 }
101
102 return idx;
103 }
104
105 bool _sir_queue_isempty(const sir_queue* q) {
106 return !q || !q->head;
107 }
108
109 bool _sir_queue_push(sir_queue* q, void* data) {
110 bool retval = false;
111
112 if (_sir_validptr(q)) {
113 if (!q->head) {
114 q->head = _sir_queue_node_create(data);
115 retval = NULL != q->head;
116 } else {
117 sir_queue_node* next = q->head;
118 while (next) {
119 if (!next->next) {
120 next->next = _sir_queue_node_create(data);
121 if (next->next) {
122 retval = true;
123 break;
124 }
125 }
126 next = next->next;
127 }
128 }
129 }
130
131 return retval;
132 }
133
134 bool _sir_queue_pop(sir_queue* q, void** data) {
135 bool retval = false;
136
137 if (!_sir_queue_isempty(q) && _sir_validptrptr(data)) {
138 sir_queue_node* old_head = q->head;
139 q->head = old_head->next;
140
141 retval = _sir_queue_node_destroy(&old_head, data);
142 }
143
144 return retval;
145 }