• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PowerDNS / pdns / 13513480535

25 Feb 2025 04:12AM UTC coverage: 64.554% (+0.03%) from 64.527%
13513480535

Pull #15201

github

web-flow
Merge 66c4a58d4 into 07688dc95
Pull Request #15201: Docs: Fix allow-from markup/link

38429 of 90428 branches covered (42.5%)

Branch coverage included in aggregate %.

127687 of 166900 relevant lines covered (76.51%)

9200732.12 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

62.72
/ext/json11/json11.cpp
1
/* Copyright (c) 2013 Dropbox, Inc.
2
 *
3
 * Permission is hereby granted, free of charge, to any person obtaining a copy
4
 * of this software and associated documentation files (the "Software"), to deal
5
 * in the Software without restriction, including without limitation the rights
6
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
 * copies of the Software, and to permit persons to whom the Software is
8
 * furnished to do so, subject to the following conditions:
9
 *
10
 * The above copyright notice and this permission notice shall be included in
11
 * all copies or substantial portions of the Software.
12
 *
13
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
 * THE SOFTWARE.
20
 */
21

22
#include "json11.hpp"
23
#include <cassert>
24
#include <cmath>
25
#include <cstdint>
26
#include <cstdlib>
27
#include <cstdio>
28
#include <limits>
29
#include <string>
30

