-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanyjson.cpp
427 lines (321 loc) · 8.98 KB
/
anyjson.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
// Copyright 2022 Gerard Gaudeau
// Distributed under MIT license
// See file LICENSE for detail at https://github.com/ggaudeau/anyjson/blob/main/LICENSE
#include "anyjson.hpp"
#include <string.h> // memset
#include <ctype.h> // isdigit
#include <iomanip> // quoted c++14
#include <sstream>
#include <stdexcept>
#include <typeindex>
#include <functional>
#include <unordered_map>
#include "anyjson_debug.hpp"
/// PARSING PART
namespace {
void consumeChar(std::istream& is, char expected) {
char ch;
print("consuming char ... ");
is.get(ch);
println(ch);
if (ch != expected) {
std::ostringstream oss;
oss << "expect " << expected << " have [" << ch << "]";
throw std::runtime_error(oss.str());
}
}
inline void consumeWhitespaces(std::istream& is) {
//print("consuming whitespaces ... ");
is >> std::ws;
//println("ok");
}
anyjson::String parseString(std::istream& is) {
anyjson::String str;
print("parsing string ... ");
is >> std::quoted(str);
println(str);
return str;
}
anyjson::Value parseValue(std::istream&);
anyjson::Object parseObject(std::istream& is) {
anyjson::Object obj;
bool bContinue;
println("parse object");
consumeChar(is, '{');
consumeWhitespaces(is);
do {
char ch = static_cast<char>(is.peek());
bContinue = false;
if (ch == '"') {
anyjson::String&& key = parseString(is);
if (obj.find(key) != obj.cend()) {
std::ostringstream oss;
oss << "duplicate object key [" << key << "]";
throw std::runtime_error(oss.str());
}
consumeWhitespaces(is);
consumeChar(is, ':');
consumeWhitespaces(is);
obj.emplace(key, parseValue(is));
consumeWhitespaces(is);
ch = static_cast<char>(is.peek());
if (ch == ',') {
consumeChar(is, ',');
consumeWhitespaces(is);
bContinue = true;
} else if (ch == '}') {
// do nth
} else {
std::ostringstream oss;
oss << "unexpected character [" << ch << "] in object (2)";
throw std::runtime_error(oss.str());
}
} else if (ch == '}') {
// do nth
} else {
std::ostringstream oss;
oss << "unexpected character [" << ch << "] in object (1)";
throw std::runtime_error(oss.str());
}
} while (bContinue);
consumeWhitespaces(is);
consumeChar(is, '}');
println("object parsed");
return obj;
}
anyjson::Array parseArray(std::istream& is) {
println("parse array");
anyjson::Array arr;
bool bContinue;
char ch;
consumeChar(is, '[');
ch = static_cast<char>(is.peek());
if (ch != ']') {
do {
bContinue = false;
consumeWhitespaces(is);
arr.emplace_back( parseValue(is) );
consumeWhitespaces(is);
ch = is.peek();
if (ch == ',') {
consumeChar(is, ',');
bContinue = true;
} else if (ch == ']') {
// do nth
} else {
std::ostringstream oss;
oss << "unexpected character [" << ch << "] in array";
throw std::runtime_error(oss.str());
}
} while (bContinue);
} else {
consumeWhitespaces(is);
}
consumeChar(is, ']');
println("array parsed");
return arr;
}
anyjson::Number parseNumber(std::istream& is) {
anyjson::Number num;
print("parsing double ... ");
is >> num;
println(num);
return num;
}
anyjson::Boolean parseBoolean(std::istream& is) {
std::string str;
print("parsing bool ... ");
std::getline(is, str, 'e');
if (str == "tru") {
println("true");
return true;
} else if (str == "fals") {
println("false");
return false;
} else {
println("ko");
std::ostringstream oss;
oss << "expect true or false have [" << str << "]";
throw std::runtime_error(oss.str());
}
}
anyjson::Null parseNull(std::istream& is) {
const size_t size = 4 + 1;
char buffer[size];
memset(buffer, 0, size);
print("parsing null ... ");
is.read(buffer, size - 1);
if (strcmp(buffer, "null") == 0) {
println("ok");
return nullptr;
} else {
println("ko");
std::ostringstream oss;
oss << "expect null have [" << buffer << "]";
throw std::runtime_error(oss.str());
}
}
anyjson::Value parseValue(std::istream& is) {
int ch = is.peek();
switch ( static_cast<char>(ch) ) {
case '"': {
return std::make_any<anyjson::String>( parseString(is) );
}
case '{': {
return std::make_any<anyjson::Object>( parseObject(is) );
}
case '[': {
return std::make_any<anyjson::Array>( parseArray(is) );
}
case 't': {
return std::make_any<anyjson::Boolean>( parseBoolean(is) );
}
case 'f': {
return std::make_any<anyjson::Boolean>( parseBoolean(is) );
}
case 'n': {
return std::make_any<anyjson::Null>( parseNull(is) );
}
default: {
if (isdigit(ch) || static_cast<char>(ch) == '-') {
return std::make_any<anyjson::Number>( parseNumber(is) );
} else {
std::ostringstream oss;
oss << "unexpected character [" << ch << "] in value";
throw std::runtime_error(oss.str());
}
}
}
}
} // anonymous namespace
namespace anyjson {
Value parse(std::istream& is)
{
std::ios_base::fmtflags flags = is.flags();
std::ios::iostate state = is.exceptions();
if ( ! (flags & std::ios_base::skipws) ) {
is.flags( flags | std::ios_base::skipws );
}
is.exceptions(std::istream::failbit | std::istream::badbit | std::istream::eofbit);
try {
Value&& val = parseValue(is);
is.exceptions(state);
is.flags(flags);
return std::move(val);
} catch (const std::istream::failure& err) {
std::cerr << err.what()
<< ", eof=" << ((is.eof()) ? 1 : 0)
<< ", fail=" << ((is.fail()) ? 1 : 0)
<< ", bad=" << ((is.bad()) ? 1 : 0)
<< std::endl;
} catch (const std::exception& err) {
std::cerr << err.what() << std::endl;
}
is.exceptions(state);
is.flags(flags);
return {};
}
} // namespace anyjson
/// STRINGIFY PART
namespace {
void stringify(const anyjson::Null&, std::ostream& os) {
os << "null";
}
void stringify(const anyjson::Boolean& b, std::ostream& os) {
os << ((b) ? "true" : "false");
}
void stringify(const anyjson::Number& num, std::ostream& os) {
os << num;
}
void stringify(const anyjson::String& str, std::ostream& os) {
os << '"' << str << '"';
}
void recStringify(const anyjson::Value&, std::ostream&);
void stringify(const anyjson::Array& arr, std::ostream& os) {
os << '[';
anyjson::Array::const_iterator cit = arr.cbegin();
while (cit != arr.cend()) {
recStringify(*cit, os);
++cit;
if (cit != arr.cend()) {
os << ',';
}
}
os << ']';
}
void stringify(const anyjson::Object& obj, std::ostream& os) {
os << '{';
anyjson::Object::const_iterator cit = obj.cbegin();
while (cit != obj.cend()) {
os << '"' << cit->first << '"';
os << ":";
recStringify(cit->second, os);
++cit;
if (cit != obj.cend()) {
os << ',';
}
}
os << '}';
}
//
// Unfortunately, we cant use type-safe proposed by std::any_cast
// because it involves copy of JSON object. We hope comparing type
// is enough safe...
//
inline void _stringify_object(const anyjson::Value& obj, std::ostream& os) {
stringify(std::any_cast<anyjson::Object const&>(obj), os);
}
inline void _stringify_array(const anyjson::Value& arr, std::ostream& os) {
stringify(std::any_cast<anyjson::Array const&>(arr), os);
}
inline void _stringify_string(const anyjson::Value& str, std::ostream& os) {
stringify(std::any_cast<anyjson::String const&>(str), os);
}
inline void _stringify_number(const anyjson::Value& num, std::ostream& os) {
stringify(std::any_cast<anyjson::Number const&>(num), os);
}
inline void _stringify_boolean(const anyjson::Value& b, std::ostream& os) {
stringify(std::any_cast<anyjson::Boolean const&>(b), os);
}
inline void _stringify_null(const anyjson::Value& n, std::ostream& os) {
stringify(std::any_cast<anyjson::Null const&>(n), os);
}
void recStringify(const anyjson::Value& val, std::ostream& os) {
using MapKeyType = std::type_index;
using MapValueType = std::function<void(anyjson::Value const&, std::ostream&)>;
const std::unordered_map<MapKeyType, MapValueType>
map {
{ std::type_index(typeid(anyjson::Object)), &_stringify_object },
{ std::type_index(typeid(anyjson::Array)), &_stringify_array },
{ std::type_index(typeid(anyjson::String)), &_stringify_string },
{ std::type_index(typeid(anyjson::Number)), &_stringify_number },
{ std::type_index(typeid(anyjson::Boolean)), &_stringify_boolean },
{ std::type_index(typeid(anyjson::Null)), &_stringify_null }
};
std::unordered_map<MapKeyType, MapValueType>::const_iterator cit =
map.find( std::type_index(val.type()) );
if (cit != map.cend()) {
((*cit).second)(val, os);
} else {
std::ostringstream oss;
oss << "unknown type index [" << val.type().name() << "]";
throw std::runtime_error(oss.str());
}
}
} // anonymous namespace
namespace anyjson {
bool stringify(const anyjson::Value& val, std::ostream& os)
{
bool res = true;
std::ios::iostate oldState = os.exceptions();
os.exceptions(std::ostream::failbit | std::ostream::badbit | std::ostream::eofbit);
try {
recStringify(val, os);
} catch (const std::exception& err) {
std::cerr << err.what() << std::endl;
res = false;
}
os.exceptions(oldState);
return res;
}
} // namespace anyjson