#include #include "queue.h" typedef struct _Queue { void** elems; int size; QueueFreeFunc free; } Queue; static void free_elem(Queue* queue) { if (queue->free) { for (int i = 0; i < queue->size; i++) queue->free(queue->elems[i]); } free(queue->elems); } Queue* queue_new() { Queue* q = malloc(sizeof(Queue)); q->size = 0; q->elems = NULL; q->free = NULL; return q; } Queue* queue_new_full(QueueFreeFunc free){ Queue* q = malloc(sizeof(Queue)); q->size = 0; q->elems = NULL; q->free = free; return q; } void queue_destroy(Queue* queue) { free_elem(queue); free(queue); } /* static void extend(Queue* queue, void* elem) { while (int i = queue->size - 1; i > 0; i--) { queue->elems[i] = queue->elems[i - 1] } queue->elems[0] elem; } */ void* queue_dequeue(Queue* queue) { if (queue_empty(queue)) return NULL; queue->size -= 1; void* elem = queue->elems[queue->size]; queue->elems[queue->size] = NULL; queue->elems = realloc(queue->elems, queue->size * sizeof(void*)); return elem; } void queue_enqueue(Queue* queue, void* elem) { if (queue == NULL) return; queue->size += 1; queue->elems = realloc(queue->elems, queue->size * sizeof(void*)); for (int i = queue->size - 1; i > 0; i--) { queue->elems[i] = queue->elems[i - 1]; } queue->elems[0] = elem; } void* queue_front(Queue* queue) { if (queue_empty(queue)) return NULL; return queue->elems[0]; } void* queue_back(Queue* queue) { if (queue_empty(queue)) return NULL; return queue->elems[queue->size - 1]; } bool queue_empty(Queue* queue) { return (queue == NULL || queue->size == 0); } void queue_clear(Queue* queue) { if (queue == NULL) return; free_elem(queue); queue->size = 0; queue->elems = NULL; } int queue_size(Queue* queue) { if (queue_empty(queue)) return 0; return queue->size; }