vfs: check userland buffers before reading them.
[haiku.git] / src / add-ons / media / plugins / ape_reader / MAClib / CircleBuffer.cpp
blob5fde87ac774a4c823645eab1d8cc61d4656f481e
1 #include "All.h"
2 #include "CircleBuffer.h"
4 CCircleBuffer::CCircleBuffer()
6 m_pBuffer = NULL;
7 m_nTotal = 0;
8 m_nHead = 0;
9 m_nTail = 0;
10 m_nEndCap = 0;
11 m_nMaxDirectWriteBytes = 0;
14 CCircleBuffer::~CCircleBuffer()
16 SAFE_ARRAY_DELETE(m_pBuffer)
19 void CCircleBuffer::CreateBuffer(int nBytes, int nMaxDirectWriteBytes)
21 SAFE_ARRAY_DELETE(m_pBuffer)
23 m_nMaxDirectWriteBytes = nMaxDirectWriteBytes;
24 m_nTotal = nBytes + 1 + nMaxDirectWriteBytes;
25 m_pBuffer = new unsigned char [m_nTotal];
26 m_nHead = 0;
27 m_nTail = 0;
28 m_nEndCap = m_nTotal;
31 int CCircleBuffer::MaxAdd()
33 int nMaxAdd = (m_nTail >= m_nHead) ? (m_nTotal - 1 - m_nMaxDirectWriteBytes) - (m_nTail - m_nHead) : m_nHead - m_nTail - 1;
34 return nMaxAdd;
37 int CCircleBuffer::MaxGet()
39 return (m_nTail >= m_nHead) ? m_nTail - m_nHead : (m_nEndCap - m_nHead) + m_nTail;
42 int CCircleBuffer::Get(unsigned char * pBuffer, int nBytes)
44 int nTotalGetBytes = 0;
46 if (pBuffer != NULL && nBytes > 0)
48 int nHeadBytes = min(m_nEndCap - m_nHead, nBytes);
49 int nFrontBytes = nBytes - nHeadBytes;
51 memcpy(&pBuffer[0], &m_pBuffer[m_nHead], nHeadBytes);
52 nTotalGetBytes = nHeadBytes;
54 if (nFrontBytes > 0)
56 memcpy(&pBuffer[nHeadBytes], &m_pBuffer[0], nFrontBytes);
57 nTotalGetBytes += nFrontBytes;
60 RemoveHead(nBytes);
63 return nTotalGetBytes;
66 void CCircleBuffer::Empty()
68 m_nHead = 0;
69 m_nTail = 0;
70 m_nEndCap = m_nTotal;
73 int CCircleBuffer::RemoveHead(int nBytes)
75 nBytes = min(MaxGet(), nBytes);
76 m_nHead += nBytes;
77 if (m_nHead >= m_nEndCap)
78 m_nHead -= m_nEndCap;
79 return nBytes;
82 int CCircleBuffer::RemoveTail(int nBytes)
84 nBytes = min(MaxGet(), nBytes);
85 m_nTail -= nBytes;
86 if (m_nTail < 0)
87 m_nTail += m_nEndCap;
88 return nBytes;