Queue
A FIFO queue of void * backed by a List. The caller owns the Queue handle. Payloads are borrowed unless a destroy callback is set.
Usage#
Initialize a Queue with NULL for borrowed payloads, or a destructor such as free for payloads the queue should free when destroyed.
Queue queue;
queue_init(&queue, NULL);
int value = 42;
if (queue_enqueue(&queue, &value) == 0) {
void *data;
if (queue_dequeue(&queue, &data) == 0) {
/* data == &value */
}
}
queue_destroy(&queue);
Dequeue writes the payload to the caller and does not call the destructor. queue_destroy frees the remaining nodes, calls the destructor on their payloads from the back toward the front, and zeros the handle. It does not free the Queue. A second destroy is a no-op.
Structs#
Queue#
typedef struct {
List impl;
} Queue;
The front is impl.head. The back is impl.tail.
Functions#
queue_init#
Initializes an empty queue and stores destroy. The destructor runs only from queue_destroy, and only on payloads still in the queue. Pass NULL for borrowed data. Do not call it on a queue that still owns nodes. queue must be non-NULL.
void queue_init(Queue *queue, void (*destroy)(void *data));queue_destroy#
Frees every node. If destroy is non-NULL, calls it on each remaining payload from the back toward the front. Does not free the Queue handle. Zeros the handle, so a second call is a no-op. queue must be non-NULL.
void queue_destroy(Queue *queue);queue_enqueue#
Adds data at the back. The pointer is stored, not the payload bytes. Returns 0 on success and -1 if node allocation fails. Failure leaves the queue unchanged. queue must be non-NULL. A NULL payload is allowed.
int queue_enqueue(Queue *queue, const void *data);queue_dequeue#
Removes the front node and writes its payload to *data. Returns 0 on success. Returns -1 if the queue is empty or data is NULL, and leaves the queue unchanged. Does not call destroy. A stored NULL payload is removed, and *data is set to NULL.
int queue_dequeue(Queue *queue, void **data);queue_peek#
Returns the front payload without removing it. Returns NULL if the queue is empty or the stored payload is NULL. queue must be non-NULL.
void *queue_peek(Queue *queue);Macros#
queue_size#
The number of elements.
#define queue_size(q) ((q)->impl.size)queue_is_empty#
Nonzero when the queue has no elements.
#define queue_is_empty(q) ((q)->impl.size == 0)