12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- #ifndef CORE_QUEUE_H
- #define CORE_QUEUE_H
- #include <assert.h>
- #include "core/ToString.h"
- #include "core/Types.h"
- #include "core/Utility.h"
- #define QUEUE(T, N) \
- typedef struct { \
- size_t writeIndex; \
- size_t readIndex; \
- size_t length; \
- size_t capacity; \
- T* data; \
- } Queue##N; \
- \
- void initQueue##N(Queue##N* r, size_t capacity); \
- void destroyQueue##N(Queue##N* r); \
- void pushQueueData##N(Queue##N* r, T data); \
- T* getQueueIndex##N(const Queue##N* r, size_t index); \
- void clearQueue##N(Queue##N* r); \
- void popQueueData##N(Queue##N* r); \
- typedef size_t (*ToString##N)(const T* data, char* buffer, size_t n); \
- size_t toStringQueue##N(const Queue##N* r, char* buffer, size_t n, \
- ToString##N c);
- #define QUEUE_SOURCE(T, N) \
- void initQueue##N(Queue##N* r, size_t capacity) { \
- *r = ((Queue##N){0, 0, 0, capacity, nullptr}); \
- } \
- \
- void destroyQueue##N(Queue##N* r) { \
- coreFree(r->data); \
- *r = (Queue##N){0}; \
- } \
- \
- void pushQueueData##N(Queue##N* r, T data) { \
- if(r->length >= r->capacity) { \
- return; \
- } else if(r->data == nullptr) { \
- r->data = coreAllocate(r->capacity * sizeof(T)); \
- } \
- r->data[r->writeIndex] = data; \
- r->writeIndex = (r->writeIndex + 1) % r->capacity; \
- r->length++; \
- } \
- \
- T* getQueueIndex##N(const Queue##N* r, size_t index) { \
- return r->data + ((index + r->readIndex) % r->capacity); \
- } \
- \
- void clearQueue##N(Queue##N* r) { \
- r->writeIndex = 0; \
- r->readIndex = 0; \
- r->length = 0; \
- } \
- \
- void popQueueData##N(Queue##N* r) { \
- assert(r->length > 0); \
- r->length--; \
- r->readIndex = (r->readIndex + 1) % r->capacity; \
- } \
- \
- size_t toStringQueue##N(const Queue##N* r, char* buffer, size_t n, \
- ToString##N c) { \
- size_t w = 0; \
- stringAdd(&w, &buffer, &n, toString(buffer, n, "[")); \
- size_t end = r->length; \
- if(end > 0) { \
- end--; \
- for(size_t i = 0; i < end; i++) { \
- stringAdd(&w, &buffer, &n, \
- c(getQueueIndex##N(r, i), buffer, n)); \
- stringAdd(&w, &buffer, &n, toString(buffer, n, ", ")); \
- } \
- stringAdd(&w, &buffer, &n, \
- c(getQueueIndex##N(r, end), buffer, n)); \
- } \
- stringAdd(&w, &buffer, &n, toString(buffer, n, "]")); \
- return w; \
- }
- #endif
|