Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speeeeeed up the protocol a bit #264

Merged
merged 1 commit into from
Mar 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions lib/redix/protocol.ex
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ defmodule Redix.Protocol do

@crlf "\r\n"
@crlf_iodata [?\r, ?\n]
@max_integer_digits 18

@doc ~S"""
Packs a list of Elixir terms to a Redis (RESP) array.
Expand Down Expand Up @@ -80,6 +81,9 @@ defmodule Redix.Protocol do
@spec parse(binary) :: on_parse(redis_value)
def parse(data)

# Clause for the most common response.
def parse("+OK\r\n" <> rest), do: {:ok, "OK", rest}

def parse("+" <> rest), do: parse_simple_string(rest)
def parse("-" <> rest), do: parse_error(rest)
def parse(":" <> rest), do: parse_integer(rest)
Expand Down Expand Up @@ -135,12 +139,25 @@ defmodule Redix.Protocol do
|> resolve_cont(&{:ok, %Redix.Error{message: &1}, &2})
end

defp parse_integer(""), do: {:continuation, &parse_integer/1}
# Fast integer clauses for non-split packets.
for n <- 1..@max_integer_digits do
defp parse_integer(<<digits::binary-size(unquote(n)), "\r\n", rest::binary>> = binary) do
String.to_integer(digits)
rescue
ArgumentError -> parse_integer_with_splits(binary)
else
int -> {:ok, int, rest}
end
end

defp parse_integer(bin), do: parse_integer_with_splits(bin)

defp parse_integer_with_splits(""), do: {:continuation, &parse_integer_with_splits/1}

defp parse_integer("-" <> rest),
defp parse_integer_with_splits("-" <> rest),
do: resolve_cont(parse_integer_without_sign(rest), &{:ok, -&1, &2})

defp parse_integer(bin), do: parse_integer_without_sign(bin)
defp parse_integer_with_splits(bin), do: parse_integer_without_sign(bin)

defp parse_integer_without_sign("") do
{:continuation, &parse_integer_without_sign/1}
Expand Down
Loading