Skip to content

Optimize Base.valid16?/2 #14429

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

Merged
merged 1 commit into from
Apr 12, 2025
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
31 changes: 16 additions & 15 deletions lib/elixir/lib/base.ex
Original file line number Diff line number Diff line change
Expand Up @@ -355,14 +355,10 @@ defmodule Base do

def valid16?(string, opts) when is_binary(string) and rem(byte_size(string), 2) == 0 do
case Keyword.get(opts, :case, :upper) do
:upper -> validate16upper!(string)
:lower -> validate16lower!(string)
:mixed -> validate16mixed!(string)
:upper -> validate16upper?(string)
:lower -> validate16lower?(string)
:mixed -> validate16mixed?(string)
end

true
rescue
ArgumentError -> false
end

def valid16?(string, _opts) when is_binary(string) do
Expand All @@ -373,21 +369,26 @@ defmodule Base do

for {base, alphabet} <- [upper: upper, lower: to_lower_dec.(upper), mixed: to_mixed_dec.(upper)] do
decode_name = :"decode16#{base}!"
validate_name = :"validate16#{base}!"
validate_name = :"validate16#{base}?"
valid_char_name = :"valid_char16#{base}?"

{min, decoded} = to_decode_list.(alphabet)

defp unquote(validate_name)(<<>>), do: :ok
defp unquote(validate_name)(<<>>), do: true

defp unquote(validate_name)(<<c1, c2, rest::binary>>) do
unquote(decode_name)(c1)
unquote(decode_name)(c2)
unquote(validate_name)(rest)
unquote(valid_char_name)(c1) and
unquote(valid_char_name)(c2) and
unquote(validate_name)(rest)
end

defp unquote(validate_name)(<<char, _rest::binary>>) do
bad_character!(char)
end
defp unquote(validate_name)(<<_char, _rest::binary>>), do: false

defp unquote(valid_char_name)(char)
when elem({unquote_splicing(decoded)}, char - unquote(min)) != nil,
do: true

defp unquote(valid_char_name)(_char), do: false

defp unquote(decode_name)(char) do
try do
Expand Down
Loading