Advertisement
tyotyotyo

StaticFIFO

Jun 10th, 2022
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.77 KB | None | 0 0
  1. template<typename _type, size_t capacity>
  2. class StaticFIFO
  3. {
  4.     size_t m_allocated = capacity;
  5.     size_t m_size = 0;
  6.     size_t m_head = 0;
  7.     size_t m_tail = 0; // must point to free cell
  8.     _type* m_data = nullptr;
  9. public:
  10.     StaticFIFO()
  11.     {
  12.         if (!m_allocated)
  13.             m_allocated = 1;
  14.  
  15.         m_data = new _type[m_allocated];
  16.     }
  17.  
  18.     ~StaticFIFO()
  19.     {
  20.         if (m_data)
  21.             delete[] m_data;
  22.     }
  23.  
  24.     bool Add(const _type& object)
  25.     {
  26.         if (m_size == m_allocated)
  27.             return false;
  28.    
  29.         m_data[m_tail] = object;
  30.         ++m_size;
  31.  
  32.         ++m_tail;
  33.         if (m_tail == m_allocated)
  34.             m_tail = 0;
  35.         return true;
  36.     }
  37.  
  38.     bool Get(_type& object)
  39.     {
  40.         if (!m_size)
  41.             return false;
  42.  
  43.         object = m_data[m_head];
  44.         --m_size;
  45.  
  46.         ++m_head;
  47.         if (m_head == m_allocated)
  48.             m_head = 0;
  49.         return true;
  50.     }
  51. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement