RingBuffer: Handle zero sized better

Sometimes (like in DataFlash) the size of the ring buffer will be
determined in run time and the object can have size zero until proper
initialization. When this was the case, an underflow in ::get_size would
mess with the initializing algorithm.

Another issue was that the 'new' operator could fail what was not being
handled. Now, we only set the size member after we are sure 'new'
successfully allocated memory.
This commit is contained in:
Murilo Belluzzo 2016-07-29 17:55:20 -03:00 committed by Lucas De Marchi
parent bf5a035024
commit 75a1b102fb

View File

@ -1,20 +1,17 @@
#include "RingBuffer.h"
#include <stdlib.h>
#include <string.h>
/*
implement a simple ringbuffer of bytes
*/
#include "RingBuffer.h"
ByteBuffer::ByteBuffer(uint32_t _size)
{
size = _size;
buf = new uint8_t[size];
buf = (uint8_t*)malloc(_size);
size = buf ? _size : 0;
}
ByteBuffer::~ByteBuffer(void)
{
delete [] buf;
free(buf);
}
/*
@ -26,10 +23,10 @@ void ByteBuffer::set_size(uint32_t _size)
head = tail = 0;
if (_size != size) {
size = _size;
oldbuf = buf;
buf = new uint8_t[size];
delete[] oldbuf;
buf = (uint8_t*)malloc(_size);
size = buf ? _size : 0;
free(oldbuf);
}
}
@ -41,8 +38,8 @@ uint32_t ByteBuffer::available(void) const
uint32_t ByteBuffer::space(void) const
{
uint32_t _head;
return (((_head=head) > tail)?(_head - tail) - 1:((size - tail) + _head) - 1);
uint32_t _head = head;
return size ? (_head > tail ? 0 : size) + _head - tail - 1 : 0;
}
bool ByteBuffer::empty(void) const