tr_queue.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "tr_queue.h"
  2. tr_queue::tr_queue(unsigned int size):m_nsize(size),m_nin(0),m_nout(0),m_pbuffer(nullptr)
  3. {
  4. if (!is_power_of_2(size))
  5. {
  6. m_nsize = roundup_power_of_two(size);
  7. }
  8. }
  9. tr_queue::~tr_queue()
  10. {
  11. if (nullptr != m_pbuffer)
  12. {
  13. delete[] m_pbuffer;
  14. m_pbuffer = nullptr;
  15. }
  16. }
  17. bool tr_queue::initialize()
  18. {
  19. m_pbuffer = new unsigned char[m_nsize];
  20. if (!m_pbuffer)
  21. return false;
  22. m_nin = m_nout = 0;
  23. return true;
  24. }
  25. unsigned long tr_queue::roundup_power_of_two(unsigned long val)
  26. {
  27. if ((val & (val-1)) == 0)
  28. return val;
  29. unsigned long maxulong = (unsigned long )((unsigned long ) ~0);
  30. unsigned long andv = ~(maxulong&(maxulong>>1));
  31. while((andv & val) == 0)
  32. andv = andv>>1;
  33. return andv<<1;
  34. }
  35. unsigned int tr_queue::get(unsigned char *_buffer, unsigned int len)
  36. {
  37. unsigned int l;
  38. len = std::min(len, m_nin - m_nout);
  39. __sync_synchronize();
  40. l = std::min(len, m_nsize -(m_nout&(m_nsize-1)));
  41. memcpy(_buffer,m_pbuffer + (m_nout& (m_nsize-1)),l);
  42. memcpy(_buffer + l,m_pbuffer,len - l);
  43. __sync_synchronize();
  44. m_nout +=len;
  45. return len;
  46. }
  47. unsigned int tr_queue::put(const unsigned char *_buffer, unsigned int len)
  48. {
  49. unsigned int l;
  50. len = std::min(len, m_nsize - m_nin + m_nout);
  51. __sync_synchronize();
  52. l = std::min(len, m_nsize - (m_nin & (m_nsize - 1)));
  53. memcpy(m_pbuffer + (m_nin & (m_nsize - 1)), _buffer, l);
  54. memcpy(m_pbuffer, _buffer + l, len - l);
  55. __sync_synchronize();
  56. m_nin += len;
  57. return len;
  58. }