Skip to content

Commit

Permalink
Cover additional escape sequences
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Jul 8, 2023
1 parent 0d2f4dc commit 60dfb45
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
34 changes: 31 additions & 3 deletions lib/ex_doc/utils.ex
Original file line number Diff line number Diff line change
Expand Up @@ -122,15 +122,43 @@ defmodule ExDoc.Utils do
end

def to_json(binary) when is_binary(binary) do
binary
|> inspect(printable_limit: :infinity)
|> String.replace("\\#\{", "#\{")
to_json_string(binary, "\"")
end

def to_json(integer) when is_integer(integer) do
Integer.to_string(integer)
end

defp to_json_string(<<?\b, rest::binary>>, acc),
do: to_json_string(rest, <<acc::binary, "\\b">>)

defp to_json_string(<<?\t, rest::binary>>, acc),
do: to_json_string(rest, <<acc::binary, "\\t">>)

defp to_json_string(<<?\n, rest::binary>>, acc),
do: to_json_string(rest, <<acc::binary, "\\n">>)

defp to_json_string(<<?\f, rest::binary>>, acc),
do: to_json_string(rest, <<acc::binary, "\\f">>)

defp to_json_string(<<?\r, rest::binary>>, acc),
do: to_json_string(rest, <<acc::binary, "\\r">>)

defp to_json_string(<<?\\, rest::binary>>, acc),
do: to_json_string(rest, <<acc::binary, "\\\\">>)

defp to_json_string(<<?", rest::binary>>, acc),
do: to_json_string(rest, <<acc::binary, "\\\"">>)

defp to_json_string(<<x, rest::binary>>, acc) when x <= 0x000F,
do: to_json_string(rest, <<acc::binary, "\\u000#{Integer.to_string(x, 16)}">>)

defp to_json_string(<<x, rest::binary>>, acc) when x <= 0x001F,
do: to_json_string(rest, <<acc::binary, "\\u00#{Integer.to_string(x, 16)}">>)

defp to_json_string(<<x, rest::binary>>, acc), do: to_json_string(rest, <<acc::binary, x>>)
defp to_json_string(<<>>, acc), do: <<acc::binary, "\"">>

@doc """
Generates a url based on the given pattern.
"""
Expand Down
3 changes: 3 additions & 0 deletions test/ex_doc/utils_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ defmodule ExDoc.UtilsTest do
}

assert map |> ExDoc.Utils.to_json() |> IO.iodata_to_binary() == Jason.encode!(map)

string = for i <- 0..0x1F, do: <<i>>, into: ""
assert string |> ExDoc.Utils.to_json() |> IO.iodata_to_binary() == Jason.encode!(string)
end

test "source_url_pattern" do
Expand Down

0 comments on commit 60dfb45

Please sign in to comment.