blob: 9f605b82e2bb41a65732b2edb8713a3db456e376 [file]
// Copyright 2021 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "json.h"
#include <cstdio>
#include <string>
void EncodeAppendJSONString(std::string* out, StringPiece in) {
const char hex_digits[] = "0123456789abcdef";
for (auto c : in) {
switch (c) {
case '\b':
out->append("\\b");
break;
case '\f':
out->append("\\f");
break;
case '\n':
out->append("\\n");
break;
case '\r':
out->append("\\r");
break;
case '\t':
out->append("\\t");
break;
case '\\':
out->append("\\\\");
break;
case '"':
out->append("\\\"");
break;
default:
if (0x0 <= c && c < 0x20) { // non-printable chars.
out->append("\\u00");
out->push_back(hex_digits[c >> 4]);
out->push_back(hex_digits[c & 0xf]);
} else {
out->push_back(c);
}
}
}
}
std::string EncodeJSONString(StringPiece in) {
std::string out;
out.reserve(in.size() * 1.2);
EncodeAppendJSONString(&out, in);
return out;
}
void PrintJSONString(StringPiece in) {
std::string out = EncodeJSONString(in);
fwrite(out.c_str(), 1, out.length(), stdout);
}