3 * Copyright 2015 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 #include <grpc/support/port_platform.h>
24 #include "absl/strings/string_view.h"
26 #include <grpc/support/alloc.h>
27 #include <grpc/support/log.h>
29 #include "src/core/lib/json/json.h"
35 /* The idea of the writer is basically symmetrical of the reader. While the
36 * reader emits various calls to your code, the writer takes basically the
37 * same calls and emit json out of it. It doesn't try to make any check on
38 * the order of the calls you do on it. Meaning you can theorically force
39 * it to generate invalid json.
41 * Also, unlike the reader, the writer expects UTF-8 encoded input strings.
42 * These strings will be UTF-8 validated, and any invalid character will
43 * cut the conversion short, before any invalid UTF-8 sequence, thus forming
44 * a valid UTF-8 string overall.
48 static std::string Dump(const Json& value, int indent);
51 explicit JsonWriter(int indent) : indent_(indent) {}
53 void OutputCheck(size_t needed);
54 void OutputChar(char c);
55 void OutputString(const absl::string_view str);
58 void EscapeUtf16(uint16_t utf16);
59 void EscapeString(const std::string& string);
60 void ContainerBegins(Json::Type type);
61 void ContainerEnds(Json::Type type);
62 void ObjectKey(const std::string& string);
63 void ValueRaw(const std::string& string);
64 void ValueString(const std::string& string);
66 void DumpObject(const Json::Object& object);
67 void DumpArray(const Json::Array& array);
68 void DumpValue(const Json& value);
72 bool container_empty_ = true;
73 bool got_key_ = false;
77 /* This function checks if there's enough space left in the output buffer,
78 * and will enlarge it if necessary. We're only allocating chunks of 256
79 * bytes at a time (or multiples thereof).
81 void JsonWriter::OutputCheck(size_t needed) {
82 size_t free_space = output_.capacity() - output_.size();
83 if (free_space >= needed) return;
85 /* Round up by 256 bytes. */
86 needed = (needed + 0xff) & ~0xffU;
87 output_.reserve(output_.capacity() + needed);
90 void JsonWriter::OutputChar(char c) {
95 void JsonWriter::OutputString(const absl::string_view str) {
96 OutputCheck(str.size());
97 output_.append(str.data(), str.size());
100 void JsonWriter::OutputIndent() {
101 static const char spacesstr[] =
106 unsigned spaces = static_cast<unsigned>(depth_ * indent_);
107 if (indent_ == 0) return;
112 while (spaces >= (sizeof(spacesstr) - 1)) {
113 OutputString(absl::string_view(spacesstr, sizeof(spacesstr) - 1));
114 spaces -= static_cast<unsigned>(sizeof(spacesstr) - 1);
116 if (spaces == 0) return;
118 absl::string_view(spacesstr + sizeof(spacesstr) - 1 - spaces, spaces));
121 void JsonWriter::ValueEnd() {
122 if (container_empty_) {
123 container_empty_ = false;
124 if (indent_ == 0 || depth_ == 0) return;
128 if (indent_ == 0) return;
133 void JsonWriter::EscapeUtf16(uint16_t utf16) {
134 static const char hex[] = "0123456789abcdef";
135 OutputString(absl::string_view("\\u", 2));
136 OutputChar(hex[(utf16 >> 12) & 0x0f]);
137 OutputChar(hex[(utf16 >> 8) & 0x0f]);
138 OutputChar(hex[(utf16 >> 4) & 0x0f]);
139 OutputChar(hex[(utf16)&0x0f]);
142 void JsonWriter::EscapeString(const std::string& string) {
144 for (size_t idx = 0; idx < string.size(); ++idx) {
145 uint8_t c = static_cast<uint8_t>(string[idx]);
148 } else if (c >= 32 && c <= 126) {
149 if (c == '\\' || c == '"') OutputChar('\\');
150 OutputChar(static_cast<char>(c));
151 } else if (c < 32 || c == 127) {
154 OutputString(absl::string_view("\\b", 2));
157 OutputString(absl::string_view("\\f", 2));
160 OutputString(absl::string_view("\\n", 2));
163 OutputString(absl::string_view("\\r", 2));
166 OutputString(absl::string_view("\\t", 2));
177 if ((c & 0xe0) == 0xc0) {
180 } else if ((c & 0xf0) == 0xe0) {
183 } else if ((c & 0xf8) == 0xf0) {
189 for (i = 0; i < extra; i++) {
192 /* Breaks out and bail if we hit the end of the string. */
193 if (idx == string.size()) {
197 c = static_cast<uint8_t>(string[idx]);
198 /* Breaks out and bail on any invalid UTF-8 sequence, including \0. */
199 if ((c & 0xc0) != 0x80) {
206 /* The range 0xd800 - 0xdfff is reserved by the surrogates ad vitam.
207 * Any other range is technically reserved for future usage, so if we
208 * don't want the software to break in the future, we have to allow
209 * anything else. The first non-unicode character is 0x110000. */
210 if (((utf32 >= 0xd800) && (utf32 <= 0xdfff)) || (utf32 >= 0x110000)) {
213 if (utf32 >= 0x10000) {
214 /* If utf32 contains a character that is above 0xffff, it needs to be
215 * broken down into a utf-16 surrogate pair. A surrogate pair is first
216 * a high surrogate, followed by a low surrogate. Each surrogate holds
217 * 10 bits of usable data, thus allowing a total of 20 bits of data.
218 * The high surrogate marker is 0xd800, while the low surrogate marker
219 * is 0xdc00. The low 10 bits of each will be the usable data.
221 * After re-combining the 20 bits of data, one has to add 0x10000 to
222 * the resulting value, in order to obtain the original character.
223 * This is obviously because the range 0x0000 - 0xffff can be written
224 * without any special trick.
226 * Since 0x10ffff is the highest allowed character, we're working in
227 * the range 0x00000 - 0xfffff after we decrement it by 0x10000.
228 * That range is exactly 20 bits.
231 EscapeUtf16(static_cast<uint16_t>(0xd800 | (utf32 >> 10)));
232 EscapeUtf16(static_cast<uint16_t>(0xdc00 | (utf32 & 0x3ff)));
234 EscapeUtf16(static_cast<uint16_t>(utf32));
241 void JsonWriter::ContainerBegins(Json::Type type) {
242 if (!got_key_) ValueEnd();
244 OutputChar(type == Json::Type::OBJECT ? '{' : '[');
245 container_empty_ = true;
250 void JsonWriter::ContainerEnds(Json::Type type) {
251 if (indent_ && !container_empty_) OutputChar('\n');
253 if (!container_empty_) OutputIndent();
254 OutputChar(type == Json::Type::OBJECT ? '}' : ']');
255 container_empty_ = false;
259 void JsonWriter::ObjectKey(const std::string& string) {
262 EscapeString(string);
267 void JsonWriter::ValueRaw(const std::string& string) {
268 if (!got_key_) ValueEnd();
270 OutputString(string);
274 void JsonWriter::ValueString(const std::string& string) {
275 if (!got_key_) ValueEnd();
277 EscapeString(string);
281 void JsonWriter::DumpObject(const Json::Object& object) {
282 ContainerBegins(Json::Type::OBJECT);
283 for (const auto& p : object) {
284 ObjectKey(p.first.data());
287 ContainerEnds(Json::Type::OBJECT);
290 void JsonWriter::DumpArray(const Json::Array& array) {
291 ContainerBegins(Json::Type::ARRAY);
292 for (const auto& v : array) {
295 ContainerEnds(Json::Type::ARRAY);
298 void JsonWriter::DumpValue(const Json& value) {
299 switch (value.type()) {
300 case Json::Type::OBJECT:
301 DumpObject(value.object_value());
303 case Json::Type::ARRAY:
304 DumpArray(value.array_value());
306 case Json::Type::STRING:
307 ValueString(value.string_value());
309 case Json::Type::NUMBER:
310 ValueRaw(value.string_value());
312 case Json::Type::JSON_TRUE:
313 ValueRaw(std::string("true", 4));
315 case Json::Type::JSON_FALSE:
316 ValueRaw(std::string("false", 5));
318 case Json::Type::JSON_NULL:
319 ValueRaw(std::string("null", 4));
322 GPR_UNREACHABLE_CODE(abort());
326 std::string JsonWriter::Dump(const Json& value, int indent) {
327 JsonWriter writer(indent);
328 writer.DumpValue(value);
329 return std::move(writer.output_);
334 std::string Json::Dump(int indent) const {
335 return JsonWriter::Dump(*this, indent);
338 } // namespace grpc_core