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

PowerDNS / pdns / 8969621481

06 May 2024 01:05PM UTC coverage: 59.472% (+0.7%) from 58.764%
8969621481

push

github

web-flow
Merge pull request #14112 from rgacogne/quiche-0.21.0

dnsdist: Update Quiche to 0.21.0

32627 of 87504 branches covered (37.29%)

Branch coverage included in aggregate %.

114287 of 159526 relevant lines covered (71.64%)

3237215.14 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 <cstdlib>
26
#include <cstdio>
27
#include <limits>
28
#include <string>
29

30
namespace json11 {
31

32
static const int max_depth = 200;
33

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

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

50
/* * * * * * * * * * * * * * * * * * * *
51
 * Serialization
52
 */
53

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

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

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

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

78
static void dump(const string &value, string &out) {
948,623✔
79
    out += '"';
948,623✔
80
    for (size_t i = 0; i < value.length(); i++) {
9,009,978✔
81
        const char ch = value[i];
8,061,355✔
82
        if (ch == '\\') {
8,061,355✔
83
            out += "\\\\";
54✔
84
        } else if (ch == '"') {
8,061,301✔
85
            out += "\\\"";
320✔
86
        } else if (ch == '\b') {
8,060,981!
87
            out += "\\b";
×
88
        } else if (ch == '\f') {
8,060,981!
89
            out += "\\f";
×
90
        } else if (ch == '\n') {
8,060,981✔
91
            out += "\\n";
264✔
92
        } else if (ch == '\r') {
8,060,717!
93
            out += "\\r";
×
94
        } else if (ch == '\t') {
8,060,717✔
95
            out += "\\t";
48✔
96
        } else if (static_cast<uint8_t>(ch) <= 0x1f) {
8,060,669!
97
            char buf[8];
×
98
            snprintf(buf, sizeof buf, "\\u%04x", ch);
×
99
            out += buf;
×
100
        } else if (static_cast<uint8_t>(ch) == 0xe2 && static_cast<uint8_t>(value[i+1]) == 0x80
8,060,669!
101
                   && static_cast<uint8_t>(value[i+2]) == 0xa8) {
8,060,669!
102
            out += "\\u2028";
×
103
            i += 2;
×
104
        } else if (static_cast<uint8_t>(ch) == 0xe2 && static_cast<uint8_t>(value[i+1]) == 0x80
8,060,669!
105
                   && static_cast<uint8_t>(value[i+2]) == 0xa9) {
8,060,669!
106
            out += "\\u2029";
×
107
            i += 2;
×
108
        } else {
8,060,669✔
109
            out += ch;
8,060,669✔
110
        }
8,060,669✔
111
    }
8,061,355✔
112
    out += '"';
948,623✔
113
}
948,623✔
114

115
static void dump(const Json::array &values, string &out) {
169,949✔
116
    bool first = true;
169,949✔
117
    out += "[";
169,949✔
118
    for (const auto &value : values) {
170,233✔
119
        if (!first)
170,202✔
120
            out += ", ";
86,337✔
121
        value.dump(out);
170,202✔
122
        first = false;
170,202✔
123
    }
170,202✔
124
    out += "]";
169,949✔
125
}
169,949✔
126

127
static void dump(const Json::object &values, string &out) {
173,350✔
128
    bool first = true;
173,350✔
129
    out += "{";
173,350✔
130
    for (const auto &kv : values) {
673,425✔
131
        if (!first)
673,425✔
132
            out += ", ";
500,089✔
133
        dump(kv.first, out);
673,425✔
134
        out += ": ";
673,425✔
135
        kv.second.dump(out);
673,425✔
136
        first = false;
673,425✔
137
    }
673,425✔
138
    out += "}";
173,350✔
139
}
173,350✔
140

141
void Json::dump(string &out) const {
846,057✔
142
    m_ptr->dump(out);
846,057✔
143
}
846,057✔
144

145
/* * * * * * * * * * * * * * * * * * * *
146
 * Value wrappers
147
 */
148

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

153
    // Constructors
154
    explicit Value(const T &value) : m_value(value) {}
485,796✔
155
    explicit Value(T &&value)      : m_value(std::move(value)) {}
289,194✔
156

157
    // Get type tag
158
    Json::Type type() const override {
31,362✔
159
        return tag;
31,362✔
160
    }
31,362✔
161

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

170
    const T m_value;
171
    void dump(string &out) const override { json11::dump(m_value, out); }
846,057✔
172
};
173

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

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

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

198
class JsonString final : public Value<Json::STRING, string> {
199
    const string &string_value() const override { return m_value; }
7,607✔
200
public:
201
    explicit JsonString(const string &value) : Value(value) {}
94,665✔
202
    explicit JsonString(string &&value)      : Value(std::move(value)) {}
187,673✔
203
};
204

