Skip to content

Commit fda0d19

Browse files
committed
Implement Collectable protocol
1 parent f9d165c commit fda0d19

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

lib/circular_buffer.ex

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,4 +90,16 @@ defmodule CircularBuffer do
9090
{:ok, cb.count, &Enumerable.List.slice(CB.to_list(cb), &1, &2)}
9191
end
9292
end
93+
94+
defimpl Collectable do
95+
def into(original) do
96+
collector_fn = fn
97+
cb, {:cont, elem} -> CB.insert(cb, elem)
98+
cb, :done -> cb
99+
_cb, :halt -> :ok
100+
end
101+
102+
{original, collector_fn}
103+
end
104+
end
93105
end

test/circular_buffer_test.exs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,14 @@ defmodule CircularBufferTest do
4949
end
5050
end
5151

52+
property "can be collected" do
53+
forall {size, is} <- size_and_list() do
54+
buffer = Enum.reduce(is, CB.new(size), fn i, cb -> CB.insert(cb, i) end)
55+
56+
Enum.into(is, CB.new(size)) == buffer
57+
end
58+
end
59+
5260
property "the number of elements never exceeds the size of the buffer" do
5361
forall {size, is} <- size_and_list() do
5462
buffer = Enum.reduce(is, CB.new(size), fn i, cb -> CB.insert(cb, i) end)

0 commit comments

Comments
 (0)