queue.h 2.4 KB

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