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

typedef struct queue  q_t;

typedef struct q_base
{
    // items always start with a next pointer.
    struct q_base* next;
} q_base_t;

q_t* q_init()
{
    q_t* queue = calloc(1, sizeof(q_t));
    if (!queue)
        return NULL;

    queue->length = 0;

    return queue;
}

int q_length(struct queue* queue)
{
    return queue->length;
}

void _q_nq(q_t* queue, void* item)
{
    if (!queue->head)
        queue->tail = queue->head = item;
    else
    {
        ((q_base_t*)queue->tail)->next = item;
        queue->tail       = item;
    }

    queue->length++;
}

void* q_dq(q_t* queue)
{
    if (!queue->head)
        return NULL;

    q_base_t* head = queue->head;
    queue->head    = head->next;

    queue->length--;

    return head;
}

void q_clean(q_t* queue)
{
    void* cur;

    while ((cur = q_dq(queue)))
        free(cur);

    free(queue);
}