Skip to content

Commit

Permalink
Merge pull request #301 from redboltz/json_escape
Browse files Browse the repository at this point in the history
Added JSON escape for values between 0x00 and 0x1f, and 0x7f.
  • Loading branch information
redboltz committed Jul 4, 2015
2 parents d26e68e + 860a5ae commit e0a2c2a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
13 changes: 10 additions & 3 deletions include/msgpack/object.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
#include <limits>
#include <ostream>
#include <typeinfo>
#include <iomanip>

namespace msgpack {

Expand Down Expand Up @@ -724,9 +725,15 @@ inline std::ostream& operator<< (std::ostream& s, const msgpack::object& o)
case '\t':
s << "\\t";
break;
default:
s << c;
break;
default: {
unsigned int code = static_cast<unsigned int>(c);
if (code < 0x20 || code == 0x7f) {
s << "\\u" << std::hex << std::setw(4) << std::setfill('0') << (code & 0xff);
}
else {
s << c;
}
} break;
}
}
s << '"';
Expand Down
14 changes: 14 additions & 0 deletions test/json.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,17 @@ TEST(json, escape)
ss << o;
EXPECT_EQ(ss.str(), "\"\\\"\\\\\\/\\b\\f\\n\\r\\tabc\"");
}

TEST(json, escape_cc)
{
std::string s;
for (int i = 0; i < 0x20; ++i)
s.push_back(static_cast<char>(i));
s.push_back(0x7f);
s.push_back(0x20);
msgpack::zone z;
msgpack::object o(s, z);
std::stringstream ss;
ss << o;
EXPECT_EQ(ss.str(), "\"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\\u007f \"");
}

0 comments on commit e0a2c2a

Please sign in to comment.