Created
January 4, 2012 21:39
-
-
Save codebrainz/1562301 to your computer and use it in GitHub Desktop.
Simple bounded queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* A very basic (and fast) fixed-sized queue data structure. | |
* | |
* Author: Matthew Brush <mbrush@codebrainz.ca> | |
* License: GNU Lesser General Public License, version 2.1 | |
* Edit Date: January 4th, 2011 | |
*/ | |
#include <stdlib.h> | |
#include "fixedqueue.h" | |
struct _fixed_queue_t | |
{ | |
void **data; /* array to hold pointers */ | |
size_t size; /* queue capacity */ | |
size_t nel; /* current number of items */ | |
size_t read; /* offset to read from */ | |
size_t write; /* offset to write to */ | |
}; | |
fixed_queue_t * | |
fixed_queue_new (size_t size) | |
{ | |
fixed_queue_t *queue; | |
queue = calloc (1, sizeof (fixed_queue_t)); | |
queue->size = size + 1; | |
queue->data = calloc (queue->size, sizeof (void*)); | |
return queue; | |
} | |
void | |
fixed_queue_free (fixed_queue_t *queue) | |
{ | |
free (queue->data); | |
free (queue); | |
} | |
int | |
fixed_queue_is_empty (fixed_queue_t *queue) | |
{ | |
#if 0 | |
return (queue->read == queue->write); | |
#else | |
return queue->nel == 0; | |
#endif | |
} | |
int | |
fixed_queue_is_full (fixed_queue_t *queue) | |
{ | |
#if 0 | |
return (((queue->write + 1) % queue->size) == queue->read); | |
#else | |
return queue->nel == (queue->size - 1); | |
#endif | |
} | |
int | |
fixed_queue_enqueue (fixed_queue_t *queue, void *value) | |
{ | |
if (!fixed_queue_is_full (queue)) | |
{ | |
queue->data[queue->write] = value; | |
if (queue->write == (queue->size - 1)) | |
queue->write = 0; /* wrap around when full */ | |
else | |
queue->write++; | |
queue->nel++; | |
return 1; | |
} | |
return 0; | |
} | |
int | |
fixed_queue_dequeue (fixed_queue_t *queue, void **value) | |
{ | |
if (!fixed_queue_is_empty (queue)) | |
{ | |
if (value) | |
*value = queue->data[queue->read]; | |
if (queue->read == (queue->size - 1)) | |
queue->read = 0; /* wrap around when full */ | |
else | |
queue->read++; | |
queue->nel--; | |
return 1; | |
} | |
return 0; | |
} | |
size_t | |
fixed_queue_size (fixed_queue_t *queue) | |
{ | |
return queue->nel; | |
} | |
void | |
fixed_queue_clear (fixed_queue_t *queue) | |
{ | |
queue->read = 0; | |
queue->write = 0; | |
queue->nel = 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment