Looking to get some feedback on a simple non-multithreaded circular buffer.
Ideally, I'd want to have a logic to prevent the data from getting overwritten but couldn't find a reasonable way.
For instance, if the buffer size is 3 and Write
is invoked, it shouldn't proceed until the buffer is no longer full.
class Fifo
{
public:
void Write(uint8_t data)
{
mBuffer[mWriteIdx++] = data;
mWriteIdx %= BUFFER_SIZE;
mIsFull = mWriteIdx == mReadIdx;
}
uint8_t Read()
{
if (IsEmpty())
{
return 0; // considering 0 is an invalid data
}
uint8_t value = mBuffer[mReadIdx];
mBuffer[mReadIdx++] = 0; // null out the index
mReadIdx %= BUFFER_SIZE;
mIsFull = false;
return value;
}
private:
bool IsEmpty() const
{
return !mIsFull && mReadIdx == mWriteIdx;
}
// Member variables
int mReadIdx = 0;
int mWriteIdx = 0;
static constexpr int BUFFER_SIZE = 4;
uint8_t mBuffer[BUFFER_SIZE] = {0};
bool mIsFull = false;
};
Here's a sample program with outputs