From 72ef0c63f1bbc0a0f15bcab7d201a9cfd33f72f8 Mon Sep 17 00:00:00 2001 From: preciz Date: Sun, 14 Jun 2026 15:26:08 +0200 Subject: [PATCH 1/2] Optimize URI.to_string/1 --- lib/elixir/lib/uri.ex | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/lib/elixir/lib/uri.ex b/lib/elixir/lib/uri.ex index 25a9edc88ad..65789669ef8 100644 --- a/lib/elixir/lib/uri.ex +++ b/lib/elixir/lib/uri.ex @@ -1090,15 +1090,18 @@ defimpl String.Chars, for: URI do ":path in URI must be empty or an absolute path if URL has a :host, got: #{inspect(uri)}" end - def to_string(%{scheme: scheme, port: port, path: path, query: query, fragment: fragment} = uri) do - uri = - case scheme && URI.default_port(scheme) do - ^port -> %{uri | port: nil} - _ -> uri - end - + def to_string(%{ + host: host, + authority: authority, + userinfo: userinfo, + scheme: scheme, + port: port, + path: path, + query: query, + fragment: fragment + }) do # Based on https://tools.ietf.org/html/rfc3986#section-5.3 - authority = extract_authority(uri) + authority = extract_authority(host, authority, scheme, userinfo, port) IO.iodata_to_binary([ if(scheme, do: [scheme, ?:], else: []), @@ -1109,19 +1112,23 @@ defimpl String.Chars, for: URI do ]) end - defp extract_authority(%{host: nil, authority: authority}) do + defp extract_authority(_host = nil, authority, _scheme, _userinfo, _port) do authority end - defp extract_authority(%{host: host, userinfo: userinfo, port: port}) do + defp extract_authority(host, _authority, scheme, userinfo, port) do # According to the grammar at # https://tools.ietf.org/html/rfc3986#appendix-A, a "host" can have a colon # in it only if it's an IPv6 or "IPvFuture" address, so if there's a colon # in the host we can safely surround it with []. + [ if(userinfo, do: [userinfo | "@"], else: []), if(String.contains?(host, ":"), do: ["[", host | "]"], else: host), - if(port, do: [":" | Integer.to_string(port)], else: []) + if(port && (is_nil(scheme) || URI.default_port(scheme) != port), + do: [":" | Integer.to_string(port)], + else: [] + ) ] end end From 0572ebb5746dde2d31942ec767351e78b86e4864 Mon Sep 17 00:00:00 2001 From: Barna Kovacs Date: Sun, 14 Jun 2026 23:49:29 +0200 Subject: [PATCH 2/2] Update lib/elixir/lib/uri.ex MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: José Valim --- lib/elixir/lib/uri.ex | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/elixir/lib/uri.ex b/lib/elixir/lib/uri.ex index 65789669ef8..07f2b3b77ea 100644 --- a/lib/elixir/lib/uri.ex +++ b/lib/elixir/lib/uri.ex @@ -1125,7 +1125,7 @@ defimpl String.Chars, for: URI do [ if(userinfo, do: [userinfo | "@"], else: []), if(String.contains?(host, ":"), do: ["[", host | "]"], else: host), - if(port && (is_nil(scheme) || URI.default_port(scheme) != port), + if(port != nil and (is_nil(scheme) or URI.default_port(scheme) != port), do: [":" | Integer.to_string(port)], else: [] )