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 using panda::helpers::string::Format;
21
22 namespace panda {
JsonEscape(std::ostream & os,std::string_view string)23 void JsonEscape(std::ostream &os, std::string_view string)
24 {
25 os << '"';
26
27 while (!string.empty()) {
28 auto iter =
29 std::find_if(string.begin(), string.end(), [](char ch) { return ch == '"' || ch == '\\' || ch < ' '; });
30 auto pos = iter - string.begin();
31
32 os << string.substr(0, pos);
33
34 if (iter == string.end()) {
35 break;
36 }
37
38 os << '\\';
39
40 switch (*iter) {
41 case '"':
42 case '\\':
43 os << *iter;
44 break;
45 case '\b':
46 os << 'b';
47 break;
48 case '\f':
49 os << 'f';
50 break;
51 case '\n':
52 os << 'n';
53 break;
54 case '\r':
55 os << 'r';
56 break;
57 case '\t':
58 os << 't';
59 break;
60 default:
61 os << Format("u%04X", *iter); // NOLINT(cppcoreguidelines-pro-type-vararg)
62 }
63
64 string.remove_prefix(pos + 1);
65 }
66
67 os << '"';
68 }
69 } // namespace panda
70