1 /**
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "json_builder.h"
17
18 #include "utils/string_helpers.h"
19
20 #include <algorithm>
21
22 using panda::helpers::string::Format;
23
24 namespace panda {
JsonEscape(std::ostream & os,std::string_view string)25 void JsonEscape(std::ostream &os, std::string_view string)
26 {
27 os << '"';
28
29 while (!string.empty()) {
30 auto iter =
31 std::find_if(string.begin(), string.end(), [](char ch) { return ch == '"' || ch == '\\' || ch < ' '; });
32 auto pos = iter - string.begin();
33
34 os << string.substr(0, pos);
35
36 if (iter == string.end()) {
37 break;
38 }
39
40 os << '\\';
41
42 switch (*iter) {
43 case '"':
44 case '\\':
45 os << *iter;
46 break;
47 case '\b':
48 os << 'b';
49 break;
50 case '\f':
51 os << 'f';
52 break;
53 case '\n':
54 os << 'n';
55 break;
56 case '\r':
57 os << 'r';
58 break;
59 case '\t':
60 os << 't';
61 break;
62 default:
63 os << Format("u%04X", *iter); // NOLINT(cppcoreguidelines-pro-type-vararg)
64 }
65
66 string.remove_prefix(pos + 1);
67 }
68
69 os << '"';
70 }
71 } // namespace panda
72