Skip to content

Commit e0a2c2a

Browse files
committed
Merge pull request #301 from redboltz/json_escape
Added JSON escape for values between 0x00 and 0x1f, and 0x7f.
2 parents d26e68e + 860a5ae commit e0a2c2a

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

include/msgpack/object.hpp

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
#include <limits>
3030
#include <ostream>
3131
#include <typeinfo>
32+
#include <iomanip>
3233

3334
namespace msgpack {
3435

@@ -724,9 +725,15 @@ inline std::ostream& operator<< (std::ostream& s, const msgpack::object& o)
724725
case '\t':
725726
s << "\\t";
726727
break;
727-
default:
728-
s << c;
729-
break;
728+
default: {
729+
unsigned int code = static_cast<unsigned int>(c);
730+
if (code < 0x20 || code == 0x7f) {
731+
s << "\\u" << std::hex << std::setw(4) << std::setfill('0') << (code & 0xff);
732+
}
733+
else {
734+
s << c;
735+
}
736+
} break;
730737
}
731738
}
732739
s << '"';

test/json.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,17 @@ TEST(json, escape)
3030
ss << o;
3131
EXPECT_EQ(ss.str(), "\"\\\"\\\\\\/\\b\\f\\n\\r\\tabc\"");
3232
}
33+
34+
TEST(json, escape_cc)
35+
{
36+
std::string s;
37+
for (int i = 0; i < 0x20; ++i)
38+
s.push_back(static_cast<char>(i));
39+
s.push_back(0x7f);
40+
s.push_back(0x20);
41+
msgpack::zone z;
42+
msgpack::object o(s, z);
43+
std::stringstream ss;
44+
ss << o;
45+
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 \"");
46+
}

0 commit comments

Comments
 (0)