#include "util.h"
jqueue_t jqueue_new(void) {
pool p;
jqueue_t q;
p = pool_new();
q = (jqueue_t) pmalloco(p, sizeof(struct _jqueue_st));
q->p = p;
return q;
}
void jqueue_free(jqueue_t q) {
assert((int) q);
pool_free(q->p);
}
void jqueue_push(jqueue_t q, void *data, int priority) {
_jqueue_node_t qn, scan;
assert((int) q);
q->size++;
qn = q->cache;
if(qn != NULL)
q->cache = qn->next;
else
qn = (_jqueue_node_t) pmalloc(q->p, sizeof(struct _jqueue_node_st));
qn->data = data;
qn->priority = priority;
qn->next = NULL;
qn->prev = NULL;
if(q->back == NULL && q->front == NULL) {
q->back = qn;
q->front = qn;
return;
}
for(scan = q->back; scan != NULL && scan->priority > priority; scan = scan->next);
if(scan == NULL) {
qn->prev = q->front;
qn->prev->next = qn;
q->front = qn;
return;
}
qn->next = scan;
qn->prev = scan->prev;
if(scan->prev != NULL)
scan->prev->next = qn;
else
q->back = qn;
scan->prev = qn;
}
void *jqueue_pull(jqueue_t q) {
void *data;
_jqueue_node_t qn;
assert((int) q);
if(q->front == NULL)
return NULL;
data = q->front->data;
qn = q->front;
if(qn->prev != NULL)
qn->prev->next = NULL;
q->front = qn->prev;
qn->next = q->cache;
q->cache = qn;
if(q->front == NULL)
q->back = NULL;
q->size--;
return data;
}
int jqueue_size(jqueue_t q) {
return q->size;
}