How it works
This section shows different buffer corner cases and provides basic understanding how data are managed internally.
Different buffer corner cases
Let’s start with reference of abbreviations in picture:
Rrepresents Read pointer. Read on read/write operations. Modified on read operation onlyWrepresents Write pointer. Read on read/write operations. Modified on write operation onlySrepresents Size of buffer. Used on all operations, never modified (atomic value)Valid number of
WandRpointers are between0andS - 1
Buffer size is
S = 8, thus valid number range forWandRpointers is0 - 7.RandWnumbers overflow atS, thus valid range is always0, 1, 2, 3, ..., S - 2, S - 1, 0, 1, 2, 3, ..., S - 2, S - 1, 0, ...Example
S = 4:0, 1, 2, 3, 0, 1, 2, 3, 0, 1, ...
Maximal number of bytes buffer can hold is always
S - 1, thus example buffer can hold up to7bytesRandWpointers always point to the next read/write operationWhen
W == R, buffer is considered empty.When
W == R - 1, buffer is considered full.W == R - 1is valid only ifWandRoverflow at buffer sizeS.Always add
Sto calculated number and then use modulusSto get final value
Note
Example 1, add 2 numbers: 2 + 3 = (3 + 2 + S) % S = (3 + 2 + 4) % 4 = (5 + 4) % 4 = 1
Example 2, subtract 2 numbers: 2 - 3 = (2 - 3 + S) % S = (2 - 3 + 4) % 4 = (-1 + 4) % 4 = 3
Different buffer corner cases
Different image cases:
Case A: Buffer is empty as
W == R = 0 == 0Case B: Buffer holds
W - R = 4 - 0 = 4bytes asW > RCase C: Buffer is full as
W == R - 1or7 == 0 - 1or7 = (0 - 1 + S) % S = (0 - 1 + 8) % 8 = (-1 + 8) % 8 = 7RandWcan holdSdifferent values, from0toS - 1, that is modulus ofSBuffer holds
W - R = 7 - 0 = 7bytes asW > R
Case D: Buffer holds
S - (R - W) = 8 - (5 - 3) = 6bytes asR > WCase E: Buffer is full as
W == R - 1(4 = 5 - 1) and holdsS - (R - W) = 8 - (5 - 4) ) = 7bytes