Skip to content

Commit

Permalink
Fix edge cases for URI.decode/1
Browse files Browse the repository at this point in the history
  • Loading branch information
lexmag committed Jun 13, 2014
1 parent 4083555 commit 6b45855
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
27 changes: 15 additions & 12 deletions lib/elixir/lib/uri.ex
Original file line number Diff line number Diff line change
Expand Up @@ -230,25 +230,28 @@ defmodule URI do
"""
def decode(uri) do
decode(uri, uri)
unpercent(uri)
catch
:malformed_uri ->
raise ArgumentError, "malformed URI #{inspect uri}"
end

def decode(<<?%, hex1, hex2, tail :: binary >>, uri) do
<<bsl(hex_to_dec(hex1, uri), 4) + hex_to_dec(hex2, uri)>> <> decode(tail, uri)
defp unpercent(<<?%, hex_1, hex_2, tail :: binary>>) do
<<bsl(hex_to_dec(hex_1), 4) + hex_to_dec(hex_2)>> <> unpercent(tail)
end
defp unpercent(<<?%, _>>), do: throw(:malformed_uri)
defp unpercent(<<?%>>), do: throw(:malformed_uri)

def decode(<<head, tail :: binary >>, uri) do
<<head>> <> decode(tail, uri)
defp unpercent(<<head, tail :: binary>>) do
<<head>> <> unpercent(tail)
end

def decode(<<>>, _uri), do: <<>>
defp unpercent(<<>>), do: <<>>

defp hex_to_dec(n, _uri) when n in ?A..?F, do: n - ?A + 10
defp hex_to_dec(n, _uri) when n in ?a..?f, do: n - ?a + 10
defp hex_to_dec(n, _uri) when n in ?0..?9, do: n - ?0
defp hex_to_dec(_n, uri) do
raise ArgumentError, "malformed URI #{inspect uri}"
end
defp hex_to_dec(n) when n in ?A..?F, do: n - ?A + 10
defp hex_to_dec(n) when n in ?a..?f, do: n - ?a + 10
defp hex_to_dec(n) when n in ?0..?9, do: n - ?0
defp hex_to_dec(_n), do: throw(:malformed_uri)

@doc """
Parses a URI into components.
Expand Down
3 changes: 3 additions & 0 deletions lib/elixir/test/elixir/uri_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ defmodule URITest do
assert_raise ArgumentError, ~R/malformed URI/, fn ->
URI.decode("% invalid")
end
assert_raise ArgumentError, ~R/malformed URI/, fn ->
URI.decode("invalid%")
end
end

test :parse_http do
Expand Down

0 comments on commit 6b45855

Please sign in to comment.