| 1 | /** |
| 2 | * @file Queue.c |
| 3 | */ |
| 4 | |
| 5 | #include "cgds/Queue.h" |
| 6 | |
| 7 | void _queue_init(Queue* queue, size_t dataSize) |
| 8 | { |
| 9 | queue->size = 0; |
| 10 | queue->dataSize = dataSize; |
| 11 | queue->front = NULL; |
| 12 | queue->back = NULL; |
| 13 | } |
| 14 | |
| 15 | Queue* _queue_new(size_t dataSize) |
| 16 | { |
| 17 | Queue* queue = (Queue*) safe_malloc(sizeof (Queue)); |
| 18 | _queue_init(queue, dataSize); |
| 19 | return queue; |
| 20 | } |
| 21 | |
| 22 | Queue* queue_copy(Queue* queue) |
| 23 | { |
| 24 | Queue* queueCopy = _queue_new(queue->dataSize); |
| 25 | QueueCell* queueCell = queue->front; |
| 26 | while (queueCell != NULL) |
| 27 | { |
| 28 | _queue_push(queueCopy, queueCell->data); |
| 29 | queueCell = queueCell->next; |
| 30 | } |
| 31 | return queueCopy; |
| 32 | } |
| 33 | |
| 34 | Bool queue_empty(Queue* queue) |
| 35 | { |
| 36 | return (queue->size == 0); |
| 37 | } |
| 38 | |
| 39 | UInt queue_size(Queue* queue) |
| 40 | { |
| 41 | return queue->size; |
| 42 | } |
| 43 | |
| 44 | void _queue_push(Queue* queue, void* data) |
| 45 | { |
| 46 | QueueCell* newQueueBack = (QueueCell*) safe_malloc(sizeof (QueueCell)); |
| 47 | newQueueBack->data = safe_malloc(queue->dataSize); |
| 48 | memcpy(newQueueBack->data, data, queue->dataSize); |
| 49 | newQueueBack->next = NULL; |
| 50 | if (queue->size > 0) |
| 51 | queue->back->next = newQueueBack; |
| 52 | queue->back = newQueueBack; |
| 53 | if (queue->size == 0) |
| 54 | queue->front = newQueueBack; |
| 55 | queue->size++; |
| 56 | } |
| 57 | |
| 58 | void* _queue_peek(Queue* queue) |
| 59 | { |
| 60 | return queue->front->data; |
| 61 | } |
| 62 | |
| 63 | void queue_pop(Queue* queue) |
| 64 | { |
| 65 | QueueCell* toTrash = queue->front; |
| 66 | queue->front = queue->front->next; |
| 67 | if (queue->front == NULL) |
| 68 | queue->back = NULL; |
| 69 | safe_free(toTrash->data); |
| 70 | safe_free(toTrash); |
| 71 | queue->size--; |
| 72 | } |
| 73 | |
| 74 | void queue_clear(Queue* queue) |
| 75 | { |
| 76 | while (queue->size > 0) |
| 77 | queue_pop(queue); |
| 78 | _queue_init(queue, queue->dataSize); |
| 79 | } |
| 80 | |
| 81 | void queue_destroy(Queue* queue) |
| 82 | { |
| 83 | queue_clear(queue); |
| 84 | safe_free(queue); |
| 85 | } |