Current section
Files
Jump to
Current section
Files
circular_buffer
README.md
README.md
<!--
SPDX-FileCopyrightText: None
SPDX-License-Identifier: CC0-1.0
-->
# CircularBuffer
[](https://hex.pm/packages/circular_buffer)
[](https://circular-buffer.hexdocs.pm/CircularBuffer.html)
[](https://github.com/elixir-toniq/circular_buffer/actions/workflows/elixir.yml)
[](https://api.reuse.software/info/github.com/elixir-toniq/circular_buffer)
CircularBuffer provides a general-purpose circular buffer data structure.
```elixir
# 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
```elixir
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`](https://www.erlang.org/docs/28/apps/stdlib/queue.html) module but
simplified for the circular buffer use case.