refactor: pattern-match Aprsme.Encoding helpers
- encoding_info/1 (binary clause): extract build_encoding_info/2 with true/false heads on String.valid?/1, so the valid-UTF-8 and invalid branches each own their map literal. - try_utf8_conversion/1: convert_to_utf8/2 dispatches on String.valid?/1 so the latin1 → UTF-8 fallback is a function head, not an inline if. No behavior change; all 34 Encoding tests still pass.
This commit is contained in:
parent
1e55d106a0
commit
cd1e5771af
1 changed files with 24 additions and 25 deletions
|
|
@ -89,25 +89,7 @@ defmodule Aprsme.Encoding do
|
|||
invalid_at: non_neg_integer() | nil
|
||||
}
|
||||
def encoding_info(input) when is_binary(input) do
|
||||
byte_count = byte_size(input)
|
||||
|
||||
if String.valid?(input) do
|
||||
%{
|
||||
valid_utf8: true,
|
||||
byte_count: byte_count,
|
||||
char_count: String.length(input),
|
||||
invalid_at: nil
|
||||
}
|
||||
else
|
||||
invalid_pos = find_invalid_byte_position(input)
|
||||
|
||||
%{
|
||||
valid_utf8: false,
|
||||
byte_count: byte_count,
|
||||
char_count: nil,
|
||||
invalid_at: invalid_pos
|
||||
}
|
||||
end
|
||||
build_encoding_info(String.valid?(input), input)
|
||||
end
|
||||
|
||||
@spec encoding_info(any()) :: %{
|
||||
|
|
@ -125,18 +107,35 @@ defmodule Aprsme.Encoding do
|
|||
}
|
||||
end
|
||||
|
||||
defp build_encoding_info(true, input) do
|
||||
%{
|
||||
valid_utf8: true,
|
||||
byte_count: byte_size(input),
|
||||
char_count: String.length(input),
|
||||
invalid_at: nil
|
||||
}
|
||||
end
|
||||
|
||||
defp build_encoding_info(false, input) do
|
||||
%{
|
||||
valid_utf8: false,
|
||||
byte_count: byte_size(input),
|
||||
char_count: nil,
|
||||
invalid_at: find_invalid_byte_position(input)
|
||||
}
|
||||
end
|
||||
|
||||
# Private functions
|
||||
|
||||
@spec try_utf8_conversion(binary()) :: binary()
|
||||
defp try_utf8_conversion(input) do
|
||||
if String.valid?(input) do
|
||||
input
|
||||
else
|
||||
# Try latin1 to UTF-8 conversion
|
||||
latin1_to_utf8(input)
|
||||
end
|
||||
convert_to_utf8(String.valid?(input), input)
|
||||
end
|
||||
|
||||
# Valid UTF-8 already — pass through. Otherwise try latin1 → UTF-8.
|
||||
defp convert_to_utf8(true, input), do: input
|
||||
defp convert_to_utf8(false, input), do: latin1_to_utf8(input)
|
||||
|
||||
@spec latin1_to_utf8(binary()) :: binary()
|
||||
defp latin1_to_utf8(input) do
|
||||
input
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue