/src/node/src/json_utils.cc
Line | Count | Source (jump to first uncovered line) |
1 | | #include "json_utils.h" |
2 | | |
3 | | namespace node { |
4 | | |
5 | 0 | std::string EscapeJsonChars(std::string_view str) { |
6 | | // 'static constexpr' is slightly better than static const |
7 | | // since the initialization occurs at compile time. |
8 | | // See https://lemire.me/blog/I3Cah |
9 | 0 | static constexpr std::string_view control_symbols[0x20] = { |
10 | 0 | "\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", |
11 | 0 | "\\u0006", "\\u0007", "\\b", "\\t", "\\n", "\\u000b", |
12 | 0 | "\\f", "\\r", "\\u000e", "\\u000f", "\\u0010", "\\u0011", |
13 | 0 | "\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017", |
14 | 0 | "\\u0018", "\\u0019", "\\u001a", "\\u001b", "\\u001c", "\\u001d", |
15 | 0 | "\\u001e", "\\u001f"}; |
16 | |
|
17 | 0 | std::string ret; |
18 | 0 | size_t last_pos = 0; |
19 | 0 | size_t pos = 0; |
20 | 0 | for (; pos < str.size(); ++pos) { |
21 | 0 | std::string replace; |
22 | 0 | char ch = str[pos]; |
23 | 0 | if (ch == '\\') { |
24 | 0 | replace = "\\\\"; |
25 | 0 | } else if (ch == '\"') { |
26 | 0 | replace = "\\\""; |
27 | 0 | } else { |
28 | 0 | size_t num = static_cast<size_t>(ch); |
29 | 0 | if (num < 0x20) replace = control_symbols[num]; |
30 | 0 | } |
31 | 0 | if (!replace.empty()) { |
32 | 0 | if (pos > last_pos) { |
33 | 0 | ret += str.substr(last_pos, pos - last_pos); |
34 | 0 | } |
35 | 0 | last_pos = pos + 1; |
36 | 0 | ret += replace; |
37 | 0 | } |
38 | 0 | } |
39 | | // Append any remaining symbols. |
40 | 0 | if (last_pos < str.size()) { |
41 | 0 | ret += str.substr(last_pos, pos - last_pos); |
42 | 0 | } |
43 | 0 | return ret; |
44 | 0 | } |
45 | | |
46 | 0 | std::string Reindent(const std::string& str, int indent_depth) { |
47 | 0 | if (indent_depth <= 0) return str; |
48 | 0 | const std::string indent(indent_depth, ' '); |
49 | 0 | std::string out; |
50 | 0 | std::string::size_type pos = 0; |
51 | 0 | for (;;) { |
52 | 0 | std::string::size_type prev_pos = pos; |
53 | 0 | pos = str.find('\n', pos); |
54 | |
|
55 | 0 | out.append(indent); |
56 | |
|
57 | 0 | if (pos == std::string::npos) { |
58 | 0 | out.append(str, prev_pos, std::string::npos); |
59 | 0 | break; |
60 | 0 | } else { |
61 | 0 | pos++; |
62 | 0 | out.append(str, prev_pos, pos - prev_pos); |
63 | 0 | } |
64 | 0 | } |
65 | |
|
66 | 0 | return out; |
67 | 0 | } |
68 | | |
69 | | } // namespace node |