Skip to content

Commit fecd6e3

Browse files
authored
Optimize Base.valid16?/2 (#14429)
1 parent 30711a7 commit fecd6e3

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed

Diff for: lib/elixir/lib/base.ex

+16-15
Original file line numberDiff line numberDiff line change
@@ -355,14 +355,10 @@ defmodule Base do
355355

356356
def valid16?(string, opts) when is_binary(string) and rem(byte_size(string), 2) == 0 do
357357
case Keyword.get(opts, :case, :upper) do
358-
:upper -> validate16upper!(string)
359-
:lower -> validate16lower!(string)
360-
:mixed -> validate16mixed!(string)
358+
:upper -> validate16upper?(string)
359+
:lower -> validate16lower?(string)
360+
:mixed -> validate16mixed?(string)
361361
end
362-
363-
true
364-
rescue
365-
ArgumentError -> false
366362
end
367363

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

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

378375
{min, decoded} = to_decode_list.(alphabet)
379376

380-
defp unquote(validate_name)(<<>>), do: :ok
377+
defp unquote(validate_name)(<<>>), do: true
381378

382379
defp unquote(validate_name)(<<c1, c2, rest::binary>>) do
383-
unquote(decode_name)(c1)
384-
unquote(decode_name)(c2)
385-
unquote(validate_name)(rest)
380+
unquote(valid_char_name)(c1) and
381+
unquote(valid_char_name)(c2) and
382+
unquote(validate_name)(rest)
386383
end
387384

388-
defp unquote(validate_name)(<<char, _rest::binary>>) do
389-
bad_character!(char)
390-
end
385+
defp unquote(validate_name)(<<_char, _rest::binary>>), do: false
386+
387+
defp unquote(valid_char_name)(char)
388+
when elem({unquote_splicing(decoded)}, char - unquote(min)) != nil,
389+
do: true
390+
391+
defp unquote(valid_char_name)(_char), do: false
391392

392393
defp unquote(decode_name)(char) do
393394
index = char - unquote(min)

0 commit comments

Comments
 (0)