Skip to content

Commit

Permalink
Escape more special chars with comprehensive test
Browse files Browse the repository at this point in the history
  • Loading branch information
expelledboy committed Dec 14, 2023
1 parent 08d30ac commit 0cd66cb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/erl2json.erl
Original file line number Diff line number Diff line change
Expand Up @@ -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) ->
Expand All @@ -105,9 +107,11 @@ escape(Acc, <<>>) ->
escape(Acc, Binary) ->
case Binary of
<<"\b", Rest/binary>> -> escape(<<Acc/binary, "\\\\b">>, Rest);
<<"\e", Rest/binary>> -> escape(<<Acc/binary, "\\\\e">>, Rest);
<<"\f", Rest/binary>> -> escape(<<Acc/binary, "\\\\f">>, Rest);
<<"\n", Rest/binary>> -> escape(<<Acc/binary, "\\\\n">>, Rest);
<<"\r", Rest/binary>> -> escape(<<Acc/binary, "\\\\r">>, Rest);
<<"\s", Rest/binary>> -> escape(<<Acc/binary, "\\\\s">>, Rest);
<<"\t", Rest/binary>> -> escape(<<Acc/binary, "\\\\t">>, Rest);
<<"\v", Rest/binary>> -> escape(<<Acc/binary, "\\\\v">>, Rest);
<<Char, Rest/binary>> -> escape(<<Acc/binary, Char>>, Rest)
Expand Down
18 changes: 18 additions & 0 deletions test/bin.bats
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 0cd66cb

Please sign in to comment.