Commit 49ccc34f authored by Anton Likhtarov's avatar Anton Likhtarov Committed by Jordan DeLong

folly/json: serialize \r and \n as \r and \n

Summary:
Background: we want to use folly::json but not change the way data is represented.
Since we need to store \r and \n in strings and the library we're currently using does this,
let's do it in folly too.

Test Plan: unit tests pass

Reviewed By: delong.j@fb.com

FB internal diff: D584960
parent 981ed984
......@@ -145,23 +145,27 @@ void escapeString(StringPiece input,
out.push_back(hexDigit((v >> 8) & 0x0f));
out.push_back(hexDigit((v >> 4) & 0x0f));
out.push_back(hexDigit(v & 0x0f));
continue;
}
if (*p == '\\' || *p == '\"') {
} else if (*p == '\\' || *p == '\"') {
out.push_back('\\');
out.push_back(*p++);
continue;
}
if (*p <= 0x1f) {
// note that this if condition captures both control characters
// and extended ascii characters
out.append("\\u00");
out.push_back(hexDigit((*p & 0xf0) >> 4));
out.push_back(hexDigit(*p & 0xf));
p++;
continue;
} else if (*p <= 0x1f) {
switch (*p) {
case '\b': out.append("\\b"); p++; break;
case '\f': out.append("\\f"); p++; break;
case '\n': out.append("\\n"); p++; break;
case '\r': out.append("\\r"); p++; break;
case '\t': out.append("\\t"); p++; break;
default:
// note that this if condition captures both control characters
// and extended ascii characters
out.append("\\u00");
out.push_back(hexDigit((*p & 0xf0) >> 4));
out.push_back(hexDigit(*p & 0xf));
p++;
}
} else {
out.push_back(*p++);
}
out.push_back(*p++);
}
out.push_back('\"');
......
......@@ -173,6 +173,13 @@ TEST(Json, Produce) {
EXPECT_TRUE(caught);
}
TEST(Json, JsonEscape) {
folly::json::serialization_opts opts;
EXPECT_EQ(
folly::json::serialize("\b\f\n\r\x01\t\\\"/\v\a", opts),
R"("\b\f\n\r\u0001\t\\\"/\u000b\u0007")");
}
TEST(Json, JsonNonAsciiEncoding) {
folly::json::serialization_opts opts;
opts.encode_non_ascii = true;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment