From 66c28fe2540bc6f4d4dfdaace26f1d31aebc9dc2 Mon Sep 17 00:00:00 2001 From: Tyler Young Date: Sat, 30 Oct 2021 20:26:37 -0500 Subject: [PATCH 1/2] Just adds a note that Enum.member?/2 uses the fast :queue implementation (I couldn't figure out why there was no Qex.member?/2) --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 2dd789b..a6c3d44 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,10 @@ iex> Enum.map Qex.new([1, 2, 3]), &(&1 + 1) iex> inspect Enum.into(1..5, %Qex{}) "#Qex<[1, 2, 3, 4, 5]>" + +# Leverages :queue.member/2 under the hood for performance +iex> Enum.member? Qex.new(1..10_000), 9_999 +true ``` #### Create a new queue from a range From 686309b143c233a906dcd89a7dc4e33f062f305f Mon Sep 17 00:00:00 2001 From: Tyler Young Date: Mon, 1 Nov 2021 09:29:02 -0500 Subject: [PATCH 2/2] Make Qex.split/2 match the behavior of Enum.split/2, silently taking the whole queue if you ask for more elements than are available --- lib/qex.ex | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/lib/qex.ex b/lib/qex.ex index c1b66e4..60465bd 100644 --- a/lib/qex.ex +++ b/lib/qex.ex @@ -147,7 +147,11 @@ defmodule Qex do end @doc """ - Split a queue into two, the front n items are put in the first queue + Split a queue into two, the front n items (up to all items) are put in the first queue + + Unlike :queue.split/2, which raises an ArgumentError when you ask to split more elements, + this matches the behavior of Enum.split/2 by silently returning the minimum of the + requested number of items and the complete queue. iex> q = Qex.new 1..5 iex> {q1, q2} = Qex.split(q, 3) @@ -155,10 +159,17 @@ defmodule Qex do [1, 2, 3] iex> Enum.to_list q2 [4, 5] + iex> {q_full, q_empty} = Qex.split(q, 1_000) + iex> Enum.to_list q_full + [1, 2, 3, 4, 5] + iex> Enum.to_list q_empty + [] """ @spec split(t, pos_integer) :: {t, t} def split(%__MODULE__{data: q}, n) do - with {q1, q2} <- :queue.split(n, q) do + count = min(:queue.len(q), n) + + with {q1, q2} <- :queue.split(count, q) do {%__MODULE__{data: q1}, %__MODULE__{data: q2}} end end