queue.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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->maxsize = maxsize;\
  66. int bytes = sizeof(type) * maxsize;\
  67. p->ptr = (type*)safe_realloc(p->ptr, bytes);\
  68. }\
  69. \
  70. static inline void qtype##_double_resize(qtype* p) {\
  71. assert(p->maxsize != 0);\
  72. return qtype##_resize(p, p->maxsize*2);\
  73. }\
  74. \
  75. static inline void qtype##_push_back(qtype* p, type* elem) {\
  76. if (p->size == p->maxsize) {\
  77. qtype##_double_resize(p);\
  78. }\
  79. else if (p->_offset + p->size == p->maxsize) {\
  80. memmove(p->ptr, p->ptr + p->_offset, p->size);\
  81. p->_offset = 0;\
  82. }\
  83. p->ptr[p->_offset + p->size] = *elem;\
  84. p->size++;\
  85. }\
  86. static inline void qtype##_pop_front(qtype* p) {\
  87. assert(p->size > 0);\
  88. p->size--;\
  89. if (++p->_offset == p->maxsize) p->_offset = 0;\
  90. }\
  91. \
  92. static inline void qtype##_pop_back(qtype* p) {\
  93. assert(p->size > 0);\
  94. p->size--;\
  95. }\
  96. #endif // HW_QUEUE_H_