void _queue_init(Queue* queue, size_t dataSize)
{
- queue->size = 0;
queue->dataSize = dataSize;
- queue->front = NULL;
- queue->back = NULL;
+ _vector_init(queue->array, dataSize);
}
Queue* _queue_new(size_t dataSize)
Queue* queue_copy(Queue* queue)
{
- Queue* queueCopy = _queue_new(queue->dataSize);
- QueueCell* queueCell = queue->front;
- while (queueCell != NULL)
- {
- _queue_push(queueCopy, queueCell->data);
- queueCell = queueCell->next;
- }
+ Queue* queueCopy = (Queue*) safe_malloc(sizeof (Queue));
+ queueCopy->dataSize = queue->dataSize;
+ Vector* arrayCopy = vector_copy(queue->array);
+ queueCopy->array = arrayCopy;
return queueCopy;
}
Bool queue_empty(Queue* queue)
{
- return (queue->size == 0);
+ return vector_empty(queue->array);
}
UInt queue_size(Queue* queue)
{
- return queue->size;
+ return vector_size(queue->array);
}
void _queue_push(Queue* queue, void* data)
{
- QueueCell* newQueueBack = (QueueCell*) safe_malloc(sizeof (QueueCell));
- newQueueBack->data = safe_malloc(queue->dataSize);
- memcpy(newQueueBack->data, data, queue->dataSize);
- newQueueBack->next = NULL;
- if (queue->size > 0)
- queue->back->next = newQueueBack;
- queue->back = newQueueBack;
- if (queue->size == 0)
- queue->front = newQueueBack;
- queue->size++;
+ _vector_push(queue->array, data);
}
void* _queue_peek(Queue* queue)
{
- return queue->front->data;
+ return vector_get(queue->array, 0);
}
void queue_pop(Queue* queue)
{
- QueueCell* toTrash = queue->front;
- queue->front = queue->front->next;
- if (queue->front == NULL)
- queue->back = NULL;
- safe_free(toTrash->data);
- safe_free(toTrash);
- queue->size--;
+ //remove first vector element and shift its internal array
+ safe_free(queue->array->datas[0]);
+ queue->array->datas++;
+ //NOTE: we remove first element, so capacity decrease too
+ queue->array->size--;
+ queue->array->capacity--;
}
void queue_clear(Queue* queue)
{
- while (queue->size > 0)
- queue_pop(queue);
- _queue_init(queue, queue->dataSize);
+ vector_clear(queue->array);
}
void queue_destroy(Queue* queue)
#include <string.h>
#include "cgds/types.h"
#include "cgds/safe_alloc.h"
-
-/**
- * @brief Generic internal queue cell.
- */
-typedef struct QueueCell {
- void* data; ///< Generic data contained in the cell.
- struct QueueCell* next; ///< Next cell in the internal single-linked list.
-} QueueCell;
+#include "cgds/Vector.h"
/**
* @brief Queue containing generic data.
* @param dataSize Size in bytes of a queue element.
*/
typedef struct Queue {
- UInt size; ///< Count elements in the queue.
size_t dataSize; ///< Size in bytes of a queue element.
- QueueCell* front; ///< Pointer to the next dequeued element.
- QueueCell* back; ///< Pointer to the last enqueued element.
+ Vector* array; ///< Internal vector representation
} Queue;
/**