 ## to Circular Buffer in the Lua Track

Published at Jul 13 2018 · 2 comments
Instructions
Test suite
Solution

A circular buffer, cyclic buffer or ring buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end.

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:

``````
``````

When the buffer is full an error will be raised, alerting the client that further writes are blocked until a slot becomes free.

When the buffer is full, the client can opt to overwrite the oldest data with a forced write. In this case, two more elements — A & B — are added and they overwrite the 3 & 4:

``````[A][B]
``````

3 & 4 have been replaced by A & B making 5 now the oldest data in the buffer. Finally, if two elements are removed then what would be returned is 5 & 6 yielding the buffer:

``````[ ][A][B][ ]
``````

Because there is space available, if the client again uses overwrite to store C & D then the space where 5 & 6 were stored previously will be used not the location of 7 & 8. 7 is still the oldest element and the buffer is once again full.

``````[D][A][B][C]
``````

## Running the tests

To run the tests, run the command `busted` from within the exercise directory.

## Further information

For more detailed information about the Lua track, including how to get help if you're having trouble, please visit the exercism.io Lua language page.

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### circular-buffer_spec.lua

``````local CircularBuffer = require('circular-buffer')

describe('circular-buffer', function()
it('reading an empty buffer throws a BufferEmptyException', function()
local buffer = CircularBuffer:new(1)
assert.has_error((function() buffer:read() end), 'buffer is empty')
end)

it('write and read back one item', function()
local buffer = CircularBuffer:new(1)
buffer:write('1')
assert.has_error((function() buffer:read() end), 'buffer is empty')
end)

it('write and read back multiple items', function()
local buffer = CircularBuffer:new(2)
buffer:write('1')
buffer:write('2')
assert.has_error((function() buffer:read() end), 'buffer is empty')
end)

it('clearing a buffer', function()
local buffer = CircularBuffer:new(2)
buffer:write('1')
buffer:write('2')
buffer:clear()
assert.has_error((function() buffer:read() end), 'buffer is empty')
buffer:write('3')
buffer:write('4')
end)

local buffer = CircularBuffer:new(2)
buffer:write('1')
buffer:write('2')
end)

local buffer = CircularBuffer:new(3)
buffer:write('1')
buffer:write('2')
buffer:write('3')
end)

it('writes of nil do not occupy buffer', function()
local buffer = CircularBuffer:new(3)
buffer:write(nil)
for i = 1, 3 do
buffer:write(tostring(i))
end
end)

it('writing to a full buffer throws a BufferFullException', function()
local buffer = CircularBuffer:new(2)
buffer:write('1')
buffer:write('2')
assert.has_error((function() buffer:write('A') end), 'buffer is full')
end)

it('forced writes over write oldest item in a full buffer', function()
local buffer = CircularBuffer:new(2)
buffer:write('1')
buffer:write('2')
buffer:forceWrite('A')
assert.has_error((function() buffer:read() end), 'buffer is empty')
end)

it('forced writes act like normal writes in a non-full buffer', function()
local buffer = CircularBuffer:new(2)
buffer:write('1')
buffer:forceWrite('2')
assert.has_error((function() buffer:read() end), 'buffer is empty')
end)

it('alternate force write and read into full buffer', function()
local buffer = CircularBuffer:new(5)
for i = 1, 3 do
buffer:write(tostring(i))
end
buffer:write('4')
for i = 5, 8 do
buffer:write(tostring(i))
end
buffer:forceWrite('A')
buffer:forceWrite('B')
assert.has_error((function() buffer:read() end), 'buffer is empty')
end)
end)``````
``````--------------------------------------------------------------------
--! @file
--! @brief Circular Buffer
---------------------------------------------------------------------
local CircularBuffer = {}
CircularBuffer.__index = CircularBuffer

local function nextIndex(index, length)
index = (index + 1) % (length + 1)
return (index > 0) and index or 1
end

local function write(self, value, writeIsForced)
if not (self or value) then return end
assert(writeIsForced or false or self.length < self.bufferLength, "buffer is full")

if(self.length == self.bufferLength) then
self.tail = nextIndex(self.tail, self.bufferLength)
else
self.length = self.length + 1
end
end

function CircularBuffer:new(bufferLength)
return setmetatable(
{ bufferLength = bufferLength,
length = 0,
buffer = {},
tail = 1
},
CircularBuffer)
end

assert(self.length > 0, "buffer is empty")
local value = self.buffer[self.tail]
self.tail = nextIndex(self.tail, self.bufferLength)
self.length = self.length - 1
return value
end

function CircularBuffer:write(value)
write(self, value)
end

function CircularBuffer:clear()
self.length = 0
end

function CircularBuffer:forceWrite(value)
write(self, value, true)
end

return CircularBuffer`````` One neat trick I played in my solution to keep things a bit simpler was to not restrict my head/tail indices to 0-len. This makes it very clear when it is empty or full because if head is equal to tail it is always empty since the indices don't wrap back around. The downside of this is that if you were to use the circular buffer for a very, very long time the indices could get too large, but that's something like 4.5 quadrillion insertions. This code will be someone else's problem long before then :) Your `nextIndex` function can be simpler to stay in the range (1,length):

``````local function nextIndex(index, length)
return (index % length) + 1
end
``````

suppose length=10. Then when index=9, the nextIndex function returns 10, and the nextIndex after that will be 1.

### What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

• What compromises have been made?