summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--apt-private/private-json-hooks.cc24
-rw-r--r--test/libapt/json_test.cc45
2 files changed, 65 insertions, 4 deletions
diff --git a/apt-private/private-json-hooks.cc b/apt-private/private-json-hooks.cc
index 0b765a4ed..b61829cbf 100644
--- a/apt-private/private-json-hooks.cc
+++ b/apt-private/private-json-hooks.cc
@@ -12,6 +12,7 @@
#include <apt-pkg/strutl.h>
#include <apt-private/private-json-hooks.h>
+#include <iomanip>
#include <ostream>
#include <sstream>
#include <stack>
@@ -23,7 +24,7 @@
/**
* @brief Simple JSON writer
*
- * This performs no error checking, or string escaping, be careful.
+ * This performs no error checking, so be careful.
*/
class APT_HIDDEN JsonWriter
{
@@ -109,22 +110,37 @@ class APT_HIDDEN JsonWriter
os << '}';
return *this;
}
+ std::ostream &encodeString(std::ostream &out, std::string const &str)
+ {
+ out << '"';
+
+ for (std::string::const_iterator c = str.begin(); c != str.end(); c++)
+ {
+ if (*c <= 0x1F || *c == '"' || *c == '\\')
+ ioprintf(out, "\\u%04X", *c);
+ else
+ out << *c;
+ }
+
+ out << '"';
+ return out;
+ }
JsonWriter &name(std::string const &name)
{
maybeComma();
- os << '"' << name << '"' << ':';
+ encodeString(os, name) << ':';
return *this;
}
JsonWriter &value(std::string const &value)
{
maybeComma();
- os << '"' << value << '"';
+ encodeString(os, value);
return *this;
}
JsonWriter &value(const char *value)
{
maybeComma();
- os << '"' << value << '"';
+ encodeString(os, value);
return *this;
}
JsonWriter &value(int value)
diff --git a/test/libapt/json_test.cc b/test/libapt/json_test.cc
new file mode 100644
index 000000000..e3317afc4
--- /dev/null
+++ b/test/libapt/json_test.cc
@@ -0,0 +1,45 @@
+#include <config.h>
+#include "../../apt-private/private-cachefile.cc"
+#include "../../apt-private/private-json-hooks.cc"
+#include <gtest/gtest.h>
+#include <string>
+
+TEST(JsonTest, JsonString)
+{
+ std::ostringstream os;
+
+ // Check for escaping backslash and quotation marks, and ensure that we do not change number formatting
+ JsonWriter(os).value("H al\"l\\o").value(17);
+
+ EXPECT_EQ("\"H al\\u0022l\\u005Co\"17", os.str());
+
+ for (int i = 0; i <= 0x1F; i++)
+ {
+ os.str("");
+
+ JsonWriter(os).encodeString(os, std::string("X") + char(i) + "Z");
+
+ std::string exp;
+ strprintf(exp, "\"X\\u%04XZ\"", i);
+
+ EXPECT_EQ(exp, os.str());
+ }
+}
+
+TEST(JsonTest, JsonObject)
+{
+ std::ostringstream os;
+
+ JsonWriter(os).beginObject().name("key").value("value").endObject();
+
+ EXPECT_EQ("{\"key\":\"value\"}", os.str());
+}
+
+TEST(JsonTest, JsonArrayAndValues)
+{
+ std::ostringstream os;
+
+ JsonWriter(os).beginArray().value(0).value("value").value(1).value(true).endArray();
+
+ EXPECT_EQ("[0,\"value\",1,true]", os.str());
+}