1
1

wrappedBuffer.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #pragma once
  2. #include <string>
  3. template <typename T, int SIZE =10>
  4. class WrappedBuffer
  5. {
  6. public:
  7. WrappedBuffer();
  8. virtual ~WrappedBuffer();
  9. void put(T item);
  10. void pop_back();
  11. unsigned int size() const;
  12. std::basic_string<T> toString() const;
  13. T* toArray(T arr[SIZE]) const;
  14. protected:
  15. T buffer[SIZE];
  16. int curR;
  17. int curW;
  18. };
  19. template<typename T, int SIZE>
  20. WrappedBuffer<T, SIZE>::WrappedBuffer(): curR(0), curW(-1)
  21. { }
  22. template<typename T, int SIZE>
  23. WrappedBuffer<T, SIZE>::~WrappedBuffer()
  24. { }
  25. template<typename T, int SIZE>
  26. void WrappedBuffer<T, SIZE>::put(T item)
  27. {
  28. if (curW +1 == SIZE)
  29. {
  30. curR = 1;
  31. curW = 0;
  32. buffer[0] = item;
  33. }
  34. else if (curW == -1)
  35. {
  36. curR = SIZE;
  37. buffer[curW = 0] = item;
  38. }
  39. else
  40. {
  41. buffer[++curW] = item;
  42. if (curR == curW)
  43. {
  44. if (++curR > SIZE)
  45. curR = 0;
  46. }
  47. }
  48. }
  49. template<typename T, int SIZE>
  50. void WrappedBuffer<T, SIZE>::pop_back()
  51. {
  52. unsigned int oldSize = size();
  53. if (oldSize == 0)
  54. return;
  55. else if (oldSize == 1)
  56. {
  57. curW = -1;
  58. curR = 0;
  59. }
  60. else if (--curW < 0)
  61. {
  62. curW += SIZE;
  63. }
  64. }
  65. template<typename T, int SIZE>
  66. unsigned int WrappedBuffer<T, SIZE>::size() const
  67. {
  68. if (curW == -1)
  69. return 0;
  70. return (curR > curW) ? (SIZE - curR + curW +1) : (curW - curR +1);
  71. }
  72. template<typename T, int SIZE>
  73. std::basic_string<T> WrappedBuffer<T, SIZE>::toString() const
  74. {
  75. std::basic_string<T> result(size(), (T) 0);
  76. const unsigned int size = this->size();
  77. int from = (curR == SIZE) ? 0 : curR;
  78. unsigned int j = 0;
  79. for (int i = from; (curW > curR && i <= curW) || (curW <= curR && i < SIZE); ++i)
  80. result[j++] = buffer[i];
  81. for (int i = 0; j < size; ++i)
  82. result[j++] = buffer[i];
  83. return result;
  84. }
  85. template<typename T, int SIZE>
  86. T* WrappedBuffer<T, SIZE>::toArray(T arr[SIZE]) const
  87. {
  88. if (!arr)
  89. arr = new T[SIZE]();
  90. //TODO
  91. return arr;
  92. }