Add queue implementation from experiments area.

This commit is contained in:
Russell Gallop
2011-08-11 15:39:49 +01:00
parent d4e1bc3906
commit ff035c8b08
2 changed files with 72 additions and 0 deletions

View File

@@ -0,0 +1,48 @@
#include <stdio.h>
#include "queue.h"
// This presumes that the xc compiler will not re-use the mem passed to init_queue
void init_queue(queue *q, int arr[], int size) {
q->rdptr = 0;
q->wrptr = 0;
q->data = (intptr_t)arr;
q->size = size; // presume that size is power of two
q->mask = size - 1;
}
extern inline void enqueue(queue *q, int value) {
((int *)q->data)[q->wrptr & q->mask] = value;
q->wrptr++;
}
extern inline int dequeue(queue *q) {
int retval = ((int *)q->data)[q->rdptr & q->mask];
q->rdptr++;
return retval;
}
extern inline int isempty(queue *q) {
return (q->rdptr == q->wrptr);
}
extern inline int isfull(queue *q) {
return ((q->wrptr - q->rdptr) == q->size);
}
extern inline int items(queue *q) {
int items = q->wrptr - q->rdptr;
return items;
}
// How to calculate size? Could make it a function call or leave it as a variable within the struct
extern inline int space(queue *q) {
return q->size - items(q);
}
void dump(queue *q) {
for (int i = q->rdptr; i != q->wrptr; i++) {
printf("a[%d] = %d\n", i & q->mask, ((int *)q->data)[i & q->mask]);
}
}

View File

@@ -0,0 +1,24 @@
#ifndef QUEUE_H
#define QUEUE_H
#include <stdint.h>
#include <xccompat.h>
typedef struct queue {
intptr_t data;
int rdptr; // Using absolute indices which count reads and writes so this needs to be considered when accessing.
int wrptr;
int size;
int mask;
} queue;
void init_queue(REFERENCE_PARAM(queue, q), int arr[], int size);
void enqueue(REFERENCE_PARAM(queue, q), int value);
int dequeue(REFERENCE_PARAM(queue, q));
int isempty(REFERENCE_PARAM(queue, q));
int isfull(REFERENCE_PARAM(queue, q));
int items(REFERENCE_PARAM(queue, q));
int space(REFERENCE_PARAM(queue, q));
void dump(REFERENCE_PARAM(queue, q));
#endif // QUEUE_H