-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathvoxgig_struct.hpp
More file actions
3379 lines (3112 loc) · 107 KB
/
Copy pathvoxgig_struct.hpp
File metadata and controls
3379 lines (3112 loc) · 107 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
// Copyright (c) 2025-2026 Voxgig Ltd. MIT LICENSE.
//
// Voxgig Struct — main API.
//
// Header-only port of the canonical TypeScript implementation. Everything
// public lives in namespace voxgig::structlib. Mirrors the Java port at
// java/src/Struct.java which itself mirrors ts/src/StructUtility.ts.
#ifndef VOXGIG_STRUCT_HPP
#define VOXGIG_STRUCT_HPP
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <iomanip>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "value.hpp"
namespace voxgig {
namespace structlib {
// ===========================================================================
// String / regex constants
// ===========================================================================
inline const std::string& S_MT() {
static const std::string s = "";
return s;
}
inline const std::string& S_DT() {
static const std::string s = ".";
return s;
}
inline const std::string& S_DTOP() {
static const std::string s = "$TOP";
return s;
}
inline const std::string& S_DSPEC() {
static const std::string s = "$SPEC";
return s;
}
inline const std::string& S_DKEY() {
static const std::string s = "$KEY";
return s;
}
inline const std::string& S_DERRS() {
static const std::string s = "$ERRS";
return s;
}
inline const std::string& S_BKEY() {
static const std::string s = "`$KEY`";
return s;
}
inline const std::string& S_BANNO() {
static const std::string s = "`$ANNO`";
return s;
}
inline const std::string& S_BVAL() {
static const std::string s = "`$VAL`";
return s;
}
inline const std::string& S_BEXACT() {
static const std::string s = "`$EXACT`";
return s;
}
inline const std::string& S_BOPEN() {
static const std::string s = "`$OPEN`";
return s;
}
inline const std::regex& R_INTEGER_KEY() {
static const std::regex r("^[-0-9]+$");
return r;
}
inline const std::regex& R_META_PATH() {
static const std::regex r("^([^$]+)\\$([=~])(.+)$");
return r;
}
inline const std::regex& R_INJECTION_FULL() {
static const std::regex r("^`(\\$[A-Z]+|[^`]*)[0-9]*`$");
return r;
}
inline const std::regex& R_INJECTION_PARTIAL() {
static const std::regex r("`([^`]+)`");
return r;
}
inline const std::regex& R_DOUBLE_DOLLAR() {
static const std::regex r("\\$\\$");
return r;
}
inline const std::regex& R_TRANSFORM_NAME() {
static const std::regex r("`\\$([A-Z]+)`");
return r;
}
inline const std::regex& R_BT_ESCAPE() {
static const std::regex r("\\$BT");
return r;
}
inline const std::regex& R_DS_ESCAPE() {
static const std::regex r("\\$DS");
return r;
}
inline const std::regex& R_ESCAPE_REGEXP() {
static const std::regex r(R"([.*+?^${}()|\[\]\\])");
return r;
}
// ===========================================================================
// Predicates (most also exposed via Value methods)
// ===========================================================================
inline bool isnode(const Value& v) {
return v.is_node() || v.is_sentinel();
}
inline bool ismap(const Value& v) {
return v.is_map() || v.is_sentinel();
}
inline bool islist(const Value& v) {
return v.is_list();
}
inline bool iskey(const Value& v) {
if (v.is_string())
return !v.as_string().empty();
if (v.is_int())
return true;
if (v.is_double())
return true;
return false;
}
inline bool isempty(const Value& v) {
if (v.is_undef() || v.is_null())
return true;
if (v.is_string())
return v.as_string().empty();
if (v.is_list())
return v.as_list()->empty();
if (v.is_map())
return v.as_map()->empty();
return false;
}
inline bool isfunc(const Value& v) {
return v.is_func();
}
inline Value getdef(const Value& v, const Value& alt) {
if (v.is_undef())
return alt;
return v;
}
inline int64_t size(const Value& v) {
return size_of(v);
}
// ===========================================================================
// Type helpers re-exported (defined in value.hpp)
// ===========================================================================
// typify(const Value&) -> int
// typename_str(int) -> std::string
// typename_str(const Value&) -> std::string
// ===========================================================================
// Forward declarations
// ===========================================================================
class Injection;
inline std::string strkey(const Value& key);
inline Value getprop(const Value& val, const Value& key, const Value& alt = Value::undef());
inline Value getelem(const Value& val, const Value& key, const Value& alt = Value::undef());
inline Value lookup_v(const Value& val, const Value& key);
inline Value setprop(Value parent, const Value& key, const Value& val);
inline Value delprop(Value parent, const Value& key);
inline std::vector<std::string> keysof(const Value& v);
inline bool haskey(const Value& v, const Value& key);
inline std::vector<Value> items(const Value& v);
inline std::string stringify(const Value& v, int maxlen = -1);
inline std::string pathify(const Value& v, int startin = 0, int endin = 0);
inline Value slice(const Value& v, const Value& start = Value::undef(),
const Value& end = Value::undef());
inline Value walk_v(
const Value& val,
std::function<Value(const Value&, const Value&, const Value&, const std::vector<std::string>&)>
before,
std::function<Value(const Value&, const Value&, const Value&, const std::vector<std::string>&)>
after,
int maxdepth = MAXDEPTH);
inline Value merge_v(const Value& list, int maxdepth = MAXDEPTH);
inline Value getpath_v(const Value& store, const Value& path, Injection* inj = nullptr);
inline Value setpath_v(const Value& store, const Value& path, const Value& val);
inline Value inject(const Value& val, const Value& store, Injection* injdef = nullptr);
inline Value transform(const Value& data, const Value& spec, const Value& options = Value::undef());
inline Value validate(const Value& data, const Value& spec, const Value& options = Value::undef());
inline std::vector<Value> select(const Value& children, const Value& query);
// ===========================================================================
// strkey / getprop / setprop / delprop / getelem
// ===========================================================================
inline std::string strkey(const Value& key) {
if (key.is_undef())
return S_MT();
if (key.is_string())
return key.as_string();
if (key.is_bool())
return S_MT();
if (key.is_int())
return std::to_string(key.as_int());
if (key.is_double()) {
double d = key.as_double();
if (std::floor(d) == d)
return std::to_string(static_cast<int64_t>(d));
return std::to_string(static_cast<int64_t>(std::floor(d)));
}
return S_MT();
}
inline Value getprop(const Value& val, const Value& key, const Value& alt) {
if (val.is_undef() || key.is_undef())
return alt;
if (val.is_map()) {
auto m = val.as_map();
if (!m)
return alt;
std::string sk = strkey(key);
Value* found = m->find(sk);
if (!found)
return alt;
// Group A: a stored JSON null counts as "no value" (canonical `null == out`
// is true for both undefined and null), so the alt is substituted.
if (found->is_undef() || found->is_null())
return alt;
return *found;
}
if (val.is_list()) {
auto l = val.as_list();
if (!l)
return alt;
int idx;
if (key.is_int()) {
idx = static_cast<int>(key.as_int());
} else if (key.is_string()) {
// Match TS: only accept strings that match /^[-0-9]+$/ entirely.
if (!std::regex_match(key.as_string(), R_INTEGER_KEY()))
return alt;
try {
idx = std::stoi(key.as_string());
} catch (...) {
return alt;
}
} else if (key.is_double()) {
idx = static_cast<int>(key.as_double());
} else {
return alt;
}
if (idx < 0 || idx >= static_cast<int>(l->size()))
return alt;
Value v = (*l)[idx];
// Group A: a stored JSON null counts as "no value" — substitute the alt.
if (v.is_undef() || v.is_null())
return alt;
return v;
}
return alt;
}
// Match TS regex /^[-0-9]+$/ check.
inline bool is_integer_key_string(const Value& key) {
if (key.is_int() || key.is_double())
return true;
if (key.is_string()) {
return std::regex_match(key.as_string(), R_INTEGER_KEY());
}
return false;
}
inline Value getelem(const Value& val, const Value& key, const Value& alt) {
Value out = Value::undef();
if (val.is_undef() || key.is_undef()) {
if (alt.is_func() && alt.is_injector())
return alt;
return alt;
}
if (val.is_list()) {
auto l = val.as_list();
int nkey;
if (key.is_int()) {
nkey = static_cast<int>(key.as_int());
} else if (key.is_string()) {
if (!is_integer_key_string(key))
return alt;
try {
nkey = std::stoi(key.as_string());
} catch (...) {
return alt;
}
} else if (key.is_double()) {
nkey = static_cast<int>(key.as_double());
} else {
return alt;
}
if (nkey < 0)
nkey = static_cast<int>(l->size()) + nkey;
if (nkey < 0 || nkey >= static_cast<int>(l->size()))
return alt;
out = (*l)[nkey];
}
// Group A: a stored JSON null at the slot counts as "no value" (canonical
// `null == out` is true for both undefined and null) — substitute the alt.
if (out.is_undef() || out.is_null())
return alt;
return out;
}
// Internal Group B lookup: read the raw stored value at a slot, preserving a
// stored JSON null. Mirrors canonical `_lookup` (StructUtility.ts). The public
// getprop / getelem / haskey treat a stored null as absent (Group A); the
// validate / transform / inject internals that need the literal value (e.g. to
// validate against $NULL or echo a null back through an injector) use this.
inline Value lookup_v(const Value& val, const Value& key) {
if (val.is_undef() || key.is_undef())
return Value::undef();
if (val.is_list()) {
auto l = val.as_list();
if (!l)
return Value::undef();
int idx;
if (key.is_int()) {
idx = static_cast<int>(key.as_int());
} else if (key.is_double()) {
idx = static_cast<int>(key.as_double());
} else if (key.is_string()) {
if (!std::regex_match(key.as_string(), R_INTEGER_KEY()))
return Value::undef();
try {
idx = std::stoi(key.as_string());
} catch (...) {
return Value::undef();
}
} else {
return Value::undef();
}
if (idx < 0)
idx = static_cast<int>(l->size()) + idx;
if (idx < 0 || idx >= static_cast<int>(l->size()))
return Value::undef();
Value v = (*l)[idx];
return v.is_undef() ? Value::undef() : v;
}
if (val.is_map()) {
auto m = val.as_map();
if (!m)
return Value::undef();
std::string sk = strkey(key);
if (sk.empty())
return Value::undef();
Value* found = m->find(sk);
if (!found)
return Value::undef();
return *found;
}
return Value::undef();
}
inline Value setprop(Value parent, const Value& key, const Value& val) {
if (!iskey(key))
return parent;
if (parent.is_map()) {
auto m = parent.as_map();
std::string sk = strkey(key);
m->set(sk, val);
return parent;
}
if (parent.is_list()) {
auto l = parent.as_list();
int idx;
if (key.is_int())
idx = static_cast<int>(key.as_int());
else if (key.is_string()) {
try {
idx = std::stoi(key.as_string());
} catch (...) {
return parent;
}
} else if (key.is_double())
idx = static_cast<int>(key.as_double());
else
return parent;
if (idx >= 0) {
if (idx >= static_cast<int>(l->size())) {
l->push_back(val);
} else {
(*l)[idx] = val;
}
} else {
l->insert(l->begin(), val);
}
return parent;
}
return parent;
}
inline Value delprop(Value parent, const Value& key) {
if (!iskey(key))
return parent;
if (parent.is_map()) {
parent.as_map()->erase(strkey(key));
return parent;
}
if (parent.is_list()) {
auto l = parent.as_list();
int idx;
if (key.is_int())
idx = static_cast<int>(key.as_int());
else if (key.is_string()) {
try {
idx = std::stoi(key.as_string());
} catch (...) {
return parent;
}
} else if (key.is_double())
idx = static_cast<int>(key.as_double());
else
return parent;
if (idx >= 0 && idx < static_cast<int>(l->size())) {
l->erase(l->begin() + idx);
}
return parent;
}
return parent;
}
// ===========================================================================
// keysof / haskey / items
// ===========================================================================
inline std::vector<std::string> keysof(const Value& v) {
std::vector<std::string> out;
if (!v.is_node())
return out;
if (v.is_map()) {
for (const auto& [k, _] : *v.as_map())
out.push_back(k);
// Matches TS canonical Object.keys(val).sort() — keysof returns
// alphabetically sorted keys regardless of insertion order.
std::sort(out.begin(), out.end());
} else {
auto l = v.as_list();
out.reserve(l->size());
for (size_t i = 0; i < l->size(); i++)
out.push_back(std::to_string(i));
}
return out;
}
inline bool haskey(const Value& v, const Value& key) {
// Canonical: `null != getprop(val, key)`. A present-but-null key is false
// (getprop already substitutes its undef default for a stored null).
Value r = getprop(v, key);
return !r.is_undef() && !r.is_null();
}
// items returns list of [key, value] pairs as Value-list-of-Value-lists.
inline Value items_v(const Value& v) {
auto out = std::make_shared<List>();
if (!v.is_node())
return Value(out);
for (const auto& key : keysof(v)) {
auto pair = std::make_shared<List>();
pair->push_back(Value(key));
pair->push_back(getprop(v, Value(key)));
out->push_back(Value(std::move(pair)));
}
return Value(out);
}
inline std::vector<Value> items(const Value& v) {
std::vector<Value> out;
if (!v.is_node())
return out;
for (const auto& key : keysof(v)) {
auto pair = std::make_shared<List>();
pair->push_back(Value(key));
pair->push_back(getprop(v, Value(key)));
out.push_back(Value(std::move(pair)));
}
return out;
}
// ===========================================================================
// flatten / filter
// ===========================================================================
inline Value flatten(const Value& list, int depth = 1) {
if (!list.is_list())
return list;
auto out = std::make_shared<List>();
std::function<void(const std::shared_ptr<List>&, int)> rec = [&](const std::shared_ptr<List>& src,
int d) {
for (const auto& e : *src) {
if (d > 0 && e.is_list())
rec(e.as_list(), d - 1);
else
out->push_back(e);
}
};
rec(list.as_list(), depth);
return Value(std::move(out));
}
using ItemCheck = std::function<bool(const Value& pair)>;
inline Value filter(const Value& v, const ItemCheck& check) {
auto out = std::make_shared<List>();
for (const auto& pair : items(v)) {
if (check(pair)) {
out->push_back(getprop(pair, Value(static_cast<int64_t>(1))));
}
}
return Value(std::move(out));
}
// ===========================================================================
// slice / pad
// ===========================================================================
//
// slice mirrors TS lines 314–383. Negative indices count from end. For
// numbers, performs min/max bounding (start inclusive, end exclusive).
inline Value slice(const Value& val, const Value& start_v, const Value& end_v) {
// Number case: bound between start and end-1.
if (val.is_number()) {
double n = val.as_double();
int64_t lo = std::numeric_limits<int64_t>::min();
int64_t hi = std::numeric_limits<int64_t>::max();
if (start_v.is_number())
lo = start_v.as_int();
if (end_v.is_number())
hi = end_v.as_int() - 1;
if (n < lo)
n = lo;
if (n > hi)
n = hi;
if (val.is_int())
return Value(static_cast<int64_t>(n));
return Value(n);
}
int vlen = static_cast<int>(size(val));
bool has_start = !start_v.is_undef();
bool has_end = !end_v.is_undef();
int start = has_start ? static_cast<int>(start_v.as_int()) : 0;
int end = has_end ? static_cast<int>(end_v.as_int()) : vlen;
if (has_end && !has_start) {
start = 0;
has_start = true; // proceed into slice block even if only end was given
}
if (has_start) {
if (start < 0) {
end = vlen + start;
if (end < 0)
end = 0;
start = 0;
} else if (has_end) {
if (end < 0) {
end = vlen + end;
if (end < 0)
end = 0;
} else if (vlen < end) {
end = vlen;
}
} else {
end = vlen;
}
if (vlen < start)
start = vlen;
if (start >= 0 && start <= end && end <= vlen) {
if (val.is_list()) {
auto src = val.as_list();
auto out = std::make_shared<List>(src->begin() + start, src->begin() + end);
return Value(std::move(out));
}
if (val.is_string()) {
return Value(val.as_string().substr(start, end - start));
}
} else {
if (val.is_list())
return Value(std::make_shared<List>());
if (val.is_string())
return Value(std::string(""));
}
}
return val;
}
inline std::string pad(const Value& v, int padding = 44, const std::string& padchar = " ") {
std::string s = v.is_string() ? v.as_string() : stringify(v);
std::string pc = padchar.empty() ? std::string(" ") : padchar.substr(0, 1);
if (padding >= 0) {
if (static_cast<int>(s.size()) < padding) {
s.append(padding - s.size(), pc[0]);
}
return s;
}
int need = -padding - static_cast<int>(s.size());
if (need > 0) {
return std::string(need, pc[0]) + s;
}
return s;
}
// Convenience overload: pad with default args using Value parameters.
inline std::string pad(const Value& v, const Value& padding_v,
const Value& padchar_v = Value::undef()) {
int p = padding_v.is_number() ? static_cast<int>(padding_v.as_int()) : 44;
std::string pc = padchar_v.is_string() ? padchar_v.as_string() : " ";
return pad(v, p, pc);
}
// ===========================================================================
// escre / escurl / replace / join
// ===========================================================================
inline std::string escre(const Value& v) {
std::string s = v.is_string() ? v.as_string() : (v.is_undef() ? "" : stringify(v));
return std::regex_replace(s, R_ESCAPE_REGEXP(), "\\$&");
}
// ----------------------------------------------------------------------------
// Regex utility — uniform re_* API (see /REGEX_API.md). C++'s <regex>
// (ECMAScript dialect by default) is a strict superset of RE2.
// ----------------------------------------------------------------------------
inline std::regex re_compile(const std::string& pattern) {
return std::regex(pattern);
}
inline bool re_test(const std::string& pattern, const std::string& input) {
return std::regex_search(input, std::regex(pattern));
}
inline std::vector<std::string> re_find(const std::string& pattern, const std::string& input) {
std::smatch m;
if (!std::regex_search(input, m, std::regex(pattern)))
return {};
std::vector<std::string> out;
for (size_t i = 0; i < m.size(); i++)
out.push_back(m[i].str());
return out;
}
inline std::vector<std::vector<std::string>> re_find_all(const std::string& pattern,
const std::string& input) {
std::vector<std::vector<std::string>> out;
std::regex rx(pattern);
auto begin = std::sregex_iterator(input.begin(), input.end(), rx);
auto end = std::sregex_iterator();
for (auto it = begin; it != end; ++it) {
std::vector<std::string> row;
for (size_t i = 0; i < it->size(); i++)
row.push_back((*it)[i].str());
out.push_back(std::move(row));
}
return out;
}
inline std::string re_replace(const std::string& pattern, const std::string& input,
const std::string& replacement) {
return std::regex_replace(input, std::regex(pattern), replacement);
}
inline std::string re_escape(const std::string& s) {
return std::regex_replace(s, R_ESCAPE_REGEXP(), "\\$&");
}
inline std::string escurl(const Value& v) {
if (v.is_undef())
return "";
std::string s = v.is_string() ? v.as_string() : stringify(v);
std::ostringstream out;
out.fill('0');
out << std::hex;
for (unsigned char c : s) {
if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
out << c;
} else {
out << '%' << std::uppercase << std::setw(2) << static_cast<int>(c);
out << std::nouppercase;
}
}
return out.str();
}
// JS-style scalar -> string: integer-valued doubles render without ".0".
inline std::string js_string(const Value& v) {
if (v.is_undef() || v.is_null())
return "null";
if (v.is_bool())
return v.as_bool() ? "true" : "false";
if (v.is_int())
return std::to_string(v.as_int());
if (v.is_double()) {
double d = v.as_double();
if (std::isfinite(d) && std::floor(d) == d) {
return std::to_string(static_cast<int64_t>(d));
}
std::ostringstream oss;
oss << d;
return oss.str();
}
if (v.is_string())
return v.as_string();
return stringify(v);
}
inline std::string join(const Value& arr, const std::string& sep = ",", bool url = false) {
if (!arr.is_list())
return "";
// Filter to non-empty strings.
std::vector<std::string> parts;
auto src = arr.as_list();
for (size_t i = 0; i < src->size(); i++) {
const Value& v = (*src)[i];
if (!v.is_string() || v.as_string().empty())
continue;
parts.push_back(v.as_string());
}
size_t sarr = parts.size();
std::string sepre = sep.size() == 1 ? std::regex_replace(sep, R_ESCAPE_REGEXP(), "\\$&") : "";
std::vector<std::string> cleaned;
for (size_t i = 0; i < parts.size(); i++) {
std::string s = parts[i];
if (!sepre.empty()) {
if (url && i == 0) {
s = std::regex_replace(s, std::regex(sepre + "+$"), "");
} else {
if (i > 0)
s = std::regex_replace(s, std::regex("^" + sepre + "+"), "");
if (i < sarr - 1 || !url) {
s = std::regex_replace(s, std::regex(sepre + "+$"), "");
}
s = std::regex_replace(s, std::regex("([^" + sepre + "])" + sepre + "+([^" + sepre + "])"),
std::string("$1") + sep + "$2");
}
}
if (!s.empty())
cleaned.push_back(s);
}
std::string out;
for (size_t i = 0; i < cleaned.size(); i++) {
if (i > 0)
out += sep;
out += cleaned[i];
}
return out;
}
inline std::string join(const Value& arr, const Value& sep_v, const Value& url_v = Value::undef()) {
std::string sep = sep_v.is_string() ? sep_v.as_string() : ",";
bool url = url_v.is_bool() ? url_v.as_bool() : false;
return join(arr, sep, url);
}
// ===========================================================================
// jsonify / stringify / pathify
// ===========================================================================
// Pure-C++ JSON emitter — mirrors c/src/utility.c::jsonify_inner. Map keys
// are emitted in INSERTION order (matching TS canonical's JSON.stringify
// behaviour), not alphabetically. Used by jsonify / stringify / partial
// inject so the library proper does not depend on nlohmann::json for
// output (nlohmann is still used by the test harness for corpus loading).
inline void _json_escape(const std::string& s, std::string& out) {
for (char c : s) {
switch (c) {
case '"':
out += "\\\"";
break;
case '\\':
out += "\\\\";
break;
case '\b':
out += "\\b";
break;
case '\f':
out += "\\f";
break;
case '\n':
out += "\\n";
break;
case '\r':
out += "\\r";
break;
case '\t':
out += "\\t";
break;
default:
if (static_cast<unsigned char>(c) < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast<unsigned char>(c));
out += buf;
} else {
out += c;
}
}
}
}
inline void _jsonify_inner(const Value& v, std::string& out, int indent, int depth,
bool sort_keys = false) {
if (v.is_undef() || v.is_null()) {
out += "null";
return;
}
if (v.is_bool()) {
out += v.as_bool() ? "true" : "false";
return;
}
if (v.is_int()) {
char buf[32];
std::snprintf(buf, sizeof(buf), "%lld", static_cast<long long>(v.as_int()));
out += buf;
return;
}
if (v.is_double()) {
double d = v.as_double();
if (!std::isfinite(d)) {
out += "null";
return;
}
char buf[48];
if (std::floor(d) == d && std::abs(d) < 1e15) {
std::snprintf(buf, sizeof(buf), "%lld", static_cast<long long>(d));
} else {
// Use %g (shortest round-trip-ish form) — matches C's doublestr and
// closely tracks JS JSON.stringify for typical fractional values.
std::snprintf(buf, sizeof(buf), "%g", d);
}
out += buf;
return;
}
if (v.is_string()) {
out += '"';
_json_escape(v.as_string(), out);
out += '"';
return;
}
if (v.is_list()) {
const auto& l = *v.as_list();
if (l.empty()) {
out += "[]";
return;
}
out += '[';
bool first = true;
for (const auto& e : l) {
if (!first)
out += ',';
first = false;
if (indent > 0) {
out += '\n';
out.append(static_cast<size_t>((depth + 1) * indent), ' ');
}
_jsonify_inner(e, out, indent, depth + 1, sort_keys);
}
if (indent > 0) {
out += '\n';
out.append(static_cast<size_t>(depth * indent), ' ');
}
out += ']';
return;
}
if (v.is_map()) {
const auto& m = *v.as_map();
if (m.empty()) {
out += "{}";
return;
}
out += '{';
// Optionally walk in sorted key order (stringify behaviour, matching
// TS canonical's stringify replacer). jsonify keeps insertion order.
std::vector<std::string> order;
order.reserve(m.size());
for (const auto& [k, _e] : m)
order.push_back(k);
if (sort_keys)
std::sort(order.begin(), order.end());
bool first = true;
for (const auto& k : order) {
const Value* ep = m.find(k);
if (!ep)
continue;
const auto& e = *ep;
if (!first)
out += ',';
first = false;
if (indent > 0) {
out += '\n';
out.append(static_cast<size_t>((depth + 1) * indent), ' ');
}
out += '"';
_json_escape(k, out);
out += indent > 0 ? "\": " : "\":";
_jsonify_inner(e, out, indent, depth + 1, sort_keys);
}
if (indent > 0) {
out += '\n';
out.append(static_cast<size_t>(depth * indent), ' ');
}
out += '}';
return;
}
// function / sentinel / unknown -> null
out += "null";
}
inline std::string jsonify(const Value& v, int indent = 2) {
if (v.is_undef() || v.is_null())
return "null";
std::string out;
_jsonify_inner(v, out, indent, 0);
return out;
}
inline std::string jsonify(const Value& v, const Value& flags) {
int indent = 2;
int offset = 0;
if (flags.is_map()) {
Value iv = getprop(flags, Value("indent"));
Value ov = getprop(flags, Value("offset"));
if (iv.is_int())
indent = static_cast<int>(iv.as_int());
if (ov.is_int())
offset = static_cast<int>(ov.as_int());
}
std::string out = jsonify(v, indent);
if (offset > 0 && out.find('\n') != std::string::npos) {
std::string pad_str(offset, ' ');
std::string padded;
bool first = true;
size_t pos = 0;
while (pos < out.size()) {
size_t nl = out.find('\n', pos);
std::string line = (nl == std::string::npos) ? out.substr(pos) : out.substr(pos, nl - pos);
if (first) {
padded += line;
first = false;
} else
padded += "\n" + pad_str + line;
if (nl == std::string::npos)
break;
pos = nl + 1;
}
out = padded;
}
return out;
}
// stringify renders a Value in a JSON-ish form, but with no quotes around
// strings (mirrors TS stringify which strips quotes for human friendliness).
inline std::string stringify(const Value& v, int maxlen) {
std::string valstr;
if (v.is_undef())
return "";
if (v.is_string()) {
valstr = v.as_string();
} else {
// Use the in-tree printer (no third-party dep) with compact output
// AND sorted keys (matches TS canonical's stringify replacer); then
// strip double-quotes (TS regex /"/g).
std::string raw;
_jsonify_inner(v, raw, 0, 0, true);
valstr.reserve(raw.size());
for (char c : raw)
if (c != '"')
valstr.push_back(c);
}
if (maxlen > 0 && static_cast<int>(valstr.size()) > maxlen) {
if (maxlen >= 3) {
return valstr.substr(0, maxlen - 3) + "...";
}
return valstr.substr(0, maxlen);