Skip to content

Commit 60dfb45

Browse files
committed
Cover additional escape sequences
1 parent 0d2f4dc commit 60dfb45

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

lib/ex_doc/utils.ex

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,15 +122,43 @@ defmodule ExDoc.Utils do
122122
end
123123

124124
def to_json(binary) when is_binary(binary) do
125-
binary
126-
|> inspect(printable_limit: :infinity)
127-
|> String.replace("\\#\{", "#\{")
125+
to_json_string(binary, "\"")
128126
end
129127

130128
def to_json(integer) when is_integer(integer) do
131129
Integer.to_string(integer)
132130
end
133131

132+
defp to_json_string(<<?\b, rest::binary>>, acc),
133+
do: to_json_string(rest, <<acc::binary, "\\b">>)
134+
135+
defp to_json_string(<<?\t, rest::binary>>, acc),
136+
do: to_json_string(rest, <<acc::binary, "\\t">>)
137+
138+
defp to_json_string(<<?\n, rest::binary>>, acc),
139+
do: to_json_string(rest, <<acc::binary, "\\n">>)
140+
141+
defp to_json_string(<<?\f, rest::binary>>, acc),
142+
do: to_json_string(rest, <<acc::binary, "\\f">>)
143+
144+
defp to_json_string(<<?\r, rest::binary>>, acc),
145+
do: to_json_string(rest, <<acc::binary, "\\r">>)
146+
147+
defp to_json_string(<<?\\, rest::binary>>, acc),
148+
do: to_json_string(rest, <<acc::binary, "\\\\">>)
149+
150+
defp to_json_string(<<?", rest::binary>>, acc),
151+
do: to_json_string(rest, <<acc::binary, "\\\"">>)
152+
153+
defp to_json_string(<<x, rest::binary>>, acc) when x <= 0x000F,
154+
do: to_json_string(rest, <<acc::binary, "\\u000#{Integer.to_string(x, 16)}">>)
155+
156+
defp to_json_string(<<x, rest::binary>>, acc) when x <= 0x001F,
157+
do: to_json_string(rest, <<acc::binary, "\\u00#{Integer.to_string(x, 16)}">>)
158+
159+
defp to_json_string(<<x, rest::binary>>, acc), do: to_json_string(rest, <<acc::binary, x>>)
160+
defp to_json_string(<<>>, acc), do: <<acc::binary, "\"">>
161+
134162
@doc """
135163
Generates a url based on the given pattern.
136164
"""

test/ex_doc/utils_test.exs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,9 @@ defmodule ExDoc.UtilsTest do
7676
}
7777

7878
assert map |> ExDoc.Utils.to_json() |> IO.iodata_to_binary() == Jason.encode!(map)
79+
80+
string = for i <- 0..0x1F, do: <<i>>, into: ""
81+
assert string |> ExDoc.Utils.to_json() |> IO.iodata_to_binary() == Jason.encode!(string)
7982
end
8083

8184
test "source_url_pattern" do

0 commit comments

Comments
 (0)