1695b41eeSopenharmony_ci// Copyright 2021 Google Inc. All Rights Reserved.
2695b41eeSopenharmony_ci//
3695b41eeSopenharmony_ci// Licensed under the Apache License, Version 2.0 (the "License");
4695b41eeSopenharmony_ci// you may not use this file except in compliance with the License.
5695b41eeSopenharmony_ci// You may obtain a copy of the License at
6695b41eeSopenharmony_ci//
7695b41eeSopenharmony_ci//     http://www.apache.org/licenses/LICENSE-2.0
8695b41eeSopenharmony_ci//
9695b41eeSopenharmony_ci// Unless required by applicable law or agreed to in writing, software
10695b41eeSopenharmony_ci// distributed under the License is distributed on an "AS IS" BASIS,
11695b41eeSopenharmony_ci// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12695b41eeSopenharmony_ci// See the License for the specific language governing permissions and
13695b41eeSopenharmony_ci// limitations under the License.
14695b41eeSopenharmony_ci
15695b41eeSopenharmony_ci#include "json.h"
16695b41eeSopenharmony_ci
17695b41eeSopenharmony_ci#include <cstdio>
18695b41eeSopenharmony_ci#include <string>
19695b41eeSopenharmony_ci
20695b41eeSopenharmony_cistd::string EncodeJSONString(const std::string& in) {
21695b41eeSopenharmony_ci  static const char* hex_digits = "0123456789abcdef";
22695b41eeSopenharmony_ci  std::string out;
23695b41eeSopenharmony_ci  out.reserve(in.length() * 1.2);
24695b41eeSopenharmony_ci  for (std::string::const_iterator it = in.begin(); it != in.end(); ++it) {
25695b41eeSopenharmony_ci    char c = *it;
26695b41eeSopenharmony_ci    if (c == '\b')
27695b41eeSopenharmony_ci      out += "\\b";
28695b41eeSopenharmony_ci    else if (c == '\f')
29695b41eeSopenharmony_ci      out += "\\f";
30695b41eeSopenharmony_ci    else if (c == '\n')
31695b41eeSopenharmony_ci      out += "\\n";
32695b41eeSopenharmony_ci    else if (c == '\r')
33695b41eeSopenharmony_ci      out += "\\r";
34695b41eeSopenharmony_ci    else if (c == '\t')
35695b41eeSopenharmony_ci      out += "\\t";
36695b41eeSopenharmony_ci    else if (0x0 <= c && c < 0x20) {
37695b41eeSopenharmony_ci      out += "\\u00";
38695b41eeSopenharmony_ci      out += hex_digits[c >> 4];
39695b41eeSopenharmony_ci      out += hex_digits[c & 0xf];
40695b41eeSopenharmony_ci    } else if (c == '\\')
41695b41eeSopenharmony_ci      out += "\\\\";
42695b41eeSopenharmony_ci    else if (c == '\"')
43695b41eeSopenharmony_ci      out += "\\\"";
44695b41eeSopenharmony_ci    else
45695b41eeSopenharmony_ci      out += c;
46695b41eeSopenharmony_ci  }
47695b41eeSopenharmony_ci  return out;
48695b41eeSopenharmony_ci}
49695b41eeSopenharmony_ci
50695b41eeSopenharmony_civoid PrintJSONString(const std::string& in) {
51695b41eeSopenharmony_ci  std::string out = EncodeJSONString(in);
52695b41eeSopenharmony_ci  fwrite(out.c_str(), 1, out.length(), stdout);
53695b41eeSopenharmony_ci}
54