Imported Upstream version 1.34.0
[platform/upstream/grpc.git] / src / core / lib / json / json_writer.cc
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
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
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  */
18
19 #include <grpc/support/port_platform.h>
20
21 #include <stdlib.h>
22 #include <string.h>
23
24 #include "absl/strings/string_view.h"
25
26 #include <grpc/support/alloc.h>
27 #include <grpc/support/log.h>
28
29 #include "src/core/lib/json/json.h"
30
31 namespace grpc_core {
32
33 namespace {
34
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.
40  *
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.
45  */
46 class JsonWriter {
47  public:
48   static std::string Dump(const Json& value, int indent);
49
50  private:
51   explicit JsonWriter(int indent) : indent_(indent) {}
52
53   void OutputCheck(size_t needed);
54   void OutputChar(char c);
55   void OutputString(const absl::string_view str);
56   void OutputIndent();
57   void ValueEnd();
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);
65
66   void DumpObject(const Json::Object& object);
67   void DumpArray(const Json::Array& array);
68   void DumpValue(const Json& value);
69
70   int indent_;
71   int depth_ = 0;
72   bool container_empty_ = true;
73   bool got_key_ = false;
74   std::string output_;
75 };
76
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).
80  */
81 void JsonWriter::OutputCheck(size_t needed) {
82   size_t free_space = output_.capacity() - output_.size();
83   if (free_space >= needed) return;
84   needed -= free_space;
85   /* Round up by 256 bytes. */
86   needed = (needed + 0xff) & ~0xffU;
87   output_.reserve(output_.capacity() + needed);
88 }
89
90 void JsonWriter::OutputChar(char c) {
91   OutputCheck(1);
92   output_.push_back(c);
93 }
94
95 void JsonWriter::OutputString(const absl::string_view str) {
96   OutputCheck(str.size());
97   output_.append(str.data(), str.size());
98 }
99
100 void JsonWriter::OutputIndent() {
101   static const char spacesstr[] =
102       "                "
103       "                "
104       "                "
105       "                ";
106   unsigned spaces = static_cast<unsigned>(depth_ * indent_);
107   if (indent_ == 0) return;
108   if (got_key_) {
109     OutputChar(' ');
110     return;
111   }
112   while (spaces >= (sizeof(spacesstr) - 1)) {
113     OutputString(absl::string_view(spacesstr, sizeof(spacesstr) - 1));
114     spaces -= static_cast<unsigned>(sizeof(spacesstr) - 1);
115   }
116   if (spaces == 0) return;
117   OutputString(
118       absl::string_view(spacesstr + sizeof(spacesstr) - 1 - spaces, spaces));
119 }
120
121 void JsonWriter::ValueEnd() {
122   if (container_empty_) {
123     container_empty_ = false;
124     if (indent_ == 0 || depth_ == 0) return;
125     OutputChar('\n');
126   } else {
127     OutputChar(',');
128     if (indent_ == 0) return;
129     OutputChar('\n');
130   }
131 }
132
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]);
140 }
141
142 void JsonWriter::EscapeString(const std::string& string) {
143   OutputChar('"');
144   for (size_t idx = 0; idx < string.size(); ++idx) {
145     uint8_t c = static_cast<uint8_t>(string[idx]);
146     if (c == 0) {
147       break;
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) {
152       switch (c) {
153         case '\b':
154           OutputString(absl::string_view("\\b", 2));
155           break;
156         case '\f':
157           OutputString(absl::string_view("\\f", 2));
158           break;
159         case '\n':
160           OutputString(absl::string_view("\\n", 2));
161           break;
162         case '\r':
163           OutputString(absl::string_view("\\r", 2));
164           break;
165         case '\t':
166           OutputString(absl::string_view("\\t", 2));
167           break;
168         default:
169           EscapeUtf16(c);
170           break;
171       }
172     } else {
173       uint32_t utf32 = 0;
174       int extra = 0;
175       int i;
176       int valid = 1;
177       if ((c & 0xe0) == 0xc0) {
178         utf32 = c & 0x1f;
179         extra = 1;
180       } else if ((c & 0xf0) == 0xe0) {
181         utf32 = c & 0x0f;
182         extra = 2;
183       } else if ((c & 0xf8) == 0xf0) {
184         utf32 = c & 0x07;
185         extra = 3;
186       } else {
187         break;
188       }
189       for (i = 0; i < extra; i++) {
190         utf32 <<= 6;
191         ++idx;
192         /* Breaks out and bail if we hit the end of the string. */
193         if (idx == string.size()) {
194           valid = 0;
195           break;
196         }
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) {
200           valid = 0;
201           break;
202         }
203         utf32 |= c & 0x3f;
204       }
205       if (!valid) break;
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)) {
211         break;
212       }
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.
220          *
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.
225          *
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.
229          */
230         utf32 -= 0x10000;
231         EscapeUtf16(static_cast<uint16_t>(0xd800 | (utf32 >> 10)));
232         EscapeUtf16(static_cast<uint16_t>(0xdc00 | (utf32 & 0x3ff)));
233       } else {
234         EscapeUtf16(static_cast<uint16_t>(utf32));
235       }
236     }
237   }
238   OutputChar('"');
239 }
240
241 void JsonWriter::ContainerBegins(Json::Type type) {
242   if (!got_key_) ValueEnd();
243   OutputIndent();
244   OutputChar(type == Json::Type::OBJECT ? '{' : '[');
245   container_empty_ = true;
246   got_key_ = false;
247   depth_++;
248 }
249
250 void JsonWriter::ContainerEnds(Json::Type type) {
251   if (indent_ && !container_empty_) OutputChar('\n');
252   depth_--;
253   if (!container_empty_) OutputIndent();
254   OutputChar(type == Json::Type::OBJECT ? '}' : ']');
255   container_empty_ = false;
256   got_key_ = false;
257 }
258
259 void JsonWriter::ObjectKey(const std::string& string) {
260   ValueEnd();
261   OutputIndent();
262   EscapeString(string);
263   OutputChar(':');
264   got_key_ = true;
265 }
266
267 void JsonWriter::ValueRaw(const std::string& string) {
268   if (!got_key_) ValueEnd();
269   OutputIndent();
270   OutputString(string);
271   got_key_ = false;
272 }
273
274 void JsonWriter::ValueString(const std::string& string) {
275   if (!got_key_) ValueEnd();
276   OutputIndent();
277   EscapeString(string);
278   got_key_ = false;
279 }
280
281 void JsonWriter::DumpObject(const Json::Object& object) {
282   ContainerBegins(Json::Type::OBJECT);
283   for (const auto& p : object) {
284     ObjectKey(p.first.data());
285     DumpValue(p.second);
286   }
287   ContainerEnds(Json::Type::OBJECT);
288 }
289
290 void JsonWriter::DumpArray(const Json::Array& array) {
291   ContainerBegins(Json::Type::ARRAY);
292   for (const auto& v : array) {
293     DumpValue(v);
294   }
295   ContainerEnds(Json::Type::ARRAY);
296 }
297
298 void JsonWriter::DumpValue(const Json& value) {
299   switch (value.type()) {
300     case Json::Type::OBJECT:
301       DumpObject(value.object_value());
302       break;
303     case Json::Type::ARRAY:
304       DumpArray(value.array_value());
305       break;
306     case Json::Type::STRING:
307       ValueString(value.string_value());
308       break;
309     case Json::Type::NUMBER:
310       ValueRaw(value.string_value());
311       break;
312     case Json::Type::JSON_TRUE:
313       ValueRaw(std::string("true", 4));
314       break;
315     case Json::Type::JSON_FALSE:
316       ValueRaw(std::string("false", 5));
317       break;
318     case Json::Type::JSON_NULL:
319       ValueRaw(std::string("null", 4));
320       break;
321     default:
322       GPR_UNREACHABLE_CODE(abort());
323   }
324 }
325
326 std::string JsonWriter::Dump(const Json& value, int indent) {
327   JsonWriter writer(indent);
328   writer.DumpValue(value);
329   return std::move(writer.output_);
330 }
331
332 }  // namespace
333
334 std::string Json::Dump(int indent) const {
335   return JsonWriter::Dump(*this, indent);
336 }
337
338 }  // namespace grpc_core