forked from FastLED/FastLED
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathjson.h
More file actions
2207 lines (1892 loc) · 74.9 KB
/
json.h
File metadata and controls
2207 lines (1892 loc) · 74.9 KB
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
/**
* @file fl/json.h
* @brief FastLED's Elegant JSON Library: `fl::Json`
*
* @details
*
* The `fl::Json` library provides a lightweight, type-safe, and highly ergonomic
* interface for both parsing and generating JSON data within the FastLED ecosystem.
*
* Key Features & Design Principles:
* ------------------------------------
* - **Fluid Chaining**: Effortlessly navigate nested JSON structures using
* `json["key"]["nested_key"]` or `json["array_key"][index]`.
* - **Default Values (`operator|`)**: The cornerstone of robust parsing. Safely
* extract values with a fallback, preventing crashes from missing keys or
* type mismatches: `int value = json["path"]["to"]["key"] | 123;`
* - **Type Safety**: Methods return `fl::optional<T>` for explicit handling of
* potential absence or type errors, ensuring predictable behavior.
* - **Unified API**: A consistent and intuitive interface for both reading
* and writing JSON data.
* - **Explicit Creation**: Clearly define JSON objects and arrays using
* `fl::Json::object()` and `fl::Json::array()`.
*
* Parsing JSON Data - The Clean Way:
* ------------------------------------
* Parse a JSON string and extract values with graceful defaults.
*
* @code
* #include "fl/json.h"
* #include "fl/warn.h" // For FL_WARN
*
* const char* jsonStr = R"({
* "config": {
* "brightness": 128,
* "enabled": true,
* "name": "my_device"
* },
* "status": "active"
* })";
*
* fl::Json jsonDoc = fl::Json::parse(jsonStr);
*
* // Accessing an integer with a default value
* int brightness = jsonDoc["config"]["brightness"] | 255; // Result: 128
* FL_WARN("Brightness: " << brightness);
*
* // Accessing a boolean with a default value
* bool enabled = jsonDoc["config"]["enabled"] | false; // Result: true
* FL_WARN("Enabled: " << enabled);
*
* // Accessing a string with a default value
* fl::string deviceName = jsonDoc["config"]["name"] | fl::string("unknown"); // Result: "my_device"
* FL_WARN("Device Name: " << deviceName);
*
* // Accessing a non-existent key with a default value
* int nonExistent = jsonDoc["config"]["non_existent_key"] | 0; // Result: 0
* FL_WARN("Non-existent: " << nonExistent);
* @endcode
*
* Generating JSON Data - Build with Ease:
* -----------------------------------------
* Construct complex JSON objects and arrays programmatically.
*
* @code
* #include "fl/json.h"
* #include "fl/string.h"
* #include "fl/vector.h"
* #include "fl/warn.h"
*
* // Create a root JSON object
* fl::Json newJson = fl::Json::object();
*
* // Set primitive values
* newJson.set("version", 1.0);
* newJson.set("isActive", true);
* newJson.set("message", "Hello, FastLED!");
*
* // Create and set a nested object
* fl::Json settings = fl::Json::object();
* settings.set("mode", "dynamic");
* settings.set("speed", 50);
* newJson.set("settings", settings);
*
* // Create and set a nested array
* fl::Json colors = fl::Json::array();
* colors.push_back(fl::Json("red"));
* colors.push_back(fl::Json("green"));
* colors.push_back(fl::Json("blue"));
* newJson.set("colors", colors);
*
* // Convert the entire JSON object to a string
* fl::string jsonString = newJson.to_string();
* FL_WARN("Generated JSON:\n" << jsonString);
* // Expected output (formatting may vary):
* // {"version":1.0,"isActive":true,"message":"Hello, FastLED!","settings":{"mode":"dynamic","speed":50},"colors":["red","green","blue"]}
* @endcode
*
* Important Considerations:
* ---------------------------
* - **Error Handling**: While `operator|` is powerful, for critical parsing
* steps (e.g., validating the root object), always use `has_value()` and
* `is_object()`/`is_array()` checks.
* - **Memory Management**: `fl::Json` leverages `fl::shared_ptr` internally,
* simplifying memory management. You typically won't need manual `new`/`delete`.
* - **`fl::` Namespace**: Adhere to FastLED's convention; always use the `fl::`
* prefix for library components (e.g., `fl::Json`, `fl::string`, `fl::vector`).
* Avoid `std::` equivalents.
*
* HIGH LEVEL: For platforms with a lot of memory, this parsing library (ArduinoJson) will automatically be included.
* Othweise you'll just get Json -> str encoding (and no parsing). You can check if you haee
* the full library by detecting if FASTLED_ENABLE_JSON is defined.
*
* It's important to note that ArduinoJson only is used for parsing. We use a custom serializer for
* output to string. But this is usually easy to do. For help serializing out, look at fl/sstream.h
* for converting a collection of values to a string.
*
* It's entirely possible that our json string output serializer is NOT 100% correct with respect to
* complex string encoding (for example an HTML document). If you see bugs, then file an issue at
* https://github.com/fastled/FastLED/issues
*
* for string parsing, we should be full featured when FASTLED_ENABLE_JSON is defined (automiatic for SKETCH_HAS_LOTS_OF_MEMORY).
* If there is some string that doesn't correctly parse, use b64 encoding. For example, you might get better luck b64 encoding
* 1024 elements of small ints then manually deserializing to a fl::vector<u8>. Infact, it's pretty much assured.
*
* That being said...
*
* This api is designed specifically to be fast for input <--> output of arrays of numbers in {u8, i16, float}.
* If you have a different encodings scheme, for example an array of tuples, then this library will be MUCH MUCH
* slower than Arduino Json. If you stick to the scheme we have optimized for (flat arrays of numbers
* and few dictionaries) then this api will be blazing fast. Otherwise? Expect pain: slowdowns and lots of memory consumption.
*
* Why?
*
* ArduinoJson only has a nice interface if you agree to bring in std::-everything. Ever bring in std::sstream?
* The amount of code that will be pulled for <sstream> will blow your mind. To keep things strict and tiny
* we have to take ArduinoJson and strip all the optional components out then seal the remaining api in cement and
* bolt on a nice fluid interface ontop. That's what fl/json.h is.
*
* And the good news is - it works great!! And if it doesn't? File a bug and we'll have it fixed in the next release.
*/
#include "fl/string.h"
#include "fl/vector.h"
#include "fl/hash_map.h"
#include "fl/variant.h"
#include "fl/optional.h"
#include "fl/unique_ptr.h"
#include "fl/shared_ptr.h"
#include "fl/functional.h"
#include "fl/str.h" // For StringFormatter
#include "fl/promise.h" // For Error type
#include "fl/sketch_macros.h"
#ifndef FASTLED_ENABLE_JSON
#define FASTLED_ENABLE_JSON SKETCH_HAS_LOTS_OF_MEMORY
#endif
namespace fl {
// Forward declarations
struct JsonValue;
// Define Array and Object as pointers to avoid incomplete type issues
// We'll use heap-allocated containers for these to avoid alignment issues
using JsonArray = fl::vector<fl::shared_ptr<JsonValue>>;
using JsonObject = fl::HashMap<fl::string, fl::shared_ptr<JsonValue>>;
// ParseResult struct to replace variant<T, Error>
template<typename T>
struct ParseResult {
T value;
Error error;
ParseResult(const T& val) : value(val), error() {}
ParseResult(const Error& err) : value(), error(err) {}
bool has_error() const { return !error.is_empty(); }
const T& get_value() const { return value; }
const Error& get_error() const { return error; }
// Implicit conversion operator to allow using ParseResult as T directly
operator const T&() const {
if (has_error()) {
// This should ideally trigger some kind of error handling
// For now, we'll just return the value (which might be default-initialized)
}
return value;
}
};
// Function to get a reference to a static null JsonValue
JsonValue& get_null_value();
// Function to get a reference to a static empty JsonObject
JsonObject& get_empty_json_object();
// AI - pay attention to this - implementing visitor pattern
template<typename T>
struct DefaultValueVisitor {
const T& fallback;
const T* result = nullptr;
T storage; // Use instance storage instead of static
DefaultValueVisitor(const T& fb) : fallback(fb) {}
// This is the method that fl::Variant expects
template<typename U>
void accept(const U& value) {
// Dispatch to the correct operator() overload
(*this)(value);
}
// Specific overload for the type T
void operator()(const T& value) {
result = &value;
}
// Special handling for integer conversions
template<typename U>
typename fl::enable_if<fl::is_integral<T>::value && fl::is_integral<U>::value, void>::type
operator()(const U& value) {
// Convert between integer types
storage = static_cast<T>(value);
result = &storage;
}
// Special handling for floating point to integer conversion
template<typename U>
typename fl::enable_if<fl::is_integral<T>::value && fl::is_floating_point<U>::value, void>::type
operator()(const U& value) {
// Convert float to integer
storage = static_cast<T>(value);
result = &storage;
}
// Special handling for integer to floating point conversion
template<typename U>
typename fl::enable_if<fl::is_floating_point<T>::value && fl::is_integral<U>::value, void>::type
operator()(const U& value) {
// Convert integer to float
storage = static_cast<T>(value);
result = &storage;
}
// Special handling for floating point to floating point conversion
template<typename U>
typename fl::enable_if<fl::is_floating_point<T>::value && fl::is_floating_point<U>::value && !fl::is_same<T, U>::value, void>::type
operator()(const U& value) {
// Convert between floating point types (e.g., double to float)
storage = static_cast<T>(value);
result = &storage;
}
// Generic overload for all other types
template<typename U>
typename fl::enable_if<
!(fl::is_integral<T>::value && fl::is_integral<U>::value) &&
!(fl::is_integral<T>::value && fl::is_floating_point<U>::value) &&
!(fl::is_floating_point<T>::value && fl::is_integral<U>::value) &&
!(fl::is_floating_point<T>::value && fl::is_floating_point<U>::value && !fl::is_same<T, U>::value),
void>::type
operator()(const U&) {
// Do nothing for other types
}
// Special handling for nullptr_t
void operator()(const fl::nullptr_t&) {
// Do nothing - will return fallback
}
};
// Visitor for converting values to int
template<typename IntType = int64_t>
struct IntConversionVisitor {
fl::optional<IntType> result;
template<typename U>
void accept(const U& value) {
// Dispatch to the correct operator() overload
(*this)(value);
}
// Special handling to avoid conflict when IntType is int64_t
template<typename T = IntType>
typename fl::enable_if<!fl::is_same<T, int64_t>::value && !fl::is_same<T, double>::value, void>::type
operator()(const IntType& value) {
result = value;
}
// Special handling for int64_t case
template<typename T = IntType>
typename fl::enable_if<fl::is_same<T, int64_t>::value, void>::type
operator()(const int64_t& value) {
result = value;
}
// Special handling for double case (when IntType is double)
template<typename T = IntType>
typename fl::enable_if<fl::is_same<T, double>::value, void>::type
operator()(const double& value) {
result = value;
}
// Special handling to avoid conflict when IntType is int64_t
template<typename T = IntType>
typename fl::enable_if<!fl::is_same<T, int64_t>::value, void>::type
operator()(const int64_t& value) {
result = static_cast<IntType>(value);
}
void operator()(const bool& value) {
result = static_cast<IntType>(value ? 1 : 0);
}
// Special handling for double to int conversion
template<typename T = IntType>
typename fl::enable_if<!fl::is_same<T, double>::value, void>::type
operator()(const double& value) {
// NEW INSTRUCTIONS: AUTO CONVERT FLOAT TO INT
result = static_cast<IntType>(value);
}
void operator()(const fl::string& str) {
// NEW INSTRUCTIONS: AUTO CONVERT STRING TO INT
// Try to parse the string as an integer using FastLED's StringFormatter
// Validate by checking if string contains only digits (and optional +/- sign)
bool isValidInt = true;
fl::size startPos = 0;
// Check for sign
if (str.length() > 0 && (str[0] == '+' || str[0] == '-')) {
startPos = 1;
}
// Check that all remaining characters are digits
for (fl::size i = startPos; i < str.length(); i++) {
if (!StringFormatter::isDigit(str[i])) {
isValidInt = false;
break;
}
}
// If it looks like a valid integer, try to parse it
if (isValidInt && str.length() > 0) {
int parsed = StringFormatter::parseInt(str.c_str(), str.length());
result = static_cast<IntType>(parsed);
}
}
template<typename T>
void operator()(const T&) {
// Do nothing for other types
}
};
// Specialization for int64_t to avoid template conflicts
template<>
struct IntConversionVisitor<int64_t> {
fl::optional<int64_t> result;
template<typename U>
void accept(const U& value) {
// Dispatch to the correct operator() overload
(*this)(value);
}
void operator()(const int64_t& value) {
result = value;
}
void operator()(const bool& value) {
result = value ? 1 : 0;
}
void operator()(const double& value) {
// NEW INSTRUCTIONS: AUTO CONVERT FLOAT TO INT
result = static_cast<int64_t>(value);
}
void operator()(const fl::string& str) {
// NEW INSTRUCTIONS: AUTO CONVERT STRING TO INT
// Try to parse the string as an integer using FastLED's StringFormatter
// Validate by checking if string contains only digits (and optional +/- sign)
bool isValidInt = true;
fl::size startPos = 0;
// Check for sign
if (str.length() > 0 && (str[0] == '+' || str[0] == '-')) {
startPos = 1;
}
// Check that all remaining characters are digits
for (fl::size i = startPos; i < str.length(); i++) {
if (!StringFormatter::isDigit(str[i])) {
isValidInt = false;
break;
}
}
// If it looks like a valid integer, try to parse it
if (isValidInt && str.length() > 0) {
int parsed = StringFormatter::parseInt(str.c_str(), str.length());
result = static_cast<int64_t>(parsed);
}
}
template<typename T>
void operator()(const T&) {
// Do nothing for other types
}
};
// Visitor for converting values to float
template<typename FloatType = double>
struct FloatConversionVisitor {
fl::optional<FloatType> result;
template<typename U>
void accept(const U& value) {
// Dispatch to the correct operator() overload
(*this)(value);
}
void operator()(const FloatType& value) {
result = value;
}
// Special handling to avoid conflict when FloatType is double
template<typename T = FloatType>
typename fl::enable_if<!fl::is_same<T, double>::value, void>::type
operator()(const double& value) {
result = static_cast<FloatType>(value);
}
// Special handling to avoid conflict when FloatType is float
template<typename T = FloatType>
typename fl::enable_if<!fl::is_same<T, float>::value, void>::type
operator()(const float& value) {
result = static_cast<FloatType>(value);
}
void operator()(const int64_t& value) {
// NEW INSTRUCTIONS: AUTO CONVERT INT TO FLOAT
result = static_cast<FloatType>(value);
}
void operator()(const bool& value) {
result = static_cast<FloatType>(value ? 1.0 : 0.0);
}
void operator()(const fl::string& str) {
// NEW INSTRUCTIONS: AUTO CONVERT STRING TO FLOAT
// Try to parse the string as a float using FastLED's StringFormatter
// Validate by checking if string contains valid float characters
bool isValidFloat = true;
bool hasDecimal = false;
fl::size startPos = 0;
// Check for sign
if (str.length() > 0 && (str[0] == '+' || str[0] == '-')) {
startPos = 1;
}
// Check that all remaining characters are valid for a float
for (fl::size i = startPos; i < str.length(); i++) {
char c = str[i];
if (c == '.') {
if (hasDecimal) {
// Multiple decimal points
isValidFloat = false;
break;
}
hasDecimal = true;
} else if (!StringFormatter::isDigit(c) && c != 'e' && c != 'E') {
isValidFloat = false;
break;
}
}
// If it looks like a valid float, try to parse it
if (isValidFloat && str.length() > 0) {
// For simple cases, we can use a more precise approach
// Check if it's a simple decimal number
bool isSimpleDecimal = true;
for (fl::size i = startPos; i < str.length(); i++) {
char c = str[i];
if (c != '.' && !StringFormatter::isDigit(c)) {
isSimpleDecimal = false;
break;
}
}
if (isSimpleDecimal) {
// For simple decimals, we can do a more direct conversion
float parsed = StringFormatter::parseFloat(str.c_str(), str.length());
result = static_cast<FloatType>(parsed);
} else {
// For complex floats (with exponents), use the standard approach
float parsed = StringFormatter::parseFloat(str.c_str(), str.length());
result = static_cast<FloatType>(parsed);
}
}
}
template<typename T>
void operator()(const T&) {
// Do nothing for other types
}
};
// Specialization for double to avoid template conflicts
template<>
struct FloatConversionVisitor<double> {
fl::optional<double> result;
template<typename U>
void accept(const U& value) {
// Dispatch to the correct operator() overload
(*this)(value);
}
void operator()(const double& value) {
result = value;
}
void operator()(const float& value) {
result = static_cast<double>(value);
}
void operator()(const int64_t& value) {
// NEW INSTRUCTIONS: AUTO CONVERT INT TO FLOAT
result = static_cast<double>(value);
}
void operator()(const bool& value) {
result = value ? 1.0 : 0.0;
}
void operator()(const fl::string& str) {
// NEW INSTRUCTIONS: AUTO CONVERT STRING TO FLOAT
// Try to parse the string as a float using FastLED's StringFormatter
// Validate by checking if string contains valid float characters
bool isValidFloat = true;
bool hasDecimal = false;
fl::size startPos = 0;
// Check for sign
if (str.length() > 0 && (str[0] == '+' || str[0] == '-')) {
startPos = 1;
}
// Check that all remaining characters are valid for a float
for (fl::size i = startPos; i < str.length(); i++) {
char c = str[i];
if (c == '.') {
if (hasDecimal) {
// Multiple decimal points
isValidFloat = false;
break;
}
hasDecimal = true;
} else if (!StringFormatter::isDigit(c) && c != 'e' && c != 'E') {
isValidFloat = false;
break;
}
}
// If it looks like a valid float, try to parse it
if (isValidFloat && str.length() > 0) {
// For simple cases, we can use a more precise approach
// Check if it's a simple decimal number
bool isSimpleDecimal = true;
for (fl::size i = startPos; i < str.length(); i++) {
char c = str[i];
if (c != '.' && !StringFormatter::isDigit(c)) {
isSimpleDecimal = false;
break;
}
}
if (isSimpleDecimal) {
// For simple decimals, we can do a more direct conversion
float parsed = StringFormatter::parseFloat(str.c_str(), str.length());
result = static_cast<double>(parsed);
} else {
// For complex floats (with exponents), use the standard approach
float parsed = StringFormatter::parseFloat(str.c_str(), str.length());
result = static_cast<double>(parsed);
}
}
}
template<typename T>
void operator()(const T&) {
// Do nothing for other types
}
};
// Visitor for converting values to string
struct StringConversionVisitor {
fl::optional<fl::string> result;
template<typename U>
void accept(const U& value) {
// Dispatch to the correct operator() overload
(*this)(value);
}
void operator()(const fl::string& value) {
result = value;
}
void operator()(const int64_t& value) {
// Convert integer to string
result = fl::to_string(value);
}
void operator()(const double& value) {
// Convert double to string with higher precision for JSON representation
result = fl::to_string(static_cast<float>(value), 6);
}
void operator()(const float& value) {
// Convert float to string with higher precision for JSON representation
result = fl::to_string(value, 6);
}
void operator()(const bool& value) {
// Convert bool to string
result = value ? "true" : "false";
}
void operator()(const fl::nullptr_t&) {
// Convert null to string
result = "null";
}
template<typename T>
void operator()(const T&) {
// Do nothing for other types (arrays, objects)
}
};
// The JSON node
struct JsonValue {
// Forward declarations for nested iterator classes
class iterator;
class const_iterator;
// Friend declarations
friend class Json;
// The variant holds exactly one of these alternatives
using variant_t = fl::Variant<
fl::nullptr_t, // null
bool, // true/false
int64_t, // integer
float, // floating-point (changed from double to float)
fl::string, // string
JsonArray, // array
JsonObject, // object
fl::vector<int16_t>, // audio data (specialized array of int16_t)
fl::vector<uint8_t>, // byte data (specialized array of uint8_t)
fl::vector<float> // float data (specialized array of float)
>;
typedef JsonValue::iterator iterator;
typedef JsonValue::const_iterator const_iterator;
variant_t data;
// Constructors
JsonValue() noexcept : data(nullptr) {}
JsonValue(fl::nullptr_t) noexcept : data(nullptr) {}
JsonValue(bool b) noexcept : data(b) {}
JsonValue(int64_t i) noexcept : data(i) {}
JsonValue(float f) noexcept : data(f) {} // Changed from double to float
JsonValue(const fl::string& s) : data(s) {
}
JsonValue(const JsonArray& a) : data(a) {
//FASTLED_WARN("Created JsonValue with array");
}
JsonValue(const JsonObject& o) : data(o) {
//FASTLED_WARN("Created JsonValue with object");
}
JsonValue(const fl::vector<int16_t>& audio) : data(audio) {
//FASTLED_WARN("Created JsonValue with audio data");
}
JsonValue(fl::vector<int16_t>&& audio) : data(fl::move(audio)) {
//FASTLED_WARN("Created JsonValue with moved audio data");
}
JsonValue(const fl::vector<uint8_t>& bytes) : data(bytes) {
//FASTLED_WARN("Created JsonValue with byte data");
}
JsonValue(fl::vector<uint8_t>&& bytes) : data(fl::move(bytes)) {
//FASTLED_WARN("Created JsonValue with moved byte data");
}
JsonValue(const fl::vector<float>& floats) : data(floats) {
//FASTLED_WARN("Created JsonValue with float data");
}
JsonValue(fl::vector<float>&& floats) : data(fl::move(floats)) {
//FASTLED_WARN("Created JsonValue with moved float data");
}
// Copy constructor
JsonValue(const JsonValue& other) : data(other.data) {}
JsonValue& operator=(const JsonValue& other) {
data = other.data;
return *this;
}
JsonValue& operator=(JsonValue&& other) {
data = fl::move(other.data);
return *this;
}
template<typename T>
typename fl::enable_if<!fl::is_same<typename fl::remove_cv<typename fl::remove_reference<T>::type>::type, JsonValue>::value, JsonValue&>::type
operator=(T&& value) {
data = fl::forward<T>(value);
return *this;
}
JsonValue& operator=(fl::nullptr_t) {
data = nullptr;
return *this;
}
JsonValue& operator=(bool b) {
data = b;
return *this;
}
JsonValue& operator=(int64_t i) {
data = i;
return *this;
}
JsonValue& operator=(double d) {
data = static_cast<float>(d);
return *this;
}
JsonValue& operator=(float f) {
data = f;
return *this;
}
JsonValue& operator=(fl::string s) {
data = fl::move(s);
return *this;
}
JsonValue& operator=(JsonArray a) {
data = fl::move(a);
return *this;
}
JsonValue& operator=(fl::vector<int16_t> audio) {
data = fl::move(audio);
return *this;
}
JsonValue& operator=(fl::vector<uint8_t> bytes) {
data = fl::move(bytes);
return *this;
}
JsonValue& operator=(fl::vector<float> floats) {
data = fl::move(floats);
return *this;
}
// Special constructor for char values
static fl::shared_ptr<JsonValue> from_char(char c) {
return fl::make_shared<JsonValue>(fl::string(1, c));
}
// Visitor pattern implementation
template<typename Visitor>
auto visit(Visitor&& visitor) -> decltype(visitor(fl::nullptr_t{})) {
return data.visit(fl::forward<Visitor>(visitor));
}
template<typename Visitor>
auto visit(Visitor&& visitor) const -> decltype(visitor(fl::nullptr_t{})) {
return data.visit(fl::forward<Visitor>(visitor));
}
// Type queries - using is<T>() instead of index() for fl::Variant
bool is_null() const noexcept {
//FASTLED_WARN("is_null called, tag=" << data.tag());
return data.is<fl::nullptr_t>();
}
bool is_bool() const noexcept {
//FASTLED_WARN("is_bool called, tag=" << data.tag());
return data.is<bool>();
}
bool is_int() const noexcept {
//FASTLED_WARN("is_int called, tag=" << data.tag());
return data.is<int64_t>() || data.is<bool>();
}
bool is_double() const noexcept {
//FASTLED_WARN("is_double called, tag=" << data.tag());
return data.is<float>();
}
bool is_float() const noexcept {
return data.is<float>();
}
bool is_string() const noexcept {
//FASTLED_WARN("is_string called, tag=" << data.tag());
return data.is<fl::string>();
}
// Visitor for array type checking
struct IsArrayVisitor {
bool result = false;
template<typename T>
void accept(const T& value) {
// Dispatch to the correct operator() overload
(*this)(value);
}
// JsonArray is an array
void operator()(const JsonArray&) {
result = true;
}
// Specialized array types ARE arrays
void operator()(const fl::vector<int16_t>&) {
result = true; // Audio data is still an array
}
void operator()(const fl::vector<uint8_t>&) {
result = true; // Byte data is still an array
}
void operator()(const fl::vector<float>&) {
result = true; // Float data is still an array
}
// Generic handler for all other types
template<typename T>
void operator()(const T&) {
result = false;
}
};
bool is_array() const noexcept {
//FASTLED_WARN("is_array called, tag=" << data.tag());
IsArrayVisitor visitor;
data.visit(visitor);
return visitor.result;
}
// Returns true only for JsonArray (not specialized array types)
bool is_generic_array() const noexcept {
return data.is<JsonArray>();
}
bool is_object() const noexcept {
//FASTLED_WARN("is_object called, tag=" << data.tag());
return data.is<JsonObject>();
}
bool is_audio() const noexcept {
//FASTLED_WARN("is_audio called, tag=" << data.tag());
return data.is<fl::vector<int16_t>>();
}
bool is_bytes() const noexcept {
//FASTLED_WARN("is_bytes called, tag=" << data.tag());
return data.is<fl::vector<uint8_t>>();
}
bool is_floats() const noexcept {
//FASTLED_WARN("is_floats called, tag=" << data.tag());
return data.is<fl::vector<float>>();
}
// Safe extractors (return optional values, not references)
fl::optional<bool> as_bool() {
auto ptr = data.ptr<bool>();
return ptr ? fl::optional<bool>(*ptr) : fl::nullopt;
}
fl::optional<int64_t> as_int() {
// Check if we have a valid value first
if (data.empty()) {
return fl::nullopt;
}
IntConversionVisitor<int64_t> visitor;
data.visit(visitor);
return visitor.result;
}
template<typename IntType>
fl::optional<IntType> as_int() {
// Check if we have a valid value first
if (data.empty()) {
return fl::nullopt;
}
IntConversionVisitor<IntType> visitor;
data.visit(visitor);
return visitor.result;
}
fl::optional<double> as_double() const {
// Check if we have a valid value first
if (data.empty()) {
return fl::nullopt;
}
FloatConversionVisitor<double> visitor;
data.visit(visitor);
return visitor.result;
}
fl::optional<float> as_float() {
return as_float<float>();
}
template<typename FloatType>
fl::optional<FloatType> as_float() {
// Check if we have a valid value first
if (data.empty()) {
return fl::nullopt;
}
FloatConversionVisitor<FloatType> visitor;
data.visit(visitor);
return visitor.result;
}
fl::optional<fl::string> as_string() {
// Check if we have a valid value first
if (data.empty()) {
return fl::nullopt;
}
StringConversionVisitor visitor;
data.visit(visitor);
return visitor.result;
}
fl::optional<JsonArray> as_array() {
auto ptr = data.ptr<JsonArray>();
if (ptr) return fl::optional<JsonArray>(*ptr);
// Handle specialized array types by converting them to regular JsonArray
if (data.is<fl::vector<int16_t>>()) {
auto audioPtr = data.ptr<fl::vector<int16_t>>();
JsonArray result;
for (const auto& item : *audioPtr) {
result.push_back(fl::make_shared<JsonValue>(static_cast<int64_t>(item)));
}
return fl::optional<JsonArray>(result);
}
if (data.is<fl::vector<uint8_t>>()) {
auto bytePtr = data.ptr<fl::vector<uint8_t>>();
JsonArray result;
for (const auto& item : *bytePtr) {
result.push_back(fl::make_shared<JsonValue>(static_cast<int64_t>(item)));
}
return fl::optional<JsonArray>(result);
}
if (data.is<fl::vector<float>>()) {
auto floatPtr = data.ptr<fl::vector<float>>();
JsonArray result;
for (const auto& item : *floatPtr) {
result.push_back(fl::make_shared<JsonValue>(item)); // Use float directly
}
return fl::optional<JsonArray>(result);
}
return fl::nullopt;
}
fl::optional<JsonObject> as_object() {
auto ptr = data.ptr<JsonObject>();