ringbuffer/ringbuffer.cpp

88 lines
1.9 KiB
C++

#include "ringbuffer.h"
#include <cstdlib>
#include <cstring>
#include <cstddef>
Ringbuffer::Ringbuffer()
{
Ringbuffer(1024*1024);
}
Ringbuffer::Ringbuffer(size_t size)
{
this->headptr = (unsigned char*)(malloc(size));
this->pSize = size;
this->endptr = this->headptr + size;
this->readptr = this->headptr;
this->writeptr = this->headptr;
}
Ringbuffer::~Ringbuffer()
{
free(headptr);
headptr=endptr=0;
readptr=writeptr=0;
}
size_t Ringbuffer::size() const
{
return pSize;
}
size_t Ringbuffer::size_free()
{
return pSize - size_used();
}
size_t Ringbuffer::size_used()
{
if(writeptr>=readptr){
return writeptr - readptr;
}
return (writeptr-headptr) + (endptr - readptr);
}
size_t Ringbuffer::read(void *buf, size_t bufSize)
{
size_t currentStored = size_used();
if(currentStored == 0){
return 0;
}
size_t read = currentStored>=bufSize?bufSize:currentStored;
if(readptr + read <= endptr){
memcpy(buf, readptr, read);
readptr = readptr + read;
} else {
// read with two step
size_t first_size = endptr - readptr;
size_t second_size = read - first_size;
memcpy(buf, readptr, first_size);
unsigned char* buf_n = (unsigned char*)(buf) + first_size;
memcpy(buf_n, headptr, second_size);
readptr = headptr + second_size;
}
return read;
}
bool Ringbuffer::write(void *buf, size_t bufSize)
{
size_t free = size_free();
if(free < bufSize){
return false;
}
if(writeptr + bufSize <= endptr){
memcpy(writeptr, buf, bufSize);
writeptr = writeptr + bufSize;
} else {
//write with two step
size_t first_size = endptr - writeptr;
size_t second_size = bufSize - first_size;
memcpy(writeptr, buf, first_size);
memcpy(headptr, (unsigned char*)buf+first_size, second_size);
writeptr = headptr + second_size;
}
return true;
}