Let the capacity be a positive integer , and allocate exactly array slots . Store the front array index and count . The representation invariant is
The logical sequence and next-write array index are
Here denotes the nonnegative remainder from modular arithmetic. The count determines which slots are live: leftover bits in other slots are not members of the FIFO queue. If , has no current front item; it identifies the position where the next successful insertion begins. If , points at a live item, so writing there requires an explicit overwrite policy.
For , enqueue(x) writes , then increments , leaving fixed. For , dequeue() saves and returns , then sets and . These are sequential updates, completed before the next call. A rejecting interface tests or first and returns full or empty, respectively, without changing state. peek returns only when ; size returns .
One can instead store and , recovering . On insertion, advance and increment ; on removal, keep fixed and decrement . Thus the next-write array index is not necessarily the front array index.
Names such as head and tail require checking the actual API: the kernel documentation calls the insertion position head and the removal position tail.[ref]
Figure 1.
A wrapped circular buffer has one logical sequence across the end of its physical array
. Capacity five, front , count , and next-write index . Follow physical slots to read . Slot 1 still shows the removed label , but it is outside the live sequence. Details.
The diagram is the state after step 8 of circular buffer operation trace. Reading the physical array from slot zero would give , which includes a removed label and puts first. Reading from for exactly items gives . The next insertion uses slot , not slot . This distinction also explains why the live sequence may need two contiguous pieces of the array: here slots through , followed by slot . No items need to move to make this wrap work.

Articles by others on the same topic (0)

There are currently no matching articles.