diff options
author | inoas <mail@inoas.com> | 2022-12-23 11:04:30 +0100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2022-12-23 12:00:27 +0000 |
commit | 8ab43ccb44cf9d913d01b1ae6ff780ee08e4e126 (patch) | |
tree | 3855c5325fb510d5a91dfc1e651b648e62edd41b /src/gleam_stdlib.erl | |
parent | 9dc8bc4b3e9b58396ceae3e2bb466c1eb4679f86 (diff) | |
download | gleam_stdlib-8ab43ccb44cf9d913d01b1ae6ff780ee08e4e126.tar.gz gleam_stdlib-8ab43ccb44cf9d913d01b1ae6ff780ee08e4e126.zip |
fix erlang string.inspect and io.debug to correctly escape ", \, \r, \n, \r\n and \t
Diffstat (limited to 'src/gleam_stdlib.erl')
-rw-r--r-- | src/gleam_stdlib.erl | 28 |
1 files changed, 20 insertions, 8 deletions
diff --git a/src/gleam_stdlib.erl b/src/gleam_stdlib.erl index b5d6ce6..80c3f2c 100644 --- a/src/gleam_stdlib.erl +++ b/src/gleam_stdlib.erl @@ -351,13 +351,9 @@ inspect(Any) when is_integer(Any) -> inspect(Any) when is_float(Any) -> io_lib_format:fwrite_g(Any); inspect(Binary) when is_binary(Binary) -> - case gleam@bit_string:is_utf8(Binary) of - true -> - Pattern = [$"], - Replacement = [$\\, $\\, $"], - Escaped = re:replace(Binary, Pattern, Replacement, [{return, binary}, global]), - ["\"", Escaped, "\""]; - false -> + case inspect_maybe_utf8_string(Binary, <<>>) of + {ok, InspectedUtf8String} -> InspectedUtf8String; + {error, not_a_utf8_string} -> Segments = [erlang:integer_to_list(X) || <<X>> <= Binary], ["<<", lists:join(", ", Segments), ">>"] end; @@ -390,7 +386,7 @@ inspect(Any) when is_function(Any) -> inspect(Any) -> ["//erl(", io_lib:format("~p", [Any]), ")"]. -inspect_list([]) -> +inspect_list([]) -> {proper, []}; inspect_list([Head]) -> {proper, [inspect(Head)]}; @@ -400,5 +396,21 @@ inspect_list([First | Rest]) when is_list(Rest) -> inspect_list([First | ImproperTail]) -> {improper, [inspect(First), <<" | ">>, inspect(ImproperTail)]}. +inspect_maybe_utf8_string(Binary, Acc) -> + case Binary of + <<>> -> {ok, <<$", Acc/binary, $">>}; + <<Head/utf8, Rest/binary>> -> + Escaped = case Head of + $" -> <<$\\, $">>; + $\\ -> <<$\\, $\\>>; + $\r -> <<$\\, $r>>; + $\n -> <<$\\, $n>>; + $\t -> <<$\\, $t>>; + Other -> <<Other/utf8>> + end, + inspect_maybe_utf8_string(Rest, <<Acc/binary, Escaped/binary>>); + _ -> {error, not_a_utf8_string} + end. + float_to_string(Float) when is_float(Float) -> erlang:iolist_to_binary(io_lib_format:fwrite_g(Float)). |