Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

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
  • Loading branch information...
commit 49ccc34faf0fed773411c344c1ccaa32a64e2d24 1 parent 981ed98
@alikhtarov alikhtarov authored jdelong committed
Showing with 25 additions and 14 deletions.
  1. +18 −14 folly/json.cpp
  2. +7 −0 folly/test/JsonTest.cpp
View
32 folly/json.cpp
@@ -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('\"');
View
7 folly/test/JsonTest.cpp
@@ -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;
Please sign in to comment.
Something went wrong with that request. Please try again.