Browse Source

Fixing quote-escaping in string parser.

Samuel Jaffe 8 years ago
parent
commit
572d120e61
1 changed files with 20 additions and 5 deletions
  1. 20 5
      json_common.cpp

+ 20 - 5
json_common.cpp

@@ -33,7 +33,7 @@ namespace json {
       }
       
       if (end == it) {
-        throw malformed_json_exception("Expected any token, got nothing");
+        throw unterminated_json_exception("Expected any token, got nothing");
       }
     }
     
@@ -63,18 +63,33 @@ namespace json {
       if (next == ',') {
         ++data;
       } else if (next != endtok) {
-        throw json::malformed_json_exception(get_no_end_error(endtok, *data));
+        throw json::unterminated_json_exception(get_no_end_error(endtok, *data));
       }
     }
     
+    int reverse_count(char const * data, char val) {
+      int i = 0;
+      while (*data-- == val) { ++i; }
+      return i;
+    }
+    
+    std::string replace_all(std::string && str, std::string const & from, std::string const & to) {
+      std::string::size_type start_pos = 0;
+      while((start_pos = str.find(from, start_pos)) != std::string::npos) {
+        str.replace(start_pos, from.length(), to);
+        start_pos += to.length(); // ...
+      }
+      return std::move(str);
+    }
+    
     std::string parse_string(char const * & data) {
       char const* start = data;
       while (*++data) {
-        if (*data == '"' && *(data-1) != '\\') {
-          return std::string(start+1, data++);
+        if (*data == '"' && (reverse_count(data-1, '\\') % 2) == 0) {
+          return replace_all(std::string(start+1, data++), "\\\"", "\"");
         }
       }
-      throw json::malformed_json_exception("Could not locate end of string");
+      throw json::unterminated_json_exception("Could not locate end of string");
     }
   }
 }