00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00036 #include "ctrump/common/queue.h"
00037 #include <stdlib.h>
00038 #include <string.h>
00039
00040 void
00041 ctrump_queue_init(struct ctrump_queue *q, size_t nelem, size_t elem_size)
00042 {
00043 q->head = 0;
00044 q->tail = 0;
00045 q->rem = nelem;
00046 q->elem_size = elem_size;
00047 q->size = nelem;
00048 q->elements = malloc(elem_size*nelem);
00049 }
00050
00051 void
00052 ctrump_queue_realloc(struct ctrump_queue *q)
00053 {
00054 size_t new_size = q->size * 2U;
00055 size_t elem_size = q->elem_size;
00056 void *new_buf = malloc(q->elem_size * new_size);
00057 char *ep = (char*)q->elements;
00058 unsigned int rem = q->rem;
00059
00060 if (rem == q->size) {
00061 q->head = q->tail = 0;
00062 q->rem = new_size;
00063 } else if (q->head > q->tail) {
00064 size_t copy_elem = q->head - q->tail;
00065 memcpy(new_buf, ep + q->tail*elem_size, copy_elem*elem_size);
00066 q->tail = 0;
00067 q->head = copy_elem;
00068 q->rem = new_size - copy_elem;
00069 } else {
00070 unsigned int nelem = q->size - q->tail + q->head;
00071 unsigned int tail_copy = (q->size - q->tail)*elem_size;
00072 memcpy(new_buf, ep + q->tail, tail_copy);
00073 memcpy((char*)new_buf + tail_copy,
00074 ep, q->head * elem_size);
00075
00076 q->tail = 0;
00077 q->head = nelem;
00078 q->rem = new_size - nelem;
00079 }
00080
00081 free(q->elements);
00082 q->elements = new_buf;
00083 q->size = new_size;
00084 }
00085
00086 void
00087 ctrump_queue_destroy(struct ctrump_queue *q)
00088 {
00089 free(q->elements);
00090 }