folly/json: serialize \r and \n as \r and \n
authorAnton Likhtarov <alikhtarov@fb.com>
Wed, 26 Sep 2012 18:09:18 +0000 (11:09 -0700)
committerJordan DeLong <jdelong@fb.com>
Fri, 12 Oct 2012 04:33:51 +0000 (21:33 -0700)
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

folly/json.cpp
folly/test/JsonTest.cpp

index bf5320d27559e301404607d7f36de5c1b3b911f2..989cccc7e2708d79f42b1139dbf24ae983db15ef 100644 (file)
@@ -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('\"');
index ea74a348929bc7339caa5c0f29128825a6dd19ca..4d47522f11cc6be24307a556310561010d34b87b 100644 (file)
@@ -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;