-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.cpp
364 lines (327 loc) · 11.6 KB
/
json.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
#include "json.h"
#include <iterator>
namespace json {
namespace {
using namespace std::literals;
Node LoadNode(std::istream& input);
Node LoadString(std::istream& input);
std::string LoadLiteral(std::istream& input) {
std::string s;
while (std::isalpha(input.peek())) {
s.push_back(static_cast<char>(input.get()));
}
return s;
}
Node LoadArray(std::istream& input) {
std::vector<Node> result;
for (char c; input >> c && c != ']';) {
if (c != ',') {
input.putback(c);
}
result.push_back(LoadNode(input));
}
if (!input) {
throw ParsingError("Array parsing error"s);
}
return Node(std::move(result));
}
Node LoadDict(std::istream& input) {
Dict dict;
for (char c; input >> c && c != '}';) {
if (c == '"') {
std::string key = LoadString(input).AsString();
if (input >> c && c == ':') {
if (dict.find(key) != dict.end()) {
throw ParsingError("Duplicate key '"s + key + "' have been found");
}
dict.emplace(std::move(key), LoadNode(input));
}
else {
throw ParsingError(": is expected but '"s + c + "' has been found"s);
}
}
else if (c != ',') {
throw ParsingError(R"(',' is expected but ')"s + c + "' has been found"s);
}
}
if (!input) {
throw ParsingError("Dictionary parsing error"s);
}
return Node(std::move(dict));
}
Node LoadString(std::istream& input) {
auto it = std::istreambuf_iterator<char>(input);
auto end = std::istreambuf_iterator<char>();
std::string s;
while (true) {
if (it == end) {
throw ParsingError("String parsing error");
}
const char ch = *it;
if (ch == '"') {
++it;
break;
}
else if (ch == '\\') {
++it;
if (it == end) {
throw ParsingError("String parsing error");
}
const char escaped_char = *(it);
switch (escaped_char) {
case 'n':
s.push_back('\n');
break;
case 't':
s.push_back('\t');
break;
case 'r':
s.push_back('\r');
break;
case '"':
s.push_back('"');
break;
case '\\':
s.push_back('\\');
break;
default:
throw ParsingError("Unrecognized escape sequence \\"s + escaped_char);
}
}
else if (ch == '\n' || ch == '\r') {
throw ParsingError("Unexpected end of line"s);
}
else {
s.push_back(ch);
}
++it;
}
return Node(std::move(s));
}
Node LoadBool(std::istream& input) {
const auto s = LoadLiteral(input);
if (s == "true"sv) {
return Node{ true };
}
else if (s == "false"sv) {
return Node{ false };
}
else {
throw ParsingError("Failed to parse '"s + s + "' as bool"s);
}
}
Node LoadNull(std::istream& input) {
if (auto literal = LoadLiteral(input); literal == "null"sv) {
return Node{ nullptr };
}
else {
throw ParsingError("Failed to parse '"s + literal + "' as null"s);
}
}
Node LoadNumber(std::istream& input) {
std::string parsed_num;
// Ñ÷èòûâàåò â parsed_num î÷åðåäíîé ñèìâîë èç input
auto read_char = [&parsed_num, &input] {
parsed_num += static_cast<char>(input.get());
if (!input) {
throw ParsingError("Failed to read number from stream"s);
}
};
// Ñ÷èòûâàåò îäíó èëè áîëåå öèôð â parsed_num èç input
auto read_digits = [&input, read_char] {
if (!std::isdigit(input.peek())) {
throw ParsingError("A digit is expected"s);
}
while (std::isdigit(input.peek())) {
read_char();
}
};
if (input.peek() == '-') {
read_char();
}
// Ïàðñèì öåëóþ ÷àñòü ÷èñëà
if (input.peek() == '0') {
read_char();
// Ïîñëå 0 â JSON íå ìîãóò èäòè äðóãèå öèôðû
}
else {
read_digits();
}
bool is_int = true;
// Ïàðñèì äðîáíóþ ÷àñòü ÷èñëà
if (input.peek() == '.') {
read_char();
read_digits();
is_int = false;
}
// Ïàðñèì ýêñïîíåíöèàëüíóþ ÷àñòü ÷èñëà
if (int ch = input.peek(); ch == 'e' || ch == 'E') {
read_char();
if (ch = input.peek(); ch == '+' || ch == '-') {
read_char();
}
read_digits();
is_int = false;
}
try {
if (is_int) {
// Ñíà÷àëà ïðîáóåì ïðåîáðàçîâàòü ñòðîêó â int
try {
return std::stoi(parsed_num);
}
catch (...) {
//  ñëó÷àå íåóäà÷è, íàïðèìåð, ïðè ïåðåïîëíåíèè
// êîä íèæå ïîïðîáóåò ïðåîáðàçîâàòü ñòðîêó â double
}
}
return std::stod(parsed_num);
}
catch (...) {
throw ParsingError("Failed to convert "s + parsed_num + " to number"s);
}
}
Node LoadNode(std::istream& input) {
char c;
if (!(input >> c)) {
throw ParsingError("Unexpected EOF"s);
}
switch (c) {
case '[':
return LoadArray(input);
case '{':
return LoadDict(input);
case '"':
return LoadString(input);
case 't':
// Àòðèáóò [[fallthrough]] (ïðîâàëèòüñÿ) íè÷åãî íå äåëàåò, è ÿâëÿåòñÿ
// ïîäñêàçêîé êîìïèëÿòîðó è ÷åëîâåêó, ÷òî çäåñü ïðîãðàììèñò ÿâíî çàäóìûâàë
// ðàçðåøèòü ïåðåõîä ê èíñòðóêöèè ñëåäóþùåé âåòêè case, à íå ñëó÷àéíî çàáûë
// íàïèñàòü break, return èëè throw.
//  äàííîì ñëó÷àå, âñòðåòèâ t èëè f, ïåðåõîäèì ê ïîïûòêå ïàðñèíãà
// ëèòåðàëîâ true ëèáî false
[[fallthrough]];
case 'f':
input.putback(c);
return LoadBool(input);
case 'n':
input.putback(c);
return LoadNull(input);
default:
input.putback(c);
return LoadNumber(input);
}
}
struct PrintContext {
std::ostream& out;
int indent_step = 4;
int indent = 0;
void PrintIndent() const {
for (int i = 0; i < indent; ++i) {
out.put(' ');
}
}
PrintContext Indented() const {
return { out, indent_step, indent_step + indent };
}
};
void PrintNode(const Node& value, const PrintContext& ctx);
template <typename Value>
void PrintValue(const Value& value, const PrintContext& ctx) {
ctx.out << value;
}
void PrintString(const std::string& value, std::ostream& out) {
out.put('"');
for (const char c : value) {
switch (c) {
case '\r':
out << "\\r"sv;
break;
case '\n':
out << "\\n"sv;
break;
case '"':
// Ñèìâîëû " è \ âûâîäÿòñÿ êàê \" èëè \\, ñîîòâåòñòâåííî
[[fallthrough]];
case '\\':
out.put('\\');
[[fallthrough]];
default:
out.put(c);
break;
}
}
out.put('"');
}
template <>
void PrintValue<std::string>(const std::string& value, const PrintContext& ctx) {
PrintString(value, ctx.out);
}
template <>
void PrintValue<std::nullptr_t>(const std::nullptr_t&, const PrintContext& ctx) {
ctx.out << "null"sv;
}
//  ñïåöèàëèçàöè øàáëîíà PrintValue äëÿ òèïà bool ïàðàìåòð value ïåðåäà¸òñÿ
// ïî êîíñòàíòíîé ññûëêå, êàê è â îñíîâíîì øàáëîíå.
//  êà÷åñòâå àëüòåðíàòèâû ìîæíî èñïîëüçîâàòü ïåðåãðóçêó:
// void PrintValue(bool value, const PrintContext& ctx);
template <>
void PrintValue<bool>(const bool& value, const PrintContext& ctx) {
ctx.out << (value ? "true"sv : "false"sv);
}
template <>
void PrintValue<Array>(const Array& nodes, const PrintContext& ctx) {
std::ostream& out = ctx.out;
out << "[\n"sv;
bool first = true;
auto inner_ctx = ctx.Indented();
for (const Node& node : nodes) {
if (first) {
first = false;
}
else {
out << ",\n"sv;
}
inner_ctx.PrintIndent();
PrintNode(node, inner_ctx);
}
out.put('\n');
ctx.PrintIndent();
out.put(']');
}
template <>
void PrintValue<Dict>(const Dict& nodes, const PrintContext& ctx) {
std::ostream& out = ctx.out;
out << "{\n"sv;
bool first = true;
auto inner_ctx = ctx.Indented();
for (const auto& [key, node] : nodes) {
if (first) {
first = false;
}
else {
out << ",\n"sv;
}
inner_ctx.PrintIndent();
PrintString(key, ctx.out);
out << ": "sv;
PrintNode(node, inner_ctx);
}
out.put('\n');
ctx.PrintIndent();
out.put('}');
}
void PrintNode(const Node& node, const PrintContext& ctx) {
std::visit(
[&ctx](const auto& value) {
PrintValue(value, ctx);
},
node.GetValue());
}
} // namespace
Document Load(std::istream& input) {
return Document{ LoadNode(input) };
}
void Print(const Document& doc, std::ostream& output) {
PrintNode(doc.GetRoot(), PrintContext{ output });
}
} // namespace json