You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.3 KiB

  1. #pragma once
  2. #include <stdio.h>
  3. #include <string.h>
  4. namespace iflytop {
  5. using namespace std;
  6. template <typename T>
  7. class LoopQueue {
  8. private:
  9. T *arr;
  10. int maxSize;
  11. int rear;
  12. int front;
  13. public:
  14. LoopQueue(/* args */) {
  15. maxSize = 1;
  16. rear = 0;
  17. front = 0;
  18. }
  19. ~LoopQueue() {}
  20. void initialize(int size) {
  21. arr = (T *)malloc(size * sizeof(T));
  22. ZASSERT(arr != NULL);
  23. maxSize = size;
  24. }
  25. bool push(T *data) {
  26. if (isFull()) {
  27. return false;
  28. }
  29. memcpy(&arr[rear], data, sizeof(T));
  30. rear = (rear + 1) % maxSize;
  31. return true;
  32. }
  33. bool pop(T *data) {
  34. if (isEmpty()) {
  35. return false;
  36. }
  37. memcpy(data, &arr[front], sizeof(T));
  38. front = (front + 1) % maxSize;
  39. return true;
  40. }
  41. bool popMuti(T *data, int numdata) {
  42. if (numdata > numElements()) return false;
  43. for (int i = 0; i < numdata; i++) {
  44. pop(&data[i]);
  45. }
  46. return true;
  47. }
  48. bool getHeader(T *data) {
  49. if (isEmpty()) {
  50. return false;
  51. }
  52. memcpy(data, &arr[front], sizeof(T));
  53. return true;
  54. }
  55. int size() { return maxSize; }
  56. int numElements() { return (rear + maxSize - front) % maxSize; }
  57. bool isEmpty() { return rear == front; }
  58. bool isFull() { return (rear + 1) % maxSize == front; }
  59. };
  60. } // namespace iflytop