Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize type selector by using pattern match #536

Merged
merged 1 commit into from
Feb 16, 2024
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
41 changes: 19 additions & 22 deletions lib/floki/selector.ex
Original file line number Diff line number Diff line change
Expand Up @@ -105,24 +105,32 @@ defmodule Floki.Selector do
defp namespace_match?(_node, namespace) when is_wildcard(namespace), do: true

defp namespace_match?(node, namespace) do
case type_maybe_with_namespace(node) do
[^namespace, _type] ->
true
namespace_size = byte_size(namespace)

_ ->
false
case type_maybe_with_namespace(node) do
<<^namespace::binary-size(namespace_size), ":", _::binary>> -> true
_ -> false
end
end

defp type_match?(_node, type) when is_wildcard(type), do: true

defp type_match?(node, type) do
case type_maybe_with_namespace(node) do
[_ns, ^type] ->
^type ->
true

[^type] ->
true
type_maybe_with_namespace when byte_size(type_maybe_with_namespace) > byte_size(type) ->
expected_namespace_size = byte_size(type_maybe_with_namespace) - byte_size(type) - 1

Kernel.match?(
<<
_ns::binary-size(expected_namespace_size),
":",
^type::binary
>>,
type_maybe_with_namespace
)

_ ->
false
Expand Down Expand Up @@ -251,20 +259,9 @@ defmodule Floki.Selector do
false
end

defp type_maybe_with_namespace({type, _attributes, _children}) when is_binary(type) do
type_maybe_with_namespace(type)
end

defp type_maybe_with_namespace(%HTMLNode{type: type}) when is_binary(type) do
type_maybe_with_namespace(type)
end

defp type_maybe_with_namespace(type_maybe_with_namespace)
when is_binary(type_maybe_with_namespace) do
String.split(type_maybe_with_namespace, ":", parts: 2)
end

defp type_maybe_with_namespace(_), do: []
defp type_maybe_with_namespace({type, _attributes, _children}) when is_binary(type), do: type
defp type_maybe_with_namespace(%HTMLNode{type: type}) when is_binary(type), do: type
defp type_maybe_with_namespace(_), do: nil

defp attribute_value(node, attribute_name) do
attributes = attributes(node)
Expand Down
Loading