1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- #include "tr_queue.h"
-
- tr_queue::tr_queue(unsigned int size):m_nsize(size),m_nin(0),m_nout(0),m_pbuffer(nullptr)
- {
- if (!is_power_of_2(size))
- {
- m_nsize = roundup_power_of_two(size);
- }
- }
- tr_queue::~tr_queue()
- {
- if (nullptr != m_pbuffer)
- {
- delete[] m_pbuffer;
- m_pbuffer = nullptr;
- }
- }
- bool tr_queue::initialize()
- {
- m_pbuffer = new unsigned char[m_nsize];
- if (!m_pbuffer)
- return false;
- m_nin = m_nout = 0;
- return true;
- }
- unsigned long tr_queue::roundup_power_of_two(unsigned long val)
- {
- if ((val & (val-1)) == 0)
- return val;
- unsigned long maxulong = (unsigned long )((unsigned long ) ~0);
- unsigned long andv = ~(maxulong&(maxulong>>1));
- while((andv & val) == 0)
- andv = andv>>1;
- return andv<<1;
- }
- unsigned int tr_queue::get(unsigned char *_buffer, unsigned int len)
- {
- unsigned int l;
- len = std::min(len, m_nin - m_nout);
- __sync_synchronize();
-
- l = std::min(len, m_nsize -(m_nout&(m_nsize-1)));
- memcpy(_buffer,m_pbuffer + (m_nout& (m_nsize-1)),l);
- memcpy(_buffer + l,m_pbuffer,len - l);
-
- __sync_synchronize();
-
- m_nout +=len;
- return len;
-
- }
- unsigned int tr_queue::put(const unsigned char *_buffer, unsigned int len)
- {
- unsigned int l;
- len = std::min(len, m_nsize - m_nin + m_nout);
- __sync_synchronize();
- l = std::min(len, m_nsize - (m_nin & (m_nsize - 1)));
- memcpy(m_pbuffer + (m_nin & (m_nsize - 1)), _buffer, l);
- memcpy(m_pbuffer, _buffer + l, len - l);
- __sync_synchronize();
- m_nin += len;
- return len;
-
- }
|