Coverage Report

Created: 2026-12-01 06:51

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/crow/include/crow/json.h
Line
Count
Source
1
#pragma once
2
3
//#define CROW_JSON_NO_ERROR_CHECK
4
//#define CROW_JSON_USE_MAP
5
//#define CROW_JSON_USE_INSERTION_ORDER
6
7
#include <string>
8
#include <map>
9
#include <unordered_map>
10
#include <iostream>
11
#include <algorithm>
12
#include <memory>
13
#include <vector>
14
#include <cmath>
15
#include <cfloat>
16
#include <utility>
17
18
#include "crow/utility.h"
19
#include "crow/settings.h"
20
#include "crow/returnable.h"
21
#include "crow/logging.h"
22
23
using std::isinf;
24
using std::isnan;
25
26
#ifdef __CHAR_UNSIGNED__
27
#define IS_CONTROL_ASCII(c) (c < 0x20)
28
#else
29
156M
#define IS_CONTROL_ASCII(c) ((c >= 0) && (c < 0x20))
30
#endif
31
32
namespace crow // NOTE: Already documented in "crow/app.h"
33
{
34
    namespace mustache
35
    {
36
        class template_t;
37
    }
38
39
    namespace json
40
    {
41
        static inline char to_hex(char c)
42
3.84M
        {
43
3.84M
            c = c & 0xf;
44
3.84M
            if (c < 10)
45
3.20M
                return '0' + c;
46
643k
            return 'a' + c - 10;
47
3.84M
        }
json_fuzzer.cpp:crow::json::to_hex(char)
Line
Count
Source
42
3.84M
        {
43
3.84M
            c = c & 0xf;
44
3.84M
            if (c < 10)
45
3.20M
                return '0' + c;
46
643k
            return 'a' + c - 10;
47
3.84M
        }
Unexecuted instantiation: b64_fuzzer.cpp:crow::json::to_hex(char)
Unexecuted instantiation: http_fuzzer.cpp:crow::json::to_hex(char)
Unexecuted instantiation: request_fuzzer.cpp:crow::json::to_hex(char)
Unexecuted instantiation: template_fuzzer.cpp:crow::json::to_hex(char)
48
49
        inline void escape(const std::string& str, std::string& ret)
50
340k
        {
51
340k
            ret.reserve(ret.size() + str.size() + str.size() / 4);
52
340k
            for (auto c : str)
53
157M
            {
54
157M
                switch (c)
55
157M
                {
56
16.6k
                    case '"': ret += "\\\""; break;
57
3.86k
                    case '\\': ret += "\\\\"; break;
58
238k
                    case '\n': ret += "\\n"; break;
59
31.9k
                    case '\b': ret += "\\b"; break;
60
46.5k
                    case '\f': ret += "\\f"; break;
61
420k
                    case '\r': ret += "\\r"; break;
62
589k
                    case '\t': ret += "\\t"; break;
63
156M
                    default:
64
156M
                        if (IS_CONTROL_ASCII(c))
65
1.92M
                        {
66
1.92M
                            ret += "\\u00";
67
1.92M
                            ret += to_hex(c / 16);
68
1.92M
                            ret += to_hex(c % 16);
69
1.92M
                        }
70
154M
                        else
71
154M
                            ret += c;
72
156M
                        break;
73
157M
                }
74
157M
            }
75
340k
        }
76
        inline std::string escape(const std::string& str)
77
0
        {
78
0
            std::string ret;
79
0
            escape(str, ret);
80
0
            return ret;
81
0
        }
82
83
        enum class type : char
84
        {
85
            Null,
86
            False,
87
            True,
88
            Number,
89
            String,
90
            List,
91
            Object,
92
            Function
93
        };
94
95
        inline const char* get_type_str(type t)
96
0
        {
97
0
            switch (t)
98
0
            {
99
0
                case type::Number: return "Number";
100
0
                case type::False: return "False";
101
0
                case type::True: return "True";
102
0
                case type::List: return "List";
103
0
                case type::String: return "String";
104
0
                case type::Object: return "Object";
105
0
                case type::Function: return "Function";
106
0
                default: return "Unknown";
107
0
            }
108
0
        }
109
110
        enum class num_type : char
111
        {
112
            Signed_integer,
113
            Unsigned_integer,
114
            Floating_point,
115
            Null,
116
            Double_precision_floating_point
117
        };
118
119
        class rvalue;
120
        rvalue load(const char* data, size_t size);
121
122
        namespace detail
123
        {
124
            /// A read string implementation with comparison functionality.
125
            struct r_string
126
            {
127
65.0M
                r_string(){}
128
                r_string(char* s, char* e):
129
4.93M
                  s_(s), e_(e){}
130
                ~r_string()
131
70.0M
                {
132
70.0M
                    if (owned_)
133
8.47k
                        delete[] s_;
134
70.0M
                }
135
136
                r_string(const r_string& r)
137
0
                {
138
0
                    *this = r;
139
0
                }
140
141
                r_string(r_string&& r)
142
0
                {
143
0
                    *this = std::move(r);
144
0
                }
145
146
                r_string& operator=(r_string&& r)
147
105M
                {
148
105M
                    if (this == &r)
149
0
                        return *this;
150
151
105M
                    if (owned_)
152
0
                        delete[] s_;
153
154
105M
                    s_ = r.s_;
155
105M
                    e_ = r.e_;
156
105M
                    owned_ = r.owned_;
157
105M
                    if (r.owned_)
158
0
                        r.owned_ = 0;
159
105M
                    return *this;
160
105M
                }
161
162
                r_string& operator=(const r_string& r)
163
0
                {
164
0
                    if (this == &r)
165
0
                        return *this;
166
0
167
0
                    s_ = r.s_;
168
0
                    e_ = r.e_;
169
0
                    owned_ = 0;
170
0
                    return *this;
171
0
                }
172
173
                operator std::string() const
174
9.40M
                {
175
9.40M
                    return std::string(s_, e_);
176
9.40M
                }
177
178
179
561M
                const char* begin() const { return s_; }
180
474M
                const char* end() const { return e_; }
181
96.1M
                size_t size() const { return end() - begin(); }
182
183
                using iterator = const char*;
184
                using const_iterator = const char*;
185
186
                char* s_;         ///< Start.
187
                mutable char* e_; ///< End.
188
                uint8_t owned_{0};
189
                friend std::ostream& operator<<(std::ostream& os, const r_string& s)
190
0
                {
191
0
                    os << static_cast<std::string>(s);
192
0
                    return os;
193
0
                }
194
195
            private:
196
                void force(char* s, size_t length)
197
8.47k
                {
198
8.47k
                    s_ = s;
199
8.47k
                    e_ = s_ + length;
200
8.47k
                    owned_ = 1;
201
8.47k
                }
202
                friend rvalue crow::json::load(const char* data, size_t size);
203
204
                friend bool operator==(const r_string& l, const r_string& r);
205
                friend bool operator==(const std::string& l, const r_string& r);
206
                friend bool operator==(const r_string& l, const std::string& r);
207
208
                template<typename T, typename U>
209
                inline static bool equals(const T& l, const U& r)
210
4.69M
                {
211
4.69M
                    if (l.size() != r.size())
212
0
                        return false;
213
214
91.4M
                    for (size_t i = 0; i < l.size(); i++)
215
86.7M
                    {
216
86.7M
                        if (*(l.begin() + i) != *(r.begin() + i))
217
0
                            return false;
218
86.7M
                    }
219
220
4.69M
                    return true;
221
4.69M
                }
bool crow::json::detail::r_string::equals<crow::json::detail::r_string, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(crow::json::detail::r_string const&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)
Line
Count
Source
210
4.69M
                {
211
4.69M
                    if (l.size() != r.size())
212
0
                        return false;
213
214
91.4M
                    for (size_t i = 0; i < l.size(); i++)
215
86.7M
                    {
216
86.7M
                        if (*(l.begin() + i) != *(r.begin() + i))
217
0
                            return false;
218
86.7M
                    }
219
220
4.69M
                    return true;
221
4.69M
                }
Unexecuted instantiation: bool crow::json::detail::r_string::equals<crow::json::detail::r_string, crow::json::detail::r_string>(crow::json::detail::r_string const&, crow::json::detail::r_string const&)
Unexecuted instantiation: bool crow::json::detail::r_string::equals<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, crow::json::detail::r_string>(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, crow::json::detail::r_string const&)
222
            };
223
224
            inline bool operator<(const r_string& l, const r_string& r)
225
153M
            {
226
153M
                return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
227
153M
            }
228
229
            inline bool operator<(const r_string& l, const std::string& r)
230
71.9M
            {
231
71.9M
                return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
232
71.9M
            }
233
234
            inline bool operator<(const std::string& l, const r_string& r)
235
0
            {
236
0
                return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
237
0
            }
238
239
            inline bool operator>(const r_string& l, const r_string& r)
240
0
            {
241
0
                return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
242
0
            }
243
244
            inline bool operator>(const r_string& l, const std::string& r)
245
0
            {
246
0
                return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
247
0
            }
248
249
            inline bool operator>(const std::string& l, const r_string& r)
250
0
            {
251
0
                return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end());
252
0
            }
253
254
            inline bool operator==(const r_string& l, const r_string& r)
255
0
            {
256
0
                return r_string::equals(l, r);
257
0
            }
258
259
            inline bool operator==(const r_string& l, const std::string& r)
260
4.69M
            {
261
4.69M
                return r_string::equals(l, r);
262
4.69M
            }
263
264
            inline bool operator==(const std::string& l, const r_string& r)
265
0
            {
266
0
                return r_string::equals(l, r);
267
0
            }
268
269
            inline bool operator!=(const r_string& l, const r_string& r)
270
0
            {
271
0
                return !(l == r);
272
0
            }
273
274
            inline bool operator!=(const r_string& l, const std::string& r)
275
0
            {
276
0
                return !(l == r);
277
0
            }
278
279
            inline bool operator!=(const std::string& l, const r_string& r)
280
0
            {
281
0
                return !(l == r);
282
0
            }
283
284
            struct unordered_policy
285
            {
286
                template<typename Value>
287
                using object_type =
288
                  std::unordered_map<std::string, Value>;
289
            };
290
291
            struct map_policy
292
            {
293
                template<typename Value>
294
                using object_type =
295
                  std::map<std::string, Value>;
296
            };
297
298
            struct insertion_order_policy
299
            {
300
                template<typename Value>
301
                using object_type = utility::ordered_object<std::string, Value>;
302
            };
303
304
#if defined(CROW_JSON_USE_INSERTION_ORDER) && defined(CROW_JSON_USE_MAP)
305
#error "Only one JSON object ordering policy may be selected"
306
#elif defined(CROW_JSON_USE_INSERTION_ORDER)
307
            using object_policy = insertion_order_policy;
308
#elif defined(CROW_JSON_USE_MAP)
309
            using object_policy = map_policy;
310
#else
311
            using object_policy = unordered_policy;
312
#endif
313
314
        } // namespace detail
315
316
        /// JSON read value.
317
318
        ///
319
        /// Value can mean any json value, including a JSON object.
320
        /// Read means this class is used to primarily read strings into a JSON value.
321
        class rvalue
322
        {
323
            static const int cached_bit = 2;
324
            static const int error_bit = 4;
325
326
        public:
327
            rvalue() noexcept:
328
40.8M
              option_{error_bit}
329
40.8M
            {
330
40.8M
            }
331
            rvalue(type t) noexcept:
332
35.3k
              lsize_{}, lremain_{}, t_{t}
333
35.3k
            {
334
35.3k
            }
335
            rvalue(type t, char* s, char* e) noexcept:
336
16.2M
              start_{s}, end_{e}, t_{t}
337
16.2M
            {
338
16.2M
                determine_num_type();
339
16.2M
            }
340
341
            rvalue(const rvalue& r):
342
              start_(r.start_), end_(r.end_), key_(r.key_), t_(r.t_), nt_(r.nt_), option_(r.option_)
343
0
            {
344
0
                copy_l(r);
345
0
            }
346
347
            rvalue(rvalue&& r) noexcept
348
8.01M
            {
349
8.01M
                *this = std::move(r);
350
8.01M
            }
351
352
            rvalue& operator=(const rvalue& r)
353
0
            {
354
0
                start_ = r.start_;
355
0
                end_ = r.end_;
356
0
                key_ = r.key_;
357
0
                t_ = r.t_;
358
0
                nt_ = r.nt_;
359
0
                option_ = r.option_;
360
0
                copy_l(r);
361
0
                return *this;
362
0
            }
363
            rvalue& operator=(rvalue&& r) noexcept
364
100M
            {
365
100M
                start_ = r.start_;
366
100M
                end_ = r.end_;
367
100M
                key_ = std::move(r.key_);
368
100M
                l_ = std::move(r.l_);
369
100M
                lsize_ = r.lsize_;
370
100M
                lremain_ = r.lremain_;
371
100M
                t_ = r.t_;
372
100M
                nt_ = r.nt_;
373
100M
                option_ = r.option_;
374
100M
                return *this;
375
100M
            }
376
377
            explicit operator bool() const noexcept
378
16.2M
            {
379
16.2M
                return (option_ & error_bit) == 0;
380
16.2M
            }
381
382
            explicit operator int64_t() const
383
0
            {
384
0
                return i();
385
0
            }
386
387
            explicit operator uint64_t() const
388
0
            {
389
0
                return u();
390
0
            }
391
392
            explicit operator int() const
393
0
            {
394
0
                return static_cast<int>(i());
395
0
            }
396
397
            /// Return any json value (not object or list) as a string.
398
            explicit operator std::string() const
399
0
            {
400
0
#ifndef CROW_JSON_NO_ERROR_CHECK
401
0
                if (t() == type::Object || t() == type::List)
402
0
                    throw std::runtime_error("json type container");
403
0
#endif
404
0
                switch (t())
405
0
                {
406
0
                    case type::String:
407
0
                        return std::string(s());
408
0
                    case type::Null:
409
0
                        return std::string("null");
410
0
                    case type::True:
411
0
                        return std::string("true");
412
0
                    case type::False:
413
0
                        return std::string("false");
414
0
                    default:
415
0
                        return std::string(start_, end_ - start_);
416
0
                }
417
0
            }
418
419
            /// The type of the JSON value.
420
            type t() const
421
65.7M
            {
422
65.7M
#ifndef CROW_JSON_NO_ERROR_CHECK
423
65.7M
                if (option_ & error_bit)
424
0
                {
425
0
                    throw std::runtime_error("invalid json object");
426
0
                }
427
65.7M
#endif
428
65.7M
                return t_;
429
65.7M
            }
430
431
            /// The number type of the JSON value.
432
            num_type nt() const
433
7.75M
            {
434
7.75M
#ifndef CROW_JSON_NO_ERROR_CHECK
435
7.75M
                if (option_ & error_bit)
436
0
                {
437
0
                    throw std::runtime_error("invalid json object");
438
0
                }
439
7.75M
#endif
440
7.75M
                return nt_;
441
7.75M
            }
442
443
            /// The integer value.
444
            int64_t i() const
445
1.93k
            {
446
1.93k
#ifndef CROW_JSON_NO_ERROR_CHECK
447
1.93k
                switch (t())
448
1.93k
                {
449
1.93k
                    case type::Number:
450
1.93k
                    case type::String:
451
1.93k
                        return utility::lexical_cast<int64_t>(start_, end_ - start_);
452
0
                    default:
453
0
                        const std::string msg = "expected number, got: " + std::string(get_type_str(t()));
454
0
                        throw std::runtime_error(msg);
455
1.93k
                }
456
#else
457
                return utility::lexical_cast<int64_t>(start_, end_ - start_);
458
#endif
459
1.93k
            }
460
461
            /// The unsigned integer value.
462
            uint64_t u() const
463
7.75M
            {
464
7.75M
#ifndef CROW_JSON_NO_ERROR_CHECK
465
7.75M
                switch (t())
466
7.75M
                {
467
7.75M
                    case type::Number:
468
7.75M
                    case type::String:
469
7.75M
                        return utility::lexical_cast<uint64_t>(start_, end_ - start_);
470
0
                    default:
471
0
                        throw std::runtime_error(std::string("expected number, got: ") + get_type_str(t()));
472
7.75M
                }
473
0
#endif
474
0
                return utility::lexical_cast<uint64_t>(start_, end_ - start_);
475
7.75M
            }
476
477
            /// The double precision floating-point number value.
478
            double d() const
479
3.98k
            {
480
3.98k
#ifndef CROW_JSON_NO_ERROR_CHECK
481
3.98k
                if (t() != type::Number)
482
0
                    throw std::runtime_error("value is not number");
483
3.98k
#endif
484
3.98k
                return utility::lexical_cast<double>(start_, end_ - start_);
485
3.98k
            }
486
487
            /// The boolean value.
488
            bool b() const
489
2
            {
490
2
#ifndef CROW_JSON_NO_ERROR_CHECK
491
2
                if (t() != type::True && t() != type::False)
492
0
                    throw std::runtime_error("value is not boolean");
493
2
#endif
494
2
                return t() == type::True;
495
2
            }
496
497
            /// The string value.
498
            detail::r_string s() const
499
4.93M
            {
500
4.93M
#ifndef CROW_JSON_NO_ERROR_CHECK
501
4.93M
                if (t() != type::String)
502
0
                    throw std::runtime_error("value is not string");
503
4.93M
#endif
504
4.93M
                unescape();
505
4.93M
                return detail::r_string{start_, end_};
506
4.93M
            }
507
508
            /// The list or object value
509
            std::vector<rvalue> lo() const
510
0
            {
511
0
#ifndef CROW_JSON_NO_ERROR_CHECK
512
0
                if (t() != type::Object && t() != type::List)
513
0
                    throw std::runtime_error("value is not a container");
514
0
#endif
515
0
                std::vector<rvalue> ret;
516
0
                ret.reserve(lsize_);
517
0
                for (uint32_t i = 0; i < lsize_; i++)
518
0
                {
519
0
                    ret.emplace_back(l_[i]);
520
0
                }
521
0
                return ret;
522
0
            }
523
524
            /// Convert escaped string character to their original form ("\\n" -> '\n').
525
            void unescape() const
526
4.93M
            {
527
4.93M
                if (*(start_ - 1))
528
206k
                {
529
206k
                    char* head = start_;
530
206k
                    char* tail = start_;
531
86.2M
                    while (head != end_)
532
86.0M
                    {
533
86.0M
                        if (*head == '\\')
534
1.77M
                        {
535
1.77M
                            switch (*++head)
536
1.77M
                            {
537
99.7k
                                case '"': *tail++ = '"'; break;
538
10.2k
                                case '\\': *tail++ = '\\'; break;
539
204
                                case '/': *tail++ = '/'; break;
540
55.2k
                                case 'b': *tail++ = '\b'; break;
541
159k
                                case 'f': *tail++ = '\f'; break;
542
116k
                                case 'n': *tail++ = '\n'; break;
543
198k
                                case 'r': *tail++ = '\r'; break;
544
293k
                                case 't': *tail++ = '\t'; break;
545
846k
                                case 'u':
546
846k
                                {
547
3.39M
                                    auto from_hex = [](char c) {
548
3.39M
                                        if (c >= 'a')
549
327k
                                            return c - 'a' + 10;
550
3.06M
                                        if (c >= 'A')
551
19.7k
                                            return c - 'A' + 10;
552
3.04M
                                        return c - '0';
553
3.06M
                                    };
554
846k
                                    unsigned int code =
555
846k
                                      (from_hex(head[1]) << 12) +
556
846k
                                      (from_hex(head[2]) << 8) +
557
846k
                                      (from_hex(head[3]) << 4) +
558
846k
                                      from_hex(head[4]);
559
846k
                                    head += 4;
560
846k
                                    if (code >= 0xD800 && code <= 0xDFFF)
561
4.26k
                                    {
562
                                        // UTF-16 surrogate: a high half followed by an escaped low half
563
                                        // encodes one code point; an unpaired half is not a valid code
564
                                        // point, so it is replaced with U+FFFD to keep the output valid UTF-8.
565
4.26k
                                        unsigned int low = 0;
566
4.26k
                                        if (code <= 0xDBFF && head[1] == '\\' && head[2] == 'u')
567
1.87k
                                        {
568
1.87k
                                            low = (from_hex(head[3]) << 12) +
569
1.87k
                                                  (from_hex(head[4]) << 8) +
570
1.87k
                                                  (from_hex(head[5]) << 4) +
571
1.87k
                                                  from_hex(head[6]);
572
1.87k
                                        }
573
4.26k
                                        if (low >= 0xDC00 && low <= 0xDFFF)
574
210
                                        {
575
210
                                            code = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00);
576
210
                                            *tail++ = 0xF0 | (code >> 18);
577
210
                                            *tail++ = 0x80 | ((code >> 12) & 0x3F);
578
210
                                            *tail++ = 0x80 | ((code >> 6) & 0x3F);
579
210
                                            *tail++ = 0x80 | (code & 0x3F);
580
210
                                            head += 6;
581
210
                                        }
582
4.05k
                                        else
583
4.05k
                                        {
584
4.05k
                                            *tail++ = 0xEF;
585
4.05k
                                            *tail++ = 0xBF;
586
4.05k
                                            *tail++ = 0xBD;
587
4.05k
                                        }
588
4.26k
                                    }
589
841k
                                    else if (code >= 0x800)
590
3.72k
                                    {
591
3.72k
                                        *tail++ = 0xE0 | (code >> 12);
592
3.72k
                                        *tail++ = 0x80 | ((code >> 6) & 0x3F);
593
3.72k
                                        *tail++ = 0x80 | (code & 0x3F);
594
3.72k
                                    }
595
838k
                                    else if (code >= 0x80)
596
235
                                    {
597
235
                                        *tail++ = 0xC0 | (code >> 6);
598
235
                                        *tail++ = 0x80 | (code & 0x3F);
599
235
                                    }
600
837k
                                    else
601
837k
                                    {
602
837k
                                        *tail++ = code;
603
837k
                                    }
604
846k
                                }
605
846k
                                break;
606
1.77M
                            }
607
1.77M
                        }
608
84.2M
                        else
609
84.2M
                            *tail++ = *head;
610
86.0M
                        head++;
611
86.0M
                    }
612
206k
                    end_ = tail;
613
206k
                    *end_ = 0;
614
206k
                    *(start_ - 1) = 0;
615
206k
                }
616
4.93M
            }
617
618
            /// Check if the json object has the passed string as a key.
619
            bool has(const char* str) const
620
0
            {
621
0
                return has(std::string(str));
622
0
            }
623
624
            bool has(const std::string& str) const
625
0
            {
626
0
                struct Pred
627
0
                {
628
0
                    bool operator()(const rvalue& l, const rvalue& r) const
629
0
                    {
630
0
                        return l.key_ < r.key_;
631
0
                    }
632
0
                    bool operator()(const rvalue& l, const std::string& r) const
633
0
                    {
634
0
                        return l.key_ < r;
635
0
                    }
636
0
                    bool operator()(const std::string& l, const rvalue& r) const
637
0
                    {
638
0
                        return l < r.key_;
639
0
                    }
640
0
                };
641
0
                if (!is_cached())
642
0
                {
643
0
                    std::sort(begin(), end(), Pred());
644
0
                    set_cached();
645
0
                }
646
0
                auto it = lower_bound(begin(), end(), str, Pred());
647
0
                return it != end() && it->key_ == str;
648
0
            }
649
650
            int count(const std::string& str) const
651
0
            {
652
0
                return has(str) ? 1 : 0;
653
0
            }
654
655
            rvalue* begin() const
656
4.74M
            {
657
4.74M
#ifndef CROW_JSON_NO_ERROR_CHECK
658
4.74M
                if (t() != type::Object && t() != type::List)
659
0
                    throw std::runtime_error("value is not a container");
660
4.74M
#endif
661
4.74M
                return l_.get();
662
4.74M
            }
663
            rvalue* end() const
664
17.2M
            {
665
17.2M
#ifndef CROW_JSON_NO_ERROR_CHECK
666
17.2M
                if (t() != type::Object && t() != type::List)
667
0
                    throw std::runtime_error("value is not a container");
668
17.2M
#endif
669
17.2M
                return l_.get() + lsize_;
670
17.2M
            }
671
672
            const detail::r_string& key() const
673
9.40M
            {
674
9.40M
                return key_;
675
9.40M
            }
676
677
            size_t size() const
678
1.67k
            {
679
1.67k
                if (t() == type::String)
680
0
                    return s().size();
681
1.67k
#ifndef CROW_JSON_NO_ERROR_CHECK
682
1.67k
                if (t() != type::Object && t() != type::List)
683
0
                    throw std::runtime_error("value is not a container");
684
1.67k
#endif
685
1.67k
                return lsize_;
686
1.67k
            }
687
688
            const rvalue& operator[](int index) const
689
0
            {
690
0
#ifndef CROW_JSON_NO_ERROR_CHECK
691
0
                if (t() != type::List)
692
0
                    throw std::runtime_error("value is not a list");
693
0
                if (index >= static_cast<int>(lsize_) || index < 0)
694
0
                    throw std::runtime_error("list out of bound");
695
0
#endif
696
0
                return l_[index];
697
0
            }
698
699
            const rvalue& operator[](size_t index) const
700
0
            {
701
0
#ifndef CROW_JSON_NO_ERROR_CHECK
702
0
                if (t() != type::List)
703
0
                    throw std::runtime_error("value is not a list");
704
0
                if (index >= lsize_)
705
0
                    throw std::runtime_error("list out of bound");
706
0
#endif
707
0
                return l_[index];
708
0
            }
709
710
            const rvalue& operator[](const char* str) const
711
0
            {
712
0
                return this->operator[](std::string(str));
713
0
            }
714
715
            const rvalue& operator[](const std::string& str) const
716
4.69M
            {
717
4.69M
#ifndef CROW_JSON_NO_ERROR_CHECK
718
4.69M
                if (t() != type::Object)
719
0
                    throw std::runtime_error("value is not an object");
720
4.69M
#endif
721
4.69M
                struct Pred
722
4.69M
                {
723
4.69M
                    bool operator()(const rvalue& l, const rvalue& r) const
724
153M
                    {
725
153M
                        return l.key_ < r.key_;
726
153M
                    }
727
4.69M
                    bool operator()(const rvalue& l, const std::string& r) const
728
71.9M
                    {
729
71.9M
                        return l.key_ < r;
730
71.9M
                    }
731
4.69M
                    bool operator()(const std::string& l, const rvalue& r) const
732
4.69M
                    {
733
0
                        return l < r.key_;
734
0
                    }
735
4.69M
                };
736
4.69M
                if (!is_cached())
737
3.46k
                {
738
3.46k
                    std::sort(begin(), end(), Pred());
739
3.46k
                    set_cached();
740
3.46k
                }
741
4.69M
                auto it = lower_bound(begin(), end(), str, Pred());
742
4.69M
                if (it != end() && it->key_ == str)
743
4.69M
                    return *it;
744
0
#ifndef CROW_JSON_NO_ERROR_CHECK
745
0
                throw std::runtime_error("cannot find key: " + str);
746
#else
747
                static rvalue nullValue;
748
                return nullValue;
749
#endif
750
4.69M
            }
751
752
            void set_error()
753
18.7k
            {
754
18.7k
                option_ |= error_bit;
755
18.7k
            }
756
757
            bool error() const
758
0
            {
759
0
                return (option_ & error_bit) != 0;
760
0
            }
761
762
            std::vector<std::string> keys() const
763
3.46k
            {
764
3.46k
#ifndef CROW_JSON_NO_ERROR_CHECK
765
3.46k
                if (t() != type::Object)
766
0
                    throw std::runtime_error("value is not an object");
767
3.46k
#endif
768
3.46k
                std::vector<std::string> ret;
769
3.46k
                ret.reserve(lsize_);
770
4.70M
                for (uint32_t i = 0; i < lsize_; i++)
771
4.69M
                {
772
4.69M
                    ret.emplace_back(std::string(l_[i].key()));
773
4.69M
                }
774
3.46k
                return ret;
775
3.46k
            }
776
777
        private:
778
            bool is_cached() const
779
4.69M
            {
780
4.69M
                return (option_ & cached_bit) != 0;
781
4.69M
            }
782
            void set_cached() const
783
3.46k
            {
784
3.46k
                option_ |= cached_bit;
785
3.46k
            }
786
            void copy_l(const rvalue& r)
787
0
            {
788
0
                if (r.t() != type::Object && r.t() != type::List)
789
0
                    return;
790
0
                lsize_ = r.lsize_;
791
0
                lremain_ = 0;
792
0
                l_.reset(new rvalue[lsize_]);
793
0
                std::copy(r.begin(), r.end(), begin());
794
0
            }
795
796
            void emplace_back(rvalue&& v)
797
11.2M
            {
798
11.2M
                if (!lremain_)
799
33.1k
                {
800
33.1k
                    int new_size = lsize_ + lsize_;
801
33.1k
                    if (new_size - lsize_ > 60000)
802
115
                        new_size = lsize_ + 60000;
803
33.1k
                    if (new_size < 4)
804
14.2k
                        new_size = 4;
805
33.1k
                    rvalue* p = new rvalue[new_size];
806
33.1k
                    rvalue* p2 = p;
807
33.1k
                    for (auto& x : *this)
808
25.8M
                        *p2++ = std::move(x);
809
33.1k
                    l_.reset(p);
810
33.1k
                    lremain_ = new_size - lsize_;
811
33.1k
                }
812
11.2M
                l_[lsize_++] = std::move(v);
813
11.2M
                lremain_--;
814
11.2M
            }
815
816
            /// Determines num_type from the string.
817
            void determine_num_type()
818
16.2M
            {
819
16.2M
                if (t_ != type::Number)
820
4.93M
                {
821
4.93M
                    nt_ = num_type::Null;
822
4.93M
                    return;
823
4.93M
                }
824
825
11.2M
                const std::size_t len = end_ - start_;
826
11.2M
                const bool has_minus = std::memchr(start_, '-', len) != nullptr;
827
11.2M
                const bool has_e = std::memchr(start_, 'e', len) != nullptr || std::memchr(start_, 'E', len) != nullptr;
828
11.2M
                const bool has_dec_sep = std::memchr(start_, '.', len) != nullptr;
829
11.2M
                if (has_dec_sep || has_e)
830
7.10k
                    nt_ = num_type::Floating_point;
831
11.2M
                else if (has_minus)
832
2.52k
                    nt_ = num_type::Signed_integer;
833
11.2M
                else
834
11.2M
                    nt_ = num_type::Unsigned_integer;
835
11.2M
            }
836
837
            mutable char* start_;
838
            mutable char* end_;
839
            detail::r_string key_;
840
            std::unique_ptr<rvalue[]> l_;
841
            uint32_t lsize_;
842
            uint16_t lremain_;
843
            type t_;
844
            num_type nt_{num_type::Null};
845
            mutable uint8_t option_{0};
846
847
            friend rvalue load_nocopy_internal(char* data, size_t size);
848
            friend rvalue load(const char* data, size_t size);
849
            friend std::ostream& operator<<(std::ostream& os, const rvalue& r)
850
0
            {
851
0
                switch (r.t_)
852
0
                {
853
0
854
0
                    case type::Null: os << "null"; break;
855
0
                    case type::False: os << "false"; break;
856
0
                    case type::True: os << "true"; break;
857
0
                    case type::Number:
858
0
                    {
859
0
                        switch (r.nt())
860
0
                        {
861
0
                            case num_type::Floating_point: os << r.d(); break;
862
0
                            case num_type::Double_precision_floating_point: os << r.d(); break;
863
0
                            case num_type::Signed_integer: os << r.i(); break;
864
0
                            case num_type::Unsigned_integer: os << r.u(); break;
865
0
                            case num_type::Null: throw std::runtime_error("Number with num_type Null");
866
0
                        }
867
0
                    }
868
0
                    break;
869
0
                    case type::String: os << '"' << r.s() << '"'; break;
870
0
                    case type::List:
871
0
                    {
872
0
                        os << '[';
873
0
                        bool first = true;
874
0
                        for (auto& x : r)
875
0
                        {
876
0
                            if (!first)
877
0
                                os << ',';
878
0
                            first = false;
879
0
                            os << x;
880
0
                        }
881
0
                        os << ']';
882
0
                    }
883
0
                    break;
884
0
                    case type::Object:
885
0
                    {
886
0
                        os << '{';
887
0
                        bool first = true;
888
0
                        for (auto& x : r)
889
0
                        {
890
0
                            if (!first)
891
0
                                os << ',';
892
0
                            os << '"' << escape(x.key_) << "\":";
893
0
                            first = false;
894
0
                            os << x;
895
0
                        }
896
0
                        os << '}';
897
0
                    }
898
0
                    break;
899
0
                    case type::Function: os << "custom function"; break;
900
0
                }
901
0
                return os;
902
0
            }
903
        };
