CircularBuffer
CircularBuffer provides a general-purpose circular buffer data structure.
# Create a new circular buffer that holds 5 elements
iex> cb = CircularBuffer.new(5)
CircularBuffer.new([], 5)
# Fill it up
iex> cb = Enum.into(1..5, cb)
CircularBuffer.new([1, 2, 3, 4, 5], 5)
# Verify that 1 is the oldest and 5 is the newest element in the buffer
iex> CircularBuffer.oldest(cb)
1
iex> CircularBuffer.newest(cb)
5
# Add another element. 1 gets pushed out.
iex> cb = CircularBuffer.insert(cb, 6)
CircularBuffer.new([2, 3, 4, 5, 6], 5)
# CircularBuffer implements Enumerable so all Enum.* functions work
iex> Enum.sum(cb)
20
Installation
def deps do
[
{:circular_buffer, "~> 1.0"}
]
end
Should I use this?
The entire codebase consists of one file, has been property-tested, and has been
in production for several years. Its implementation is similar to Erlang’s
queue module but
simplified for the circular buffer use case.