Skip to content
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
29 changes: 24 additions & 5 deletions lib/plug/conn/utils.ex
Original file line number Diff line number Diff line change
Expand Up @@ -286,25 +286,44 @@ defmodule Plug.Conn.Utils do
do: stripped
end

# 56-bit SWAR guard: all 7 bytes are ASCII (< 128)
defguardp ascii_swar?(w)
when Bitwise.band(w, 0x80808080808080) == 0

@doc """
Validates the given binary is valid UTF-8.
"""
@spec validate_utf8!(binary, module, binary) :: :ok | no_return
def validate_utf8!(binary, exception, context)

def validate_utf8!(<<binary::binary>>, exception, context) do
do_validate_utf8!(binary, exception, context)
if byte_size(binary) < 12 do
do_validate_utf8_small!(binary, exception, context)
else
do_validate_utf8_swar!(binary, exception, context)
end
end

# SWAR loop
defp do_validate_utf8_swar!(<<w::56, b, rest::bits>>, exception, context)
when b <= 127 and ascii_swar?(w) do
do_validate_utf8_swar!(rest, exception, context)
end

defp do_validate_utf8_swar!(rest, exception, context) do
do_validate_utf8_small!(rest, exception, context)
end

defp do_validate_utf8!(<<_::utf8, rest::bits>>, exception, context) do
do_validate_utf8!(rest, exception, context)
# Small loop (identical to original character loop)
defp do_validate_utf8_small!(<<_::utf8, rest::bits>>, exception, context) do
do_validate_utf8_small!(rest, exception, context)
end

defp do_validate_utf8!(<<byte, _::bits>>, exception, context) do
defp do_validate_utf8_small!(<<byte, _::bits>>, exception, context) do
raise exception, "invalid UTF-8 on #{context}, got byte #{byte}"
end

defp do_validate_utf8!(<<>>, _exception, _context) do
defp do_validate_utf8_small!(<<>>, _exception, _context) do
:ok
end

Expand Down