904
        namespace detail
905
        {
906
        }
907
908
        inline bool operator==(const rvalue& l, const std::string& r)
909
0
        {
910
0
            return l.s() == r;
911
0
        }
912
913
        inline bool operator==(const std::string& l, const rvalue& r)
914
0
        {
915
0
            return l == r.s();
916
0
        }
917
918
        inline bool operator!=(const rvalue& l, const std::string& r)
919
0
        {
920
0
            return l.s() != r;
921
0
        }
922
923
        inline bool operator!=(const std::string& l, const rvalue& r)
924
0
        {
925
0
            return l != r.s();
926
0
        }
927
928
        inline bool operator==(const rvalue& l, const int& r)
929
0
        {
930
0
          return l.i() == r;
931
0
        }
932
933
        inline bool operator==(const int& l, const rvalue& r)
934
0
        {
935
0
          return l == r.i();
936
0
        }
937
938
        inline bool operator!=(const rvalue& l, const int& r)
939
0
        {
940
0
          return l.i() != r;
941
0
        }
942
943
        inline bool operator!=(const int& l, const rvalue& r)
944
0
        {
945
0
          return l != r.i();
946
0
        }
947
948
949
        inline rvalue load_nocopy_internal(char* data, size_t size)
950
9.43k
        {
951
            // Defend against excessive recursion
952
9.43k
            static constexpr unsigned max_depth = 1024;
953
954
            //static const char* escaped = "\"\\/\b\f\n\r\t";
955
9.43k
            struct Parser
956
9.43k
            {
957
9.43k
                Parser(char* data_, size_t /*size*/):
958
9.43k
                  data(data_)
959
9.43k
                {
960
9.43k
                }
961
962
9.43k
                bool consume(char c)
963
21.1M
                {
964
21.1M
                    if (CROW_UNLIKELY(*data != c))
965
328
                        return false;
966
21.1M
                    data++;
967
21.1M
                    return true;
968
21.1M
                }
969
970
9.43k
                void ws_skip()
971
32.5M
                {
972
34.3M
                    while (*data == ' ' || *data == '\t' || *data == '\r' || *data == '\n')
973
1.84M
                        ++data;
974
32.5M
                }
975
976
9.43k
                rvalue decode_string()
977
4.93M
                {
978
4.93M
                    if (CROW_UNLIKELY(!consume('"')))
979
131
                        return {};
980
4.93M
                    char* start = data;
981
4.93M
                    uint8_t has_escaping = 0;
982
190M
                    while (1)
983
190M
                    {
984
190M
                        if (CROW_LIKELY(*data != '"' && *data != '\\' && *data != '\0'))
985
183M
                        {
986
183M
                            data++;
987
183M
                        }
988
6.85M
                        else if (*data == '"')
989
4.93M
                        {
990
4.93M
                            *data = 0;
991
4.93M
                            *(start - 1) = has_escaping;
992
4.93M
                            data++;
993
4.93M
                            return {type::String, start, data - 1};
994
4.93M
                        }
995
1.92M
                        else if (*data == '\\')
996
1.92M
                        {
997
1.92M
                            has_escaping = 1;
998
1.92M
                            data++;
999
1.92M
                            switch (*data)
1000
1.92M
                            {
1001
970k
                                case 'u':
1002
970k
                                {
1003
3.88M
                                    auto check = [](char c) {
1004
3.88M
                                        return ('0' <= c && c <= '9') ||
1005
351k
                                               ('a' <= c && c <= 'f') ||
1006
19.1k
                                               ('A' <= c && c <= 'F');
1007
3.88M
                                    };
1008
970k
                                    if (!(check(*(data + 1)) &&
1009
970k
                                          check(*(data + 2)) &&
1010
970k
                                          check(*(data + 3)) &&
1011
970k
                                          check(*(data + 4))))
1012
125
                                        return {};
1013
970k
                                }
1014
970k
                                    data += 5;
1015
970k
                                    break;
1016
99.8k
                                case '"':
1017
110k
                                case '\\':
1018
110k
                                case '/':
1019
166k
                                case 'b':
1020
325k
                                case 'f':
1021
445k
                                case 'n':
1022
656k
                                case 'r':
1023
950k
                                case 't':
1024
950k
                                    data++;
1025
950k
                                    break;
1026
2
                                default:
1027
2
                                    return {};
1028
1.92M
                            }
1029
1.92M
                        }
1030
61
                        else
1031
61
                            return {};
1032
190M
                    }
1033
0
                    return {};
1034
4.93M
                }
1035
1036
9.43k
                rvalue decode_list(unsigned depth)
1037
20.2k
                {
1038
20.2k
                    rvalue ret(type::List);
1039
20.2k
                    if (CROW_UNLIKELY(!consume('[')) || CROW_UNLIKELY(depth > max_depth))
1040
1
                    {
1041
1
                        ret.set_error();
1042
1
                        return ret;
1043
1
                    }
1044
20.2k
                    ws_skip();
1045
20.2k
                    if (CROW_UNLIKELY(*data == ']'))
1046
607
                    {
1047
607
                        data++;
1048
607
                        return ret;
1049
607
                    }
1050
1051
6.38M
                    while (1)
1052
6.38M
                    {
1053
6.38M
                        auto v = decode_value(depth + 1);
1054
6.38M
                        if (CROW_UNLIKELY(!v))
1055
16.8k
                        {
1056
16.8k
                            ret.set_error();
1057
16.8k
                            break;
1058
16.8k
                        }
1059
6.36M
                        ws_skip();
1060
6.36M
                        ret.emplace_back(std::move(v));
1061
6.36M
                        if (*data == ']')
1062
2.72k
                        {
1063
2.72k
                            data++;
1064
2.72k
                            break;
1065
2.72k
                        }
1066
6.36M
                        if (CROW_UNLIKELY(!consume(',')))
1067
87
                        {
1068
87
                            ret.set_error();
1069
87
                            break;
1070
87
                        }
1071
6.36M
                        ws_skip();
1072
6.36M
                    }
1073
19.6k
                    return ret;
1074
20.2k
                }
1075
1076
9.43k
                rvalue decode_number()
1077
11.2M
                {
1078
11.2M
                    char* start = data;
1079
1080
11.2M
                    enum NumberParsingState
1081
11.2M
                    {
1082
11.2M
                        Minus,
1083
11.2M
                        AfterMinus,
1084
11.2M
                        ZeroFirst,
1085
11.2M
                        Digits,
1086
11.2M
                        DigitsAfterPoints,
1087
11.2M
                        E,
1088
11.2M
                        DigitsAfterE,
1089
11.2M
                        Invalid,
1090
11.2M
                    } state{Minus};
1091
22.5M
                    while (CROW_LIKELY(state != Invalid))
1092
22.5M
                    {
1093
22.5M
                        switch (*data)
1094
22.5M
                        {
1095
608k
                            case '0':
1096
608k
                                state = static_cast<NumberParsingState>("\2\2\7\3\4\6\6"[state]);
1097
                                /*if (state == NumberParsingState::Minus || state == NumberParsingState::AfterMinus)
1098
                                {
1099
                                    state = NumberParsingState::ZeroFirst;
1100
                                }
1101
                                else if (state == NumberParsingState::Digits ||
1102
                                    state == NumberParsingState::DigitsAfterE ||
1103
                                    state == NumberParsingState::DigitsAfterPoints)
1104
                                {
1105
                                    // ok; pass
1106
                                }
1107
                                else if (state == NumberParsingState::E)
1108
                                {
1109
                                    state = NumberParsingState::DigitsAfterE;
1110
                                }
1111
                                else
1112
                                    return {};*/
1113
608k
                                break;
1114
4.39M
                            case '1':
1115
7.06M
                            case '2':
1116
9.40M
                            case '3':
1117
9.75M
                            case '4':
1118
10.0M
                            case '5':
1119
10.1M
                            case '6':
1120
10.2M
                            case '7':
1121
10.6M
                            case '8':
1122
10.6M
                            case '9':
1123
10.6M
                                state = static_cast<NumberParsingState>("\3\3\7\3\4\6\6"[state]);
1124
11.2M
                                while (*(data + 1) >= '0' && *(data + 1) <= '9')
1125
521k
                                    data++;
1126
                                /*if (state == NumberParsingState::Minus || state == NumberParsingState::AfterMinus)
1127
                                {
1128
                                    state = NumberParsingState::Digits;
1129
                                }
1130
                                else if (state == NumberParsingState::Digits ||
1131
                                    state == NumberParsingState::DigitsAfterE ||
1132
                                    state == NumberParsingState::DigitsAfterPoints)
1133
                                {
1134
                                    // ok; pass
1135
                                }
1136
                                else if (state == NumberParsingState::E)
1137
                                {
1138
                                    state = NumberParsingState::DigitsAfterE;
1139
                                }
1140
                                else
1141
                                    return {};*/
1142
10.6M
                                break;
1143
4.20k
                            case '.':
1144
4.20k
                                state = static_cast<NumberParsingState>("\7\7\4\4\7\7\7"[state]);
1145
                                /*
1146
                                if (state == NumberParsingState::Digits || state == NumberParsingState::ZeroFirst)
1147
                                {
1148
                                    state = NumberParsingState::DigitsAfterPoints;
1149
                                }
1150
                                else
1151
                                    return {};
1152
                                */
1153
4.20k
                                break;
1154
2.65k
                            case '-':
1155
2.65k
                                state = static_cast<NumberParsingState>("\1\7\7\7\7\6\7"[state]);
1156
                                /*if (state == NumberParsingState::Minus)
1157
                                {
1158
                                    state = NumberParsingState::AfterMinus;
1159
                                }
1160
                                else if (state == NumberParsingState::E)
1161
                                {
1162
                                    state = NumberParsingState::DigitsAfterE;
1163
                                }
1164
                                else
1165
                                    return {};*/
1166
2.65k
                                break;
1167
606
                            case '+':
1168
606
                                state = static_cast<NumberParsingState>("\7\7\7\7\7\6\7"[state]);
1169
                                /*if (state == NumberParsingState::E)
1170
                                {
1171
                                    state = NumberParsingState::DigitsAfterE;
1172
                                }
1173
                                else
1174
                                    return {};*/
1175
606
                                break;
1176
2.49k
                            case 'e':
1177
2.95k
                            case 'E':
1178
2.95k
                                state = static_cast<NumberParsingState>("\7\7\7\5\5\7\7"[state]);
1179
                                /*if (state == NumberParsingState::Digits ||
1180
                                    state == NumberParsingState::DigitsAfterPoints)
1181
                                {
1182
                                    state = NumberParsingState::E;
1183
                                }
1184
                                else
1185
                                    return {};*/
1186
2.95k
                                break;
1187
11.2M
                            default:
1188
11.2M
                                if (CROW_LIKELY(state == NumberParsingState::ZeroFirst ||
1189
11.2M
                                                state == NumberParsingState::Digits ||
1190
11.2M
                                                state == NumberParsingState::DigitsAfterPoints ||
1191
11.2M
                                                state == NumberParsingState::DigitsAfterE))
1192
11.2M
                                    return {type::Number, start, data};
1193
289
                                else
1194
289
                                    return {};
1195
22.5M
                        }
1196
11.3M
                        data++;
1197
11.3M
                    }
1198
1199
33
                    return {};
1200
11.2M
                }
1201
1202
1203
9.43k
                rvalue decode_value(unsigned depth)
1204
11.3M
                {
1205
11.3M
                    if (CROW_UNLIKELY(depth > max_depth))
1206
0
                    {
1207
0
                        rvalue ret;
1208
0
                        ret.set_error();
1209
0
                        return ret;
1210
0
                    }
1211
1212
11.3M
                    switch (*data)
1213
11.3M
                    {
1214
20.2k
                        case '[':
1215
20.2k
                            return decode_list(depth + 1);
1216
13.7k
                        case '{':
1217
13.7k
                            return decode_object(depth + 1);
1218
3.65k
                        case '"':
1219
3.65k
                            return decode_string();
1220
564
                        case 't':
1221
564
                            if ( //e-data >= 4 &&
1222
564
                              data[1] == 'r' &&
1223
553
                              data[2] == 'u' &&
1224
543
                              data[3] == 'e')
1225
532
                            {
1226
532
                                data += 4;
1227
532
                                return {type::True};
1228
532
                            }
1229
32
                            else
1230
32
                                return {};
1231
267
                        case 'f':
1232
267
                            if ( //e-data >= 5 &&
1233
267
                              data[1] == 'a' &&
1234
257
                              data[2] == 'l' &&
1235
247
                              data[3] == 's' &&
1236
237
                              data[4] == 'e')
1237
226
                            {
1238
226
                                data += 5;
1239
226
                                return {type::False};
1240
226
                            }
1241
41
                            else
1242
41
                                return {};
1243
674
                        case 'n':
1244
674
                            if ( //e-data >= 4 &&
1245
674
                              data[1] == 'u' &&
1246
663
                              data[2] == 'l' &&
1247
652
                              data[3] == 'l')
1248
642
                            {
1249
642
                                data += 4;
1250
642
                                return {type::Null};
1251
642
                            }
1252
32
                            else
1253
32
                                return {};
1254
                        //case '1': case '2': case '3':
1255
                        //case '4': case '5': case '6':
1256
                        //case '7': case '8': case '9':
1257
                        //case '0': case '-':
1258
11.2M
                        default:
1259
11.2M
                            return decode_number();
1260
11.3M
                    }
1261
0
                    return {};
1262
11.3M
                }
crow::json::load_nocopy_internal(char*, unsigned long)::Parser::decode_value(unsigned int)
Line
Count
Source
1204
11.3M
                {
1205
11.3M
                    if (CROW_UNLIKELY(depth > max_depth))
1206
0
                    {
1207
0
                        rvalue ret;
1208
0
                        ret.set_error();
1209
0
                        return ret;
1210
0
                    }
1211
1212
11.3M
                    switch (*data)
1213
11.3M
                    {
1214
20.2k
                        case '[':
1215
20.2k
                            return decode_list(depth + 1);
1216
13.7k
                        case '{':
1217
13.7k
                            return decode_object(depth + 1);
1218
3.65k
                        case '"':
1219
3.65k
                            return decode_string();
1220
564
                        case 't':
1221
564
                            if ( //e-data >= 4 &&
1222
564
                              data[1] == 'r' &&
1223
553
                              data[2] == 'u' &&
1224
543
                              data[3] == 'e')
1225
532
                            {
1226
532
                                data += 4;
1227
532
                                return {type::True};
1228
532
                            }
1229
32
                            else
1230
32
                                return {};
1231
267
                        case 'f':
1232
267
                            if ( //e-data >= 5 &&
1233
267
                              data[1] == 'a' &&
1234
257
                              data[2] == 'l' &&
1235
247
                              data[3] == 's' &&
1236
237
                              data[4] == 'e')
1237
226
                            {
1238
226
                                data += 5;
1239
226
                                return {type::False};
1240
226
                            }
1241
41
                            else
1242
41
                                return {};
1243
674
                        case 'n':
1244
674
                            if ( //e-data >= 4 &&
1245
674
                              data[1] == 'u' &&
1246
663
                              data[2] == 'l' &&
1247
652
                              data[3] == 'l')
1248
642
                            {
1249
642
                                data += 4;
1250
642
                                return {type::Null};
1251
642
                            }
1252
32
                            else
1253
32
                                return {};
1254
                        //case '1': case '2': case '3':
1255
                        //case '4': case '5': case '6':
1256
                        //case '7': case '8': case '9':
1257
                        //case '0': case '-':
1258
11.2M
                        default:
1259
11.2M
                            return decode_number();
1260
11.3M
                    }
1261
0
                    return {};
1262
11.3M
                }
Unexecuted instantiation: crow::json::load_nocopy_internal(char*, unsigned long)::Parser::decode_value(unsigned int)
1263
1264
9.43k
                rvalue decode_object(unsigned depth)
1265
13.7k
                {
1266
13.7k
                    rvalue ret(type::Object);
1267
13.7k
                    if (CROW_UNLIKELY(!consume('{')) || CROW_UNLIKELY(depth > max_depth))
1268
1
                    {
1269
1
                        ret.set_error();
1270
1
                        return ret;
1271
1
                    }
1272
1273
13.7k
                    ws_skip();
1274
1275
13.7k
                    if (CROW_UNLIKELY(*data == '}'))
1276
653
                    {
1277
653
                        data++;
1278
653
                        return ret;
1279
653
                    }
1280
1281
4.93M
                    while (1)
1282
4.93M
                    {
1283
4.93M
                        auto t = decode_string();
1284
4.93M
                        if (CROW_UNLIKELY(!t))
1285
145
                        {
1286
145
                            ret.set_error();
1287
145
                            break;
1288
145
                        }
1289
1290
4.93M
                        ws_skip();
1291
4.93M
                        if (CROW_UNLIKELY(!consume(':')))
1292
54
                        {
1293
54
                            ret.set_error();
1294
54
                            break;
1295
54
                        }
1296
1297
                        // TODO(ipkn) caching key to speed up (flyweight?)
1298
                        // I have no idea how flyweight could apply here, but maybe some speedup can happen if we stopped checking type since decode_string returns a string anyway
1299
4.93M
                        auto key = t.s();
1300
1301
4.93M
                        ws_skip();
1302
4.93M
                        auto v = decode_value(depth + 1);
1303
4.93M
                        if (CROW_UNLIKELY(!v))
1304
1.57k
                        {
1305
1.57k
                            ret.set_error();
1306
1.57k
                            break;
1307
1.57k
                        }
1308
4.93M
                        ws_skip();
1309
1310
4.93M
                        v.key_ = std::move(key);
1311
4.93M
                        ret.emplace_back(std::move(v));
1312
4.93M
                        if (CROW_UNLIKELY(*data == '}'))
1313
11.2k
                        {
1314
11.2k
                            data++;
1315
11.2k
                            break;
1316
11.2k
                        }
1317
4.92M
                        if (CROW_UNLIKELY(!consume(',')))
1318
56
                        {
1319
56
                            ret.set_error();
1320
56
                            break;
1321
56
                        }
1322
4.92M
                        ws_skip();
1323
4.92M
                    }
1324
13.0k
                    return ret;
1325
13.7k
                }
1326
1327
9.43k
                rvalue parse()
1328
9.43k
                {
1329
9.43k
                    ws_skip();
1330
9.43k
                    auto ret = decode_value(0); // or decode object?
1331
9.43k
                    ws_skip();
1332
9.43k
                    if (ret && *data != '\0')
1333
23
                        ret.set_error();
1334
9.43k
                    return ret;
1335
9.43k
                }
1336
1337
9.43k
                char* data;
1338
9.43k
            };
1339
9.43k
            return Parser(data, size).parse();
1340
9.43k
        }
