1 |
|
|
#include "json_utils.h" |
2 |
|
|
|
3 |
|
|
namespace node { |
4 |
|
|
|
5 |
|
40037 |
std::string EscapeJsonChars(const std::string& str) { |
6 |
|
|
const std::string control_symbols[0x20] = { |
7 |
|
|
"\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", |
8 |
|
|
"\\u0006", "\\u0007", "\\b", "\\t", "\\n", "\\u000b", |
9 |
|
|
"\\f", "\\r", "\\u000e", "\\u000f", "\\u0010", "\\u0011", |
10 |
|
|
"\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017", |
11 |
|
|
"\\u0018", "\\u0019", "\\u001a", "\\u001b", "\\u001c", "\\u001d", |
12 |
✓✓ |
1361258 |
"\\u001e", "\\u001f"}; |
13 |
|
|
|
14 |
|
40037 |
std::string ret; |
15 |
|
40037 |
size_t last_pos = 0; |
16 |
|
40037 |
size_t pos = 0; |
17 |
✓✓ |
507109 |
for (; pos < str.size(); ++pos) { |
18 |
|
934144 |
std::string replace; |
19 |
|
467072 |
char ch = str[pos]; |
20 |
✓✓ |
467072 |
if (ch == '\\') { |
21 |
|
1 |
replace = "\\\\"; |
22 |
✓✓ |
467071 |
} else if (ch == '\"') { |
23 |
|
5 |
replace = "\\\""; |
24 |
|
|
} else { |
25 |
|
467066 |
size_t num = static_cast<size_t>(ch); |
26 |
✓✓ |
467066 |
if (num < 0x20) replace = control_symbols[num]; |
27 |
|
|
} |
28 |
✓✓ |
467072 |
if (!replace.empty()) { |
29 |
✓✓ |
72 |
if (pos > last_pos) { |
30 |
|
40 |
ret += str.substr(last_pos, pos - last_pos); |
31 |
|
|
} |
32 |
|
72 |
last_pos = pos + 1; |
33 |
|
72 |
ret += replace; |
34 |
|
|
} |
35 |
|
|
} |
36 |
|
|
// Append any remaining symbols. |
37 |
✓✓ |
40037 |
if (last_pos < str.size()) { |
38 |
|
39940 |
ret += str.substr(last_pos, pos - last_pos); |
39 |
|
|
} |
40 |
|
40037 |
return ret; |
41 |
|
|
} |
42 |
|
|
|
43 |
|
2 |
std::string Reindent(const std::string& str, int indent_depth) { |
44 |
✗✓ |
2 |
if (indent_depth <= 0) return str; |
45 |
|
4 |
const std::string indent(indent_depth, ' '); |
46 |
|
4 |
std::string out; |
47 |
|
2 |
std::string::size_type pos = 0; |
48 |
|
|
for (;;) { |
49 |
|
2507 |
std::string::size_type prev_pos = pos; |
50 |
|
2507 |
pos = str.find('\n', pos); |
51 |
|
|
|
52 |
|
2507 |
out.append(indent); |
53 |
|
|
|
54 |
✓✓ |
2507 |
if (pos == std::string::npos) { |
55 |
|
2 |
out.append(str, prev_pos, std::string::npos); |
56 |
|
2 |
break; |
57 |
|
|
} else { |
58 |
|
2505 |
pos++; |
59 |
|
2505 |
out.append(str, prev_pos, pos - prev_pos); |
60 |
|
|
} |
61 |
|
2505 |
} |
62 |
|
|
|
63 |
|
2 |
return out; |
64 |
|
|
} |
65 |
|
|
|
66 |
|
|
} // namespace node |