zeroSquitto – Rev 1

Subversion Repositories:
Rev:
/*************************************************************************/
/* Queue implementation.                                                 */
/*************************************************************************/

#include "queue.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*************************************************************************/
/* Constructor with given size.                                          */
/*************************************************************************/
Queue *queueCreate(int size) {
  Queue *q = (Queue *)calloc(1, sizeof(Queue));
  if ((q->store = (char **)calloc(size, sizeof(char *))) == NULL)
    return NULL;
  q->size = size;
  q->head = 0;
  q->tail = 0;
  return q;
}

/*************************************************************************/
/* Enqueue an item to the queue.                                         */
/*************************************************************************/
void queueEnqueue(Queue *q, char *e) {
  if (q->tail > q->size - 1)
    q->store = (char **)realloc(q->store, ++q->size * sizeof(char *));
  q->store[q->tail] = (char *)calloc(strlen(e) + 1, sizeof(char));
  memcpy(q->store[q->tail], e, strlen(e) + 1);
  ++q->tail;
}

/*************************************************************************/
/* Dequeue an item off the queue.                                        */
/*************************************************************************/
char *queueDequeue(Queue *q) {
  char *e;
  if (queueIsEmpty(q))
    return NULL;
  e = (char *)calloc(strlen(q->store[q->head]) + 1, sizeof(char));
  memcpy(e, q->store[q->head], strlen(q->store[q->head]) + 1);
  ++q->head;
  return e;
}

/*************************************************************************/
/* Clears the queue.                                                     */
/*************************************************************************/
Queue *queueClear(Queue *q) {
  if (q != NULL)
    free(q);
  return queueCreate(1);
}

/*************************************************************************/
/* Prints the items in the queue.                                        */
/*************************************************************************/
void queuePrint(Queue *q) {
  int i;
  if (queueIsEmpty(q)) {
    printf("Queue is empty.\n");
    return;
  }
  printf("Items: ");
  i = q->head;
  do {
    printf("%s ", q->store[i]);
  } while (++i < q->tail);
  printf("\n");
}