Skip to content

Commit a735b14

Browse files
authored
Avoid per-byte binary construction and backtracking in Plug.Conn.Utils.token/1 (#1335)
1 parent 6955eb3 commit a735b14

1 file changed

Lines changed: 29 additions & 10 deletions

File tree

‎lib/plug/conn/utils.ex‎

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -239,23 +239,42 @@ defmodule Plug.Conn.Utils do
239239
240240
"""
241241
@spec token(binary) :: binary | false
242-
def token(""), do: false
243-
def token(<<?", quoted::binary>>), do: quoted_token(quoted, "")
244-
def token(token), do: unquoted_token(token, "")
242+
def token(token) when is_binary(token), do: do_token(token, token)
243+
244+
defp do_token(<<token::binary>>, original), do: unquoted_token(token, original, 0)
245245

246-
defp quoted_token(<<>>, _acc), do: false
247246
defp quoted_token(<<?", t::binary>>, acc), do: strip_spaces(t) == "" and acc
248-
defp quoted_token(<<?\\, h, t::binary>>, acc), do: quoted_token(t, <<acc::binary, h>>)
247+
248+
defp quoted_token(<<?\\, rest::binary>>, acc) do
249+
case rest do
250+
<<h, t::binary>> -> quoted_token(t, <<acc::binary, h>>)
251+
<<>> -> false
252+
end
253+
end
254+
249255
defp quoted_token(<<h, t::binary>>, acc), do: quoted_token(t, <<acc::binary, h>>)
256+
defp quoted_token(<<>>, _acc), do: false
257+
258+
defp unquoted_token(<<?", quoted::binary>>, _token, len),
259+
do: len == 0 and quoted_token(quoted, "")
260+
261+
defp unquoted_token(<<?\r, rest::binary>>, token, len) do
262+
case rest do
263+
<<?\n, t::binary>> -> strip_spaces(t) == "" and binary_part(token, 0, len)
264+
_ -> false
265+
end
266+
end
250267

251-
defp unquoted_token(<<>>, acc), do: acc
252-
defp unquoted_token("\r\n" <> t, acc), do: strip_spaces(t) == "" and acc
253-
defp unquoted_token(<<h, t::binary>>, acc) when h in @space, do: strip_spaces(t) == "" and acc
268+
defp unquoted_token(<<h, t::binary>>, token, len) when h in @space,
269+
do: strip_spaces(t) == "" and binary_part(token, 0, len)
254270

255-
defp unquoted_token(<<h, _::binary>>, _acc) when h in @specials or h < 32 or h === 127,
271+
defp unquoted_token(<<h, _::binary>>, _token, _len) when h in @specials or h < 32 or h === 127,
256272
do: false
257273

258-
defp unquoted_token(<<h, t::binary>>, acc), do: unquoted_token(t, <<acc::binary, h>>)
274+
defp unquoted_token(<<_, t::binary>>, token, len),
275+
do: unquoted_token(t, token, len + 1)
276+
277+
defp unquoted_token(<<>>, token, len), do: len != 0 and token
259278

260279
@doc """
261280
Parses a comma-separated list of header values.

0 commit comments

Comments
 (0)