Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>With a circular buffer, there are at least two ways to distinguish a full state from an empty one (<code>head == tail</code> in both those cases).</p> <ol> <li><p>Allow for one more item in the buffer than you actually need and don't ever let <code>head</code> advance to <code>tail</code> when adding (raise a "buffer full" error instead). That way, <code>head == tail</code> <em>always</em> means empty.</p></li> <li><p>Maintain a "free slots" variable as well as the head and tail, initialising it to the size of the buffer, decrementing it when adding and incrementing when removing. That way you can detect buffer full by the fact that it's set to zero, or buffer empty if it's set to the original size.</p></li> </ol> <hr> <p>For option 1, something like:</p> <pre><code>def buffInit(sz): global buffSz = sz global buffData = alloc(buffSz+1) # allow for extra slot. global buffHead = 0 global buffTail = 0 def buffAdd(item): if (buffHead + 1) % buffSz == buffTail: # never fill extra slot. return BUFFER_FULL buffData[buffHead] = item buffHead = (buffHead + 1) % buffSz return OK def buffGet(): if buffHead == buffTail: return BUFFER_EMPTY item = buffData[buffHead] buffHead = (buffHead + 1) % buffSz return item </code></pre> <hr> <p>For option 2, something like:</p> <pre><code>def buffInit(sz): global buffSz = sz global buffFree = buffSz # extra information. global buffData = alloc(buffSz) global buffHead = 0 global buffTail = 0 def buffAdd(item): if buffFree == 0: # zero free slots means full. return BUFFER_FULL buffData[buffHead] = item buffHead = (buffHead + 1) % buffSz buffFree = buffFree - 1 # keep in sync. return OK def buffGet(): if buffFree == buffSz: return BUFFER_EMPTY item = buffData[buffHead] buffHead = (buffHead + 1) % buffSz buffFree = buffFree + 1 # keep in sync. return item </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload