From 0cd66cb8d236d1a38decb7b82afc016ee34e38b0 Mon Sep 17 00:00:00 2001 From: expelledboy <102334+expelledboy@users.noreply.github.com> Date: Thu, 14 Dec 2023 11:59:42 +0200 Subject: [PATCH] Escape more special chars with comprehensive test --- src/erl2json.erl | 4 ++++ test/bin.bats | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/erl2json.erl b/src/erl2json.erl index 4cfacdd..a7d5e53 100644 --- a/src/erl2json.erl +++ b/src/erl2json.erl @@ -95,6 +95,8 @@ encode_nested(Map) when is_map(Map) -> %% -- +% https://www.erlang.org/doc/reference_manual/data_types#escape-sequences + escape(List) when is_list(List) -> escape(<<>>, list_to_binary(List)); escape(Binary) when is_binary(Binary) -> @@ -105,9 +107,11 @@ escape(Acc, <<>>) -> escape(Acc, Binary) -> case Binary of <<"\b", Rest/binary>> -> escape(<>, Rest); + <<"\e", Rest/binary>> -> escape(<>, Rest); <<"\f", Rest/binary>> -> escape(<>, Rest); <<"\n", Rest/binary>> -> escape(<>, Rest); <<"\r", Rest/binary>> -> escape(<>, Rest); + <<"\s", Rest/binary>> -> escape(<>, Rest); <<"\t", Rest/binary>> -> escape(<>, Rest); <<"\v", Rest/binary>> -> escape(<>, Rest); <> -> escape(<>, Rest) diff --git a/test/bin.bats b/test/bin.bats index e536717..ad13bde 100644 --- a/test/bin.bats +++ b/test/bin.bats @@ -50,4 +50,22 @@ setup() { run bash -o pipefail -c "echo '\"\\n\"' | $BIN | jq empty" assert_success + + chars=( + '\b' + '\e' + '\f' + '\n' + '\r' + '\s' + '\t' + '\v' + ) + + for char in "${chars[@]}"; do + echo "\"$char\"" + echo "\"\\$char\"" + output=$(echo "\"$char\"" | $BIN) + assert_equal "$output" "\"\\$char\"" + done }