1341
        inline rvalue load(const char* data, size_t size)
1342
9.43k
        {
1343
9.43k
            char* s = new char[size + 1];
1344
9.43k
            memcpy(s, data, size);
1345
9.43k
            s[size] = 0;
1346
9.43k
            auto ret = load_nocopy_internal(s, size);
1347
9.43k
            if (ret)
1348
8.47k
                ret.key_.force(s, size);
1349
968
            else
1350
968
                delete[] s;
1351
9.43k
            return ret;
1352
9.43k
        }
1353
1354
        inline rvalue load(const char* data)
1355
0
        {
1356
0
            return load(data, strlen(data));
1357
0
        }
1358
1359
        inline rvalue load(const std::string& str)
1360
9.43k
        {
1361
9.43k
            return load(str.data(), str.size());
1362
9.43k
        }
1363
1364
        struct wvalue_reader;
1365
1366
        /**
1367
         * @brief JSON write value.
1368
         *
1369
         * Value can mean any json value, including a JSON object.<br>
1370
         * Write means this class is used to primarily assemble JSON objects using keys and values and export those into a string.
1371
         * The object container is selected at compile time. By default, object keys use an
1372
         * `std::unordered_map`; `CROW_JSON_USE_MAP` selects lexicographically sorted keys,
1373
         * while `CROW_JSON_USE_INSERTION_ORDER` preserves the order of newly inserted keys.
1374
         * Updating an existing key does not change its position. These options affect the
1375
         * order of serialized JSON object keys and cannot be used together.
1376
         */
