Skip to content

Commit 854cab5

Browse files
committed
Implement Binary.Chars for URI.Info
1 parent ffdf9e9 commit 854cab5

File tree

2 files changed

+37
-4
lines changed

2 files changed

+37
-4
lines changed

lib/elixir/lib/uri.ex

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,8 @@ defmodule URI do
150150
scheme_specific(scheme, info)
151151
end
152152

153-
defp scheme_specific(scheme, info) do
153+
@doc false
154+
def scheme_module(scheme) do
154155
if scheme do
155156
module =
156157
try do
@@ -160,10 +161,14 @@ defmodule URI do
160161
end
161162

162163
if module && Code.ensure_loaded?(module) do
163-
module.parse(default_port(info, module))
164-
else
165-
info
164+
module
166165
end
166+
end
167+
end
168+
169+
defp scheme_specific(scheme, info) do
170+
if module = scheme_module(scheme) do
171+
module.parse(default_port(info, module))
167172
else
168173
info
169174
end
@@ -202,3 +207,22 @@ defmodule URI do
202207
:ok
203208
end
204209
end
210+
211+
defimpl Binary.Chars, for: URI.Info do
212+
def to_binary(uri) do
213+
result = ""
214+
215+
if module = URI.scheme_module(uri.scheme) do
216+
if module.default_port == uri.port, do: uri = uri.port(nil)
217+
end
218+
219+
if uri.scheme, do: result = result <> uri.scheme <> "://"
220+
if uri.userinfo, do: result = result <> uri.userinfo <> "@"
221+
if uri.host, do: result = result <> uri.host
222+
if uri.port, do: result = result <> ":" <> integer_to_binary(uri.port)
223+
if uri.query, do: result = result <> "?" <> uri.query
224+
if uri.fragment, do: result = result <> "#" <> uri.fragment
225+
226+
result
227+
end
228+
end

lib/elixir/test/elixir/uri_test.exs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,4 +129,13 @@ defmodule URITest do
129129
assert URI.parse("http://GoOgLe.CoM").host == "google.com"
130130
assert URI.parse("http://LOL:[email protected]").authority == "LOL:[email protected]"
131131
end
132+
133+
test :to_binary do
134+
assert to_binary(URI.parse("http://google.com")) == "http://google.com"
135+
assert to_binary(URI.parse("http://google.com:443")) == "http://google.com:443"
136+
assert to_binary(URI.parse("https://google.com:443")) == "https://google.com"
137+
assert to_binary(URI.parse("http://lol:[email protected]")) == "http://lol:[email protected]"
138+
assert to_binary(URI.parse("http://google.com?q=lol")) == "http://google.com?q=lol"
139+
assert to_binary(URI.parse("http://google.com?q=lol#omg")) == "http://google.com?q=lol#omg"
140+
end
132141
end

0 commit comments

Comments
 (0)