1 2 3 4 5
|
void push(T x)
{
write_pos %= SZ; // write_pos is now valid
data[write_pos++] = x; // You increment write_pos, which might make it invalid.
}
|
So the
write_pos is only valid between these two statements. That means code like:
1 2 3 4
|
int getWritePos()
{
return write_pos;
}
|
is incorrect because write_pos may be invalid.
You want write_pos to always be valid, except perhaps when it's getting updated:
1 2 3 4 5
|
void push(T x)
{
data[write_pos++] = x;
if (write_pos >= SZ) write_pos = 0; // faster than %
}
|
Do the same sort of thing with read_pos.
Now, let's work on computing how many items are in the buffer. Once you have this, deciding if you can read or write to the buffer is easy.
Normally, the size of the buffer (the number of items in it) is just the difference between the pointers:
size = write_pos - read_pos
. Check that for off-by-one errors. A new buffer is empty and write_pos == read_pos == 0, so that's good.
The formula falls apart when the buffer wraps around. That's when
write_pos < read_pos. In that case, the size is
(write_pos - read_pos) + SZ
Create a method that returns the size of the buffer.
Then modify push() and pop() to use size() to check for an overflow or underflow. You'll have to decide what to do when it underflows or overflows.
Finally, modify showbuffer to print only the items that are actually in the buffer. In other words, skip the unused slots.