Repository navigation
Expand file tree
/
Copy pathjson.cpp
More file actions
219 lines (195 loc) · 6.68 KB
/
Copy pathjson.cpp
File metadata and controls
219 lines (195 loc) · 6.68 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
#include "json.h"
#include <charconv>
#include <cstring>
#include <system_error>
#include <stdexcept>
namespace mrt2 {
// Reset a value to Null, releasing whatever it held.
void json_reset(Json &v) {
v = Json{};
}
const Json *Json::get(const std::string &key) const {
if (type != Obj) return nullptr;
for (const auto &kv : obj) {
if (kv.first == key) return &kv.second;
}
return nullptr;
}
double Json::as_num() const {
if (type != Num) throw std::runtime_error("json: expected number");
return num;
}
const std::string &Json::as_str() const {
if (type != Str) throw std::runtime_error("json: expected string");
return str;
}
const std::vector<Json> &Json::as_arr() const {
if (type != Arr) throw std::runtime_error("json: expected array");
return arr;
}
namespace {
// A recursive-descent parser over the byte range [p, end).
struct Parser {
const char *p; // current position
const char *end; // one past the last byte
std::string err;
int depth = 0; // how many value() calls are active right now
// Record the first error and report failure.
bool fail(const char *msg) {
if (err.empty()) err = msg;
return false;
}
// Skip spaces, tabs and newlines.
void ws() {
while (p < end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t'))
p++;
}
bool value(Json &out);
bool value_inner(Json &out);
bool string(std::string &out);
bool literal(const char *word);
bool number(double &out);
};
// Parse a string; called with *p == '"'.
bool Parser::string(std::string &out) {
p++; // opening quote
out.clear();
while (p < end && *p != '"') {
char c = *p++;
if (c != '\\') {
out.push_back(c);
continue;
}
if (p >= end) return fail("json: bad escape");
char e = *p++;
switch (e) {
case '"': out.push_back('"'); break;
case '\\': out.push_back('\\'); break;
case '/': out.push_back('/'); break;
case 'b': out.push_back('\b'); break;
case 'f': out.push_back('\f'); break;
case 'n': out.push_back('\n'); break;
case 'r': out.push_back('\r'); break;
case 't': out.push_back('\t'); break;
case 'u': {
// \uXXXX -> UTF-8 (BMP only).
if (end - p < 4) return fail("json: bad \\u");
unsigned cp = 0;
for (int i = 0; i < 4; i++) {
char h = *p++;
cp <<= 4;
if (h >= '0' && h <= '9') cp |= (unsigned)(h - '0');
else if (h >= 'a' && h <= 'f') cp |= (unsigned)(h - 'a' + 10);
else if (h >= 'A' && h <= 'F') cp |= (unsigned)(h - 'A' + 10);
else return fail("json: bad hex");
}
if (cp < 0x80) {
out.push_back((char)cp);
} else if (cp < 0x800) {
out.push_back((char)(0xC0 | (cp >> 6)));
out.push_back((char)(0x80 | (cp & 0x3F)));
} else {
out.push_back((char)(0xE0 | (cp >> 12)));
out.push_back((char)(0x80 | ((cp >> 6) & 0x3F)));
out.push_back((char)(0x80 | (cp & 0x3F)));
}
break;
}
default: return fail("json: bad escape");
}
}
if (p >= end) return fail("json: unterminated string");
p++; // closing quote
return true;
}
// Match and consume an exact keyword such as "true".
bool Parser::literal(const char *word) {
size_t n = std::strlen(word);
if ((size_t)(end - p) < n || std::memcmp(p, word, n) != 0)
return fail("json: bad literal");
p += n;
return true;
}
// Parse a number; handles signs, fractions and exponents.
bool Parser::number(double &out) {
// A JSON number starts with '-' or a digit. This rejects "+1", "inf"
// and "nan", which from_chars would otherwise accept.
if (*p != '-' && (*p < '0' || *p > '9')) return fail("json: bad number");
// from_chars, not strtod: it stops at `end` (strtod needs a '\0' and
// reads past the buffer), and it ignores the C locale (under it_IT,
// strtod reads "1.5" as 1 because the decimal mark there is ',').
auto r = std::from_chars(p, end, out);
if (r.ec != std::errc()) return fail("json: bad number");
p = r.ptr;
return true;
}
// Every nested '{' or '[' recurses once, so a hostile file made of
// "[[[[..." would overflow the stack. Real headers nest 3 deep.
static constexpr int kMaxDepth = 64;
bool Parser::value(Json &out) {
if (++depth > kMaxDepth) return fail("json: nested too deep");
bool ok = value_inner(out);
depth--;
return ok;
}
bool Parser::value_inner(Json &out) {
ws();
if (p >= end) return fail("json: unexpected end");
char c = *p;
if (c == '{') {
p++;
out.type = Json::Obj;
ws();
if (p < end && *p == '}') { p++; return true; }
while (true) {
ws();
if (p >= end || *p != '"') return fail("json: expected key");
std::string key;
if (!string(key)) return false;
ws();
if (p >= end || *p != ':') return fail("json: expected ':'");
p++;
Json child;
if (!value(child)) return false;
out.obj.emplace_back(std::move(key), std::move(child));
ws();
if (p < end && *p == ',') { p++; continue; }
if (p < end && *p == '}') { p++; return true; }
return fail("json: expected ',' or '}'");
}
}
if (c == '[') {
p++;
out.type = Json::Arr;
ws();
if (p < end && *p == ']') { p++; return true; }
while (true) {
Json child;
if (!value(child)) return false;
out.arr.push_back(std::move(child));
ws();
if (p < end && *p == ',') { p++; continue; }
if (p < end && *p == ']') { p++; return true; }
return fail("json: expected ',' or ']'");
}
}
if (c == '"') { out.type = Json::Str; return string(out.str); }
if (c == 't') { out.type = Json::Bool; out.b = true; return literal("true"); }
if (c == 'f') { out.type = Json::Bool; out.b = false; return literal("false"); }
if (c == 'n') { out.type = Json::Null; return literal("null"); }
out.type = Json::Num;
return number(out.num);
}
} // namespace
bool json_parse(const char *s, size_t len, Json &out, std::string &err) {
Parser parser{s, s + len, {}};
json_reset(out);
bool ok = parser.value(out);
if (ok) {
parser.ws();
if (parser.p != parser.end) ok = parser.fail("json: trailing data");
}
err = parser.err;
return ok;
}
} // namespace mrt2