Skip to content

Commit

Permalink
Fix Issue 17553 - std.json should not do UTF decoding when encoding JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
CyberShadow committed Jun 26, 2017
1 parent 226f8e0 commit 68149a3
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions std/json.d
Expand Up @@ -707,7 +707,8 @@ if (isInputRange!T && !isInfinite!T && isSomeChar!(ElementEncodingType!T))
JSONValue root;
root.type_tag = JSON_TYPE.NULL;

// UTF decoding is unnecessary when parsing JSON.
// Avoid UTF decoding when possible, as it is unnecessary when
// processing JSON.
static if (is(T : const(char)[]))
alias Char = char;
else
Expand Down Expand Up @@ -1142,11 +1143,11 @@ string toJSON(const ref JSONValue root, in bool pretty = false, in JSONOptions o
{
auto json = appender!string();

void toString(string str) @safe
void toStringImpl(Char)(string str) @safe
{
json.put('"');

foreach (dchar c; str)
foreach (Char c; str)
{
switch (c)
{
Expand All @@ -1160,7 +1161,7 @@ string toJSON(const ref JSONValue root, in bool pretty = false, in JSONOptions o
case '\t': json.put("\\t"); break;
default:
{
import std.uni : isControl;
import std.ascii : isControl;
import std.utf : encode;

with (JSONOptions) if (isControl(c) ||
Expand Down Expand Up @@ -1192,6 +1193,16 @@ string toJSON(const ref JSONValue root, in bool pretty = false, in JSONOptions o
json.put('"');
}

void toString(string str) @safe
{
// Avoid UTF decoding when possible, as it is unnecessary when
// processing JSON.
if (options & JSONOptions.escapeNonAsciiChars)
toStringImpl!dchar(str);
else
toStringImpl!char(str);
}

void toValue(ref in JSONValue value, ulong indentLevel) @safe
{
void putTabs(ulong additionalIndent = 0)
Expand Down Expand Up @@ -1813,3 +1824,9 @@ pure nothrow @safe unittest // issue 15884
assert(parseJSON("\"\xFF\"").str == "\xFF");
assert(parseJSON("\"\U0001D11E\"").str == "\U0001D11E");
}

@safe unittest // issue 17553
{
auto v = JSONValue("\xFF");
assert(toJSON(v) == "\"\xFF\"");
}

0 comments on commit 68149a3

Please sign in to comment.