Repository navigation
Expand file tree
/
Copy pathjson.hpp
More file actions
344 lines (316 loc) · 12.3 KB
/
Copy pathjson.hpp
File metadata and controls
344 lines (316 loc) · 12.3 KB
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
#pragma once
#include <string>
#include <string_view>
#include <vector>
#include <map>
#include <variant>
#include <memory>
#include <stdexcept>
#include <cmath>
#include <sstream>
#include <iomanip>
namespace json {
class Value;
using Null = std::monostate;
using Bool = bool;
using Number = double;
using String = std::string;
using Array = std::vector<Value>;
using Object = std::map<std::string, Value>;
class Value {
public:
enum class Type { Null, Bool, Number, String, Array, Object };
Value() : type_(Type::Null), data_(Null{}) {}
Value(Null) : type_(Type::Null), data_(Null{}) {}
Value(Bool b) : type_(Type::Bool), data_(b) {}
Value(Number n): type_(Type::Number), data_(n) {}
Value(int n) : type_(Type::Number), data_(static_cast<Number>(n)) {}
Value(String s): type_(Type::String), data_(std::move(s)) {}
Value(const char* s) : type_(Type::String), data_(std::string(s)) {}
Value(Array a) : type_(Type::Array), data_(std::move(a)) {}
Value(Object o): type_(Type::Object), data_(std::move(o)) {}
Type type() const { return type_; }
bool is_null() const { return type_ == Type::Null; }
bool is_bool() const { return type_ == Type::Bool; }
bool is_number() const { return type_ == Type::Number; }
bool is_string() const { return type_ == Type::String; }
bool is_array() const { return type_ == Type::Array; }
bool is_object() const { return type_ == Type::Object; }
Bool as_bool() const { return std::get<Bool>(data_); }
Number as_number() const { return std::get<Number>(data_); }
const String& as_string() const { return std::get<String>(data_); }
const Array& as_array() const { return std::get<Array>(data_); }
const Object& as_object() const { return std::get<Object>(data_); }
Value& operator[](const std::string& key) {
if (type_ != Type::Object) { type_ = Type::Object; data_ = Object{}; }
return std::get<Object>(data_)[key];
}
Value& operator[](size_t i) {
return std::get<Array>(data_)[i];
}
std::string dump(int indent = -1, int depth = 0) const {
std::ostringstream os;
dump_impl(os, indent, depth);
return os.str();
}
private:
Type type_;
std::variant<Null, Bool, Number, String, Array, Object> data_;
void dump_impl(std::ostringstream& os, int indent, int depth) const {
switch (type_) {
case Type::Null: os << "null"; break;
case Type::Bool: os << (std::get<Bool>(data_) ? "true" : "false"); break;
case Type::Number: {
Number n = std::get<Number>(data_);
if (std::isnan(n) || std::isinf(n)) { os << "null"; break; }
if (n == static_cast<long long>(n) && std::abs(n) < 1e15) {
os << static_cast<long long>(n);
} else {
os << std::setprecision(17) << n;
}
break;
}
case Type::String: dump_string(os, std::get<String>(data_)); break;
case Type::Array: {
const auto& a = std::get<Array>(data_);
if (a.empty()) { os << "[]"; break; }
os << "[";
for (size_t i = 0; i < a.size(); ++i) {
if (indent >= 0) os << "\n" << std::string((depth + 1) * indent, ' ');
a[i].dump_impl(os, indent, depth + 1);
if (i + 1 < a.size()) os << ",";
}
if (indent >= 0) os << "\n" << std::string(depth * indent, ' ');
os << "]";
break;
}
case Type::Object: {
const auto& o = std::get<Object>(data_);
if (o.empty()) { os << "{}"; break; }
os << "{";
size_t i = 0;
for (const auto& [k, v] : o) {
if (indent >= 0) os << "\n" << std::string((depth + 1) * indent, ' ');
dump_string(os, k);
os << (indent >= 0 ? ": " : ":");
v.dump_impl(os, indent, depth + 1);
if (++i < o.size()) os << ",";
}
if (indent >= 0) os << "\n" << std::string(depth * indent, ' ');
os << "}";
break;
}
}
}
static void dump_string(std::ostringstream& os, const std::string& s) {
os << '"';
for (unsigned char c : s) {
switch (c) {
case '"': os << "\\\""; break;
case '\\': os << "\\\\"; break;
case '\n': os << "\\n"; break;
case '\r': os << "\\r"; break;
case '\t': os << "\\t"; break;
case '\b': os << "\\b"; break;
case '\f': os << "\\f"; break;
default:
if (c < 0x20) {
os << "\\u" << std::hex << std::setw(4) << std::setfill('0') << static_cast<int>(c)
<< std::dec << std::setfill(' ');
} else {
os << c;
}
}
}
os << '"';
}
};
class ParseError : public std::runtime_error {
public:
ParseError(const std::string& msg, size_t pos)
: std::runtime_error(msg + " at position " + std::to_string(pos)), pos_(pos) {}
size_t position() const { return pos_; }
private:
size_t pos_;
};
class Parser {
public:
explicit Parser(std::string_view src) : src_(src), pos_(0) {}
Value parse() {
skip_ws();
Value v = parse_value();
skip_ws();
if (pos_ < src_.size())
throw ParseError("trailing characters", pos_);
return v;
}
private:
std::string_view src_;
size_t pos_;
char peek() const { return pos_ < src_.size() ? src_[pos_] : '\0'; }
char next() { return pos_ < src_.size() ? src_[pos_++] : '\0'; }
bool eof() const { return pos_ >= src_.size(); }
void skip_ws() {
while (pos_ < src_.size() && (src_[pos_] == ' ' || src_[pos_] == '\t' ||
src_[pos_] == '\n' || src_[pos_] == '\r'))
++pos_;
}
Value parse_value() {
skip_ws();
if (eof()) throw ParseError("unexpected end of input", pos_);
char c = peek();
if (c == '{') return parse_object();
if (c == '[') return parse_array();
if (c == '"') return parse_string();
if (c == 't' || c == 'f') return parse_bool();
if (c == 'n') return parse_null();
if (c == '-' || (c >= '0' && c <= '9')) return parse_number();
throw ParseError("unexpected character", pos_);
}
Value parse_object() {
++pos_;
Object obj;
skip_ws();
if (peek() == '}') { ++pos_; return Value(std::move(obj)); }
while (true) {
skip_ws();
if (peek() != '"') throw ParseError("expected string key", pos_);
String key = parse_string().as_string();
skip_ws();
if (peek() != ':') throw ParseError("expected ':'", pos_);
++pos_;
obj.emplace(std::move(key), parse_value());
skip_ws();
if (peek() == ',') { ++pos_; continue; }
if (peek() == '}') { ++pos_; break; }
throw ParseError("expected ',' or '}'", pos_);
}
return Value(std::move(obj));
}
Value parse_array() {
++pos_;
Array arr;
skip_ws();
if (peek() == ']') { ++pos_; return Value(std::move(arr)); }
while (true) {
arr.push_back(parse_value());
skip_ws();
if (peek() == ',') { ++pos_; continue; }
if (peek() == ']') { ++pos_; break; }
throw ParseError("expected ',' or ']'", pos_);
}
return Value(std::move(arr));
}
Value parse_string() {
++pos_;
String out;
while (true) {
if (eof()) throw ParseError("unterminated string", pos_);
char c = next();
if (c == '"') break;
if (c == '\\') {
if (eof()) throw ParseError("unterminated escape", pos_);
char e = next();
switch (e) {
case '"': out += '"'; break;
case '\\': out += '\\'; break;
case '/': out += '/'; break;
case 'n': out += '\n'; break;
case 'r': out += '\r'; break;
case 't': out += '\t'; break;
case 'b': out += '\b'; break;
case 'f': out += '\f'; break;
case 'u': {
if (pos_ + 4 > src_.size()) throw ParseError("invalid \\u escape", pos_);
unsigned cp = 0;
for (int i = 0; i < 4; ++i) {
char h = src_[pos_++];
cp <<= 4;
if (h >= '0' && h <= '9') cp |= h - '0';
else if (h >= 'a' && h <= 'f') cp |= h - 'a' + 10;
else if (h >= 'A' && h <= 'F') cp |= h - 'A' + 10;
else throw ParseError("invalid hex digit", pos_ - 1);
}
if (cp >= 0xD800 && cp <= 0xDBFF) {
if (pos_ + 6 > src_.size() || src_[pos_] != '\\' || src_[pos_+1] != 'u')
throw ParseError("expected low surrogate", pos_);
pos_ += 2;
unsigned lo = 0;
for (int i = 0; i < 4; ++i) {
char h = src_[pos_++];
lo <<= 4;
if (h >= '0' && h <= '9') lo |= h - '0';
else if (h >= 'a' && h <= 'f') lo |= h - 'a' + 10;
else if (h >= 'A' && h <= 'F') lo |= h - 'A' + 10;
else throw ParseError("invalid hex digit", pos_ - 1);
}
cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
}
encode_utf8(out, cp);
break;
}
default: throw ParseError("invalid escape character", pos_ - 1);
}
} else {
out += c;
}
}
return Value(std::move(out));
}
Value parse_bool() {
if (src_.substr(pos_, 4) == "true") { pos_ += 4; return Value(true); }
if (src_.substr(pos_, 5) == "false") { pos_ += 5; return Value(false); }
throw ParseError("invalid literal", pos_);
}
Value parse_null() {
if (src_.substr(pos_, 4) == "null") { pos_ += 4; return Value(Null{}); }
throw ParseError("invalid literal", pos_);
}
Value parse_number() {
size_t start = pos_;
if (peek() == '-') ++pos_;
if (peek() == '0') { ++pos_; }
else if (peek() >= '1' && peek() <= '9') {
while (peek() >= '0' && peek() <= '9') ++pos_;
} else throw ParseError("invalid number", pos_);
bool is_float = false;
if (peek() == '.') {
is_float = true;
++pos_;
if (!(peek() >= '0' && peek() <= '9')) throw ParseError("expected digit after '.'", pos_);
while (peek() >= '0' && peek() <= '9') ++pos_;
}
if (peek() == 'e' || peek() == 'E') {
is_float = true;
++pos_;
if (peek() == '+' || peek() == '-') ++pos_;
if (!(peek() >= '0' && peek() <= '9')) throw ParseError("expected digit in exponent", pos_);
while (peek() >= '0' && peek() <= '9') ++pos_;
}
std::string num(src_.substr(start, pos_ - start));
if (is_float) return Value(std::stod(num));
return Value(static_cast<Number>(std::stoll(num)));
}
static void encode_utf8(std::string& out, unsigned cp) {
if (cp <= 0x7F) {
out += static_cast<char>(cp);
} else if (cp <= 0x7FF) {
out += static_cast<char>(0xC0 | (cp >> 6));
out += static_cast<char>(0x80 | (cp & 0x3F));
} else if (cp <= 0xFFFF) {
out += static_cast<char>(0xE0 | (cp >> 12));
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
out += static_cast<char>(0x80 | (cp & 0x3F));
} else {
out += static_cast<char>(0xF0 | (cp >> 18));
out += static_cast<char>(0x80 | ((cp >> 12) & 0x3F));
out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
out += static_cast<char>(0x80 | (cp & 0x3F));
}
}
};
inline Value parse(std::string_view src) {
Parser p(src);
return p.parse();
}
}