icinga2/base/fifo.cpp

98 lines
1.6 KiB
C++
Raw Normal View History

2012-03-28 13:24:49 +02:00
#include "i2-base.h"
using namespace icinga;
FIFO::FIFO(void)
{
m_Buffer = NULL;
m_DataSize = 0;
m_AllocSize = 0;
2012-03-28 13:24:49 +02:00
m_Offset = 0;
}
FIFO::~FIFO(void)
{
Memory::Free(m_Buffer);
}
void FIFO::ResizeBuffer(size_t newSize)
2012-03-28 13:24:49 +02:00
{
if (m_AllocSize >= newSize)
return;
2012-03-28 13:24:49 +02:00
newSize = (newSize / FIFO::BlockSize + 1) * FIFO::BlockSize;
2012-03-28 13:24:49 +02:00
m_Buffer = (char *)Memory::Reallocate(m_Buffer, newSize);
m_AllocSize = newSize;
2012-03-28 13:24:49 +02:00
}
void FIFO::Optimize(void)
{
//char *newBuffer;
2012-03-28 13:24:49 +02:00
if (m_DataSize < m_Offset) {
memcpy(m_Buffer, m_Buffer + m_Offset, m_DataSize);
2012-03-28 13:24:49 +02:00
m_Offset = 0;
return;
}
/*newBuffer = (char *)ResizeBuffer(NULL, 0, m_BufferSize - m_Offset);
2012-03-28 13:24:49 +02:00
if (newBuffer == NULL)
return;
memcpy(newBuffer, m_Buffer + m_Offset, m_BufferSize - m_Offset);
free(m_Buffer);
m_Buffer = newBuffer;
m_BufferSize -= m_Offset;
m_Offset = 0;*/
2012-03-28 13:24:49 +02:00
}
size_t FIFO::GetSize(void) const
{
return m_DataSize;
2012-03-28 13:24:49 +02:00
}
2012-03-28 19:50:55 +02:00
const void *FIFO::GetReadBuffer(void) const
2012-03-28 13:24:49 +02:00
{
return m_Buffer + m_Offset;
}
size_t FIFO::Read(void *buffer, size_t count)
{
count = (count <= m_DataSize) ? count : m_DataSize;
2012-03-28 13:24:49 +02:00
if (buffer != NULL)
memcpy(buffer, m_Buffer + m_Offset, count);
m_DataSize -= count;
2012-03-28 13:24:49 +02:00
m_Offset += count;
Optimize();
return count;
}
void *FIFO::GetWriteBuffer(size_t *count)
2012-03-28 13:24:49 +02:00
{
ResizeBuffer(m_Offset + m_DataSize + *count);
*count = m_AllocSize - m_Offset - m_DataSize;
2012-03-28 19:50:55 +02:00
return m_Buffer + m_Offset + m_DataSize;
2012-03-28 19:50:55 +02:00
}
size_t FIFO::Write(const void *buffer, size_t count)
{
if (buffer != NULL) {
size_t bufferSize = count;
void *target_buffer = GetWriteBuffer(&bufferSize);
2012-03-28 19:50:55 +02:00
memcpy(target_buffer, buffer, count);
}
m_DataSize += count;
2012-03-28 19:50:55 +02:00
2012-03-28 13:24:49 +02:00
return count;
}