205
class JsonArray final : public Value<Json::ARRAY, Json::array> {
206
    const Json::array &array_items() const override { return m_value; }
2,722✔
207
    const Json & operator[](size_t i) const override;
208
public:
209
    explicit JsonArray(const Json::array &value) : Value(value) {}
165,492✔
210
    explicit JsonArray(Json::array &&value)      : Value(std::move(value)) {}
6,873✔
211
};
212

213
class JsonObject final : public Value<Json::OBJECT, Json::object> {
214
    const Json::object &object_items() const override { return m_value; }
790✔
215
    const Json & operator[](const string &key) const override;
216
public:
217
    explicit JsonObject(const Json::object &value) : Value(value) {}
83,201✔
218
    explicit JsonObject(Json::object &&value)      : Value(std::move(value)) {}
94,441✔
219
};
220

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

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

239
static const Statics & statics() {
527,746✔
240
    static const Statics s {};
527,746✔
241
    return s;
527,746✔
242
}
527,746✔
243

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

250
/* * * * * * * * * * * * * * * * * * * *
251
 * Constructors
252
 */
253

254
Json::Json() noexcept                  : m_ptr(statics().null) {}
437,086✔
255
Json::Json(std::nullptr_t) noexcept    : m_ptr(statics().null) {}
972✔
256
Json::Json(double value)               : m_ptr(make_shared<JsonDouble>(value)) {}
138,028✔
257
Json::Json(int value)                  : m_ptr(make_shared<JsonInt>(value)) {}
3,996✔
258
Json::Json(bool value)                 : m_ptr(value ? statics().t : statics().f) {}
88,802✔
259
Json::Json(const string &value)        : m_ptr(make_shared<JsonString>(value)) {}
94,665✔
260
Json::Json(string &&value)             : m_ptr(make_shared<JsonString>(std::move(value))) {}
182,383✔
261
Json::Json(const char * value)         : m_ptr(make_shared<JsonString>(value)) {}
5,290✔
262
Json::Json(const Json::array &values)  : m_ptr(make_shared<JsonArray>(values)) {}
165,492✔
263
Json::Json(Json::array &&values)       : m_ptr(make_shared<JsonArray>(std::move(values))) {}
6,873✔
264
Json::Json(const Json::object &values) : m_ptr(make_shared<JsonObject>(values)) {}
83,201✔
265
Json::Json(Json::object &&values)      : m_ptr(make_shared<JsonObject>(std::move(values))) {}
94,441✔
266

267
/* * * * * * * * * * * * * * * * * * * *
268
 * Accessors
269
 */
270

271
Json::Type Json::type()                           const { return m_ptr->type();         }
24,012✔
272
double Json::number_value()                       const { return m_ptr->number_value(); }
132✔
273
int Json::int_value()                             const { return m_ptr->int_value();    }
2,392✔
274
bool Json::bool_value()                           const { return m_ptr->bool_value();   }
789✔
275
const string & Json::string_value()               const { return m_ptr->string_value(); }
8,175✔
276
const vector<Json> & Json::array_items()          const { return m_ptr->array_items();  }
2,808✔
277
const map<string, Json> & Json::object_items()    const { return m_ptr->object_items(); }
1,022✔
278
const Json & Json::operator[] (size_t i)          const { return (*m_ptr)[i];           }
2,355✔
279
const Json & Json::operator[] (const string &key) const { return (*m_ptr)[key];         }
31,318✔
280

281
double                    JsonValue::number_value()              const { return 0; }
24✔
282
int                       JsonValue::int_value()                 const { return 0; }
772✔
283
bool                      JsonValue::bool_value()                const { return false; }
1✔
284
const string &            JsonValue::string_value()              const { return statics().empty_string; }
568✔
285
const vector<Json> &      JsonValue::array_items()               const { return statics().empty_vector; }
86✔
286
const map<string, Json> & JsonValue::object_items()              const { return statics().empty_map; }
232✔
287
const Json &              JsonValue::operator[] (size_t)         const { return static_null(); }
×
288
const Json &              JsonValue::operator[] (const string &) const { return static_null(); }
×
289

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

299
/* * * * * * * * * * * * * * * * * * * *
300
 * Comparison
301
 */
302

303
bool Json::operator== (const Json &other) const {
3,675✔
304
    if (m_ptr->type() != other.m_ptr->type())
3,675✔
305
        return false;
2,666✔
306

307
    return m_ptr->equals(other.m_ptr.get());
1,009✔
308
}
3,675✔
309

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

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

317
/* * * * * * * * * * * * * * * * * * * *
318
 * Parsing
319
 */
320

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

335
static inline bool in_range(long x, long lower, long upper) {
186,247✔
336
    return (x >= lower && x <= upper);
186,247✔
337
}
186,247✔
338

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

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

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

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

