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:
parent
bf5a035024
commit
75a1b102fb
@ -1,20 +1,17 @@
|
|||||||
#include "RingBuffer.h"
|
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
|
|
||||||
/*
|
#include "RingBuffer.h"
|
||||||
implement a simple ringbuffer of bytes
|
|
||||||
*/
|
|
||||||
|
|
||||||
ByteBuffer::ByteBuffer(uint32_t _size)
|
ByteBuffer::ByteBuffer(uint32_t _size)
|
||||||
{
|
{
|
||||||
size = _size;
|
buf = (uint8_t*)malloc(_size);
|
||||||
buf = new uint8_t[size];
|
size = buf ? _size : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
ByteBuffer::~ByteBuffer(void)
|
ByteBuffer::~ByteBuffer(void)
|
||||||
{
|
{
|
||||||
delete [] buf;
|
free(buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@ -26,10 +23,10 @@ void ByteBuffer::set_size(uint32_t _size)
|
|||||||
|
|
||||||
head = tail = 0;
|
head = tail = 0;
|
||||||
if (_size != size) {
|
if (_size != size) {
|
||||||
size = _size;
|
|
||||||
oldbuf = buf;
|
oldbuf = buf;
|
||||||
buf = new uint8_t[size];
|
buf = (uint8_t*)malloc(_size);
|
||||||
delete[] oldbuf;
|
size = buf ? _size : 0;
|
||||||
|
free(oldbuf);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -41,8 +38,8 @@ uint32_t ByteBuffer::available(void) const
|
|||||||
|
|
||||||
uint32_t ByteBuffer::space(void) const
|
uint32_t ByteBuffer::space(void) const
|
||||||
{
|
{
|
||||||
uint32_t _head;
|
uint32_t _head = head;
|
||||||
return (((_head=head) > tail)?(_head - tail) - 1:((size - tail) + _head) - 1);
|
return size ? (_head > tail ? 0 : size) + _head - tail - 1 : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool ByteBuffer::empty(void) const
|
bool ByteBuffer::empty(void) const
|
||||||
|
Loading…
Reference in New Issue
Block a user