#include "stdafx.h"
#include "CircleBuffer.h"
CircleBuffer::CircleBuffer(int MaxSize) : _size(MaxSize)
{
if(_size < 1) _size = 1;
Arr = new RADSIGSAMPLES[MaxSize];
_l = _c = _size - 1;
_cnt = 0;
_mutex = CreateMutex(NULL,FALSE,NULL);
}
CircleBuffer::~CircleBuffer()
{
delete []Arr;
Arr = NULL;
CloseHandle(_mutex);
}
int CircleBuffer::conv(int i)
{
return (i < _size) ? i : 0;
}
bool CircleBuffer::push(const RADSIGSAMPLES& ele)
{
if(_cnt < _size)
{
try
{
WaitForSingleObject(_mutex,INFINITE);
_l = conv(_l + 1);
Arr[_l] = ele;
_cnt++;
ReleaseMutex(_mutex);
return true;
}
catch (...)
{
ReleaseMutex(_mutex);
return false;
}
}
else return false;
}
bool CircleBuffer::push(const vector<RADSIGSAMPLES>& ele)
{
vector<RADSIGSAMPLES>::const_iterator SigIt;
try
{
WaitForSingleObject(_mutex, INFINITE);
for (SigIt = ele.begin(); SigIt != ele.end(); SigIt++)
{
_l = conv(_l + 1);
Arr[_l] = *SigIt;
_cnt++;
if (_cnt >= _size) break;
}
ReleaseMutex(_mutex);
return true;
}
catch (...)
{
ReleaseMutex(_mutex);
return false;
}
}
bool CircleBuffer::pop(RADSIGSAMPLES &ele)
{
if(_cnt == 0) return false;
else
{
try
{
WaitForSingleObject(_mutex,INFINITE);
_cnt--;
_c = conv(_c + 1);
ele = Arr[_c];
ReleaseMutex(_mutex);
return true;
}
catch (...)
{
ReleaseMutex(_mutex);
return false;
}
}
}
bool CircleBuffer::pop(std::vector<RADSIGSAMPLES> &ele, double tbegin, double tend)
{
ele.clear();
try
{
WaitForSingleObject(_mutex,INFINITE);
bool retFlag = false;
while (1)
{
if (_cnt == 0)
break;
if ( Arr[conv(_c + 1)].TimeIndex < tbegin)
{
_cnt--;
_c = conv(_c + 1);
}
if (Arr[conv(_c + 1)].TimeIndex < tend && Arr[conv(_c + 1)].TimeIndex >= tbegin)
{
_cnt--;
_c = conv(_c + 1);
ele.push_back(Arr[_c]) ;
}
if (Arr[conv(_c + 1)].TimeIndex >= tend)
{
retFlag = true;
break;
}
}
ReleaseMutex(_mutex);
return retFlag;
}
catch (...)
{
ReleaseMutex(_mutex);
return false;
}
}
int CircleBuffer::count()
{
return _cnt;
}
bool CircleBuffer::empty()
{
if(!_cnt) return true;
else return false;
}
bool CircleBuffer::full()
{
return (_cnt == _size) ? true : false;
}
int CircleBuffer::GetSize()
{
return _size;
}
void CircleBuffer::clear()
{
_l = _c = _size - 1;
_cnt = 0;
}