1377
        class wvalue : public returnable
1378
        {
1379
            friend class crow::mustache::template_t;
1380
            friend struct wvalue_reader;
1381
1382
        public:
1383
            using object = detail::object_policy::object_type<wvalue>;
1384
1385
            using list = std::vector<wvalue>;
1386
1387
46.0M
            type t() const { return t_; }
1388
1389
            /// Create an empty json value (outputs "{}" instead of a "null" string)
1390
0
            static crow::json::wvalue empty_object() { return crow::json::wvalue::object(); }
1391
1392
        private:
1393
            type t_{type::Null};         ///< The type of the value.
1394
            num_type nt{num_type::Null}; ///< The specific type of the number if \ref t_ is a number.
1395
            union number
1396
            {
1397
                double d;
1398
                int64_t si;
1399
                uint64_t ui;
1400
1401
            public:
1402
                constexpr number() noexcept:
1403
7.77M
                  ui() {} /* default constructor initializes unsigned integer. */
1404
                constexpr number(std::uint64_t value) noexcept:
1405
0
                  ui(value) {}
1406
                constexpr number(std::int64_t value) noexcept:
1407
0
                  si(value) {}
1408
                explicit constexpr number(double value) noexcept:
1409
0
                  d(value) {}
1410
                explicit constexpr number(float value) noexcept:
1411
0
                  d(value) {}
1412
            } num;                                      ///< Value if type is a number.
1413
            std::string s;                              ///< Value if type is a string.
1414
            std::unique_ptr<list> l;                    ///< Value if type is a list.
1415
            std::unique_ptr<object> o;                  ///< Value if type is a JSON object.
1416
            std::function<std::string(std::string&)> f; ///< Value if type is a function (C++ lambda)
1417
1418
        public:
1419
            wvalue():
1420
7.70k
              returnable("application/json") {}
1421
1422
            wvalue(std::nullptr_t):
1423
0
              returnable("application/json"), t_(type::Null) {}
1424
1425
            wvalue(bool value):
1426
0
              returnable("application/json"), t_(value ? type::True : type::False) {}
1427
1428
            wvalue(std::uint8_t value):
1429
0
              returnable("application/json"), t_(type::Number), nt(num_type::Unsigned_integer), num(static_cast<std::uint64_t>(value)) {}
1430
            wvalue(std::uint16_t value):
1431
0
              returnable("application/json"), t_(type::Number), nt(num_type::Unsigned_integer), num(static_cast<std::uint64_t>(value)) {}
1432
            wvalue(std::uint32_t value):
1433
0
              returnable("application/json"), t_(type::Number), nt(num_type::Unsigned_integer), num(static_cast<std::uint64_t>(value)) {}
1434
            wvalue(std::uint64_t value):
1435
0
              returnable("application/json"), t_(type::Number), nt(num_type::Unsigned_integer), num(static_cast<std::uint64_t>(value)) {}
1436
1437
            wvalue(std::int8_t value):
1438
0
              returnable("application/json"), t_(type::Number), nt(num_type::Signed_integer), num(static_cast<std::int64_t>(value)) {}
1439
            wvalue(std::int16_t value):
1440
0
              returnable("application/json"), t_(type::Number), nt(num_type::Signed_integer), num(static_cast<std::int64_t>(value)) {}
1441
            wvalue(std::int32_t value):
1442
0
              returnable("application/json"), t_(type::Number), nt(num_type::Signed_integer), num(static_cast<std::int64_t>(value)) {}
1443
            wvalue(std::int64_t value):
1444
0
              returnable("application/json"), t_(type::Number), nt(num_type::Signed_integer), num(static_cast<std::int64_t>(value)) {}
1445
1446
            wvalue(float value):
1447
0
              returnable("application/json"), t_(type::Number), nt(num_type::Floating_point), num(static_cast<double>(value)) {}
1448
            wvalue(double value):
1449
0
              returnable("application/json"), t_(type::Number), nt(num_type::Double_precision_floating_point), num(static_cast<double>(value)) {}
1450
1451
            wvalue(char const* value):
1452
0
              returnable("application/json"), t_(type::String), s(value) {}
1453
1454
            wvalue(std::string const& value):
1455
0
              returnable("application/json"), t_(type::String), s(value) {}
1456
            wvalue(std::string&& value):
1457
0
              returnable("application/json"), t_(type::String), s(std::move(value)) {}
1458
1459
            wvalue(std::initializer_list<std::pair<std::string const, wvalue>> initializer_list):
1460
0
              returnable("application/json"), t_(type::Object), o(new object(initializer_list)) {}
1461
1462
            wvalue(object const& value):
1463
0
              returnable("application/json"), t_(type::Object), o(new object(value)) {}
1464
            wvalue(object&& value):
1465
0
              returnable("application/json"), t_(type::Object), o(new object(std::move(value))) {}
1466
1467
            wvalue(const list& r):
1468
              returnable("application/json")
1469
0
            {
1470
0
                t_ = type::List;
1471
0
                l = std::make_unique<list>();
1472
0
                l->reserve(r.size());
1473
0
                for (auto it = r.begin(); it != r.end(); ++it)
1474
0
                    l->emplace_back(*it);
1475
0
            }
1476
            wvalue(list& r):
1477
              returnable("application/json")
1478
0
            {
1479
0
                t_ = type::List;
1480
0
                l = std::make_unique<list>();
1481
0
                l->reserve(r.size());
1482
0
                for (auto it = r.begin(); it != r.end(); ++it)
1483
0
                    l->emplace_back(*it);
1484
0
            }
1485
1486
            /// Create a write value from a read value (useful for editing JSON strings).
1487
            wvalue(const rvalue& r):
1488
7.76M
              returnable("application/json")
1489
7.76M
            {
1490
7.76M
                t_ = r.t();
1491
7.76M
                switch (r.t())
1492
7.76M
                {
1493
99
                    case type::Null:
1494
210
                    case type::False:
1495
474
                    case type::True:
1496
474
                    case type::Function:
1497
474
                        return;
1498
7.75M
                    case type::Number:
1499
7.75M
                        nt = r.nt();
1500
7.75M
                        if (nt == num_type::Floating_point || nt == num_type::Double_precision_floating_point)
1501
3.89k
                            num.d = r.d();
1502
7.75M
                        else if (nt == num_type::Signed_integer)
1503
1.84k
                            num.si = r.i();
1504
7.75M
                        else
1505
7.75M
                            num.ui = r.u();
1506
7.75M
                        return;
1507
1.79k
                    case type::String:
1508
1.79k
                        s = r.s();
1509
1.79k
                        return;
1510
1.67k
                    case type::List:
1511
1.67k
                        l = std::make_unique<list>();
1512
1.67k
                        l->reserve(r.size());
1513
3.05M
                        for (auto it = r.begin(); it != r.end(); ++it)
1514
3.05M
                            l->emplace_back(*it);
1515
1.67k
                        return;
1516
6.21k
                    case type::Object:
1517
6.21k
                        o = std::make_unique<object>();
1518
4.71M
                        for (auto it = r.begin(); it != r.end(); ++it)
1519
4.70M
                            o->emplace(it->key(), *it);
1520
6.21k
                        return;
1521
7.76M
                }
1522
7.76M
            }
1523
1524
            wvalue(const wvalue& r):
1525
0
              returnable("application/json")
1526
0
            {
1527
0
                t_ = r.t();
1528
0
                switch (r.t())
1529
0
                {
1530
0
                    case type::Null:
1531
0
                    case type::False:
1532
0
                    case type::True:
1533
0
                        return;
1534
0
                    case type::Number:
1535
0
                        nt = r.nt;
1536
0
                        if (nt == num_type::Floating_point || nt == num_type::Double_precision_floating_point)
1537
0
                            num.d = r.num.d;
1538
0
                        else if (nt == num_type::Signed_integer)
1539
0
                            num.si = r.num.si;
1540
0
                        else
1541
0
                            num.ui = r.num.ui;
1542
0
                        return;
1543
0
                    case type::String:
1544
0
                        s = r.s;
1545
0
                        return;
1546
0
                    case type::List:
1547
0
                        l = std::make_unique<list>();
1548
0
                        l->reserve(r.size());
1549
0
                        for (auto it = r.l->begin(); it != r.l->end(); ++it)
1550
0
                            l->emplace_back(*it);
1551
0
                        return;
1552
0
                    case type::Object:
1553
0
                        o = std::make_unique<object>();
1554
0
                        o->insert(r.o->begin(), r.o->end());
1555
0
                        return;
1556
0
                    case type::Function:
1557
0
                        f = r.f;
1558
0
                }
1559
0
            }
1560
1561
            wvalue(wvalue&& r):
1562
              returnable("application/json")
1563
0
            {
1564
0
                *this = std::move(r);
1565
0
            }
1566
1567
            wvalue& operator=(wvalue&& r)
1568
0
            {
1569
0
                t_ = r.t_;
1570
0
                nt = r.nt;
1571
0
                num = r.num;
1572
0
                s = std::move(r.s);
1573
0
                l = std::move(r.l);
1574
0
                o = std::move(r.o);
1575
0
                return *this;
1576
0
            }
1577
1578
            /// Used for compatibility, same as \ref reset()
1579
            void clear()
1580
0
            {
1581
0
                reset();
1582
0
            }
1583
1584
            void reset()
1585
267k
            {
1586
267k
                t_ = type::Null;
1587
267k
                l.reset();
1588
267k
                o.reset();
1589
267k
            }
1590
1591
            wvalue& operator=(std::nullptr_t)
1592
0
            {
1593
0
                reset();
1594
0
                return *this;
1595
0
            }
1596
            wvalue& operator=(bool value)
1597
0
            {
1598
0
                reset();
1599
0
                if (value)
1600
0
                    t_ = type::True;
1601
0
                else
1602
0
                    t_ = type::False;
1603
0
                return *this;
1604
0
            }
1605
1606
            wvalue& operator=(float value)
1607
0
            {
1608
0
                reset();
1609
0
                t_ = type::Number;
1610
0
                num.d = value;
1611
0
                nt = num_type::Floating_point;
1612
0
                return *this;
1613
0
            }
1614
1615
            wvalue& operator=(double value)
1616
0
            {
1617
0
                reset();
1618
0
                t_ = type::Number;
1619
0
                num.d = value;
1620
0
                nt = num_type::Double_precision_floating_point;
1621
0
                return *this;
1622
0
            }
1623
1624
            wvalue& operator=(unsigned short value)
1625
0
            {
1626
0
                reset();
1627
0
                t_ = type::Number;
1628
0
                num.ui = value;
1629
0
                nt = num_type::Unsigned_integer;
1630
0
                return *this;
1631
0
            }
1632
1633
            wvalue& operator=(short value)
1634
0
            {
1635
0
                reset();
1636
0
                t_ = type::Number;
1637
0
                num.si = value;
1638
0
                nt = num_type::Signed_integer;
1639
0
                return *this;
1640
0
            }
1641
1642
            wvalue& operator=(long long value)
1643
0
            {
1644
0
                reset();
1645
0
                t_ = type::Number;
1646
0
                num.si = value;
1647
0
                nt = num_type::Signed_integer;
1648
0
                return *this;
1649
0
            }
1650
1651
            wvalue& operator=(long value)
1652
0
            {
1653
0
                reset();
1654
0
                t_ = type::Number;
1655
0
                num.si = value;
1656
0
                nt = num_type::Signed_integer;
1657
0
                return *this;
1658
0
            }
1659
1660
            wvalue& operator=(int value)
1661
0
            {
1662
0
                reset();
1663
0
                t_ = type::Number;
1664
0
                num.si = value;
1665
0
                nt = num_type::Signed_integer;
1666
0
                return *this;
1667
0
            }
1668
1669
            wvalue& operator=(unsigned long long value)
1670
0
            {
1671
0
                reset();
1672
0
                t_ = type::Number;
1673
0
                num.ui = value;
1674
0
                nt = num_type::Unsigned_integer;
1675
0
                return *this;
1676
0
            }
1677
1678
            wvalue& operator=(unsigned long value)
1679
0
            {
1680
0
                reset();
1681
0
                t_ = type::Number;
1682
0
                num.ui = value;
1683
0
                nt = num_type::Unsigned_integer;
1684
0
                return *this;
1685
0
            }
1686
1687
            wvalue& operator=(unsigned int value)
1688
0
            {
1689
0
                reset();
1690
0
                t_ = type::Number;
1691
0
                num.ui = value;
1692
0
                nt = num_type::Unsigned_integer;
1693
0
                return *this;
1694
0
            }
1695
1696
            wvalue& operator=(const char* str)
1697
262k
            {
1698
262k
                reset();
1699
262k
                t_ = type::String;
1700
262k
                s = str;
1701
262k
                return *this;
1702
262k
            }
1703
1704
            wvalue& operator=(const std::string& str)
1705
3.60k
            {
1706
3.60k
                reset();
1707
3.60k
                t_ = type::String;
1708
3.60k
                s = str;
1709
3.60k
                return *this;
1710
3.60k
            }
1711
1712
            wvalue& operator=(list&& v)
1713
0
            {
1714
0
                if (t_ != type::List)
1715
0
                    reset();
1716
0
                t_ = type::List;
1717
0
                if (!l)
1718
0
                    l = std::make_unique<list>();
1719
0
                l->clear();
1720
0
                l->resize(v.size());
1721
0
                size_t idx = 0;
1722
0
                for (auto& x : v)
1723
0
                {
1724
0
                    (*l)[idx++] = std::move(x);
1725
0
                }
1726
0
                return *this;
1727
0
            }
1728
1729
            template<typename T>
1730
            wvalue& operator=(const std::vector<T>& v)
1731
            {
1732
                if (t_ != type::List)
1733
                    reset();
1734
                t_ = type::List;
1735
                if (!l)
1736
                    l = std::make_unique<list>();
1737
                l->clear();
1738
                l->resize(v.size());
1739
                size_t idx = 0;
1740
                for (auto& x : v)
1741
                {
1742
                    (*l)[idx++] = x;
1743
                }
1744
                return *this;
1745
            }
1746
1747
            wvalue& operator=(std::initializer_list<std::pair<std::string const, wvalue>> initializer_list)
1748
0
            {
1749
0
                if (t_ != type::Object)
1750
0
                {
1751
0
                    reset();
1752
0
                    t_ = type::Object;
1753
0
                    o = std::make_unique<object>(initializer_list);
1754
0
                }
1755
0
                else
1756
0
                {
1757
0
#if defined(__APPLE__) || defined(__MACH__) || defined(__FreeBSD__) || defined(__ANDROID__) || defined(_LIBCPP_VERSION)
1758
0
                    o = std::make_unique<object>(initializer_list);
1759
0
#else
1760
0
                    (*o) = initializer_list;
1761
0
#endif
1762
0
                }
1763
0
                return *this;
1764
0
            }
1765
1766
            wvalue& operator=(object const& value)
1767
0
            {
1768
0
                if (t_ != type::Object)
1769
0
                {
1770
0
                    reset();
1771
0
                    t_ = type::Object;
1772
0
                    o = std::make_unique<object>(value);
1773
0
                }
1774
0
                else
1775
0
                {
1776
0
#if defined(__APPLE__) || defined(__MACH__) || defined(__FreeBSD__) || defined(__ANDROID__) || defined(_LIBCPP_VERSION)
1777
0
                    o = std::make_unique<object>(value);
1778
0
#else
1779
0
                    (*o) = value;
1780
0
#endif
1781
0
                }
1782
0
                return *this;
1783
0
            }
1784
1785
            wvalue& operator=(object&& value)
1786
0
            {
1787
0
                if (t_ != type::Object)
1788
0
                {
1789
0
                    reset();
1790
0
                    t_ = type::Object;
1791
0
                    o = std::make_unique<object>(std::move(value));
1792
0
                }
1793
0
                else
1794
0
                {
1795
0
                    (*o) = std::move(value);
1796
0
                }
1797
0
                return *this;
1798
0
            }
1799
1800
            wvalue& operator=(std::function<std::string(std::string&)>&& func)
1801
0
            {
1802
0
                reset();
1803
0
                t_ = type::Function;
1804
0
                f = std::move(func);
1805
0
                return *this;
1806
0
            }
1807
1808
            wvalue& operator[](unsigned index)
1809
0
            {
1810
0
                if (t_ != type::List)
1811
0
                    reset();
1812
0
                t_ = type::List;
1813
0
                if (!l)
1814
0
                    l = std::make_unique<list>();
1815
0
                if (l->size() < index + 1)
1816
0
                    l->resize(index + 1);
1817
0
                return (*l)[index];
1818
0
            }
1819
1820
            const wvalue& operator[](unsigned index) const
1821
0
            {
1822
0
                return const_cast<wvalue*>(this)->operator[](index);
1823
0
            }
1824
1825
            /// Check if the object contains the given key.
1826
            bool has(const char* key) const
1827
0
            {
1828
0
                return has(std::string(key));
1829
0
            }
1830
1831
            /// Check if the object contains the given key.
1832
            bool has(const std::string& key) const
1833
0
            {
1834
0
                if (t_ != type::Object)
1835
0
                    return false;
1836
0
                if (!o)
1837
0
                    return false;
1838
0
#if (__cplusplus>=202002L)
1839
0
                return o->contains(key);
1840
0
#else
1841
0
                return o->count(key)>0;
1842
0
#endif
1843
0
            }
1844
1845
            size_t count(const std::string& str) const
1846
118k
            {
1847
118k
                if (t_ != type::Object)
1848
0
                    return 0;
1849
118k
                if (!o)
1850
0
                    return 0;
1851
118k
                return o->count(str);
1852
118k
            }
1853
1854
            wvalue& operator[](const std::string& str)
1855
11.9k
            {
1856
11.9k
                if (t_ != type::Object)
1857
1.32k
                    reset();
1858
11.9k
                t_ = type::Object;
1859
11.9k
                if (!o)
1860
1.32k
                    o = std::make_unique<object>();
1861
11.9k
                return (*o)[str];
1862
11.9k
            }
1863
1864
            const wvalue& operator[](const std::string& str) const
1865
8.36k
            {
1866
8.36k
                return const_cast<wvalue*>(this)->operator[](str);
1867
8.36k
            }
1868
1869
            std::vector<std::string> keys() const
1870
0
            {
1871
0
                if (t_ != type::Object)
1872
0
                    return {};
1873
0
                std::vector<std::string> result;
1874
0
                for (auto& kv : *o)
1875
0
                {
1876
0
                    result.push_back(kv.first);
1877
0
                }
1878
0
                return result;
1879
0
            }
1880
1881
            std::string execute(std::string txt = "") const //Not using reference because it cannot be used with a default rvalue
1882
0
            {
1883
0
                if (t_ != type::Function)
1884
0
                    return "";
1885
0
                return f(txt);
1886
0
            }
1887
1888
            /// If the wvalue is a list, it returns the length of the list, otherwise it returns 1.
1889
            std::size_t size() const
1890
0
            {
1891
0
                if (t_ != type::List)
1892
0
                    return 1;
1893
0
                return l->size();
1894
0
            }
1895
1896
            /// Returns an estimated size of the value in bytes.
1897
            size_t estimate_length() const
1898
6.45M
            {
1899
6.45M
                switch (t_)
1900
6.45M
                {
1901
198
                    case type::Null: return 4;
1902
222
                    case type::False: return 5;
1903
528
                    case type::True: return 4;
1904
6.43M
                    case type::Number: return 30;
1905
3.16k
                    case type::String: return 2 + s.size() + s.size() / 2;
1906
3.29k
                    case type::List:
1907
3.29k
                    {
1908
3.29k
                        size_t sum{};
1909
3.29k
                        if (l)
1910
3.29k
                        {
1911
3.29k
                            for (auto& x : *l)
1912
6.11M
                            {
1913
6.11M
                                sum += 1;
1914
6.11M
                                sum += x.estimate_length();
1915
6.11M
                            }
1916
3.29k
                        }
1917
3.29k
                        return sum + 2;
1918
0
                    }
1919
11.3k
                    case type::Object:
1920
11.3k
                    {
1921
11.3k
                        size_t sum{};
1922
11.3k
                        if (o)
1923
11.3k
                        {
1924
11.3k
                            for (auto& kv : *o)
1925
337k
                            {
1926
337k
                                sum += 2;
1927
337k
                                sum += 2 + kv.first.size() + kv.first.size() / 2;
1928
337k
                                sum += kv.second.estimate_length();
1929
337k
                            }
1930
11.3k
                        }
1931
11.3k
                        return sum + 2;
1932
0
                    }
1933
0
                    case type::Function:
1934
0
                        return 0;
1935
6.45M
                }
1936
0
                return 1;
1937
6.45M
            }
1938
1939
        private:
1940
            inline void dump_string(const std::string& str, std::string& out) const
1941
340k
            {
1942
340k
                out.push_back('"');
1943
340k
                escape(str, out);
1944
340k
                out.push_back('"');
1945
340k
            }
1946
1947
            inline void dump_indentation_part(std::string& out, const size_t indent, const char separator, const int indent_level) const
1948
3.23M
            {
1949
3.23M
                out.push_back('\n');
1950
3.23M
                out.append(indent_level * indent, separator);
1951
3.23M
            }
1952
1953
1954
            inline void dump_internal(const wvalue& v, std::string& out, const size_t indent, const char separator, const int indent_level = 0) const
1955
6.45M
            {
1956
6.45M
                switch (v.t_)
1957
6.45M
                {
1958
198
                    case type::Null: out += "null"; break;
1959
222
                    case type::False: out += "false"; break;
1960
528
                    case type::True: out += "true"; break;
1961
6.43M
                    case type::Number:
1962
6.43M
                    {
1963
6.43M
                        if (v.nt == num_type::Floating_point || v.nt == num_type::Double_precision_floating_point)
1964
5.37k
                        {
1965
5.37k
                            if (isnan(v.num.d) || isinf(v.num.d))
1966
888
                            {
1967
888
                                out += "null";
1968
888
                                CROW_LOG_WARNING << "Invalid JSON value detected (" << v.num.d << "), value set to null";
1969
888
                                break;
1970
888
                            }
1971
4.48k
                            enum
1972
4.48k
                            {
1973
4.48k
                                start,
1974
4.48k
                                decp, // Decimal point
1975
4.48k
                                zero,
1976
4.48k
                                exp // in the exponent
1977
4.48k
                            } f_state;
1978
4.48k
                            char outbuf[128];
1979
4.48k
                            if (v.nt == num_type::Double_precision_floating_point)
1980
0
                            {
1981
#ifdef _MSC_VER
1982
                                sprintf_s(outbuf, sizeof(outbuf), "%.*g", std::numeric_limits<double>::max_digits10, v.num.d);
1983
#else
1984
0
                                snprintf(outbuf, sizeof(outbuf), "%.*g", std::numeric_limits<double>::max_digits10, v.num.d);
1985
0
#endif
1986
0
                            }
1987
4.48k
                            else
1988
4.48k
                            {
1989
#ifdef _MSC_VER
1990
                                sprintf_s(outbuf, sizeof(outbuf), "%f", v.num.d);
1991
#else
1992
4.48k
                                snprintf(outbuf, sizeof(outbuf), "%f", v.num.d);
1993
4.48k
#endif
1994
4.48k
                            }
1995
4.48k
                            char* p = &outbuf[0];
1996
4.48k
                            char* pos_first_trailing_0 = nullptr;
1997
4.48k
                            char* pos_exponent = nullptr;
1998
4.48k
                            f_state = start;
1999
304k
                            while (*p != '\0')
2000
300k
                            {
2001
                                //std::cout << *p << std::endl;
2002
300k
                                char ch = *p;
2003
300k
                                switch (f_state)
2004
300k
                                {
2005
287k
                                    case start: // Loop and lookahead until a decimal point is found
2006
287k
                                        if (ch == '.')
2007
4.35k
                                        {
2008
4.35k
                                            char fch = *(p + 1);
2009
                                            // if the first character is 0, leave it be (this is so that "1.00000" becomes "1.0" and not "1.")
2010
4.35k
                                            if (fch != '\0' && fch == '0') p++;
2011
4.35k
                                            f_state = decp;
2012
4.35k
                                        }
2013
287k
                                        p++;
2014
287k
                                        break;
2015
3.92k
                                    case decp: // Loop until a 0 is found, if found, record its position
2016
3.92k
                                        if (ch == '0')
2017
2.67k
                                        {
2018
2.67k
                                            f_state = zero;
2019
2.67k
                                            pos_first_trailing_0 = p;
2020
2.67k
                                        }
2021
1.24k
                                        else if (ch == 'e')
2022
0
                                        {
2023
0
                                            pos_exponent = p;
2024
0
                                            f_state = exp;
2025
0
                                        }
2026
3.92k
                                        p++;
2027
3.92k
                                        break;
2028
8.91k
                                    case zero: // if a non 0 is found (e.g. 1.00004) remove the earlier recorded 0 position and look for more trailing 0s
2029
8.91k
                                        if (ch == 'e')
2030
0
                                        {
2031
0
                                            pos_exponent = p;
2032
0
                                            f_state = exp;
2033
0
                                        }
2034
8.91k
                                        else if (ch != '0')
2035
354
                                        {
2036
354
                                            pos_first_trailing_0 = nullptr;
2037
354
                                            f_state = decp;
2038
354
                                        }
2039
8.91k
                                        p++;
2040
8.91k
                                        break;
2041
0
                                    case exp: // if an 'e' has been found, one is in the exponent; no more looking for trailing zeroes
2042
0
                                        p++;
2043
0
                                        break;
2044
300k
                                }
2045
300k
                            }
2046
4.48k
                            if (pos_first_trailing_0 != nullptr) // if any trailing 0s are found, terminate the string where they begin
2047
2.32k
                            {
2048
2.32k
                                *pos_first_trailing_0 = '\0';
2049
2.32k
                                if (pos_exponent != nullptr) // if there is an exponent, include it
2050
0
                                {
2051
0
                                    strcpy(pos_first_trailing_0, pos_exponent);
2052
0
                                }
2053
2.32k
                            }
2054
4.48k
                            out += outbuf;
2055
4.48k
                        }
2056
6.43M
                        else if (v.nt == num_type::Signed_integer)
2057
1.31k
                        {
2058
1.31k
                            out += std::to_string(v.num.si);
2059
1.31k
                        }
2060
6.43M
                        else
2061
6.43M
                        {
2062
6.43M
                            out += std::to_string(v.num.ui);
2063
6.43M
                        }
2064
6.43M
                    }
2065
6.43M
                    break;
2066
6.43M
                    case type::String: dump_string(v.s, out); break;
2067
3.29k
                    case type::List:
2068
3.29k
                    {
2069
3.29k
                        out.push_back('[');
2070
2071
3.29k
                        if (indent !=std::string::npos)
2072
1.64k
                        {
2073
1.64k
                            dump_indentation_part(out, indent, separator, indent_level + 1);
2074
1.64k
                        }
2075
2076
3.29k
                        if (v.l)
2077
3.29k
                        {
2078
3.29k
                            bool first = true;
2079
3.29k
                            for (auto& x : *v.l)
2080
6.11M
                            {
2081
6.11M
                                if (!first)
2082
6.10M
                                {
2083
6.10M
                                    out.push_back(',');
2084
2085
6.10M
                                    if (indent != std::string::npos)
2086
3.05M
                                    {
2087
3.05M
                                        dump_indentation_part(out, indent, separator, indent_level + 1);
2088
3.05M
                                    }
2089
6.10M
                                }
2090
6.11M
                                first = false;
2091
6.11M
                                dump_internal(x, out, indent, separator, indent_level + 1);
2092
6.11M
                            }
2093
3.29k
                        }
2094
2095
3.29k
                        if (indent !=std::string::npos)
2096
1.64k
                        {
2097
1.64k
                            dump_indentation_part(out, indent, separator, indent_level);
2098
1.64k
                        }
2099
2100
3.29k
                        out.push_back(']');
2101
3.29k
                    }
2102
3.29k
                    break;
2103
11.3k
                    case type::Object:
2104
11.3k
                    {
2105
11.3k
                        out.push_back('{');
2106
2107
11.3k
                        if (indent != std::string::npos)
2108
5.68k
                        {
2109
5.68k
                            dump_indentation_part(out, indent, separator, indent_level + 1);
2110
5.68k
                        }
2111
2112
11.3k
                        if (v.o)
2113
11.3k
                        {
2114
11.3k
                            bool first = true;
2115
11.3k
                            for (auto& kv : *v.o)
2116
337k
                            {
2117
337k
                                if (!first)
2118
327k
                                {
2119
327k
                                    out.push_back(',');
2120
327k
                                    if (indent != std::string::npos)
2121
163k
                                    {
2122
163k
                                        dump_indentation_part(out, indent, separator, indent_level + 1);
2123
163k
                                    }
2124
327k
                                }
2125
337k
                                first = false;
2126
337k
                                dump_string(kv.first, out);
2127
337k
                                out.push_back(':');
2128
2129
337k
                                if (indent != std::string::npos)
2130
168k
                                {
2131
168k
                                    out.push_back(' ');
2132
168k
                                }
2133
2134
337k
                                dump_internal(kv.second, out, indent, separator, indent_level + 1);
2135
337k
                            }
2136
11.3k
                        }
2137
2138
11.3k
                        if (indent != std::string::npos)
2139
5.68k
                        {
2140
5.68k
                            dump_indentation_part(out, indent, separator, indent_level);
2141
5.68k
                        }
2142
2143
11.3k
                        out.push_back('}');
2144
11.3k
                    }
2145
11.3k
                    break;
2146
2147
0
                    case type::Function:
2148
0
                        out += "custom function";
2149
0
                        break;
2150
6.45M
                }
2151
6.45M
            }
2152
2153
        public:
2154
            std::string dump(const size_t indent, const char separator = ' ') const
2155
8.47k
            {
2156
8.47k
                std::string ret;
2157
8.47k
                ret.reserve(estimate_length());
2158
8.47k
                dump_internal(*this, ret, indent, separator);
2159
8.47k
                return ret;
2160
8.47k
            }
2161
2162
            std::string dump() const override
2163
4.23k
            {
2164
4.23k
                static constexpr size_t DontIndent = std::string::npos;
2165
2166
4.23k
                return dump(DontIndent);
2167
4.23k
            }
2168
2169
            /// Return json string.
2170
            explicit operator std::string() const
2171
0
            {
2172
0
                return dump();
2173
0
            }
2174
        };
