1
0

queue.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #ifndef HW_QUEUE_H_
  2. #define HW_QUEUE_H_
  3. /*
  4. * queue
  5. * FIFO: push_back,pop_front
  6. */
  7. #include <assert.h> // for assert
  8. #include <stdlib.h> // for malloc,realloc,free
  9. #include <string.h> // for memset,memmove
  10. #include "hbase.h"
  11. // #include <deque>
  12. // typedef std::deque<type> qtype;
  13. #define QUEUE_DECL(type, qtype) \
  14. struct qtype { \
  15. type* ptr; \
  16. size_t size; \
  17. size_t maxsize;\
  18. size_t _offset;\
  19. }; \
  20. typedef struct qtype qtype;\
  21. \
  22. static inline type* qtype##_data(qtype* p) {\
  23. return p->ptr + p->_offset;\
  24. }\
  25. \
  26. static inline int qtype##_size(qtype* p) {\
  27. return p->size;\
  28. }\
  29. \
  30. static inline int qtype##_maxsize(qtype* p) {\
  31. return p->maxsize;\
  32. }\
  33. \
  34. static inline int qtype##_empty(qtype* p) {\
  35. return p->size == 0;\
  36. }\
  37. \
  38. static inline type* qtype##_front(qtype* p) {\
  39. return p->size == 0 ? NULL : p->ptr + p->_offset;\
  40. }\
  41. \
  42. static inline type* qtype##_back(qtype* p) {\
  43. return p->size == 0 ? NULL : p->ptr + p->_offset + p->size-1;\
  44. }\
  45. \
  46. static inline void qtype##_init(qtype* p, int maxsize) {\
  47. p->_offset = 0;\
  48. p->size = 0;\
  49. p->maxsize = maxsize;\
  50. SAFE_ALLOC(p->ptr, sizeof(type) * maxsize);\
  51. }\
  52. \
  53. static inline void qtype##_clear(qtype* p) {\
  54. p->_offset = 0;\
  55. p->size = 0;\
  56. memset(p->ptr, 0, sizeof(type) * p->maxsize);\
  57. }\
  58. \
  59. static inline void qtype##_cleanup(qtype* p) {\
  60. SAFE_FREE(p->ptr);\
  61. p->_offset = p->size = p->maxsize = 0;\
  62. }\
  63. \
  64. static inline void qtype##_resize(qtype* p, int maxsize) {\
  65. p->ptr = (type*)safe_realloc(p->ptr, sizeof(type)*maxsize, sizeof(type)*p->maxsize);\
  66. p->maxsize = maxsize;\
  67. }\
  68. \
  69. static inline void qtype##_double_resize(qtype* p) {\
  70. assert(p->maxsize != 0);\
  71. return qtype##_resize(p, p->maxsize*2);\
  72. }\
  73. \
  74. static inline void qtype##_push_back(qtype* p, type* elem) {\
  75. if (p->size == p->maxsize) {\
  76. qtype##_double_resize(p);\
  77. }\
  78. else if (p->_offset + p->size == p->maxsize) {\
  79. memmove(p->ptr, p->ptr + p->_offset, p->size);\
  80. p->_offset = 0;\
  81. }\
  82. p->ptr[p->_offset + p->size] = *elem;\
  83. p->size++;\
  84. }\
  85. static inline void qtype##_pop_front(qtype* p) {\
  86. assert(p->size > 0);\
  87. p->size--;\
  88. if (++p->_offset == p->maxsize) p->_offset = 0;\
  89. }\
  90. \
  91. static inline void qtype##_pop_back(qtype* p) {\
  92. assert(p->size > 0);\
  93. p->size--;\
  94. }\
  95. #endif // HW_QUEUE_H_