forked from CleverRaven/Cataclysm-DDA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.h
1650 lines (1503 loc) · 55 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
#pragma once
#ifndef CATA_SRC_JSON_H
#define CATA_SRC_JSON_H
#include <array>
#include <bitset>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <iterator>
#include <map>
#include <set>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "colony.h"
#include "enum_conversions.h"
#include "int_id.h"
#include "memory_fast.h"
#include "string_id.h"
/* Cataclysm-DDA homegrown JSON tools
* copyright CC-BY-SA-3.0 2013 CleverRaven
*
* Consists of four JSON manipulation tools:
* JsonIn - for low-level parsing of an input JSON stream
* JsonOut - for outputting JSON
* JsonObject - convenience-wrapper for reading JSON objects from a JsonIn
* JsonArray - convenience-wrapper for reading JSON arrays from a JsonIn
*
* Further documentation can be found below.
*/
template<typename E>
class enum_bitset;
class JsonArray;
class JsonIn;
class JsonObject;
class JsonValue;
class item;
namespace cata
{
template<typename T>
class optional;
} // namespace cata
class JsonError : public std::runtime_error
{
public:
explicit JsonError( const std::string &msg );
const char *c_str() const noexcept {
return what();
}
};
template<typename T, typename Enable = void>
struct key_from_json_string;
template<>
struct key_from_json_string<std::string, void> {
std::string operator()( const std::string &s ) {
return s;
}
};
template<typename T>
struct key_from_json_string<string_id<T>, void> {
string_id<T> operator()( const std::string &s ) {
return string_id<T>( s );
}
};
template<typename T>
struct key_from_json_string<int_id<T>, void> {
int_id<T> operator()( const std::string &s ) {
return int_id<T>( s );
}
};
template<typename Enum>
struct key_from_json_string<Enum, std::enable_if_t<std::is_enum<Enum>::value>> {
Enum operator()( const std::string &s ) {
return io::string_to_enum<Enum>( s );
}
};
struct number_sci_notation {
bool negative = false;
// AKA the significand
uint64_t number = 0;
// AKA the order of magnitude
int64_t exp = 0;
};
struct json_source_location {
shared_ptr_fast<std::string> path;
int offset = 0;
};
class JsonValue
{
private:
JsonIn &jsin_;
int pos_;
JsonIn &seek() const;
public:
JsonValue( JsonIn &jsin, int pos ) : jsin_( jsin ), pos_( pos ) { }
// NOLINTNEXTLINE(google-explicit-constructor)
operator std::string() const;
// NOLINTNEXTLINE(google-explicit-constructor)
operator int() const;
// NOLINTNEXTLINE(google-explicit-constructor)
operator bool() const;
// NOLINTNEXTLINE(google-explicit-constructor)
operator double() const;
// NOLINTNEXTLINE(google-explicit-constructor)
operator JsonObject() const;
// NOLINTNEXTLINE(google-explicit-constructor)
operator JsonArray() const;
template<typename T>
bool read( T &t, bool throw_on_error = false ) const;
bool test_string() const;
bool test_int() const;
bool test_bool() const;
bool test_float() const;
bool test_object() const;
bool test_array() const;
bool test_null() const;
std::string get_string() const;
int get_int() const;
bool get_bool() const;
double get_float() const;
JsonObject get_object() const;
JsonArray get_array() const;
[[noreturn]] void string_error( const std::string &err ) const;
[[noreturn]] void string_error( int offset, const std::string &err ) const;
[[noreturn]] void throw_error( const std::string &err ) const;
[[noreturn]] void throw_error( int offset, const std::string &err ) const;
};
namespace detail
{
// A c++11 compatible older compiler compatible implementation of void_t
template<typename... Ts> struct make_void {
using type = void;
};
template<typename... Ts> using void_t = typename make_void<Ts...>::type;
template<class, typename = void>
struct IsJsonInDeserializable : std::false_type {};
template<class T>
struct IsJsonInDeserializable<T, void_t<decltype( std::declval<T>().deserialize( std::declval<JsonIn &>() ) )>> :
std::true_type {};
template<class, typename = void>
struct IsJsonValueDeserializable : std::false_type {};
template<class T>
struct IsJsonValueDeserializable<T, void_t<decltype( std::declval<T>().deserialize( std::declval<const JsonValue &>() ) )>> :
std::true_type {};
} // namespace detail
/* JsonIn
* ======
*
* The JsonIn class provides a wrapper around a std::istream,
* with methods for reading JSON data directly from the stream.
*
* JsonObject and JsonArray provide higher-level wrappers,
* and are a little easier to use in most cases,
* but have the small overhead of indexing the members or elements before use.
*
* Typical JsonIn usage might be something like the following:
*
* JsonIn jsin(myistream);
* // expecting an array of objects
* jsin.start_array(); // throws JsonError if array not found
* while (!jsin.end_array()) { // end_array returns false if not the end
* JsonObject jo = jsin.get_object();
* ... // load object using JsonObject methods
* }
*
* The array could have been loaded into a JsonArray for convenience.
* Not doing so saves one full pass of the data,
* as the element positions don't have to be read beforehand.
*
* If the JSON structure is not as expected,
* verbose error messages are provided, indicating the problem,
* and the exact line number and byte offset within the istream.
*
*
* Single-Pass Loading
* -------------------
*
* A JsonIn can also be used for single-pass loading,
* by passing off members as they arrive according to their names.
*
* Typical usage might be:
*
* JsonIn jsin(&myistream);
* // expecting an array of objects, to be mapped by id
* std::map<std::string,my_data_type> myobjects;
* jsin.start_array();
* while (!jsin.end_array()) {
* my_data_type myobject;
* jsin.start_object();
* while (!jsin.end_object()) {
* std::string name = jsin.get_member_name();
* if (name == "id") {
* myobject.id = jsin.get_string();
* } else if (name == "name") {
* myobject.name = _(jsin.get_string());
* } else if (name == "description") {
* myobject.description = _(jsin.get_string());
* } else if (name == "points") {
* myobject.points = jsin.get_int();
* } else if (name == "flags") {
* if (jsin.test_string()) { // load single string tag
* myobject.tags.insert(jsin.get_string());
* } else { // load tag array
* jsin.start_array();
* while (!jsin.end_array()) {
* myobject.tags.insert(jsin.get_string());
* }
* }
* } else {
* jsin.skip_value();
* }
* }
* myobjects[myobject.id] = myobject;
* }
*
* The get_* methods automatically verify and skip separators and whitespace.
*
* Using this method, unrecognized members are silently ignored,
* allowing for things like "comment" members,
* but the user must remember to provide an "else" clause,
* explicitly skipping them.
*
* If an if;else if;... is missing the "else", it /will/ cause bugs,
* so preindexing as a JsonObject is safer, as well as tidier.
*/
class JsonIn
{
private:
std::istream *stream;
shared_ptr_fast<std::string> path;
bool ate_separator = false;
void sanity_check_stream();
void skip_separator();
void skip_pair_separator();
void end_value();
public:
explicit JsonIn( std::istream &s );
JsonIn( std::istream &s, const std::string &path );
JsonIn( std::istream &s, const json_source_location &loc );
JsonIn( const JsonIn & ) = delete;
JsonIn &operator=( const JsonIn & ) = delete;
shared_ptr_fast<std::string> get_path() const {
return path;
}
bool get_ate_separator() {
return ate_separator;
}
void set_ate_separator( bool s ) {
ate_separator = s;
}
int tell(); // get current stream position
void seek( int pos ); // seek to specified stream position
char peek(); // what's the next char gonna be?
bool good(); // whether stream is ok
// advance seek head to the next non-whitespace character
void eat_whitespace();
// or rewind to the previous one
void uneat_whitespace();
// quick skipping for when values don't have to be parsed
void skip_member();
void skip_string();
void skip_value();
void skip_object();
void skip_array();
void skip_true();
void skip_false();
void skip_null();
void skip_number();
// data parsing
std::string get_string(); // get the next value as a string
int get_int(); // get the next value as an int
unsigned int get_uint(); // get the next value as an unsigned int
int64_t get_int64(); // get the next value as an int64
uint64_t get_uint64(); // get the next value as a uint64
bool get_bool(); // get the next value as a bool
double get_float(); // get the next value as a double
std::string get_member_name(); // also strips the ':'
JsonObject get_object();
JsonArray get_array();
JsonValue get_value(); // just returns a JsonValue at the current position.
template<typename E, typename = typename std::enable_if<std::is_enum<E>::value>::type>
E get_enum_value() {
const int old_offset = tell();
try {
return io::string_to_enum<E>( get_string() );
} catch( const io::InvalidEnumString & ) {
seek( old_offset ); // so the error message points to the correct place.
error( "invalid enumeration value" );
}
}
// container control and iteration
void start_array(); // verify array start
bool end_array(); // returns false if it's not the end
void start_object();
bool end_object(); // returns false if it's not the end
// type testing
bool test_null();
bool test_bool();
bool test_number();
bool test_int() {
return test_number();
}
bool test_float() {
return test_number();
}
bool test_string();
bool test_bitset();
bool test_array();
bool test_object();
// optionally-fatal reading into values by reference
// returns true if the data was read successfully, false otherwise
// if throw_on_error then throws JsonError rather than returning false.
bool read_null( bool throw_on_error = false );
bool read( bool &b, bool throw_on_error = false );
bool read( char &c, bool throw_on_error = false );
bool read( signed char &c, bool throw_on_error = false );
bool read( unsigned char &c, bool throw_on_error = false );
bool read( short unsigned int &s, bool throw_on_error = false );
bool read( short int &s, bool throw_on_error = false );
bool read( int &i, bool throw_on_error = false );
bool read( int64_t &i, bool throw_on_error = false );
bool read( uint64_t &i, bool throw_on_error = false );
bool read( unsigned int &u, bool throw_on_error = false );
bool read( float &f, bool throw_on_error = false );
bool read( double &d, bool throw_on_error = false );
bool read( std::string &s, bool throw_on_error = false );
template<size_t N>
bool read( std::bitset<N> &b, bool throw_on_error = false );
template <typename T>
auto read( string_id<T> &thing, bool throw_on_error = false ) -> bool {
std::string tmp;
if( !read( tmp, throw_on_error ) ) {
return false;
}
thing = string_id<T>( tmp );
return true;
}
// This is for the int_id type
template <typename T>
auto read( int_id<T> &thing, bool throw_on_error = false ) -> bool {
std::string tmp;
if( !read( tmp, throw_on_error ) ) {
return false;
}
thing = int_id<T>( tmp );
return true;
}
/// Overload that calls a global function `deserialize(T&,JsonIn&)`, if available.
template<typename T>
auto read( T &v, bool throw_on_error = false ) ->
decltype( deserialize( v, *this ), true ) {
try {
deserialize( v, *this );
return true;
} catch( const JsonError & ) {
if( throw_on_error ) {
throw;
}
return false;
}
}
/// Overload that calls a member function `T::deserialize(JsonIn&)`, if available.
/// And also that `T::deserialize(const JsonValue&)` is not available.
template<typename T>
auto read( T &v, bool throw_on_error = false ) -> typename std::enable_if <
detail::IsJsonInDeserializable<T>::value &&
!detail::IsJsonValueDeserializable<T>::value, bool >::type {
try {
v.deserialize( *this );
return true;
} catch( const JsonError & ) {
if( throw_on_error ) {
throw;
}
return false;
}
}
/// Overload that calls a member function `T::deserialize(const JsonValue&)`, if available.
/// But only if `T::deserialize(JsonIn&)` is not available.
template<typename T>
auto read( T &v, bool throw_on_error = false ) -> typename std::enable_if <
!detail::IsJsonInDeserializable<T>::value &&
detail::IsJsonValueDeserializable<T>::value, bool >::type {
try {
v.deserialize( this->get_value() );
return true;
} catch( const JsonError & ) {
if( throw_on_error ) {
throw;
}
return false;
}
}
template<typename T, std::enable_if_t<std::is_enum<T>::value, int> = 0>
bool read( T &val, bool throw_on_error = false ) {
int i;
if( read( i, false ) ) {
val = static_cast<T>( i );
return true;
}
std::string s;
if( read( s, throw_on_error ) ) {
val = io::string_to_enum<T>( s );
return true;
}
return false;
}
/// Overload for std::pair
template<typename T, typename U>
bool read( std::pair<T, U> &p, bool throw_on_error = false ) {
if( !test_array() ) {
return error_or_false( throw_on_error, "Expected json array encoding pair" );
}
try {
start_array();
bool result = !end_array() &&
read( p.first, throw_on_error ) &&
!end_array() &&
read( p.second, throw_on_error ) &&
end_array();
if( !result && throw_on_error ) {
error( "Array had wrong number of elements for pair" );
}
return result;
} catch( const JsonError & ) {
if( throw_on_error ) {
throw;
}
return false;
}
}
// array ~> vector, deque, list
template < typename T, typename std::enable_if <
!std::is_same<void, typename T::value_type>::value >::type * = nullptr
>
auto read( T &v, bool throw_on_error = false ) -> decltype( v.front(), true ) {
if( !test_array() ) {
return error_or_false( throw_on_error, "Expected json array" );
}
try {
start_array();
v.clear();
while( !end_array() ) {
typename T::value_type element;
if( read( element, throw_on_error ) ) {
v.push_back( std::move( element ) );
} else {
skip_value();
}
}
} catch( const JsonError & ) {
if( throw_on_error ) {
throw;
}
return false;
}
return true;
}
// array ~> array
template <typename T, size_t N>
bool read( std::array<T, N> &v, bool throw_on_error = false ) {
if( !test_array() ) {
return error_or_false( throw_on_error, "Expected json array" );
}
try {
start_array();
for( size_t i = 0; i < N; ++i ) {
if( end_array() ) {
if( throw_on_error ) {
error( "Json array is too short" );
}
return false; // json array is too small
}
if( !read( v[i], throw_on_error ) ) {
return false; // invalid entry
}
}
bool result = end_array();
if( !result && throw_on_error ) {
error( "Array had too many elements" );
}
return result;
} catch( const JsonError & ) {
if( throw_on_error ) {
throw;
}
return false;
}
}
// object ~> containers with matching key_type and value_type
// set, unordered_set ~> object
template <typename T, typename std::enable_if<
std::is_same<typename T::key_type, typename T::value_type>::value>::type * = nullptr
>
bool read( T &v, bool throw_on_error = false ) {
if( !test_array() ) {
return error_or_false( throw_on_error, "Expected json array" );
}
try {
start_array();
v.clear();
while( !end_array() ) {
typename T::value_type element;
if( read( element, throw_on_error ) ) {
if( !v.insert( std::move( element ) ).second ) {
return error_or_false(
throw_on_error,
"Duplicate entry in set defined by json array" );
}
} else {
skip_value();
}
}
} catch( const JsonError & ) {
if( throw_on_error ) {
throw;
}
return false;
}
return true;
}
// special case for enum_bitset
template <typename T>
bool read( enum_bitset<T> &v, bool throw_on_error = false ) {
if( !test_array() ) {
return error_or_false( throw_on_error, "Expected json array" );
}
try {
start_array();
v = {};
while( !end_array() ) {
T element;
if( read( element, throw_on_error ) ) {
if( v.test( element ) ) {
return error_or_false(
throw_on_error,
"Duplicate entry in set defined by json array" );
}
v.set( element );
} else {
skip_value();
}
}
} catch( const JsonError & ) {
if( throw_on_error ) {
throw;
}
return false;
}
return true;
}
// special case for colony<item> as it supports RLE
// see corresponding `write` for details
template <typename T, std::enable_if_t<std::is_same<T, item>::value> * = nullptr >
bool read( cata::colony<T> &v, bool throw_on_error = false ) {
if( !test_array() ) {
return error_or_false( throw_on_error, "Expected json array" );
}
try {
start_array();
v.clear();
while( !end_array() ) {
T element;
const int prev_pos = tell();
if( test_array() ) {
start_array();
int run_l;
if( read( element, throw_on_error ) &&
read( run_l, throw_on_error ) &&
end_array()
) { // all is good
// first insert (run_l-1) elements
for( int i = 0; i < run_l - 1; i++ ) {
v.insert( element );
}
// micro-optimization, move last element
v.insert( std::move( element ) );
} else { // array is malformed, skipping it entirely
error_or_false( throw_on_error, "Expected end of array" );
seek( prev_pos );
skip_array();
}
} else {
if( read( element, throw_on_error ) ) {
v.insert( std::move( element ) );
} else {
skip_value();
}
}
}
} catch( const JsonError & ) {
if( throw_on_error ) {
throw;
}
return false;
}
return true;
}
// special case for colony as it uses `insert()` instead of `push_back()`
// and therefore doesn't fit with vector/deque/list
// for colony of items there is another specialization with RLE
template < typename T, std::enable_if_t < !std::is_same<T, item>::value > * = nullptr >
bool read( cata::colony<T> &v, bool throw_on_error = false ) {
if( !test_array() ) {
return error_or_false( throw_on_error, "Expected json array" );
}
try {
start_array();
v.clear();
while( !end_array() ) {
T element;
if( read( element, throw_on_error ) ) {
v.insert( std::move( element ) );
} else {
skip_value();
}
}
} catch( const JsonError & ) {
if( throw_on_error ) {
throw;
}
return false;
}
return true;
}
// object ~> containers with unmatching key_type and value_type
// map, unordered_map ~> object
template < typename T, typename std::enable_if <
!std::is_same<typename T::key_type, typename T::value_type>::value >::type * = nullptr
>
bool read( T &m, bool throw_on_error = true ) {
if( !test_object() ) {
return error_or_false( throw_on_error, "Expected json object" );
}
try {
start_object();
m.clear();
while( !end_object() ) {
using key_type = typename T::key_type;
key_type key = key_from_json_string<key_type>()( get_member_name() );
typename T::mapped_type element;
if( read( element, throw_on_error ) ) {
m[std::move( key )] = std::move( element );
} else {
skip_value();
}
}
} catch( const JsonError & ) {
if( throw_on_error ) {
throw;
}
return false;
}
return true;
}
// error messages
std::string line_number( int offset_modifier = 0 ); // for occasional use only
[[noreturn]] void error( const std::string &message ); // ditto
[[noreturn]] void error( int offset, const std::string &message ); // ditto
// if the next element is a string, throw error after the `offset`th unicode
// character in the parsed string. if `offset` is 0, throw error right after
// the starting quotation mark.
[[noreturn]] void string_error( int offset, const std::string &message );
// If throw_, then call error( message, offset ), otherwise return
// false
bool error_or_false( bool throw_, const std::string &message );
bool error_or_false( bool throw_, int offset, const std::string &message );
void rewind( int max_lines = -1, int max_chars = -1 );
std::string substr( size_t pos, size_t len = std::string::npos );
private:
// This should be used to get any and all numerical data types.
number_sci_notation get_any_number();
// Calls get_any_number() then applies operations common to all integer types.
number_sci_notation get_any_int();
};
/* JsonOut
* =======
*
* The JsonOut class provides a straightforward interface for outputting JSON.
*
* It wraps a std::ostream, providing methods for writing JSON data directly.
*
* Typical usage might be as follows:
*
* JsonOut jsout(myostream);
* jsout.start_object(); // {
* jsout.member("type", "point"); // "type":"point"
* jsout.member("data"); // ,"data":
* jsout.start_array(); // [
* jsout.write(5) // 5
* jsout.write(9) // ,9
* jsout.end_array(); // ]
* jsout.end_object(); // }
*
* which writes {"type":"point","data":[5,9]} to myostream.
*
* Separators are handled automatically,
* and the constructor also has an option for crude pretty-printing,
* which inserts newlines and whitespace liberally, if turned on.
*
* Basic containers such as maps, sets and vectors,
* can be serialized automatically by write() and member().
*/
class JsonOut
{
private:
std::ostream *stream;
bool pretty_print;
std::vector<bool> need_wrap;
int indent_level = 0;
bool need_separator = false;
public:
explicit JsonOut( std::ostream &stream, bool pretty_print = false, int depth = 0 );
JsonOut( const JsonOut & ) = delete;
JsonOut &operator=( const JsonOut & ) = delete;
// punctuation
void write_indent();
void write_separator();
void write_member_separator();
bool get_need_separator() {
return need_separator;
}
void set_need_separator() {
need_separator = true;
}
std::ostream *get_stream() {
return stream;
}
int tell();
void seek( int pos );
void start_pretty();
void end_pretty();
void start_object( bool wrap = false );
void end_object();
void start_array( bool wrap = false );
void end_array();
// write data to the output stream as JSON
void write_null();
template <typename T, typename std::enable_if<std::is_fundamental<T>::value, int>::type = 0>
void write( T val ) {
if( need_separator ) {
write_separator();
}
*stream << val;
need_separator = true;
}
/// Overload that calls a global function `serialize(const T&,JsonOut&)`, if available.
template<typename T>
auto write( const T &v ) -> decltype( serialize( v, *this ), void() ) {
serialize( v, *this );
}
/// Overload that calls a member function `T::serialize(JsonOut&) const`, if available.
template<typename T>
auto write( const T &v ) -> decltype( v.serialize( *this ), void() ) {
v.serialize( *this );
}
template <typename T, typename std::enable_if<std::is_enum<T>::value, int>::type = 0>
void write( T val ) {
write( static_cast<typename std::underlying_type<T>::type>( val ) );
}
// strings need escaping and quoting
void write( const std::string &val );
void write( const char *val ) {
write( std::string( val ) );
}
// char should always be written as an unquoted numeral
void write( char val ) {
write( static_cast<int>( val ) );
}
void write( signed char val ) {
write( static_cast<int>( val ) );
}
void write( unsigned char val ) {
write( static_cast<int>( val ) );
}
template<size_t N>
void write( const std::bitset<N> &b );
template <typename T>
auto write( const string_id<T> &thing ) {
write( thing.str() );
}
template <typename T>
auto write( const int_id<T> &thing ) {
write( thing.id().str() );
}
// enum ~> string
template <typename E, typename std::enable_if<std::is_enum<E>::value>::type * = nullptr>
void write_as_string( const E value ) {
write( io::enum_to_string<E>( value ) );
}
void write_as_string( const std::string &s ) {
write( s );
}
template<typename T>
void write_as_string( const string_id<T> &s ) {
write( s );
}
template<typename T>
void write_as_string( const int_id<T> &s ) {
write( s.id() );
}
template<typename T, typename U>
void write( const std::pair<T, U> &p ) {
start_array();
write( p.first );
write( p.second );
end_array();
}
template <typename T>
void write_as_array( const T &container ) {
start_array();
for( const auto &e : container ) {
write( e );
}
end_array();
}
// containers with front() ~> array
// vector, deque, forward_list, list
template < typename T, typename std::enable_if <
!std::is_same<void, typename T::value_type>::value >::type * = nullptr
>
auto write( const T &container ) -> decltype( container.front(), ( void )0 ) {
write_as_array( container );
}
// containers with matching key_type and value_type ~> array
// set, unordered_set
template <typename T, typename std::enable_if<
std::is_same<typename T::key_type, typename T::value_type>::value>::type * = nullptr
>
void write( const T &container ) {
write_as_array( container );
}
// special case for item colony, adds simple RLE-based compression
template <typename T, std::enable_if_t<std::is_same<T, item>::value> * = nullptr>
void write( const cata::colony<T> &container ) {
start_array();
// simple RLE implementation:
// run_l is the length of the "running sequence" of identical items, ending with the current item.
// when sequence ends, it's written as either the single item object (run_l==1) or as a two-element
// array (run_l > 1), where the first element is the item and second element is the size of the sequence.
int run_l = 1;
for( auto it = container.begin(); it != container.end(); ++it ) {
const auto nxt = std::next( it );
if( nxt == container.end() || !it->same_for_rle( *nxt ) ) {
if( run_l == 1 ) {
write( *it );
} else {
start_array();
write( *it );
write( run_l );
end_array();
}
run_l = 1;
} else {
run_l++;
}
}
end_array();
}
// special case for colony, since it doesn't fit in other categories
// for colony of items there is another specialization with RLE
template < typename T, std::enable_if_t < !std::is_same<T, item>::value > * = nullptr >
void write( const cata::colony<T> &container ) {
write_as_array( container );
}
// containers with unmatching key_type and value_type ~> object
// map, unordered_map ~> object
template < typename T, typename std::enable_if <
!std::is_same<typename T::key_type, typename T::value_type>::value >::type * = nullptr
>
void write( const T &map ) {
start_object();
for( const auto &it : map ) {
write_as_string( it.first );
write_member_separator();
write( it.second );
}
end_object();
}
// convenience methods for writing named object members
// TODO: enforce value after
void member( const std::string &name );
void null_member( const std::string &name );
template <typename T> void member( const std::string &name, const T &value ) {
member( name );
write( value );
}
template <typename T> void member( const std::string &name, const T &value,
const T &value_default ) {
if( value != value_default ) {
member( name, value );
}
}
template <typename T> void member_as_string( const std::string &name, const T &value ) {
member( name );
write_as_string( value );
}
};
/* JsonObject
* ==========
*
* The JsonObject class provides easy access to incoming JSON object data.
*
* JsonObject maps member names to the byte offset of the paired value,
* given an underlying JsonIn stream.
*
* It provides data by seeking the stream to the relevant position,
* and calling the correct JsonIn method to read the value from the stream.
*