-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.h
393 lines (363 loc) · 11.1 KB
/
json.h
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
// A pretty distilled JSON parser.
#ifndef PME_JSON_H
#define PME_JSON_H
#include <cctype>
#include <cmath>
#include <istream>
#include <sstream>
#include <iomanip>
namespace JSON {
class InvalidJSON : public std::exception {
std::string err;
public:
const char *what() const throw() { return err.c_str(); }
InvalidJSON(const std::string &err_) throw() : err(err_) {}
~InvalidJSON() throw() {};
};
enum Type { Array, Boolean, Null, Number, Object, String, Eof, JSONTypeCount };
static inline int
skipSpace(std::istream &l)
{
while (!l.eof() && isspace(l.peek()))
l.ignore();
return l.eof() ? -1 : l.peek();
}
static inline char
expectAfterSpace(std::istream &l, char expected)
{
char c = skipSpace(l);
if (c != expected)
throw InvalidJSON(std::string("expected '") + expected + "', got '" + c + "'");
l.ignore();
return c;
}
static inline void
skipText(std::istream &l, const char *text)
{
for (size_t i = 0; text[i]; ++i) {
char c;
l.get(c);
if (c != text[i])
throw InvalidJSON(std::string("expected '") + text + "'");
}
}
static inline Type
peekType(std::istream &l)
{
char c = skipSpace(l);
switch (c) {
case '{': return Object;
case '[': return Array;
case '"': return String;
case '-': return Number;
case 't' : case 'f': return Boolean;
case 'n' : return Null;
case -1: return Eof;
default: {
if (c >= '0' && c <= '9')
return Number;
throw InvalidJSON(std::string("unexpected token '") + char(c) + "' at start of JSON object");
}
}
}
template <typename Context> void parseObject(std::istream &l, Context &&ctx);
template <typename Context> void parseArray(std::istream &l, Context &&ctx);
template <typename I> I
parseInt(std::istream &l)
{
int sign;
char c;
if (skipSpace(l) == '-') {
sign = -1;
l.ignore();
} else {
sign = 1;
}
I rv = 0;
if (l.peek() == '0') {
l.ignore(); // leading zero.
} else if (isdigit(l.peek())) {
while (isdigit(c = l.peek())) {
rv = rv * 10 + c - '0';
l.ignore();
}
} else {
throw InvalidJSON("expected digit");
}
return rv * sign;
}
/*
* Note that you can use parseInt instead when you know the value will be
* integral.
*/
template <typename FloatType> static inline FloatType
parseFloat(std::istream &l)
{
FloatType rv = parseInt<FloatType>(l);
if (l.peek() == '.') {
l.ignore();
FloatType scale = rv < 0 ? -1 : 1;
char c;
while (isdigit(c = l.peek())) {
l.ignore();
scale /= 10;
rv = rv + scale * (c - '0');
}
}
if (l.peek() == 'e' || l.peek() == 'E') {
l.ignore();
int sign;
char c = l.peek();
if (c == '+' || c == '-') {
sign = c == '+' ? 1 : -1;
l.ignore();
c = l.peek();
} else if (isdigit(c)) {
sign = 1;
} else {
throw InvalidJSON("expected sign or numeric after exponent");
}
auto exponent = sign * parseInt<int>(l);
rv *= std::pow(10.0, exponent);
}
return rv;
}
template <typename Integer> inline Integer parseNumber(std::istream &i) { return parseInt<long double>(i); }
template <> inline double parseNumber<double> (std::istream &i) { return parseFloat<double>(i); }
template <> inline float parseNumber<float> (std::istream &i) { return parseFloat<float>(i); }
template <> inline long double parseNumber<long double> (std::istream &i) { return parseFloat<long double>(i); }
static inline int hexval(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
throw InvalidJSON(std::string("not a hex char: " + c));
}
struct UTF8 {
unsigned long code;
UTF8(unsigned long code_) : code(code_) {}
};
inline std::ostream &
operator<<(std::ostream &os, const UTF8 &utf)
{
if ((utf.code & 0x7f) == utf.code) {
os.put(char(utf.code));
return os;
}
uint8_t prefixBits = 0x80; // start with 100xxxxx
int byteCount = 0; // one less than entire bytecount of encoding.
unsigned long value = utf.code;
for (size_t mask = 0x7ff;; mask = mask << 5 | 0x1f) {
prefixBits = prefixBits >> 1 | 0x80;
byteCount++;
if ((value & mask) == value)
break;
}
os << char(value >> 6 * byteCount | prefixBits);
while (byteCount--)
os.put(char((value >> 6 * byteCount & ~0xc0) | 0x80));
return os;
}
static std::string
parseString(std::istream &l)
{
expectAfterSpace(l, '"');
std::ostringstream rv;
for (;;) {
char c;
l.get(c);
switch (c) {
case '"':
return rv.str();
case '\\':
l.get(c);
switch (c) {
case '"':
case '\\':
case '/':
rv << c;
break;
case 'b':
rv << '\b';
break;
case 'f':
rv << '\f';
break;
case 'n':
rv << '\n';
break;
case 'r':
rv << '\r';
break;
case 't':
rv << '\t';
break;
default:
throw InvalidJSON(std::string("invalid quoted char '") + c + "'");
case 'u': {
// get unicode char.
int codePoint = 0;
for (size_t i = 0; i < 4; ++i) {
l.get(c);
codePoint = codePoint * 16 + hexval(c);
}
rv << UTF8(codePoint);
}
break;
}
break;
default:
rv << c;
break;
}
}
}
static inline bool
parseBoolean(std::istream &l)
{
char c = skipSpace(l);
switch (c) {
case 't': skipText(l, "true"); return true;
case 'f': skipText(l, "false"); return false;
default: throw InvalidJSON("expected 'true' or 'false'");
}
}
static inline void
parseNull(std::istream &l)
{
skipSpace(l);
skipText(l, "null");
}
static inline void // Parse any value but discard the result.
parseValue(std::istream &l)
{
switch (peekType(l)) {
case Array: parseArray(l, parseValue); break;
case Boolean: parseBoolean(l); break;
case Null: parseNull(l); break;
case Number: parseNumber<float>(l); break;
case Object: parseObject(l, [](std::istream &l, std::string) -> void { parseValue(l); }); break;
case String: parseString(l); break;
default: throw InvalidJSON("unknown type for JSON construct");
}
}
template <typename Context> void
parseObject(std::istream &l, Context &&ctx)
{
expectAfterSpace(l, '{');
for (;;) {
std::string fieldName;
char c;
switch (c = skipSpace(l)) {
case '"': // Name of next field.
fieldName = parseString(l);
expectAfterSpace(l, ':');
ctx(l, fieldName);
break;
case '}': // End of this object
l.ignore();
return;
case ',': // Separator to next field
l.ignore();
break;
default: {
throw InvalidJSON(std::string("unexpected character '") + char(c) + "' parsing object");
}
}
}
}
template <typename Context> void
parseArray(std::istream &l, Context &&ctx)
{
expectAfterSpace(l, '[');
char c;
if ((c = skipSpace(l)) == ']') {
l.ignore();
return; // empty array
}
for (size_t i = 0;; i++) {
skipSpace(l);
ctx(l);
c = skipSpace(l);
switch (c) {
case ']':
l.ignore();
return;
case ',':
l.ignore();
break;
default:
throw InvalidJSON(std::string("expected ']' or ',', got '") + c + "'");
}
}
}
struct Escape {
std::string value;
Escape(std::string value_) : value(value_) { }
};
inline std::ostream & operator << (std::ostream &o, const Escape &escape)
{
auto flags(o.flags());
for (auto i = escape.value.begin(); i != escape.value.end();) {
int c;
switch (c = (unsigned char)*i++) {
case '\b': o << "\\b"; break;
case '\f': o << "\\f"; break;
case '\n': o << "\\n"; break;
case '"': o << "\\\""; break;
case '\\': o << "\\\\"; break;
case '\r': o << "\\r"; break;
case '\t': o << "\\t"; break;
default:
if (unsigned(c) < 32) {
o << "\\u" << std::hex << unsigned(c);
} else if (c & 0x80) {
// multibyte UTF-8: build up the unicode codepoint.
unsigned long v = c;
int count = 0;
for (int mask = 0x80; mask & v; mask >>= 1) {
if (mask == 0)
throw InvalidJSON("malformed UTF-8 string");
count++;
v &= ~mask;
}
while (--count) {
c = (unsigned char)*i++;
if ((c & 0xc0) != 0x80)
throw InvalidJSON("illegal character in multibyte sequence");
v = (v << 6) | (c & 0x3f);
}
o << "\\u" << std::hex << std::setfill('0') << std::setw(4) << v;
} else {
o << (char)c;
}
break;
}
}
o.flags(flags);
return o;
}
template <typename Parsee> void parse(std::istream &is, Parsee &);
template <> void parse<int>(std::istream &is, int &parsee) { parsee = parseInt<int>(is); }
template <> void parse<long>(std::istream &is, long &parsee) { parsee = parseInt<long>(is); }
template <> void parse<float>(std::istream &is, float &parsee) { parsee = parseFloat<float>(is); }
template <> void parse<double>(std::istream &is, double &parsee) { parsee = parseFloat<double>(is); }
template <> void parse<std::string>(std::istream &is, std::string &parsee) { parsee = parseString(is); }
template <> void parse<bool>(std::istream &is, bool &parsee) { parsee = parseBoolean(is); }
}
static inline std::ostream &
operator<<(std::ostream &os, const JSON::Type &t)
{
switch (t) {
case JSON::Array: os << "Array"; break;
case JSON::Number: os << "Number"; break;
case JSON::Object: os << "Object"; break;
case JSON::String: os << "String"; break;
default: throw JSON::InvalidJSON("not a JSON type");
}
return os;
}
#endif