From: Anton Likhtarov Date: Wed, 26 Sep 2012 18:09:18 +0000 (-0700) Subject: folly/json: serialize \r and \n as \r and \n X-Git-Tag: v0.22.0~1175 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=49ccc34faf0fed773411c344c1ccaa32a64e2d24;p=folly.git 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 --- diff --git a/folly/json.cpp b/folly/json.cpp index bf5320d2..989cccc7 100644 --- a/folly/json.cpp +++ b/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('\"'); diff --git a/folly/test/JsonTest.cpp b/folly/test/JsonTest.cpp index ea74a348..4d47522f 100644 --- a/folly/test/JsonTest.cpp +++ b/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;