# `CircularBuffer`
[🔗](https://github.com/elixir-toniq/circular_buffer/blob/v1.0.1/lib/circular_buffer.ex#L7)

Circular Buffer

When creating a circular buffer you must specify the max size:

```
cb = CircularBuffer.new(10)
```

CircularBuffers are implemented as Okasaki queues like Erlang's `:queue`
module, but with additional optimizations thanks to the reduced set
of operations.

CircularBuffer implements both the
[`Enumerable`](https://hexdocs.pm/elixir/Enumerable.html) and
[`Collectable`](https://hexdocs.pm/elixir/Collectable.html) protocols, so code
like the following works:

    iex> cb = Enum.into([1, 2, 3, 4], CircularBuffer.new(3))
    #CircularBuffer<[2, 3, 4]>
    iex> Enum.map(cb, fn x -> x * 2 end)
    [4, 6, 8]

# `t`

```elixir
@opaque t()
```

A circular buffer

# `empty?`

```elixir
@spec empty?(t()) :: boolean()
```

Checks the buffer to see if its empty

Returns `true` if the given circular buffer is empty, otherwise `false`.

## Examples

    iex> cb = CircularBuffer.new(1)
    iex> CircularBuffer.empty?(cb)
    true
    iex> cb |> CircularBuffer.insert(1) |> CircularBuffer.empty?()
    false

# `insert`

```elixir
@spec insert(t(), any()) :: t()
```

Inserts a new item into the next location of the circular buffer

# `new`

```elixir
@spec new(pos_integer()) :: t()
```

Creates a new circular buffer with a given size.

# `newest`

```elixir
@spec newest(t()) :: any()
```

Returns the newest element in the buffer

## Examples

    iex> cb = CircularBuffer.new(3)
    iex> CircularBuffer.newest(cb)
    nil
    iex> cb = Enum.reduce(1..4, cb, fn n, cb -> CircularBuffer.insert(cb, n) end)
    iex> CircularBuffer.newest(cb)
    4

# `oldest`

```elixir
@spec oldest(t()) :: any()
```

Returns the oldest element in the buffer

# `to_list`

```elixir
@spec to_list(t()) :: list()
```

Converts a circular buffer to a list. The list is ordered from oldest to newest
elements based on their insertion order.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
