Repository navigation
Expand file tree
/
Copy pathjson.cpp
More file actions
533 lines (477 loc) · 18.8 KB
/
Copy pathjson.cpp
File metadata and controls
533 lines (477 loc) · 18.8 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
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
// SPDX-FileCopyrightText: 2026 Paolo Anzani
// SPDX-License-Identifier: Apache-2.0
#include "json.h"
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace microcodex::json {
using JsonMember = std::expected<std::optional<std::string_view>, std::string>;
// Advance past JSON whitespace so callers can examine the next token.
// Example: for " true", starting at 0 leaves position at the 't'.
void skipWhitespace(const std::string_view json, std::size_t& position) {
while (position < json.size() && (std::isspace(static_cast<unsigned char>(json[position])) != 0)) {
++position;
}
}
namespace {
int hexDigit(const char character) {
if (character >= '0' && character <= '9') {
return character - '0';
}
if (character >= 'a' && character <= 'f') {
return character - 'a' + 10;
}
if (character >= 'A' && character <= 'F') {
return character - 'A' + 10;
}
return -1;
}
std::expected<std::uint32_t, std::string> parseHexCodePoint(const std::string_view json, std::size_t& position) {
if (json.size() - position < 4) {
return std::unexpected("Incomplete Unicode escape in JSON string");
}
std::uint32_t code_point = 0;
for (std::size_t index = 0; index < 4; ++index) {
const int digit = hexDigit(json[position++]);
if (digit < 0) {
return std::unexpected("Invalid Unicode escape in JSON string");
}
code_point = code_point * 16 + static_cast<std::uint32_t>(digit);
}
return code_point;
}
// Encode one decoded \uXXXX value as UTF-8. Surrogate pairs are combined by
// parseJsonString before reaching this routine.
void appendUtf8(std::string& output, const std::uint32_t code_point) {
if (code_point <= 0x7f) {
output += static_cast<char>(code_point);
} else if (code_point <= 0x7ff) {
output += static_cast<char>(0xc0 | (code_point >> 6));
output += static_cast<char>(0x80 | (code_point & 0x3f));
} else if (code_point <= 0xffff) {
output += static_cast<char>(0xe0 | (code_point >> 12));
output += static_cast<char>(0x80 | ((code_point >> 6) & 0x3f));
output += static_cast<char>(0x80 | (code_point & 0x3f));
} else {
output += static_cast<char>(0xf0 | (code_point >> 18));
output += static_cast<char>(0x80 | ((code_point >> 12) & 0x3f));
output += static_cast<char>(0x80 | ((code_point >> 6) & 0x3f));
output += static_cast<char>(0x80 | (code_point & 0x3f));
}
}
// Decode the \uXXXX escape whose "\u" was just consumed, combining a surrogate
// pair into one code point, and append it to result as UTF-8.
std::expected<void, std::string> appendUnicodeEscape(const std::string_view json, std::size_t& position,
std::string& result) {
auto first = parseHexCodePoint(json, position);
if (!first) {
return std::unexpected(first.error());
}
std::uint32_t code_point = first.value();
if (code_point >= 0xd800 && code_point <= 0xdbff) {
if (json.size() - position < 6 || json[position] != '\\' || json[position + 1] != 'u') {
return std::unexpected("Missing low surrogate in JSON string");
}
position += 2;
auto second = parseHexCodePoint(json, position);
if (!second || second.value() < 0xdc00 || second.value() > 0xdfff) {
return std::unexpected("Invalid low surrogate in JSON string");
}
code_point = 0x10000 + ((code_point - 0xd800) << 10) + (second.value() - 0xdc00);
} else if (code_point >= 0xdc00 && code_point <= 0xdfff) {
return std::unexpected("Unexpected low surrogate in JSON string");
}
appendUtf8(result, code_point);
return {};
}
// Append the character an escape sequence stands for. escaped is the byte after
// the backslash; position points just past it.
std::expected<void, std::string> appendEscape(const char escaped, const std::string_view json, std::size_t& position,
std::string& result) {
switch (escaped) {
case '"': result += '"'; return {};
case '\\': result += '\\'; return {};
case '/': result += '/'; return {};
case 'b': result += '\b'; return {};
case 'f': result += '\f'; return {};
case 'n': result += '\n'; return {};
case 'r': result += '\r'; return {};
case 't': result += '\t'; return {};
case 'u': return appendUnicodeEscape(json, position, result);
default: return std::unexpected("Invalid escape in JSON string");
}
}
} // namespace
// Parse one quoted JSON string, unescaping characters and Unicode escapes.
// Example: parsing "\"line\\n\"" returns a string containing line + '\n'.
// On success position points immediately after the closing quote.
std::expected<std::string, std::string> parseJsonString(const std::string_view json, std::size_t& position) {
if (position == json.size() || json[position] != '"') {
return std::unexpected("Expected a JSON string");
}
++position;
std::string result;
while (position < json.size()) {
const auto character = static_cast<unsigned char>(json[position++]);
if (character == '"') {
return result;
}
if (character < 0x20) {
return std::unexpected("Control character in JSON string");
}
if (character != '\\') {
result += static_cast<char>(character);
continue;
}
if (position == json.size()) {
return std::unexpected("Incomplete escape in JSON string");
}
const char escaped = json[position++];
auto appended = appendEscape(escaped, json, position, result);
if (!appended) {
return std::unexpected(std::move(appended.error()));
}
}
return std::unexpected("Unterminated JSON string");
}
namespace {
// Advance past a run of decimal digits.
void skipDigits(const std::string_view json, std::size_t& position) {
while (position < json.size() && (std::isdigit(static_cast<unsigned char>(json[position])) != 0)) {
++position;
}
}
// Skip the members of an object whose '{' was just consumed.
std::expected<void, std::string> skipJsonObject(const std::string_view json, std::size_t& position,
const std::size_t depth) {
skipWhitespace(json, position);
if (position < json.size() && json[position] == '}') {
++position;
return {};
}
while (position < json.size()) {
auto key = parseJsonString(json, position);
if (!key) {
return std::unexpected(key.error());
}
skipWhitespace(json, position);
if (position == json.size()) {
return std::unexpected("Expected ':' in JSON object");
}
const char colon = json[position++];
if (colon != ':') {
return std::unexpected("Expected ':' in JSON object");
}
auto value = skipJsonValue(json, position, depth + 1);
if (!value) {
return value;
}
skipWhitespace(json, position);
if (position == json.size()) {
return std::unexpected("Unterminated JSON object");
}
const char separator = json[position++];
if (separator == '}') {
return {};
}
if (separator != ',') {
return std::unexpected("Expected ',' in JSON object");
}
skipWhitespace(json, position);
}
return std::unexpected("Unterminated JSON object");
}
// Skip the elements of an array whose '[' was just consumed.
std::expected<void, std::string> skipJsonArray(const std::string_view json, std::size_t& position,
const std::size_t depth) {
skipWhitespace(json, position);
if (position < json.size() && json[position] == ']') {
++position;
return {};
}
while (position < json.size()) {
auto value = skipJsonValue(json, position, depth + 1);
if (!value) {
return value;
}
skipWhitespace(json, position);
if (position == json.size()) {
return std::unexpected("Unterminated JSON array");
}
const char separator = json[position++];
if (separator == ']') {
return {};
}
if (separator != ',') {
return std::unexpected("Expected ',' in JSON array");
}
}
return std::unexpected("Unterminated JSON array");
}
// Skip a JSON number: an optional minus, an integer part without leading zeros,
// then an optional fraction and exponent.
std::expected<void, std::string> skipJsonNumber(const std::string_view json, std::size_t& position) {
const std::size_t start = position;
if (json[position] == '-') {
++position;
}
if (position == json.size()) {
return std::unexpected("Invalid JSON number");
}
if (json[position] == '0') {
++position;
} else if (json[position] >= '1' && json[position] <= '9') {
skipDigits(json, position);
} else {
return std::unexpected("Invalid JSON value");
}
if (position < json.size() && json[position] == '.') {
++position;
const std::size_t fraction_start = position;
skipDigits(json, position);
if (position == fraction_start) {
return std::unexpected("Invalid JSON number");
}
}
if (position < json.size() && (json[position] == 'e' || json[position] == 'E')) {
++position;
if (position < json.size() && (json[position] == '+' || json[position] == '-')) {
++position;
}
const std::size_t exponent_start = position;
skipDigits(json, position);
if (position == exponent_start) {
return std::unexpected("Invalid JSON number");
}
}
if (position == start) {
return std::unexpected("Invalid JSON value");
}
return {};
}
} // namespace
// Validate and skip exactly one JSON value without building a value tree.
// This makes it possible to retain lightweight views, e.g. skip {"a":[1,2]}
// and then slice the original input. The depth limit rejects hostile nesting.
std::expected<void, std::string> skipJsonValue(const std::string_view json, std::size_t& position,
const std::size_t depth) {
if (depth > 128) {
return std::unexpected("JSON is nested too deeply");
}
skipWhitespace(json, position);
if (position == json.size()) {
return std::unexpected("Expected a JSON value");
}
if (json[position] == '"') {
auto string = parseJsonString(json, position);
if (!string) {
return std::unexpected(string.error());
}
return {};
}
if (json[position] == '{') {
++position;
return skipJsonObject(json, position, depth);
}
if (json[position] == '[') {
++position;
return skipJsonArray(json, position, depth);
}
for (const std::string_view literal : {"true", "false", "null"}) {
if (json.substr(position, literal.size()) == literal) {
position += literal.size();
return {};
}
}
return skipJsonNumber(json, position);
}
// Locate a direct member of an object and return an unparsed view of its value.
// Example: findJsonMember("{\"ok\":true}", "ok") yields the view "true".
// A missing key is successful and represented by an empty optional.
// NOLINTNEXTLINE(bugprone-easily-swappable-parameters): the document and the key it is searched for.
JsonMember findJsonMember(const std::string_view object, const std::string_view wanted_key) {
std::size_t position = 0;
skipWhitespace(object, position);
if (position == object.size() || object[position] != '{') {
return std::unexpected("Expected a JSON object");
}
++position;
skipWhitespace(object, position);
if (position < object.size() && object[position] == '}') {
return std::optional<std::string_view>{};
}
while (position < object.size()) {
auto key = parseJsonString(object, position);
if (!key) {
return std::unexpected(key.error());
}
skipWhitespace(object, position);
if (position == object.size()) {
return std::unexpected("Expected ':' in JSON object");
}
const char colon = object[position++];
if (colon != ':') {
return std::unexpected("Expected ':' in JSON object");
}
skipWhitespace(object, position);
const std::size_t value_start = position;
auto value = skipJsonValue(object, position);
if (!value) {
return std::unexpected(value.error());
}
if (key.value() == wanted_key) {
return std::optional<std::string_view>{object.substr(value_start, position - value_start)};
}
skipWhitespace(object, position);
if (position == object.size()) {
return std::unexpected("Unterminated JSON object");
}
const char separator = object[position++];
if (separator == '}') {
return std::optional<std::string_view>{};
}
if (separator != ',') {
return std::unexpected("Expected ',' in JSON object");
}
skipWhitespace(object, position);
}
return std::unexpected("Unterminated JSON object");
}
// Read an optional string-valued member, decoding JSON escapes when present.
// Example: jsonStringMember("{\"name\":\"Ada\"}", "name") returns "Ada".
std::expected<std::optional<std::string>, std::string> jsonStringMember(const std::string_view object,
const std::string_view key) {
auto member = findJsonMember(object, key);
if (!member) {
return std::unexpected(member.error());
}
const std::optional<std::string_view>& member_json = *member;
if (!member_json) {
return std::optional<std::string>{};
}
std::size_t position = 0;
auto value = parseJsonString(*member_json, position);
if (!value) {
return std::unexpected("JSON member '" + std::string(key) + "' is not a string");
}
skipWhitespace(*member_json, position);
if (position != member_json->size()) {
return std::unexpected("Invalid JSON string member '" + std::string(key) + "'");
}
return std::optional<std::string>{std::move(value.value())};
}
// Like jsonStringMember, but report an error when the key is absent.
std::expected<std::string, std::string> requiredJsonString(const std::string_view object, const std::string_view key) {
auto value = jsonStringMember(object, key);
if (!value) {
return std::unexpected(value.error());
}
std::optional<std::string>& text = *value;
if (!text) {
return std::unexpected("Missing JSON string member '" + std::string(key) + "'");
}
return std::move(*text);
}
// Split a JSON array into views of its original element text.
// Example: jsonArrayElements("[1, {\"id\":2}]") returns "1" and "{\"id\":2}".
// The views remain valid only while the input array text remains alive.
std::expected<std::vector<std::string_view>, std::string> jsonArrayElements(const std::string_view array) {
std::size_t position = 0;
skipWhitespace(array, position);
if (position == array.size() || array[position] != '[') {
return std::unexpected("Expected a JSON array");
}
++position;
std::vector<std::string_view> elements;
skipWhitespace(array, position);
if (position < array.size() && array[position] == ']') {
return elements;
}
while (position < array.size()) {
skipWhitespace(array, position);
const std::size_t start = position;
auto value = skipJsonValue(array, position);
if (!value) {
return std::unexpected(value.error());
}
elements.push_back(array.substr(start, position - start));
skipWhitespace(array, position);
if (position == array.size()) {
return std::unexpected("Unterminated JSON array");
}
const char separator = array[position++];
if (separator == ']') {
skipWhitespace(array, position);
if (position != array.size()) {
return std::unexpected("Unexpected data after JSON array");
}
return elements;
}
if (separator != ',') {
return std::unexpected("Expected ',' in JSON array");
}
}
return std::unexpected("Unterminated JSON array");
}
// Append a JSON-quoted string, escaping quotes, backslashes, and control bytes.
// Example: appending "a\nb" produces "\"a\\nb\"" in the JSON output.
void appendJsonString(std::string& json, const std::string_view value) {
constexpr std::string_view hex = "0123456789abcdef";
json += '"';
for (const char byte : value) {
const auto character = static_cast<unsigned char>(byte);
switch (character) {
case '"': json += "\\\""; break;
case '\\': json += "\\\\"; break;
case '\b': json += "\\b"; break;
case '\f': json += "\\f"; break;
case '\n': json += "\\n"; break;
case '\r': json += "\\r"; break;
case '\t': json += "\\t"; break;
default:
if (character < 0x20) {
json += "\\u00";
json += hex[character >> 4];
json += hex[character & 0x0f];
} else {
json += static_cast<char>(character);
}
}
}
json += '"';
}
// Return a required member as raw JSON text; use string() to decode it if needed.
std::expected<std::string_view, std::string> scalarMember(const std::string_view object, const std::string_view name) {
auto member = findJsonMember(object, name);
if (!member) {
return std::unexpected(member.error());
}
const std::optional<std::string_view>& value = *member;
if (!value) {
return std::unexpected("Missing JSON member '" + std::string(name) + "'");
}
return *value;
}
// Decode a complete JSON string value, rejecting trailing non-whitespace data.
// Example: string("\"hello\"") returns "hello".
std::expected<std::string, std::string> string(const std::string_view value) {
std::size_t position = 0;
auto parsed = parseJsonString(value, position);
if (!parsed) {
return std::unexpected(parsed.error());
}
skipWhitespace(value, position);
if (position != value.size()) {
return std::unexpected("Expected a JSON string");
}
return parsed;
}
// Compatibility wrapper for appendJsonString.
void appendString(std::string& output, const std::string_view value) { appendJsonString(output, value); }
} // namespace microcodex::json