-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.h
12992 lines (10788 loc) · 428 KB
/
json.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
__ _____ _____ _____
__| | __| | | | JSON for Modern C++
| | |__ | | | | | | version 2.1.1
|_____|_____|_____|_|___| https://github.com/nlohmann/json
Licensed under the MIT License <http://opensource.org/licenses/MIT>.
Copyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef NLOHMANN_JSON_HPP
#define NLOHMANN_JSON_HPP
#include <algorithm> // all_of, copy, fill, find, for_each, none_of, remove, reverse, transform
#include <array> // array
#include <cassert> // assert
#include <ciso646> // and, not, or
#include <clocale> // lconv, localeconv
#include <cmath> // isfinite, labs, ldexp, signbit
#include <cstddef> // nullptr_t, ptrdiff_t, size_t
#include <cstdint> // int64_t, uint64_t
#include <cstdlib> // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull
#include <cstring> // strlen
#include <forward_list> // forward_list
#include <functional> // function, hash, less
#include <initializer_list> // initializer_list
#include <iostream> // istream, ostream
#include <iterator> // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator
#include <limits> // numeric_limits
#include <locale> // locale
#include <map> // map
#include <memory> // addressof, allocator, allocator_traits, unique_ptr
#include <numeric> // accumulate
#include <sstream> // stringstream
#include <string> // getline, stoi, string, to_string
#include <type_traits> // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type
#include <utility> // declval, forward, make_pair, move, pair, swap
#include <vector> // vector
// exclude unsupported compilers
#if defined(__clang__)
#if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
#error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
#endif
#elif defined(__GNUC__)
#if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900
#error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
#endif
#endif
// disable float-equal warnings on GCC/clang
#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
#endif
// disable documentation warnings on clang
#if defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdocumentation"
#endif
// allow for portable deprecation warnings
#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
#define JSON_DEPRECATED __attribute__((deprecated))
#elif defined(_MSC_VER)
#define JSON_DEPRECATED __declspec(deprecated)
#else
#define JSON_DEPRECATED
#endif
// allow to disable exceptions
#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && not defined(JSON_NOEXCEPTION)
#define JSON_THROW(exception) throw exception
#define JSON_TRY try
#define JSON_CATCH(exception) catch(exception)
#else
#define JSON_THROW(exception) std::abort()
#define JSON_TRY if(true)
#define JSON_CATCH(exception) if(false)
#endif
/*!
@brief namespace for Niels Lohmann
@see https://github.com/nlohmann
@since version 1.0.0
*/
namespace nlohmann {
/*!
@brief unnamed namespace with internal helper functions
This namespace collects some functions that could not be defined inside the
@ref basic_json class.
@since version 2.1.0
*/
namespace detail {
////////////////
// exceptions //
////////////////
/*!
@brief general exception of the @ref basic_json class
Extension of std::exception objects with a member @a id for exception ids.
@note To have nothrow-copy-constructible exceptions, we internally use
std::runtime_error which can cope with arbitrary-length error messages.
Intermediate strings are built with static functions and then passed to
the actual constructor.
@since version 3.0.0
*/
class exception : public std::exception {
public:
/// returns the explanatory string
virtual const char* what( ) const noexcept override {
return m.what( );
}
/// the id of the exception
const int id;
protected:
exception( int id_, const char* what_arg )
: id( id_ ), m( what_arg ) {}
static std::string name( const std::string& ename, int id ) {
return "[json.exception." + ename + "." + std::to_string( id ) + "] ";
}
private:
/// an exception object as storage for error messages
std::runtime_error m;
};
/*!
@brief exception indicating a parse error
This excpetion is thrown by the library when a parse error occurs. Parse
errors can occur during the deserialization of JSON text as well as when
using JSON Patch.
Member @a byte holds the byte index of the last read character in the input
file.
@note For an input with n bytes, 1 is the index of the first character
and n+1 is the index of the terminating null byte or the end of
file. This also holds true when reading a byte vector (CBOR or
MessagePack).
Exceptions have ids 1xx.
name / id | example massage | description
------------------------------ | --------------- | -------------------------
json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position.
json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.
json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects.
json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors.
json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number wihtout a leading `0`.
json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character.
json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences.
json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
json.exception.parse_error.111 | parse error: bad input stream | Parsing CBOR or MessagePack from an input stream where the [`badbit` or `failbit`](http://en.cppreference.com/w/cpp/io/ios_base/iostate) is set.
json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xf8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read.
json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read.
@since version 3.0.0
*/
class parse_error : public exception {
public:
/*!
@brief create a parse error exception
@param[in] id the id of the exception
@param[in] byte_ the byte index where the error occured (or 0 if
the position cannot be determined)
@param[in] what_arg the explanatory string
@return parse_error object
*/
static parse_error create( int id, size_t byte_, const std::string& what_arg ) {
std::string w = exception::name( "parse_error", id ) + "parse error" +
( byte_ != 0 ? ( " at " + std::to_string( byte_ ) ) : "" ) +
": " + what_arg;
return parse_error( id, byte_, w.c_str( ) );
}
/*!
@brief byte index of the parse error
The byte index of the last read character in the input file.
@note For an input with n bytes, 1 is the index of the first character
and n+1 is the index of the terminating null byte or the end of
file. This also holds true when reading a byte vector (CBOR or
MessagePack).
*/
const size_t byte;
private:
parse_error( int id_, size_t byte_, const char* what_arg )
: exception( id_, what_arg ), byte( byte_ ) {}
};
/*!
@brief exception indicating errors with iterators
Exceptions have ids 2xx.
name / id | example massage | description
----------------------------------- | --------------- | -------------------------
json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid.
json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.
json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.
json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to.
json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compated, because JSON objects are unordered.
json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin().
@since version 3.0.0
*/
class invalid_iterator : public exception {
public:
static invalid_iterator create( int id, const std::string& what_arg ) {
std::string w = exception::name( "invalid_iterator", id ) + what_arg;
return invalid_iterator( id, w.c_str( ) );
}
private:
invalid_iterator( int id_, const char* what_arg )
: exception( id_, what_arg ) {}
};
/*!
@brief exception indicating executing a member function with a wrong type
Exceptions have ids 3xx.
name / id | example massage | description
----------------------------- | --------------- | -------------------------
json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&.
json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types.
json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types.
json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined.
json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive.
@since version 3.0.0
*/
class type_error : public exception {
public:
static type_error create( int id, const std::string& what_arg ) {
std::string w = exception::name( "type_error", id ) + what_arg;
return type_error( id, w.c_str( ) );
}
private:
type_error( int id_, const char* what_arg )
: exception( id_, what_arg ) {}
};
/*!
@brief exception indicating access out of the defined range
Exceptions have ids 4xx.
name / id | example massage | description
------------------------------- | --------------- | -------------------------
json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1.
json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF.
@since version 3.0.0
*/
class out_of_range : public exception {
public:
static out_of_range create( int id, const std::string& what_arg ) {
std::string w = exception::name( "out_of_range", id ) + what_arg;
return out_of_range( id, w.c_str( ) );
}
private:
out_of_range( int id_, const char* what_arg )
: exception( id_, what_arg ) {}
};
/*!
@brief exception indicating other errors
Exceptions have ids 5xx.
name / id | example massage | description
------------------------------ | --------------- | -------------------------
json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
@since version 3.0.0
*/
class other_error : public exception {
public:
static other_error create( int id, const std::string& what_arg ) {
std::string w = exception::name( "other_error", id ) + what_arg;
return other_error( id, w.c_str( ) );
}
private:
other_error( int id_, const char* what_arg )
: exception( id_, what_arg ) {}
};
///////////////////////////
// JSON type enumeration //
///////////////////////////
/*!
@brief the JSON type enumeration
This enumeration collects the different JSON types. It is internally used to
distinguish the stored values, and the functions @ref basic_json::is_null(),
@ref basic_json::is_object(), @ref basic_json::is_array(),
@ref basic_json::is_string(), @ref basic_json::is_boolean(),
@ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
@ref basic_json::is_structured() rely on it.
@note There are three enumeration entries (number_integer, number_unsigned, and
number_float), because the library distinguishes these three types for numbers:
@ref basic_json::number_unsigned_t is used for unsigned integers,
@ref basic_json::number_integer_t is used for signed integers, and
@ref basic_json::number_float_t is used for floating-point numbers or to
approximate integers which do not fit in the limits of their respective type.
@sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
value with the default value for a given type
@since version 1.0.0
*/
enum class value_t : uint8_t {
null, ///< null value
object, ///< object (unordered set of name/value pairs)
array, ///< array (ordered collection of values)
string, ///< string value
boolean, ///< boolean value
number_integer, ///< number value (signed integer)
number_unsigned, ///< number value (unsigned integer)
number_float, ///< number value (floating-point)
discarded ///< discarded by the the parser callback function
};
/*!
@brief comparison operator for JSON types
Returns an ordering that is similar to Python:
- order: null < boolean < number < object < array < string
- furthermore, each type is not smaller than itself
@since version 1.0.0
*/
inline bool operator<( const value_t lhs, const value_t rhs ) noexcept {
static constexpr std::array<uint8_t, 8> order = { {
0, // null
3, // object
4, // array
5, // string
1, // boolean
2, // integer
2, // unsigned
2, // float
}
};
// discarded values are not comparable
if( lhs == value_t::discarded or rhs == value_t::discarded ) {
return false;
}
return order[ static_cast<std::size_t>( lhs ) ] <
order[ static_cast<std::size_t>( rhs ) ];
}
/////////////
// helpers //
/////////////
// alias templates to reduce boilerplate
template<bool B, typename T = void>
using enable_if_t = typename std::enable_if<B, T>::type;
template<typename T>
using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
/*
Implementation of two C++17 constructs: conjunction, negation. This is needed
to avoid evaluating all the traits in a condition
For example: not std::is_same<void, T>::value and has_value_type<T>::value
will not compile when T = void (on MSVC at least). Whereas
conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
stop evaluating if negation<...>::value == false
Please note that those constructs must be used with caution, since symbols can
become very long quickly (which can slow down compilation and cause MSVC
internal compiler errors). Only use it when you have to (see example ahead).
*/
template<class...> struct conjunction : std::true_type {};
template<class B1> struct conjunction<B1> : B1 {};
template<class B1, class... Bn>
struct conjunction<B1, Bn...> : std::conditional<bool( B1::value ), conjunction<Bn...>, B1>::type {};
template<class B> struct negation : std::integral_constant < bool, !B::value > {};
// dispatch utility (taken from ranges-v3)
template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
template<> struct priority_tag<0> {};
//////////////////
// constructors //
//////////////////
template<value_t> struct external_constructor;
template<>
struct external_constructor<value_t::boolean> {
template<typename BasicJsonType>
static void construct( BasicJsonType& j, typename BasicJsonType::boolean_t b ) noexcept {
j.m_type = value_t::boolean;
j.m_value = b;
j.assert_invariant( );
}
};
template<>
struct external_constructor<value_t::string> {
template<typename BasicJsonType>
static void construct( BasicJsonType& j, const typename BasicJsonType::string_t& s ) {
j.m_type = value_t::string;
j.m_value = s;
j.assert_invariant( );
}
};
template<>
struct external_constructor<value_t::number_float> {
template<typename BasicJsonType>
static void construct( BasicJsonType& j, typename BasicJsonType::number_float_t val ) noexcept {
j.m_type = value_t::number_float;
j.m_value = val;
j.assert_invariant( );
}
};
template<>
struct external_constructor<value_t::number_unsigned> {
template<typename BasicJsonType>
static void construct( BasicJsonType& j, typename BasicJsonType::number_unsigned_t val ) noexcept {
j.m_type = value_t::number_unsigned;
j.m_value = val;
j.assert_invariant( );
}
};
template<>
struct external_constructor<value_t::number_integer> {
template<typename BasicJsonType>
static void construct( BasicJsonType& j, typename BasicJsonType::number_integer_t val ) noexcept {
j.m_type = value_t::number_integer;
j.m_value = val;
j.assert_invariant( );
}
};
template<>
struct external_constructor<value_t::array> {
template<typename BasicJsonType>
static void construct( BasicJsonType& j, const typename BasicJsonType::array_t& arr ) {
j.m_type = value_t::array;
j.m_value = arr;
j.assert_invariant( );
}
template<typename BasicJsonType, typename CompatibleArrayType,
enable_if_t<not std::is_same<CompatibleArrayType,
typename BasicJsonType::array_t>::value,
int> = 0>
static void construct( BasicJsonType& j, const CompatibleArrayType& arr ) {
using std::begin;
using std::end;
j.m_type = value_t::array;
j.m_value.array = j.template create<typename BasicJsonType::array_t>( begin( arr ), end( arr ) );
j.assert_invariant( );
}
template<typename BasicJsonType>
static void construct( BasicJsonType& j, const std::vector<bool>& arr ) {
j.m_type = value_t::array;
j.m_value = value_t::array;
j.m_value.array->reserve( arr.size( ) );
for( bool x : arr ) {
j.m_value.array->push_back( x );
}
j.assert_invariant( );
}
};
template<>
struct external_constructor<value_t::object> {
template<typename BasicJsonType>
static void construct( BasicJsonType& j, const typename BasicJsonType::object_t& obj ) {
j.m_type = value_t::object;
j.m_value = obj;
j.assert_invariant( );
}
template<typename BasicJsonType, typename CompatibleObjectType,
enable_if_t<not std::is_same<CompatibleObjectType,
typename BasicJsonType::object_t>::value,
int> = 0>
static void construct( BasicJsonType& j, const CompatibleObjectType& obj ) {
using std::begin;
using std::end;
j.m_type = value_t::object;
j.m_value.object = j.template create<typename BasicJsonType::object_t>( begin( obj ), end( obj ) );
j.assert_invariant( );
}
};
////////////////////////
// has_/is_ functions //
////////////////////////
/*!
@brief Helper to determine whether there's a key_type for T.
This helper is used to tell associative containers apart from other containers
such as sequence containers. For instance, `std::map` passes the test as it
contains a `mapped_type`, whereas `std::vector` fails the test.
@sa http://stackoverflow.com/a/7728728/266378
@since version 1.0.0, overworked in version 2.0.6
*/
#define NLOHMANN_JSON_HAS_HELPER(type) \
template<typename T> struct has_##type { \
private: \
template<typename U, typename = typename U::type> \
static int detect(U &&); \
static void detect(...); \
public: \
static constexpr bool value = \
std::is_integral<decltype(detect(std::declval<T>()))>::value; \
}
NLOHMANN_JSON_HAS_HELPER( mapped_type );
NLOHMANN_JSON_HAS_HELPER( key_type );
NLOHMANN_JSON_HAS_HELPER( value_type );
NLOHMANN_JSON_HAS_HELPER( iterator );
#undef NLOHMANN_JSON_HAS_HELPER
template<bool B, class RealType, class CompatibleObjectType>
struct is_compatible_object_type_impl : std::false_type {};
template<class RealType, class CompatibleObjectType>
struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType> {
static constexpr auto value =
std::is_constructible<typename RealType::key_type,
typename CompatibleObjectType::key_type>::value and
std::is_constructible<typename RealType::mapped_type,
typename CompatibleObjectType::mapped_type>::value;
};
template<class BasicJsonType, class CompatibleObjectType>
struct is_compatible_object_type {
static auto constexpr value = is_compatible_object_type_impl <
conjunction<negation<std::is_same<void, CompatibleObjectType>>,
has_mapped_type<CompatibleObjectType>,
has_key_type<CompatibleObjectType>>::value,
typename BasicJsonType::object_t, CompatibleObjectType >::value;
};
template<typename BasicJsonType, typename T>
struct is_basic_json_nested_type {
static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
std::is_same<T, typename BasicJsonType::const_iterator>::value or
std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value or
std::is_same<T, typename BasicJsonType::json_pointer>::value;
};
template<class BasicJsonType, class CompatibleArrayType>
struct is_compatible_array_type {
static auto constexpr value =
conjunction<negation<std::is_same<void, CompatibleArrayType>>,
negation<is_compatible_object_type<
BasicJsonType, CompatibleArrayType>>,
negation<std::is_constructible<typename BasicJsonType::string_t,
CompatibleArrayType>>,
negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,
has_value_type<CompatibleArrayType>,
has_iterator<CompatibleArrayType>>::value;
};
template<bool, typename, typename>
struct is_compatible_integer_type_impl : std::false_type {};
template<typename RealIntegerType, typename CompatibleNumberIntegerType>
struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType> {
// is there an assert somewhere on overflows?
using RealLimits = std::numeric_limits<RealIntegerType>;
using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
static constexpr auto value =
std::is_constructible<RealIntegerType,
CompatibleNumberIntegerType>::value and
CompatibleLimits::is_integer and
RealLimits::is_signed == CompatibleLimits::is_signed;
};
template<typename RealIntegerType, typename CompatibleNumberIntegerType>
struct is_compatible_integer_type {
static constexpr auto value =
is_compatible_integer_type_impl <
std::is_integral<CompatibleNumberIntegerType>::value and
not std::is_same<bool, CompatibleNumberIntegerType>::value,
RealIntegerType, CompatibleNumberIntegerType > ::value;
};
// trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
template<typename BasicJsonType, typename T>
struct has_from_json {
private:
// also check the return type of from_json
template<typename U, typename = enable_if_t<std::is_same<void, decltype( uncvref_t<U>::from_json(
std::declval<BasicJsonType>( ), std::declval<T&>( ) ) )>::value>>
static int detect( U&& );
static void detect( ... );
public:
static constexpr bool value = std::is_integral<decltype(
detect( std::declval<typename BasicJsonType::template json_serializer<T, void>>( ) ) )>::value;
};
// This trait checks if JSONSerializer<T>::from_json(json const&) exists
// this overload is used for non-default-constructible user-defined-types
template<typename BasicJsonType, typename T>
struct has_non_default_from_json {
private:
template <
typename U,
typename = enable_if_t<std::is_same<
T, decltype( uncvref_t<U>::from_json( std::declval<BasicJsonType>( ) ) )>::value >>
static int detect( U&& );
static void detect( ... );
public:
static constexpr bool value = std::is_integral<decltype( detect(
std::declval<typename BasicJsonType::template json_serializer<T, void>>( ) ) )>::value;
};
// This trait checks if BasicJsonType::json_serializer<T>::to_json exists
template<typename BasicJsonType, typename T>
struct has_to_json {
private:
template<typename U, typename = decltype( uncvref_t<U>::to_json(
std::declval<BasicJsonType&>( ), std::declval<T>( ) ) )>
static int detect( U&& );
static void detect( ... );
public:
static constexpr bool value = std::is_integral<decltype( detect(
std::declval<typename BasicJsonType::template json_serializer<T, void>>( ) ) )>::value;
};
/////////////
// to_json //
/////////////
template<typename BasicJsonType, typename T, enable_if_t<
std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
void to_json( BasicJsonType& j, T b ) noexcept {
external_constructor<value_t::boolean>::construct( j, b );
}
template<typename BasicJsonType, typename CompatibleString,
enable_if_t<std::is_constructible<typename BasicJsonType::string_t,
CompatibleString>::value, int> = 0>
void to_json( BasicJsonType& j, const CompatibleString& s ) {
external_constructor<value_t::string>::construct( j, s );
}
template<typename BasicJsonType, typename FloatType,
enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
void to_json( BasicJsonType& j, FloatType val ) noexcept {
external_constructor<value_t::number_float>::construct( j, static_cast<typename BasicJsonType::number_float_t>( val ) );
}
template <
typename BasicJsonType, typename CompatibleNumberUnsignedType,
enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t,
CompatibleNumberUnsignedType>::value, int> = 0 >
void to_json( BasicJsonType& j, CompatibleNumberUnsignedType val ) noexcept {
external_constructor<value_t::number_unsigned>::construct( j, static_cast<typename BasicJsonType::number_unsigned_t>( val ) );
}
template <
typename BasicJsonType, typename CompatibleNumberIntegerType,
enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t,
CompatibleNumberIntegerType>::value, int> = 0 >
void to_json( BasicJsonType& j, CompatibleNumberIntegerType val ) noexcept {
external_constructor<value_t::number_integer>::construct( j, static_cast<typename BasicJsonType::number_integer_t>( val ) );
}
template<typename BasicJsonType, typename EnumType,
enable_if_t<std::is_enum<EnumType>::value, int> = 0>
void to_json( BasicJsonType& j, EnumType e ) noexcept {
using underlying_type = typename std::underlying_type<EnumType>::type;
external_constructor<value_t::number_integer>::construct( j, static_cast<underlying_type>( e ) );
}
template<typename BasicJsonType>
void to_json( BasicJsonType& j, const std::vector<bool>& e ) {
external_constructor<value_t::array>::construct( j, e );
}
template <
typename BasicJsonType, typename CompatibleArrayType,
enable_if_t <
is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
int > = 0 >
void to_json( BasicJsonType& j, const CompatibleArrayType& arr ) {
external_constructor<value_t::array>::construct( j, arr );
}
template <
typename BasicJsonType, typename CompatibleObjectType,
enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value,
int> = 0 >
void to_json( BasicJsonType& j, const CompatibleObjectType& arr ) {
external_constructor<value_t::object>::construct( j, arr );
}
template <typename BasicJsonType, typename T, std::size_t N,
enable_if_t<not std::is_constructible<
typename BasicJsonType::string_t, T( &)[ N ]>::value,
int> = 0>
void to_json( BasicJsonType& j, T( &arr )[ N ] ) {
external_constructor<value_t::array>::construct( j, arr );
}
///////////////
// from_json //
///////////////
// overloads for basic_json template parameters
template<typename BasicJsonType, typename ArithmeticType,
enable_if_t<std::is_arithmetic<ArithmeticType>::value and
not std::is_same<ArithmeticType,
typename BasicJsonType::boolean_t>::value,
int> = 0>
void get_arithmetic_value( const BasicJsonType& j, ArithmeticType& val ) {
switch( static_cast<value_t>( j ) ) {
case value_t::number_unsigned:
{
val = static_cast<ArithmeticType>(
*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>( ) );
break;
}
case value_t::number_integer:
{
val = static_cast<ArithmeticType>(
*j.template get_ptr<const typename BasicJsonType::number_integer_t*>( ) );
break;
}
case value_t::number_float:
{
val = static_cast<ArithmeticType>(
*j.template get_ptr<const typename BasicJsonType::number_float_t*>( ) );
break;
}
default:
{
JSON_THROW( type_error::create( 302, "type must be number, but is " + j.type_name( ) ) );
}
}
}
template<typename BasicJsonType>
void from_json( const BasicJsonType& j, typename BasicJsonType::boolean_t& b ) {
if( not j.is_boolean( ) ) {
JSON_THROW( type_error::create( 302, "type must be boolean, but is " + j.type_name( ) ) );
}
b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>( );
}
template<typename BasicJsonType>
void from_json( const BasicJsonType& j, typename BasicJsonType::string_t& s ) {
if( not j.is_string( ) ) {
JSON_THROW( type_error::create( 302, "type must be string, but is " + j.type_name( ) ) );
}
s = *j.template get_ptr<const typename BasicJsonType::string_t*>( );
}
template<typename BasicJsonType>
void from_json( const BasicJsonType& j, typename BasicJsonType::number_float_t& val ) {
get_arithmetic_value( j, val );
}
template<typename BasicJsonType>
void from_json( const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val ) {
get_arithmetic_value( j, val );
}
template<typename BasicJsonType>
void from_json( const BasicJsonType& j, typename BasicJsonType::number_integer_t& val ) {
get_arithmetic_value( j, val );
}
template<typename BasicJsonType, typename EnumType,
enable_if_t<std::is_enum<EnumType>::value, int> = 0>
void from_json( const BasicJsonType& j, EnumType& e ) {
typename std::underlying_type<EnumType>::type val;
get_arithmetic_value( j, val );
e = static_cast<EnumType>( val );
}
template<typename BasicJsonType>
void from_json( const BasicJsonType& j, typename BasicJsonType::array_t& arr ) {
if( not j.is_array( ) ) {
JSON_THROW( type_error::create( 302, "type must be array, but is " + j.type_name( ) ) );
}
arr = *j.template get_ptr<const typename BasicJsonType::array_t*>( );
}
// forward_list doesn't have an insert method
template<typename BasicJsonType, typename T, typename Allocator,
enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
void from_json( const BasicJsonType& j, std::forward_list<T, Allocator>& l ) {
if( not j.is_array( ) ) {
JSON_THROW( type_error::create( 302, "type must be array, but is " + j.type_name( ) ) );
}
for( auto it = j.rbegin( ), end = j.rend( ); it != end; ++it ) {
l.push_front( it->template get<T>( ) );
}
}
template<typename BasicJsonType, typename CompatibleArrayType>
void from_json_array_impl( const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> ) {
using std::begin;
using std::end;
std::transform( j.begin( ), j.end( ),
std::inserter( arr, end( arr ) ), []( const BasicJsonType & i ) {
// get<BasicJsonType>() returns *this, this won't call a from_json
// method when value_type is BasicJsonType
return i.template get<typename CompatibleArrayType::value_type>( );
} );
}
template<typename BasicJsonType, typename CompatibleArrayType>
auto from_json_array_impl( const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> )
-> decltype(
arr.reserve( std::declval<typename CompatibleArrayType::size_type>( ) ),
void( ) ) {
using std::begin;
using std::end;
arr.reserve( j.size( ) );
std::transform( j.begin( ), j.end( ),
std::inserter( arr, end( arr ) ), []( const BasicJsonType & i ) {
// get<BasicJsonType>() returns *this, this won't call a from_json
// method when value_type is BasicJsonType
return i.template get<typename CompatibleArrayType::value_type>( );
} );
}
template<typename BasicJsonType, typename CompatibleArrayType,
enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and
std::is_convertible<BasicJsonType, typename CompatibleArrayType::value_type>::value and
not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0>
void from_json( const BasicJsonType& j, CompatibleArrayType& arr ) {
if( not j.is_array( ) ) {
JSON_THROW( type_error::create( 302, "type must be array, but is " + j.type_name( ) ) );
}
from_json_array_impl( j, arr, priority_tag<1> {} );
}
template<typename BasicJsonType, typename CompatibleObjectType,
enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
void from_json( const BasicJsonType& j, CompatibleObjectType& obj ) {
if( not j.is_object( ) ) {
JSON_THROW( type_error::create( 302, "type must be object, but is " + j.type_name( ) ) );
}
auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>( );
using std::begin;
using std::end;
// we could avoid the assignment, but this might require a for loop, which
// might be less efficient than the container constructor for some
// containers (would it?)
obj = CompatibleObjectType( begin( *inner_object ), end( *inner_object ) );
}
// overload for arithmetic types, not chosen for basic_json template arguments
// (BooleanType, etc..); note: Is it really necessary to provide explicit
// overloads for boolean_t etc. in case of a custom BooleanType which is not
// an arithmetic type?
template<typename BasicJsonType, typename ArithmeticType,
enable_if_t <
std::is_arithmetic<ArithmeticType>::value and
not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
int> = 0>
void from_json( const BasicJsonType& j, ArithmeticType& val ) {
switch( static_cast<value_t>( j ) ) {
case value_t::number_unsigned:
{
val = static_cast<ArithmeticType>( *j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>( ) );
break;
}
case value_t::number_integer:
{
val = static_cast<ArithmeticType>( *j.template get_ptr<const typename BasicJsonType::number_integer_t*>( ) );
break;
}
case value_t::number_float:
{
val = static_cast<ArithmeticType>( *j.template get_ptr<const typename BasicJsonType::number_float_t*>( ) );
break;
}
case value_t::boolean:
{
val = static_cast<ArithmeticType>( *j.template get_ptr<const typename BasicJsonType::boolean_t*>( ) );
break;
}
default:
{
JSON_THROW( type_error::create( 302, "type must be number, but is " + j.type_name( ) ) );
}
}
}
struct to_json_fn {
private:
template<typename BasicJsonType, typename T>
auto call( BasicJsonType& j, T&& val, priority_tag<1> ) const noexcept( noexcept( to_json( j, std::forward<T>( val ) ) ) )
-> decltype( to_json( j, std::forward<T>( val ) ), void( ) ) {
return to_json( j, std::forward<T>( val ) );
}