370
    /* consume_whitespace()
371
     *
372
     * Advance until the current character is non-whitespace.
373
     */
374
    void consume_whitespace() {
55,200✔
375
        while (str[i] == ' ' || str[i] == '\r' || str[i] == '\n' || str[i] == '\t')
73,916!
376
            i++;
18,716✔
377
    }
55,200✔
378

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

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

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

450
        return str[i++];
53,116✔
451
    }
53,117✔
452

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

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

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

489
            char ch = str[i++];
197,671✔
490

491
            if (ch == '"') {
197,671✔
492
                encode_utf8(last_escaped_codepoint, out);
17,219✔
493
                return out;
17,219✔
494
            }
17,219✔
495

496
            if (in_range(ch, 0, 0x1f))
180,452!
497
                return fail("unescaped " + esc(ch) + " in string", "");
×
498

499
            // The usual case: non-escaped characters
500
            if (ch != '\\') {
180,452✔
501
                encode_utf8(last_escaped_codepoint, out);
179,884✔
502
                last_escaped_codepoint = -1;
179,884✔
503
                out += ch;
179,884✔
504
                continue;
179,884✔
505
            }
179,884✔
506

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

511
            ch = str[i++];
568✔
512

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

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

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

546
                i += 4;
8✔
547
                continue;
8✔
548
            }
8✔
549

550
            encode_utf8(last_escaped_codepoint, out);
560✔
551
            last_escaped_codepoint = -1;
560✔
552

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

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

578
        if (str[i] == '-')
1,714✔
579
            i++;
4✔
580

581
        // Integer part
582
        if (str[i] == '0') {
1,714✔
583
            i++;
38✔
584
            if (in_range(str[i], '0', '9'))
38!
585
                return fail("leading 0s not permitted in numbers");
×
586
        } else if (in_range(str[i], '1', '9')) {
1,676!
587
            i++;
1,676✔
588
            while (in_range(str[i], '0', '9'))
4,001✔
589
                i++;
2,325✔
590
        } else {
1,676✔
591
            return fail("invalid " + esc(str[i]) + " in number");
×
592
        }
×
593

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

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

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

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

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

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

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

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

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

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

651
        char ch = get_next_token();
15,208✔
652
        if (failed)
15,208✔
653
            return Json();
1✔
654

655
        if (ch == '-' || (ch >= '0' && ch <= '9')) {
15,207✔
656
            i--;
1,714✔
657
            return parse_number();
1,714✔
658
        }
1,714✔
659

660
        if (ch == 't')
13,493✔
661
            return expect("true", true);
379✔
662

663
        if (ch == 'f')
13,114✔
664
            return expect("false", false);
319✔
665

666
        if (ch == 'n')
12,795!
667
            return expect("null", Json());
×
668

669
        if (ch == '"')
12,795✔
670
            return parse_string();
6,523✔
671

672
        if (ch == '{') {
6,272✔
673
            map<string, Json> data;
3,866✔
674
            ch = get_next_token();
3,866✔
675
            if (ch == '}')
3,866✔
676
                return data;
48✔
677

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

682
                string key = parse_string();
10,696✔
683
                if (failed)
10,696!
684
                    return Json();
×
685

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

690
                data[std::move(key)] = parse_json(depth + 1);
10,696✔
691
                if (failed)
10,696✔
692
                    return Json();
2✔
693

694
                ch = get_next_token();
10,694✔
695
                if (ch == '}')
10,694✔
696
                    break;
3,816✔
697
                if (ch != ',')
6,878!
698
                    return fail("expected ',' in object, got " + esc(ch));
×
699

700
                ch = get_next_token();
6,878✔
701
            }
6,878✔
702
            return data;
3,816✔
703
        }
3,818✔
704

705
        if (ch == '[') {
2,406!
706
            vector<Json> data;
2,406✔
707
            ch = get_next_token();
2,406✔
708
            if (ch == ']')
2,406✔
709
                return data;
918✔
710

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

717
                ch = get_next_token();
2,428✔
718
                if (ch == ']')
2,428✔
719
                    break;
1,487✔
720
                if (ch != ',')
941!
721
                    return fail("expected ',' in list, got " + esc(ch));
×
722

723
                ch = get_next_token();
941✔
724
                (void)ch;
941✔
725
            }
941✔
726
            return data;
1,487✔
727
        }
1,488✔
728

729
        return fail("expected value, got " + esc(ch));
×
730
    }
2,406✔
731
};
732
}//namespace {
733

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

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

743
    return result;
2,083✔
744
}
2,083✔
745

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

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

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

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

781
    return true;
×
782
}
×
783

784
} // 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

© 2025 Coveralls, Inc