// CirBuffer.cpp: implementation of the CCirBuffer class. // // #include "stdafx.h" #include "CirBuffer.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif // // Construction/Destruction // CCirBuffer::CCirBuffer() { m_iSize=0; m_iReadPointer=0; m_iWritePointer=0; m_iLen=0; m_iOverflow=0; m_iUnderflow=0; } CCirBuffer::CCirBuffer(int size) { pBuf = new unsigned char[size]; m_iSize=size; m_iReadPointer=0; m_iWritePointer=0; m_iLen=0; m_iOverflow=0; m_iUnderflow=0; } CCirBuffer::~CCirBuffer() { if(m_iSize!=0) delete[] pBuf; } int CCirBuffer::ReadBuffer(unsigned char *pBufDes, int len) { if(len>m_iLen) { m_iUnderflow++; return -1; } if(m_iReadPointer+len<=m_iSize) memcpy(pBufDes, pBuf+m_iReadPointer, len); else { int iTemp=m_iSize-m_iReadPointer; memcpy(pBufDes, pBuf+m_iReadPointer, iTemp); memcpy(pBufDes+iTemp, pBuf, len-iTemp); } m_iReadPointer+=len; m_iReadPointer%=m_iSize; m_criticalSec.Lock(); m_iLen-=len; m_criticalSec.Unlock(); return 0; } int CCirBuffer::WriteBuffer(unsigned char *pSrc, int len) { if(len>m_iSize-m_iLen) { m_iOverflow++; TRACE("OVERFLOW %dn",m_iOverflow); return -1; } if(m_iWritePointer+len<=m_iSize) { memcpy(pBuf+m_iWritePointer, pSrc, len); } else { int iTemp = m_iSize-m_iWritePointer; memcpy(pBuf+m_iWritePointer, pSrc, iTemp); memcpy(pBuf, pSrc+iTemp, len-iTemp); } m_iWritePointer+=len; m_iWritePointer%=m_iSize; m_criticalSec.Lock(); m_iLen+=len; m_criticalSec.Unlock(); return 0; } void CCirBuffer::Reset() { m_iReadPointer=0; m_iWritePointer=0; m_iLen=0; m_iOverflow=0; m_iUnderflow=0; } int CCirBuffer::ReadBufferAll(unsigned char *pBufDes, int len) { if(len>m_iLen) { this->ReadBuffer(pBufDes, m_iLen); return m_iLen; } else { this->ReadBuffer(pBufDes, len); return len; } } int CCirBuffer::GetRemainedSpace() { return (m_iSize-m_iLen); }
转载请注明原文地址: https://ju.6miu.com/read-700045.html