Circular buffer
Circular buffer
Jump to navigation
Jump to search
This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages)
(Learn how and when to remove this template message) |
A circular buffer, circular queue, cyclic buffer or ring buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end.
This structure lends itself easily to buffering data streams.
Contents
1 Uses
2 How it works
3 Circular buffer mechanics
4 Fixed-length-element and contiguous-block circular buffer
5 References
6 External links
Uses[edit]
The useful property of a circular buffer is that it does not need to have its elements shuffled around when one is consumed.
(If a non-circular buffer were used then it would be necessary to shift all elements when one is consumed.)
In other words, the circular buffer is well-suited as a FIFO buffer while a standard, non-circular buffer is well suited as a LIFO buffer.
Circular buffering makes a good implementation strategy for a queue that has fixed maximum size. Should a maximum size be adopted for a queue, then a circular buffer is a completely ideal implementation; all queue operations are constant time. However, expanding a circular buffer requires shifting memory, which is comparatively costly. For arbitrarily expanding queues, a linked list approach may be preferred instead.
In some situations, overwriting circular buffer can be used, e.g. in multimedia. If the buffer is used as the bounded buffer in the producer-consumer problem then it is probably desired for the producer (e.g., an audio generator) to overwrite old data if the consumer (e.g., the sound card) is unable to momentarily keep up. Also, the LZ77 family of lossless data compression algorithms operates on the assumption that strings seen more recently in a data stream are more likely to occur soon in the stream. Implementations store the most recent data in a circular buffer.
How it works[edit]
A circular buffer first starts empty and of some predefined length.
For example, this is a 7-element buffer:
Assume that a 1 is written into the middle of the buffer (exact starting location does not matter in a circular buffer):
Then assume that two more elements are added — 2 & 3 — which get appended after the 1:
If two elements are then removed from the buffer, the oldest values inside the buffer are removed.
The two elements removed, in this case, are 1 & 2, leaving the buffer with just a 3:
If the buffer has 7 elements then it is completely full:
A consequence of the circular buffer is that when it is full and a subsequent write is performed, then it starts overwriting the oldest data.
In this case, two more elements — A & B — are added and they overwrite the 3 & 4:
Alternatively, the routines that manage the buffer could prevent overwriting the data and return an error or raise an exception.
Whether or not data is overwritten is up to the semantics of the buffer routines or the application using the circular buffer.
Finally, if two elements are now removed then what would be returned is not 3 & 4 but 5 & 6 because A & B overwrote the 3 & the 4 yielding the buffer with:
Circular buffer mechanics[edit]
A circular buffer can be implemented using four pointers, or two pointers and two integers:
- buffer start in memory
- buffer end in memory, or buffer capacity
- start of valid data (index or pointer)
- end of valid data (index or pointer), or amount of data currently in the buffer (integer)
This image shows a partially full buffer:
This image shows a full buffer with four elements (numbers 1 through 4) having been overwritten:
When an element is overwritten, the start pointer is incremented to the next element.
In utilizing full buffer capacity with pointer-based implementation strategy, the buffer's full or empty state could not be resolved directly from checking the positions of the start and end indexes.[1] Therefore, an additional mechanism must be implemented for checking this. One common way to deal with this, when using 2 pointers, is to only allow the buffer to hold (size - 1) items. When both pointers are equal, the buffer is empty, and when the end pointer is one less than the start pointer, the buffer is full.
When the buffer is instead designed to track the number of inserted elements n, checking for emptiness means checking n = 0 and checking for fullness means checking whether n equals the capacity.[2]
Incrementing and Decrementing the circular buffer address pointers is accomplishing in software using the following modulus formulas:
increment_address_one = (address + 1) % Length
decrement_address_one = (address + Length -1) % Length
Note, the extra Length addition for the decrement by one operation is required to prevent negative results and to ensure proper rollover the end address of the circular buffer.
Fixed-length-element and contiguous-block circular buffer[edit]
Perhaps the most common version of the circular buffer uses 8-bit bytes as elements.
Some implementations of the circular buffer use fixed-length elements that are bigger than 8-bit bytes—16-bit integers for audio buffers,
53-byte ATM cells for telecom buffers, etc.
Each item is contiguous and has the correct data alignment,
so software reading and writing these values can be faster than software that handles non-contiguous and non-aligned values.
Ping-pong buffering can be considered a very specialized circular buffer with exactly two large fixed-length elements.
The Bip Buffer (bipartite buffer) is very similar to a circular buffer, except it always returns contiguous blocks which can be variable length. This offers nearly all the efficiency advantages of a circular buffer while maintaining the ability for the buffer to be used in APIs that only accept contiguous blocks.[3]
Fixed-sized compressed circular buffers use an alternative indexing strategy based on elementary number theory to maintain a fixed-sized compressed representation of the entire data sequence.[4]
References[edit]
^ Chandrasekaran, Siddharth. "Implementing Circular/Ring Buffer in Embedded C". Embed Journal. EmbedJournal Team. Retrieved 14 August 2017..mw-parser-output cite.citation{font-style:inherit}.mw-parser-output q{quotes:"""""""'""'"}.mw-parser-output code.cs1-code{color:inherit;background:inherit;border:inherit;padding:inherit}.mw-parser-output .cs1-lock-free a{background:url("//upload.wikimedia.org/wikipedia/commons/thumb/6/65/Lock-green.svg/9px-Lock-green.svg.png")no-repeat;background-position:right .1em center}.mw-parser-output .cs1-lock-limited a,.mw-parser-output .cs1-lock-registration a{background:url("//upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Lock-gray-alt-2.svg/9px-Lock-gray-alt-2.svg.png")no-repeat;background-position:right .1em center}.mw-parser-output .cs1-lock-subscription a{background:url("//upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Lock-red-alt-2.svg/9px-Lock-red-alt-2.svg.png")no-repeat;background-position:right .1em center}.mw-parser-output .cs1-subscription,.mw-parser-output .cs1-registration{color:#555}.mw-parser-output .cs1-subscription span,.mw-parser-output .cs1-registration span{border-bottom:1px dotted;cursor:help}.mw-parser-output .cs1-hidden-error{display:none;font-size:100%}.mw-parser-output .cs1-visible-error{font-size:100%}.mw-parser-output .cs1-subscription,.mw-parser-output .cs1-registration,.mw-parser-output .cs1-format{font-size:95%}.mw-parser-output .cs1-kern-left,.mw-parser-output .cs1-kern-wl-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right,.mw-parser-output .cs1-kern-wl-right{padding-right:0.2em}
^ Morin, Pat. "ArrayQueue: An Array-Based Queue". Open Data Structures (in pseudocode). Retrieved 7 November 2015.
^ Simon Cooke (2003), "The Bip Buffer - The Circular Buffer with a Twist"
^ Gunther, John C. (March 2014). "Algorithm 938: Compressing circular buffers". ACM Transactions on Mathematical Software. 40 (2): 1–12. doi:10.1145/2559995.
External links[edit]
CircularBuffer at the Portland Pattern Repository
- Boost: Templated Circular Buffer Container
- Circular Buffering
- Circular queue in C
Categories:
- Computer memory
- Arrays
(window.RLQ=window.RLQ||).push(function(){mw.config.set({"wgPageParseReport":{"limitreport":{"cputime":"0.220","walltime":"0.294","ppvisitednodes":{"value":532,"limit":1000000},"ppgeneratednodes":{"value":0,"limit":1500000},"postexpandincludesize":{"value":36368,"limit":2097152},"templateargumentsize":{"value":5511,"limit":2097152},"expansiondepth":{"value":10,"limit":40},"expensivefunctioncount":{"value":3,"limit":500},"unstrip-depth":{"value":1,"limit":20},"unstrip-size":{"value":8349,"limit":5000000},"entityaccesscount":{"value":1,"limit":400},"timingprofile":["100.00% 222.718 1 -total"," 52.24% 116.338 3 Template:Ambox"," 46.47% 103.504 1 Template:Reflist"," 43.26% 96.356 1 Template:Multiple_issues"," 30.73% 68.435 2 Template:Cite_web"," 14.01% 31.212 1 Template:Tone"," 11.48% 25.561 1 Template:Cite_journal"," 5.64% 12.563 1 Template:Data_structures"," 4.69% 10.455 1 Template:Navbox"," 4.50% 10.023 1 Template:Refimprove"]},"scribunto":{"limitreport-timeusage":{"value":"0.111","limit":"10.000"},"limitreport-memusage":{"value":2597676,"limit":52428800}},"cachereport":{"origin":"mw1267","timestamp":"20181026163419","ttl":1900800,"transientcontent":false}}});mw.config.set({"wgBackendResponseTime":105,"wgHostname":"mw1270"});});