Skip to content
Snippets Groups Projects
queue.c 1.56 KiB
#include "queue.h"

int queue_init(struct Queue *q, volatile unsigned char *buff, unsigned int max_size_plus1) {
  q->buff = buff;
  q->max_size_plus1 = max_size_plus1;
  q->start = max_size_plus1 - 1;
  q->end = 0;
  return 0;
}

struct Queue * queue_malloc(unsigned int max_size) {
  unsigned char *buff = malloc(sizeof(unsigned char) * (max_size + 1));
  if (buff == NULL) return NULL;
  struct Queue *q = malloc(sizeof(struct Queue));
  if (q == NULL) return NULL;
  queue_init(q, buff, max_size + 1);
  return q;
}

void queue_free(struct Queue *q) {
  free((unsigned char *) q->buff);
  free(q);
}

int queue_add(struct Queue *q, unsigned char c) {
  if (queue_full(q)) {
    return -1;
  }
  q->buff[q->end] = c;
  q->end += 1;
  q->end %= q->max_size_plus1;
  return 0;
}

int queue_remove(struct Queue *q, unsigned char *c) {
  if (queue_empty(q)) {
    return -1;
  }
  q->start += 1;
  q->start %= q->max_size_plus1;
  *c = q->buff[q->start];
  return 0;
}

int queue_size(struct Queue *q) {
  return (q->max_size_plus1 + q->end - q->start - 1) % q->max_size_plus1;
}

int queue_full(struct Queue *q) {
  return q->start == q->end;
}

int queue_empty(struct Queue *q) {
  return queue_size(q) == 0;
}

void queue_print(struct Queue *q) {
  int i;
  printf("buffer: (size: %d, full: %d, empty: %d)\n", queue_size(q), queue_full(q), queue_empty(q));
  for (i = 0; i < q->max_size_plus1; i += 1) {
    char c = (char) q->buff[i];
    if (c == 0) c = '-';
    printf("%c", c);;
    if (i == q->start) printf("  <- start");
    if (i == q->end) printf("  <- end");
    printf("\n");
  }
}