00001 #ifndef __QUEUE_H__ 00002 #define __QUEUE_H__ 00003 00004 #include <malloc.h> 00005 00020 typedef long queue_elem_t; 00021 00023 #define OK 0 00024 00025 #define E_NO_MEMORY -1 00026 00028 typedef struct { 00029 queue_elem_t *data; 00030 int num_elements; 00031 int max_num_elements; 00033 int ins_pos; 00035 int del_pos; 00036 } queue_t; 00037 00046 static int queue_init(queue_t *queue, int max_num_elems) { 00047 queue->data = (queue_elem_t *) malloc(sizeof(queue_elem_t) * max_num_elems); 00048 if (queue->data == 0) 00049 return E_NO_MEMORY; 00050 queue->num_elements = 0; 00051 queue->max_num_elements = max_num_elems; 00052 queue->ins_pos = queue->del_pos = 0; 00053 return OK; 00054 } 00055 00057 static inline void queue_cleanup(queue_t *queue) { 00058 free(queue->data); 00059 } 00060 00066 static void queue_insert(queue_t *queue, queue_elem_t elem) { 00067 queue->data[queue->ins_pos] = elem; 00068 queue->ins_pos = (queue->ins_pos + 1) % queue->max_num_elements; 00069 queue->num_elements++; 00070 } 00071 00079 static queue_elem_t queue_extract(queue_t *queue) { 00080 queue_elem_t elem; 00081 elem = queue->data[queue->del_pos]; 00082 queue->del_pos = (queue->del_pos + 1) % queue->max_num_elements; 00083 queue->num_elements--; 00084 return elem; 00085 } 00086 00093 static int queue_get_num_elements(queue_t *queue) { 00094 return queue->num_elements; 00095 } 00096 00103 static inline int queue_get_max_num_elements(queue_t *queue) { 00104 return queue->max_num_elements; 00105 } 00106 00113 static inline int queue_is_empty(queue_t *queue) { 00114 return (queue->num_elements == 0 ? 1 : 0); 00115 } 00116 00123 static inline int queue_is_full(queue_t *queue) { 00124 return (queue->num_elements == queue->max_num_elements ? 1 : 0); 00125 } 00126 00127 typedef struct { 00128 queue_t *queue; 00129 int pos; 00131 } queue_iterator_t; 00132 00135 static queue_iterator_t queue_begin(queue_t *self) { 00136 queue_iterator_t qit = { 00137 .queue = self, 00138 .pos = self->del_pos 00139 }; 00140 return qit; 00141 } 00142 00144 static int queue_it_has_next(queue_iterator_t *self) { 00145 return (self->pos != self->queue->ins_pos); 00146 } 00147 00149 static queue_elem_t queue_it_next(queue_iterator_t *self) { 00150 queue_elem_t value = self->queue->data[self->pos]; 00151 self->pos = (self->pos + 1) % self->queue->max_num_elements; 00152 return value; 00153 } 00154 00155 #endif