2175
2176
        // Used for accessing the internals of a wvalue
2177
        struct wvalue_reader
2178
        {
2179
            int64_t get(int64_t fallback)
2180
0
            {
2181
0
                if (ref.t() != type::Number || ref.nt == num_type::Floating_point ||
2182
0
                    ref.nt == num_type::Double_precision_floating_point)
2183
0
                    return fallback;
2184
0
                return ref.num.si;
2185
0
            }
2186
2187
            double get(double fallback)
2188
0
            {
2189
0
                if (ref.t() != type::Number || ref.nt != num_type::Floating_point ||
2190
0
                    ref.nt == num_type::Double_precision_floating_point)
2191
0
                    return fallback;
2192
0
                return ref.num.d;
2193
0
            }
2194
2195
            bool get(bool fallback)
2196
0
            {
2197
0
                if (ref.t() == type::True) return true;
2198
0
                if (ref.t() == type::False) return false;
2199
0
                return fallback;
2200
0
            }
2201
2202
            std::string get(const std::string& fallback)
2203
0
            {
2204
0
                if (ref.t() != type::String) return fallback;
2205
0
                return ref.s;
2206
0
            }
2207
2208
            const wvalue& ref;
2209
        };
2210
2211
        //std::vector<asio::const_buffer> dump_ref(wvalue& v)
2212
        //{
2213
        //}
2214
    } // namespace json
2215
} // namespace crow