31
namespace json11 {
32

33
static const int max_depth = 200;
34

35
using std::string;
36
using std::vector;
37
using std::map;
38
using std::make_shared;
39
using std::initializer_list;
40
using std::move;
41

42
/* Helper for representing null - just a do-nothing struct, plus comparison
43
 * operators so the helpers in JsonValue work. We can't use nullptr_t because
44
 * it may not be orderable.
45
 */
46
struct NullStruct {
47
    bool operator==(NullStruct /*unused*/) const { return true; }
2,018✔
48
    bool operator<(NullStruct /*unused*/) const { return false; }
×
49
};
50

51
/* * * * * * * * * * * * * * * * * * * *
52
 * Serialization
53
 */
54

55
static void dump(NullStruct /*unused*/, string &out) {
28✔
56
    out += "null";
28✔
57
}
28✔
58

59
static void dump(double value, string &out) {
281,284✔
60
    if (std::isfinite(value)) {
281,284!
61
        char buf[32];
281,284✔
62
        snprintf(buf, sizeof buf, "%.17g", value);
281,284✔
63
        out += buf;
281,284✔
64
    } else {
281,284✔
65
        out += "null";
×
66
    }
×
67
}
281,284✔
68

69
static void dump(int value, string &out) {
4,704✔
70
    char buf[32];
4,704✔
71
    snprintf(buf, sizeof buf, "%d", value);
4,704✔
72
    out += buf;
4,704✔
73
}
4,704✔
74

75
static void dump(bool value, string &out) {
174,962✔
76
    out += value ? "true" : "false";
174,962✔
77
}
174,962✔
78

79
static void dump(const string &value, string &out) {
2,130,786✔
80
    out += '"';
2,130,786✔
81
    for (size_t i = 0; i < value.length(); i++) {
20,167,455✔
82
        const char ch = value[i];
18,036,669✔
83
        if (ch == '\\') {
18,036,669✔
84
            out += "\\\\";
108✔
85
        } else if (ch == '"') {
18,036,561✔
86
            out += "\\\"";
640✔
87
        } else if (ch == '\b') {
18,035,921!
88
            out += "\\b";
×
89
        } else if (ch == '\f') {
18,035,921!
90
            out += "\\f";
×
91
        } else if (ch == '\n') {
18,035,921✔
92
            out += "\\n";
528✔
93
        } else if (ch == '\r') {
18,035,393!
94
            out += "\\r";
×
95
        } else if (ch == '\t') {
18,035,393✔
96
            out += "\\t";
96✔
97
        } else if (static_cast<uint8_t>(ch) <= 0x1f) {
18,035,297!
98
            char buf[8];
×
99
            snprintf(buf, sizeof buf, "\\u%04x", ch);
×
100
            out += buf;
×
101
        } else if (static_cast<uint8_t>(ch) == 0xe2 && static_cast<uint8_t>(value[i+1]) == 0x80
18,035,297!
102
                   && static_cast<uint8_t>(value[i+2]) == 0xa8) {
18,035,297!
103
            out += "\\u2028";
×
104
            i += 2;
×
105
        } else if (static_cast<uint8_t>(ch) == 0xe2 && static_cast<uint8_t>(value[i+1]) == 0x80
18,035,297!
106
                   && static_cast<uint8_t>(value[i+2]) == 0xa9) {
18,035,297!
107
            out += "\\u2029";
×
108
            i += 2;
×
109
        } else {
18,035,297✔
110
            out += ch;
18,035,297✔
111
        }
18,035,297✔
112
    }
18,036,669✔
113
    out += '"';
2,130,786✔
114
}
2,130,786✔
115

116
static void dump(const Json::array &values, string &out) {
340,926✔
117
    bool first = true;
340,926✔
118
    out += "[";
340,926✔
119
    for (const auto &value : values) {
378,786✔
120
        if (!first)
378,736✔
121
            out += ", ";
210,342✔
122
        value.dump(out);
378,736✔
123
        first = false;
378,736✔
124
    }
378,736✔
125
    out += "]";
340,926✔
126
}
340,926✔
127

128
static void dump(const Json::object &values, string &out) {
385,000✔
129
    bool first = true;
385,000✔
130
    out += "{";
385,000✔
131
    for (const auto &kv : values) {
1,466,936✔
132
        if (!first)
1,466,936✔
133
            out += ", ";
1,081,964✔
134
        dump(kv.first, out);
1,466,936✔
135
        out += ": ";
1,466,936✔
136
        kv.second.dump(out);
1,466,936✔
137
        first = false;
1,466,936✔
138
    }
1,466,936✔
139
    out += "}";
385,000✔
140
}
385,000✔
141

142
void Json::dump(string &out) const {
1,850,754✔
143
    m_ptr->dump(out);
1,850,754✔
144
}
1,850,754✔
145

146
/* * * * * * * * * * * * * * * * * * * *
147
 * Value wrappers
148
 */
149

150
template <Json::Type tag, typename T>
151
class Value : public JsonValue {
152
protected:
153

154
    // Constructors
155
    explicit Value(const T &value) : m_value(value) {}
1,052,382✔
156
    explicit Value(T &&value)      : m_value(std::move(value)) {}
656,840✔
157

158
    // Get type tag
159
    Json::Type type() const override {
63,222✔
160
        return tag;
63,222✔
161
    }
63,222✔
162

163
    // Comparisons
164
    bool equals(const JsonValue * other) const override {
2,018✔
165
        return m_value == static_cast<const Value<tag, T> *>(other)->m_value;
2,018✔
166
    }
2,018✔
167
    bool less(const JsonValue * other) const override {
×
168
        return m_value < static_cast<const Value<tag, T> *>(other)->m_value;
×
169
    }
×
170

171
    const T m_value;
172
    void dump(string &out) const override { json11::dump(m_value, out); }
1,850,754✔
173
};
174

175
class JsonDouble final : public Value<Json::NUMBER, double> {
176
    double number_value() const override { return m_value; }
96✔
177
    int int_value() const override { return static_cast<int>(m_value); }
208✔
178
    bool equals(const JsonValue * other) const override { return m_value == other->number_value(); }
×
179
    bool less(const JsonValue * other)   const override { return m_value <  other->number_value(); }
×
180
public:
181
    explicit JsonDouble(double value) : Value(value) {}
281,592✔
182
};
183

184
class JsonInt final : public Value<Json::NUMBER, int> {
185
    double number_value() const override { return m_value; }
120✔
186
    int int_value() const override { return m_value; }
3,032✔
187
    bool equals(const JsonValue * other) const override { return m_value == other->number_value(); }
×
188
    bool less(const JsonValue * other)   const override { return m_value <  other->number_value(); }
×
189
public:
190
    explicit JsonInt(int value) : Value(value) {}
8,192✔
191
};
192

193
class JsonBoolean final : public Value<Json::BOOL, bool> {
194
    bool bool_value() const override { return m_value; }
1,572✔
195
public:
196
    explicit JsonBoolean(bool value) : Value(value) {}
1,060✔
197
};
198

199
class JsonString final : public Value<Json::STRING, string> {
200
    const string &string_value() const override { return m_value; }
15,456✔
201
public:
202
    explicit JsonString(const string &value) : Value(value) {}
263,456✔
203
    explicit JsonString(string &&value)      : Value(std::move(value)) {}
414,854✔
204
};
205

206
class JsonArray final : public Value<Json::ARRAY, Json::array> {
207
    const Json::array &array_items() const override { return m_value; }
5,482✔
208
    const Json & operator[](size_t i) const override;
209
public:
210
    explicit JsonArray(const Json::array &value) : Value(value) {}
331,604✔
211
    explicit JsonArray(Json::array &&value)      : Value(std::move(value)) {}
14,194✔
212
};
213

214
class JsonObject final : public Value<Json::OBJECT, Json::object> {
215
    const Json::object &object_items() const override { return m_value; }
1,652✔
216
    const Json & operator[](const string &key) const override;
217
public:
218
    explicit JsonObject(const Json::object &value) : Value(value) {}
166,478✔
219
    explicit JsonObject(Json::object &&value)      : Value(std::move(value)) {}
227,262✔
220
};
221

222
class JsonNull final : public Value<Json::NUL, NullStruct> {
223
public:
224
    JsonNull() : Value({}) {}
530✔
225
};
226

227
/* * * * * * * * * * * * * * * * * * * *
228
 * Static globals - static-init-safe
229
 */
230
struct Statics {
231
    const std::shared_ptr<JsonValue> null = make_shared<JsonNull>();
232
    const std::shared_ptr<JsonValue> t = make_shared<JsonBoolean>(true);
233
    const std::shared_ptr<JsonValue> f = make_shared<JsonBoolean>(false);
234
    const string empty_string;
235
    const vector<Json> empty_vector;
236
    const map<string, Json> empty_map;
237
    Statics() {}
530✔
238
};
239

240
static const Statics & statics() {
1,056,276✔
241
    static const Statics s {};
1,056,276✔
242
    return s;
1,056,276✔
243
}
1,056,276✔
244

245
static const Json & static_null() {
22,076✔
246
    // This has to be separate, not in Statics, because Json() accesses statics().null.
247
    static const Json json_null;
22,076✔
248
    return json_null;
22,076✔
249
}
22,076✔
250

251
/* * * * * * * * * * * * * * * * * * * *
252
 * Constructors
253
 */
254

255
Json::Json() noexcept                  : m_ptr(statics().null) {}
874,838✔
256
Json::Json(std::nullptr_t) noexcept    : m_ptr(statics().null) {}
1,936✔
257
Json::Json(double value)               : m_ptr(make_shared<JsonDouble>(value)) {}
281,592✔
258
Json::Json(int value)                  : m_ptr(make_shared<JsonInt>(value)) {}
8,192✔
259
Json::Json(bool value)                 : m_ptr(value ? statics().t : statics().f) {}
177,730✔
260
Json::Json(const string &value)        : m_ptr(make_shared<JsonString>(value)) {}
263,456✔
261
Json::Json(string &&value)             : m_ptr(make_shared<JsonString>(std::move(value))) {}
366,440✔
262
Json::Json(const char * value)         : m_ptr(make_shared<JsonString>(value)) {}
48,414✔
263
Json::Json(const Json::array &values)  : m_ptr(make_shared<JsonArray>(values)) {}
331,604✔
264
Json::Json(Json::array &&values)       : m_ptr(make_shared<JsonArray>(std::move(values))) {}
14,194✔
265
Json::Json(const Json::object &values) : m_ptr(make_shared<JsonObject>(values)) {}
166,478✔
266
Json::Json(Json::object &&values)      : m_ptr(make_shared<JsonObject>(std::move(values))) {}
227,262✔
267

268
/* * * * * * * * * * * * * * * * * * * *
269
 * Accessors
270
 */
271

272
Json::Type Json::type()                           const { return m_ptr->type();         }
48,538✔
273
double Json::number_value()                       const { return m_ptr->number_value(); }
264✔
274
int Json::int_value()                             const { return m_ptr->int_value();    }
4,784✔
275
bool Json::bool_value()                           const { return m_ptr->bool_value();   }
1,574✔
276
const string & Json::string_value()               const { return m_ptr->string_value(); }
16,592✔
277
const vector<Json> & Json::array_items()          const { return m_ptr->array_items();  }
5,654✔
278
const map<string, Json> & Json::object_items()    const { return m_ptr->object_items(); }
2,116✔
279
const Json & Json::operator[] (size_t i)          const { return (*m_ptr)[i];           }
4,710✔
280
const Json & Json::operator[] (const string &key) const { return (*m_ptr)[key];         }
62,818✔
281

282
double                    JsonValue::number_value()              const { return 0; }
48✔
283
int                       JsonValue::int_value()                 const { return 0; }
1,544✔
284
bool                      JsonValue::bool_value()                const { return false; }
2✔
285
const string &            JsonValue::string_value()              const { return statics().empty_string; }
1,136✔
286
const vector<Json> &      JsonValue::array_items()               const { return statics().empty_vector; }
172✔
287
const map<string, Json> & JsonValue::object_items()              const { return statics().empty_map; }
464✔
288
const Json &              JsonValue::operator[] (size_t)         const { return static_null(); }
×
289
const Json &              JsonValue::operator[] (const string &) const { return static_null(); }
×
290

291
const Json & JsonObject::operator[] (const string &key) const {
62,818✔
292
    auto iter = m_value.find(key);
62,818✔
293
    return (iter == m_value.end()) ? static_null() : iter->second;
62,818✔
294
}
62,818✔
295
const Json & JsonArray::operator[] (size_t i) const {
4,710✔
296
    if (i >= m_value.size()) return static_null();
4,710!
297
    else return m_value[i];
4,710✔
298
}
4,710✔
299

300
/* * * * * * * * * * * * * * * * * * * *
301
 * Comparison
302
 */
303

304
bool Json::operator== (const Json &other) const {
7,342✔
305
    if (m_ptr->type() != other.m_ptr->type())
7,342✔
306
        return false;
5,324✔
307

308
    return m_ptr->equals(other.m_ptr.get());
2,018✔
309
}
7,342✔
310

311
bool Json::operator< (const Json &other) const {
×
312
    if (m_ptr->type() != other.m_ptr->type())
×
313
        return m_ptr->type() < other.m_ptr->type();
×
314

315
    return m_ptr->less(other.m_ptr.get());
×
316
}
×
317

318
/* * * * * * * * * * * * * * * * * * * *
319
 * Parsing
320
 */
321

322
/* esc(c)
323
 *
324
 * Format char c suitable for printing in an error message.
325
 */
326
static inline string esc(char c) {
×
327
    char buf[12];
×
328
    if (static_cast<uint8_t>(c) >= 0x20 && static_cast<uint8_t>(c) <= 0x7f) {
×
329
        snprintf(buf, sizeof buf, "'%c' (%d)", c, c);
×
330
    } else {
×
331
        snprintf(buf, sizeof buf, "(%d)", c);
×
332
    }
×
333
    return string(buf);
×
334
}
×
335

336
static inline bool in_range(long x, long lower, long upper) {
376,022✔
337
    return (x >= lower && x <= upper);
376,022✔
338
}
376,022✔
339

340
namespace {
341
/* JsonParser
342
 *
343
 * Object that tracks all state of an in-progress parse.
344
 */
345
struct JsonParser final {
346

347
    /* State
348
     */
349
    const string &str;
350
    size_t i;
351
    string &err;
352
    bool failed;
353
    const JsonParse strategy;
354

355
    /* fail(msg, err_ret = Json())
356
     *
357
     * Mark this parse as failed.
358
     */
359
    Json fail(string &&msg) {
×
360
        return fail(std::move(msg), Json());
×
361
    }
×
362

363
    template <typename T>
364
    T fail(string &&msg, const T err_ret) {
2✔
365
        if (!failed)
2!
366
            err = std::move(msg);
2✔
367
        failed = true;
2✔
368
        return err_ret;
2✔
369
    }
2✔
370

371
    /* consume_whitespace()
372
     *
373
     * Advance until the current character is non-whitespace.
374
     */
375
    void consume_whitespace() {
111,700✔
376
        while (str[i] == ' ' || str[i] == '\r' || str[i] == '\n' || str[i] == '\t')
149,476!
377
            i++;
37,776✔
378
    }
111,700✔
379

380
    /* consume_comment()
381
     *
382
     * Advance comments (c-style inline and multiline).
383
     */
384
    bool consume_comment() {
×
385
      bool comment_found = false;
×
386
      if (str[i] == '/') {
×
387
        i++;
×
388
        if (i == str.size())
×
389
          return fail("unexpected end of input inside comment", false);
×
390
        if (str[i] == '/') { // inline comment
×
391
          i++;
×
392
          if (i == str.size())
×
393
            return fail("unexpected end of input inside inline comment", false);
×
394
          // advance until next line
395
          while (str[i] != '\n') {
×
396
            i++;
×
397
            if (i == str.size())
×
398
              return fail("unexpected end of input inside inline comment", false);
×
399
          }
×
400
          comment_found = true;
×
401
        }
×
402
        else if (str[i] == '*') { // multiline comment
×
403
          i++;
×
404
          if (i > str.size()-2)
×
405
            return fail("unexpected end of input inside multi-line comment", false);
×
406
          // advance until closing tokens
407
          while (!(str[i] == '*' && str[i+1] == '/')) {
×
408
            i++;
×
409
            if (i > str.size()-2)
×
410
              return fail(
×
411
                "unexpected end of input inside multi-line comment", false);
×
412
          }
×
413
          i += 2;
×
414
          if (i == str.size())
×
415
            return fail(
×
416
              "unexpected end of input inside multi-line comment", false);
×
417
          comment_found = true;
×
418
        }
×
419
        else
×
420
          return fail("malformed comment", false);
×
421
      }
×
422
      return comment_found;
×
423
    }
×
424

425
    /* consume_garbage()
426
     *
427
     * Advance until the current character is non-whitespace and non-comment.
428
     */
429
    void consume_garbage() {
111,700✔
430
      consume_whitespace();
111,700✔
431
      if(strategy == JsonParse::COMMENTS) {
111,700!
432
        bool comment_found = false;
×
433
        do {
×
434
          comment_found = consume_comment();
×
435
          consume_whitespace();
×
436
        }
×
437
        while(comment_found);
×
438
      }
×
439
    }
111,700✔
440

441
    /* get_next_token()
442
     *
443
     * Return the next non-whitespace character. If the end of the input is reached,
444
     * flag an error and return 0.
445
     */
446
    char get_next_token() {
107,466✔
447
        consume_garbage();
107,466✔
448
        if (i == str.size())
107,466✔
449
            return fail("unexpected end of input", (char)0);
2✔
450

451
        return str[i++];
107,464✔
452
    }
107,466✔
453

454
    /* encode_utf8(pt, out)
455
     *
456
     * Encode pt as UTF-8 and add it to out.
457
     */
458
    void encode_utf8(long pt, string & out) {
399,238✔
459
        if (pt < 0)
399,238✔
460
            return;
399,222✔
461

462
        if (pt < 0x80) {
16!
463
            out += static_cast<char>(pt);
×
464
        } else if (pt < 0x800) {
16✔
465
            out += static_cast<char>((pt >> 6) | 0xC0);
8✔
466
            out += static_cast<char>((pt & 0x3F) | 0x80);
8✔
467
        } else if (pt < 0x10000) {
8!
468
            out += static_cast<char>((pt >> 12) | 0xE0);
8✔
469
            out += static_cast<char>(((pt >> 6) & 0x3F) | 0x80);
8✔
470
            out += static_cast<char>((pt & 0x3F) | 0x80);
8✔
471
        } else {
8✔
472
            out += static_cast<char>((pt >> 18) | 0xF0);
×
473
            out += static_cast<char>(((pt >> 12) & 0x3F) | 0x80);
×
474
            out += static_cast<char>(((pt >> 6) & 0x3F) | 0x80);
×
475
            out += static_cast<char>((pt & 0x3F) | 0x80);
×
476
        }
×
477
    }
16✔
478

479
    /* parse_string()
480
     *
481
     * Parse a string, starting at the current position.
482
     */
483
    string parse_string() {
34,846✔
484
        string out;
34,846✔
485
        long last_escaped_codepoint = -1;
34,846✔
486
        while (true) {
399,238✔
487
            if (i == str.size())
399,238!
488
                return fail("unexpected end of input in string", "");
×
489

490
            char ch = str[i++];
399,238✔
491

492
            if (ch == '"') {
399,238✔
493
                encode_utf8(last_escaped_codepoint, out);
34,846✔
494
                return out;
34,846✔
495
            }
34,846✔
496

497
            if (in_range(ch, 0, 0x1f))
364,392!
498
                return fail("unescaped " + esc(ch) + " in string", "");
×
499

500
            // The usual case: non-escaped characters
501
            if (ch != '\\') {
364,392✔
502
                encode_utf8(last_escaped_codepoint, out);
363,256✔
503
                last_escaped_codepoint = -1;
363,256✔
504
                out += ch;
363,256✔
505
                continue;
363,256✔
506
            }
363,256✔
507

508
            // Handle escapes
509
            if (i == str.size())
1,136!
510
                return fail("unexpected end of input in string", "");
×
511

512
            ch = str[i++];
1,136✔
513

514
            if (ch == 'u') {
1,136✔
515
                // Extract 4-byte escape sequence
516
                string esc = str.substr(i, 4);
16✔
517
                // Explicitly check length of the substring. The following loop
518
                // relies on std::string returning the terminating NUL when
519
                // accessing str[length]. Checking here reduces brittleness.
520
                if (esc.length() < 4) {
16!
521
                    return fail("bad \\u escape: " + esc, "");
×
522
                }
×
523
                for (size_t j = 0; j < 4; j++) {
80✔
524
                    if (!in_range(esc[j], 'a', 'f') && !in_range(esc[j], 'A', 'F')
64!
525
                            && !in_range(esc[j], '0', '9'))
64!
526
                        return fail("bad \\u escape: " + esc, "");
×
527
                }
64✔
528

529
                long codepoint = strtol(esc.data(), nullptr, 16);
16✔
530

531
                // JSON specifies that characters outside the BMP shall be encoded as a pair
532
                // of 4-hex-digit \u escapes encoding their surrogate pair components. Check
533
                // whether we're in the middle of such a beast: the previous codepoint was an
534
                // escaped lead (high) surrogate, and this is a trail (low) surrogate.
535
                if (in_range(last_escaped_codepoint, 0xD800, 0xDBFF)
16!
536
                        && in_range(codepoint, 0xDC00, 0xDFFF)) {
16!
537
                    // Reassemble the two surrogate pairs into one astral-plane character, per
538
                    // the UTF-16 algorithm.
539
                    encode_utf8((((last_escaped_codepoint - 0xD800) << 10)
×
540
                                 | (codepoint - 0xDC00)) + 0x10000, out);
×
541
                    last_escaped_codepoint = -1;
×
542
                } else {
16✔
543
                    encode_utf8(last_escaped_codepoint, out);
16✔
544
                    last_escaped_codepoint = codepoint;
16✔
545
                }
16✔
546

547
                i += 4;
16✔
548
                continue;
16✔
549
            }
16✔
550

551
            encode_utf8(last_escaped_codepoint, out);
1,120✔
552
            last_escaped_codepoint = -1;
1,120✔
553

554
            if (ch == 'b') {
1,120!
555
                out += '\b';
×
556
            } else if (ch == 'f') {
1,120!
557
                out += '\f';
×
558
            } else if (ch == 'n') {
1,120✔
559
                out += '\n';
1,072✔
560
            } else if (ch == 'r') {
1,072!
561
                out += '\r';
×
562
            } else if (ch == 't') {
48!
563
                out += '\t';
×
564
            } else if (ch == '"' || ch == '\\' || ch == '/') {
48!
565
                out += ch;
48✔
566
            } else {
48✔
567
                return fail("invalid escape character " + esc(ch), "");
×
568
            }
×
569
        }
1,120✔
570
    }
34,846✔
571

572
    /* parse_number()
573
     *
574
     * Parse a double.
575
     */
576
    Json parse_number() {
3,436✔
577
        size_t start_pos = i;
3,436✔
578

579
        if (str[i] == '-')
3,436✔
580
            i++;
8✔
581

582
        // Integer part
583
        if (str[i] == '0') {
3,436✔
584
            i++;
76✔
585
            if (in_range(str[i], '0', '9'))
76!
586
                return fail("leading 0s not permitted in numbers");
×
587
        } else if (in_range(str[i], '1', '9')) {
3,360!
588
            i++;
3,360✔
589
            while (in_range(str[i], '0', '9'))
8,034✔
590
                i++;
4,674✔
591
        } else {
3,360✔
592
            return fail("invalid " + esc(str[i]) + " in number");
×
593
        }
×
594

595
        if (str[i] != '.' && str[i] != 'e' && str[i] != 'E'
3,436!
596
                && (i - start_pos) <= static_cast<size_t>(std::numeric_limits<int>::digits10)) {
3,436✔
597
            return std::atoi(str.c_str() + start_pos);
3,340✔
598
        }
3,340✔
599

600
        // Decimal part
601
        if (str[i] == '.') {
96!
602
            i++;
×
603
            if (!in_range(str[i], '0', '9'))
×
604
                return fail("at least one digit required in fractional part");
×
605

606
            while (in_range(str[i], '0', '9'))
×
607
                i++;
×
608
        }
×
609

610
        // Exponent part
611
        if (str[i] == 'e' || str[i] == 'E') {
96!
612
            i++;
×
613

614
            if (str[i] == '+' || str[i] == '-')
×
615
                i++;
×
616

617
            if (!in_range(str[i], '0', '9'))
×
618
                return fail("at least one digit required in exponent");
×
619

620
            while (in_range(str[i], '0', '9'))
×
621
                i++;
×
622
        }
×
623

624
        return std::strtod(str.c_str() + start_pos, nullptr);
96✔
625
    }
96✔
626

627
    /* expect(str, res)
628
     *
629
     * Expect that 'str' starts at the character that was just read. If it does, advance
630
     * the input and return res. If not, flag an error.
631
     */
632
    Json expect(const string &expected, Json res) {
1,392✔
633
        assert(i != 0);
1,392✔
634
        i--;
×
635
        if (str.compare(i, expected.length(), expected) == 0) {
1,392!
636
            i += expected.length();
1,392✔
637
            return res;
1,392✔
638
        } else {
1,392✔
639
            return fail("parse error: expected " + expected + ", got " + str.substr(i, expected.length()));
×
640
        }
×
641
    }
1,392✔
642

643
    /* parse_json()
644
     *
645
     * Parse a JSON object.
646
     */
647
    Json parse_json(int depth) {
30,796✔
648
        if (depth > max_depth) {
30,796!
649
            return fail("exceeded maximum nesting depth");
×
650
        }
×
651

652
        char ch = get_next_token();
30,796✔
653
        if (failed)
30,796✔
654
            return Json();
2✔
655

656
        if (ch == '-' || (ch >= '0' && ch <= '9')) {
30,794✔
657
            i--;
3,436✔
658
            return parse_number();
3,436✔
659
        }
3,436✔
660

661
        if (ch == 't')
27,358✔
662
            return expect("true", true);
754✔
663

664
        if (ch == 'f')
26,604✔
665
            return expect("false", false);
638✔
666

667
        if (ch == 'n')
25,966!
668
            return expect("null", Json());
×
669

670
        if (ch == '"')
25,966✔
671
            return parse_string();
13,226✔
672

673
        if (ch == '{') {
12,740✔
674
            map<string, Json> data;
7,888✔
675
            ch = get_next_token();
7,888✔
676
            if (ch == '}')
7,888✔
677
                return data;
96✔
678

679
            while (1) {
21,620✔
680
                if (ch != '"')
21,620!
681
                    return fail("expected '\"' in object, got " + esc(ch));
×
682

683
                string key = parse_string();
21,620✔
684
                if (failed)
21,620!
685
                    return Json();
×
686

687
                ch = get_next_token();
21,620✔
688
                if (ch != ':')
21,620!
689
                    return fail("expected ':' in object, got " + esc(ch));
×
690

691
                data[std::move(key)] = parse_json(depth + 1);
21,620✔
692
                if (failed)
21,620✔
693
                    return Json();
4✔
694

695
                ch = get_next_token();
21,616✔
696
                if (ch == '}')
21,616✔
697
                    break;
7,788✔
698
                if (ch != ',')
13,828!
699
                    return fail("expected ',' in object, got " + esc(ch));
×
700

701
                ch = get_next_token();
13,828✔
702
            }
13,828✔
703
            return data;
7,788✔
704
        }
7,792✔
705

706
        if (ch == '[') {
4,852!
707
            vector<Json> data;
4,852✔
708
            ch = get_next_token();
4,852✔
709
            if (ch == ']')
4,852✔
710
                return data;
1,836✔
711

712
            while (1) {
4,942✔
713
                i--;
4,942✔
714
                data.push_back(parse_json(depth + 1));
4,942✔
715
                if (failed)
4,942✔
716
                    return Json();
2✔
717

718
                ch = get_next_token();
4,940✔
719
                if (ch == ']')
4,940✔
720
                    break;
3,014✔
721
                if (ch != ',')
1,926!
722
                    return fail("expected ',' in list, got " + esc(ch));
×
723

724
                ch = get_next_token();
1,926✔
725
                (void)ch;
1,926✔
726
            }
1,926✔
727
            return data;
3,014✔
728
        }
3,016✔
729

730
        return fail("expected value, got " + esc(ch));
×
731
    }
4,852✔
732
};
733
}//namespace {
734

735
Json Json::parse(const string &in, string &err, JsonParse strategy) {
4,234✔
736
    JsonParser parser { in, 0, err, false, strategy };
4,234✔
737
    Json result = parser.parse_json(0);
4,234✔
738

739
    // Check for any trailing garbage
740
    parser.consume_garbage();
4,234✔
741
    if (parser.i != in.size())
4,234!
742
        return parser.fail("unexpected trailing " + esc(in[parser.i]));
×
743

744
    return result;
4,234✔
745
}
4,234✔
746

747
// Documented in json11.hpp
748
vector<Json> Json::parse_multi(const string &in,
749
                               std::string::size_type &parser_stop_pos,
750
                               string &err,
751
                               JsonParse strategy) {
×
752
    JsonParser parser { in, 0, err, false, strategy };
×
753
    parser_stop_pos = 0;
×
754
    vector<Json> json_vec;
×
755
    while (parser.i != in.size() && !parser.failed) {
×
756
        json_vec.push_back(parser.parse_json(0));
×
757
        // Check for another object
758
        parser.consume_garbage();
×
759
        if (!parser.failed)
×
760
            parser_stop_pos = parser.i;
×
761
    }
×
762
    return json_vec;
×
763
}
×
764

765
/* * * * * * * * * * * * * * * * * * * *
766
 * Shape-checking
767
 */
768

769
bool Json::has_shape(const shape & types, string & err) const {
×
770
    if (!is_object()) {
×
771
        err = "expected JSON object, got " + dump();
×
772
        return false;
×
773
    }
×
774

775
    for (auto & item : types) {
×
776
        if ((*this)[item.first].type() != item.second) {
×
777
            err = "bad type for " + item.first + " in " + dump();
×
778
            return false;
×
779
        }
×
780
    }
×
781

782
    return true;
×
783
}
×
784

785
} // namespace json11
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc