-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcJSON.ts
More file actions
3139 lines (3005 loc) · 193 KB
/
Copy pathcJSON.ts
File metadata and controls
3139 lines (3005 loc) · 193 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
/**
* This project is a direct translation of cJSON, from C to TypeScript.
*
* Original cJSON:
* Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
* Licensed under the MIT License.
*
* TypeScript translation:
* Copyright (c) 2026 Scott Moore
* Licensed under the MIT License.
*/
function _dclass(x: number): number { if (Number.isNaN(x)) return 2; if (!Number.isFinite(x)) return 1; if (x === 0) return 0; const a = Math.abs(x); if (a < 2.2250738585072014e-308) return -2; return -1; /* MinGW codes: NaN=2, INF=1, ZERO=0, NORMAL=-1, SUBNORMAL=-2; isfinite=(<=0), isnormal=(==-1) */ }
function _fdclass(x: number): number { return _dclass(x); }
function _ldclass(x: number): number { return _dclass(x); }
function __safe_div(a: number, b: number): number { if (b === 0) throw new Error('Division by zero'); return Math.trunc(a / b); }
function __safe_mod(a: number, b: number): number { if (b === 0) throw new Error('Division by zero'); return a % b; }
function sscanf(str: any, fmt: string, ...args: any[]): number {
if (str?.buf) str = cptr_to_string(str);
if (typeof str !== 'string') str = String(str ?? '');
let pos = 0, fi = 0, argIdx = 0, matched = 0;
while (fi < fmt.length && pos <= str.length) {
if (fmt[fi] === " " || fmt[fi] === "\t" || fmt[fi] === "\n") { fi++; while (pos < str.length && " \t\n\r".includes(str[pos])) pos++; continue; }
if (fmt[fi] !== "%") { if (pos < str.length && str[pos] === fmt[fi]) { pos++; fi++; continue; } else break; }
fi++;
if (fmt[fi] === "%") { if (str[pos] === "%") { pos++; fi++; continue; } else break; }
let suppress = false; if (fmt[fi] === "*") { suppress = true; fi++; }
let ws = ""; while (fi < fmt.length && fmt[fi] >= "0" && fmt[fi] <= "9") ws += fmt[fi++];
const mw = ws ? parseInt(ws) : 0;
let lenMod = ""; if (fi < fmt.length && "hlLzjt".includes(fmt[fi])) { lenMod = fmt[fi]; fi++; if (fi < fmt.length && (fmt[fi]==="h"||fmt[fi]==="l")) { lenMod += fmt[fi]; fi++; } }
const is64 = (lenMod === "ll" || lenMod === "z" || lenMod === "j" || lenMod === "L");
const sp = fmt[fi++]; let val: any, ok = false;
if (sp !== "c" && sp !== "n") { while (pos < str.length && " \t\n\r".includes(str[pos])) pos++; }
if (pos >= str.length && sp !== "n") break;
const sub = mw ? str.substring(pos, pos + mw) : str.substring(pos);
if (sp === "d" || sp === "i") { const m = sub.match(/^[+-]?\d+/); if (m) { val = is64 ? BigInt(m[0]) : parseInt(m[0], 10); pos += m[0].length; ok = true; } }
else if (sp === "u") { const m = sub.match(/^\d+/); if (m) { val = is64 ? BigInt.asUintN(64, BigInt(m[0])) : (parseInt(m[0], 10) >>> 0); pos += m[0].length; ok = true; } }
else if (sp === "x" || sp === "X") { const m = sub.match(/^[+-]?(?:0[xX])?[0-9a-fA-F]+/); if (m) { const clean = m[0].replace(/^[+-]?0[xX]/, (pre) => pre.replace(/0[xX]/, "")); val = is64 ? BigInt("0x" + clean.replace(/^[+-]/, "")) * (clean.startsWith("-") ? -1n : 1n) : parseInt(m[0], 16); pos += m[0].length; ok = true; } }
else if (sp === "o") { const m = sub.match(/^[+-]?[0-7]+/); if (m) { val = is64 ? BigInt.asUintN(64, BigInt("0o" + m[0].replace(/^[+-]/, ""))) : parseInt(m[0], 8); pos += m[0].length; ok = true; } }
else if ("fega".includes(sp)) { const m = sub.match(/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/); if (m) { val = parseFloat(m[0]); pos += m[0].length; ok = true; } }
else if (sp === "s") { let e = 0; const lim = mw || sub.length; while (e < lim && !" \t\n\r".includes(sub[e])) e++; if (e > 0) { val = sub.substring(0, e); pos += e; ok = true; } }
else if (sp === "c") { const cnt = mw || 1; if (pos + cnt <= str.length) { val = cnt === 1 ? str.charCodeAt(pos) : str.substring(pos, pos + cnt); pos += cnt; ok = true; } }
else if (sp === "n") { val = pos; ok = true; }
if (!ok) break;
if (!suppress) { const a = args[argIdx++]; if (a && a.buf) { if (typeof val === "string") { for (let _i = 0; _i < val.length; _i++) a.buf[a.off + _i] = val.charCodeAt(_i); a.buf[a.off + val.length] = 0; } else if (typeof val === "bigint") { try { new DataView(a.buf.buffer).setBigInt64(a.off, BigInt.asIntN(64, val), true); } catch { new DataView(a.buf.buffer).setFloat64(a.off, Number(val), true); } } else { new DataView(a.buf.buffer).setInt32(a.off, val, true); } } else if (a && typeof a === "object" && "value" in a) a.value = val; if (sp !== "n") matched++; }
}
return matched;
}
function dup(fd: number): number { return fd; }
function _write(fd: number, buf: any, count: number): number { try { const data = typeof buf === 'string' ? buf : Buffer.from(buf); require('fs').writeSync(fd, data, 0, count); return count; } catch { return -1; } }
function _read(fd: number, buf: any, count: number): number { try { const b = Buffer.alloc(count); const n = require('fs').readSync(fd, b, 0, count, null); if (Array.isArray(buf)) { for (let i = 0; i < n; i++) buf[i] = b[i]; } else if (buf && typeof buf === 'object' && 'value' in buf) { buf.value = b.toString('utf-8', 0, n); } return n; } catch { return -1; } }
function strdup(s: any): any { const str = typeof s === 'string' ? s : cptr_to_string(s); return cptr_from_string(str); }
function div(numer: number, denom: number): any { return { quot: Math.trunc(numer / denom), rem: numer % denom }; }
const ENOENT = 2, EACCES = 13, EEXIST = 17, EINTR = 4, EAGAIN = 11, EBADF = 9, EPERM = 1, ENOMEM = 12, EINVAL = 22, ENOSYS = 38, ERANGE = 34, EDOM = 33, EILSEQ = 84, ENFILE = 23, EMFILE = 24, ENOTTY = 25, EBUSY = 16, ENOSPC = 28, EROFS = 30, EPIPE = 32, ECONNREFUSED = 111, EADDRINUSE = 98, ETIMEDOUT = 110, ECONNRESET = 104;
let errno = 0;
function nan(tag: string): number { return NaN; }
function rint(x: number): number { return Math.round(x); }
function __builtin_nan(s: string): number { return NaN; }
function __builtin_nanf(s: string): number { return NaN; }
function __builtin_nanl(s: string): number { return NaN; }
function round(x: number): number { return x >= 0 ? Math.floor(x + 0.5) : Math.ceil(x - 0.5); }
function printf_format(fmt: string, ...args: any[]): string {
if (fmt == null) return '';
let result = "", argIdx = 0, i = 0;
while (i < fmt.length) {
if (fmt[i] === "%" && i + 1 < fmt.length) {
i++; let flags = ""; while ("-+ 0#".includes(fmt[i])) flags += fmt[i++];
let width = ""; if (fmt[i] === "*") { width = String(args[argIdx++]); i++; } else { while (fmt[i] >= "0" && fmt[i] <= "9") width += fmt[i++]; }
let prec = ""; if (fmt[i] === ".") { i++; if (fmt[i] === "*") { prec = String(args[argIdx++]); i++; } else { while (fmt[i] >= "0" && fmt[i] <= "9") prec += fmt[i++]; } }
let lenMod = ""; if ("hlLzjt".includes(fmt[i])) { lenMod = fmt[i]; i++; if (fmt[i] === fmt[i-1]) { lenMod += fmt[i]; i++; } }
const is64 = (lenMod === "z" || lenMod === "ll" || lenMod === "j" || lenMod === "L");
const spec = fmt[i++], a = args[argIdx++];
const toU = (v: any, r: number, up: boolean): string => { if (typeof v === "bigint") { const s2 = BigInt.asUintN(is64 ? 64 : 32, v).toString(r); return up ? s2.toUpperCase() : s2; } const nn = Number(v); if (is64 && nn < 0) { const b = BigInt.asUintN(64, BigInt(Math.trunc(nn))); const s2 = b.toString(r); return up ? s2.toUpperCase() : s2; } const s2 = (Math.trunc(nn) >>> 0).toString(r); return up ? s2.toUpperCase() : s2; };
let s = "";
switch (spec) {
case "d": case "i": { if (typeof a === "bigint") { const n = is64 ? BigInt.asIntN(64, a) : a; let mag = (n < 0n ? -n : n).toString(); if (prec) { const p = parseInt(prec); if (mag.length < p) mag = mag.padStart(p, "0"); } s = (n < 0n ? "-" : "") + mag; if (n >= 0n && flags.includes("+")) s = "+" + s; else if (n >= 0n && flags.includes(" ")) s = " " + s; break; } const n = Math.trunc(Number(a)); let mag = Math.abs(n).toString(); if (prec) { const p = parseInt(prec); if (mag.length < p) mag = mag.padStart(p, "0"); } s = (n < 0 ? "-" : "") + mag; if (n >= 0 && flags.includes("+")) s = "+" + s; else if (n >= 0 && flags.includes(" ")) s = " " + s; break; }
case "u": s = toU(a, 10, false); if (prec) { const p = parseInt(prec); if (s.length < p) s = s.padStart(p, "0"); } break;
case "x": s = toU(a, 16, false); if (prec) { const p = parseInt(prec); if (s.length < p) s = s.padStart(p, "0"); } if (flags.includes("#") && s !== "0") s = "0x" + s; break;
case "X": s = toU(a, 16, true); if (prec) { const p = parseInt(prec); if (s.length < p) s = s.padStart(p, "0"); } if (flags.includes("#") && s !== "0") s = "0X" + s; break;
case "o": s = toU(a, 8, false); if (prec) { const p = parseInt(prec); if (s.length < p) s = s.padStart(p, "0"); } if (flags.includes("#") && !s.startsWith("0")) s = "0" + s; break;
case "s": s = (a?.buf ? cptr_to_string(a) : (a && typeof a === "object" && typeof a.c_str === "function") ? a : ("" + (a ?? ""))); if (prec) s = s.slice(0, parseInt(prec)); break;
case "f": case "F": { const nn = Number(a); if (Number.isNaN(nn)) { s = spec === "F" ? "NAN" : "nan"; } else if (!Number.isFinite(nn)) { s = (nn < 0 ? "-" : (flags.includes("+") ? "+" : (flags.includes(" ") ? " " : ""))) + (spec === "F" ? "INF" : "inf"); } else { s = nn.toFixed(prec && parseInt(prec) >= 0 ? parseInt(prec) : 6); if (nn >= 0 && flags.includes("+")) s = "+" + s; else if (nn >= 0 && flags.includes(" ")) s = " " + s; } break; }
case "e": { const nn = Number(a); if (Number.isNaN(nn)) { s = "nan"; } else if (!Number.isFinite(nn)) { s = (nn < 0 ? "-" : (flags.includes("+") ? "+" : (flags.includes(" ") ? " " : ""))) + "inf"; } else { s = nn.toExponential(prec ? parseInt(prec) : 6).replace(/e([+-])(\d)$/, 'e$10$2'); if (nn >= 0 && flags.includes("+")) s = "+" + s; else if (nn >= 0 && flags.includes(" ")) s = " " + s; } break; }
case "E": { const nn = Number(a); if (Number.isNaN(nn)) { s = "NAN"; } else if (!Number.isFinite(nn)) { s = (nn < 0 ? "-" : (flags.includes("+") ? "+" : (flags.includes(" ") ? " " : ""))) + "INF"; } else { s = nn.toExponential(prec ? parseInt(prec) : 6).replace(/e([+-])(\d)$/, 'e$10$2').toUpperCase(); if (nn >= 0 && flags.includes("+")) s = "+" + s; else if (nn >= 0 && flags.includes(" ")) s = " " + s; } break; }
case "g": case "G": { const v = Number(a); if (Number.isNaN(v)) { s = spec === "G" ? "NAN" : "nan"; } else if (!Number.isFinite(v)) { s = (v < 0 ? "-" : (flags.includes("+") ? "+" : (flags.includes(" ") ? " " : ""))) + (spec === "G" ? "INF" : "inf"); } else { const gPrec = prec ? parseInt(prec) : 6; s = v.toPrecision(gPrec).replace(/(\.\d*?)0+(?=e|$)/, "$1").replace(/\.(?=e|$)/, "").replace(/e([+-])(\d)$/, "e$1" + "0$2"); if (spec === "G") s = s.toUpperCase(); if (v >= 0 && flags.includes("+")) s = "+" + s; else if (v >= 0 && flags.includes(" ")) s = " " + s; } break; }
case "a": case "A": { const v = Number(a); if (v === 0) { s = (spec === "A" ? "0X0P+0" : "0x0p+0"); break; } const __bb = new ArrayBuffer(8); new DataView(__bb).setFloat64(0, v, true); const __dv = new DataView(__bb); const __lo = __dv.getUint32(0, true), __hi = __dv.getUint32(4, true); const __sg = (__hi >>> 31) & 1; const __ex = ((__hi >>> 20) & 0x7FF) - 1023; let __m = (__hi & 0xFFFFF).toString(16).padStart(5, "0") + __lo.toString(16).padStart(8, "0"); __m = __m.replace(/0+$/, ""); const __exStr = __ex >= 0 ? ("+" + __ex) : String(__ex); const __head = spec === "A" ? "0X1" : "0x1"; const __mid = __m ? ("." + (spec === "A" ? __m.toUpperCase() : __m)) : ""; const __p = spec === "A" ? "P" : "p"; s = (__sg ? "-" : "") + __head + __mid + __p + __exStr; break; }
case "c": s = typeof a === "string" ? a.charAt(0) : String.fromCharCode(Number(a)); break;
case "p": s = "0x" + (Number(a) >>> 0).toString(16); break;
case "n": { if (a?.buf) new DataView(a.buf.buffer, a.buf.byteOffset).setInt32(a.off ?? 0, result.length, true); else if (a && typeof a === "object" && "value" in a) a.value = result.length; s = ""; break; }
case "%": s = "%"; argIdx--; break;
default: s = spec; break;
}
if (width) { let w = parseInt(width); let leftAlign = flags.includes("-"); if (w < 0) { leftAlign = true; w = -w; } if (s.length < w) { const zero = flags.includes("0") && !leftAlign && "diouxXeEfFgG".includes(spec); if (leftAlign) s = s.padEnd(w); else if (zero) { /* C17 §7.21.6.1: zero-pad goes BETWEEN sign and magnitude. */ const padLen = w - s.length; const pad = "0".repeat(padLen); if (s.startsWith("-") || s.startsWith("+") || s.startsWith(" ")) s = s[0] + pad + s.slice(1); else if (s.startsWith("0x") || s.startsWith("0X")) s = s.slice(0, 2) + pad + s.slice(2); else s = pad + s; } else s = s.padStart(w); } }
result += s;
} else { result += fmt[i++]; }
}
return result;
}
function realloc(ptr: any, size: any): any {
if (typeof ptr === 'string') ptr = cptr_from_string(ptr);
const sz = typeof size === 'bigint' ? Number(size) : Number(size ?? 0); if (ptr && ptr.__cptr_overlay === true) { const cp = ptr.__cptr; ptr = { buf: cp.buf, off: (cp.off ?? 0) + (ptr.__byteOff ?? 0) }; return cptr_realloc(ptr, sz); } if (ptr && typeof ptr === 'object' && !ptr.buf && ptr.constructor && (ptr.constructor as any).__fieldNames) { /* BRIDGE: struct-as-class realloc */ const existing = ptr.__cptr; const newBuf = new Uint8Array(sz); if (existing && existing.buf) { const srcOff = existing.off ?? 0; const copyLen = Math.min(existing.buf.length - srcOff, sz); if (copyLen > 0) newBuf.set(existing.buf.subarray(srcOff, srcOff + copyLen)); } ptr.__cptr = { buf: newBuf, off: 0 }; ptr.__byteOff = 0; return ptr; } return cptr_realloc(ptr, sz); }
function free(ptr: any): void { /* no-op in JS — GC handles it */ }
// CPtr runtime for C pointer semantics
const __LITTLE_ENDIAN = true;
interface CPtr { buf: Uint8Array; off: number; }
function cptr_create(size: any): CPtr { const n = typeof size === "bigint" ? Number(size) : Number(size ?? 0); return { buf: new Uint8Array(n), off: 0 }; }
function cptr_box_int32(val: number): CPtr { const b = new Uint8Array(4); new DataView(b.buffer).setInt32(0, val, true); return {buf: b, off: 0}; }
function cptr_box_int8(val: number): CPtr { const b = new Uint8Array(1); b[0] = val & 0xFF; return {buf: b, off: 0}; }
function cptr_box_float32(val: number): CPtr { const b = new Uint8Array(4); new DataView(b.buffer).setFloat32(0, val, true); return {buf: b, off: 0}; }
function cptr_box_float64(val: number): CPtr { const b = new Uint8Array(8); new DataView(b.buffer).setFloat64(0, val, true); return {buf: b, off: 0}; }
function __cptr_cached_array(arr: any, key: string, byteLen: number, writer: (view: DataView, index: number, value: number) => void, elemSize?: number): CPtr {
// Idempotence: if the caller already has a CPtr wrapper {buf, off}, pass through.
if (arr && typeof arr === "object" && "buf" in arr && arr.buf instanceof Uint8Array) return arr as CPtr;
// C17 §6.5.3.2 + §6.5.16.1: the CPtr is a live view into the source JS
// array. On every call, refresh buf from arr so JS-side writes are seen
// through the CPtr. __src_arr + __src_writer + __elem_size are retained on
// the CPtr so cptr_write_* helpers can back-propagate through cptr_offset.
const existing = arr?.[key];
const b = existing?.buf ?? new Uint8Array(byteLen);
const v = new DataView(b.buffer);
for (let i = 0; i < arr.length; i++) writer(v, i, Number(arr[i] ?? 0));
if (existing?.buf) return existing;
const ptr: any = { buf: b, off: 0, __src_arr: arr, __src_writer: writer, __elem_size: elemSize ?? 1 };
if (arr && typeof arr === "object") {
try { Object.defineProperty(arr, key, { value: ptr, enumerable: false, configurable: true, writable: true }); } catch { (arr as any)[key] = ptr; }
}
return ptr;
}
function cptr_from_int_array(arr: number[]): CPtr { return __cptr_cached_array(arr, "__cptr_int32", arr.length * 4, (v, i, x) => v.setInt32(i * 4, x, true), 4); }
function cptr_from_uint32_array(arr: number[]): CPtr { return __cptr_cached_array(arr, "__cptr_uint32", arr.length * 4, (v, i, x) => v.setUint32(i * 4, x >>> 0, true), 4); }
function cptr_from_int16_array(arr: number[]): CPtr { return __cptr_cached_array(arr, "__cptr_int16", arr.length * 2, (v, i, x) => v.setInt16(i * 2, x, true), 2); }
function cptr_from_uint16_array(arr: number[]): CPtr { return __cptr_cached_array(arr, "__cptr_uint16", arr.length * 2, (v, i, x) => v.setUint16(i * 2, x & 0xFFFF, true), 2); }
function cptr_from_int8_array(arr: number[]): CPtr { return __cptr_cached_array(arr, "__cptr_int8", arr.length, (v, i, x) => v.setInt8(i, x), 1); }
function cptr_from_uint8_array(arr: number[]): CPtr { return __cptr_cached_array(arr, "__cptr_uint8", arr.length, (v, i, x) => v.setUint8(i, x & 0xFF), 1); }
function cptr_from_float32_array(arr: number[]): CPtr { return __cptr_cached_array(arr, "__cptr_float32", arr.length * 4, (v, i, x) => v.setFloat32(i * 4, x, true), 4); }
function cptr_from_float64_array(arr: number[]): CPtr { return __cptr_cached_array(arr, "__cptr_float64", arr.length * 8, (v, i, x) => v.setFloat64(i * 8, x, true), 8); }
// C17 §6.2.5 p5 / §7.20: uint64_t / int64_t are exactly 64 bits. Use BigInt accessors
// to preserve full precision through DataView.setBigUint64 / setBigInt64.
function __cptr_cached_array_bigint(arr: any, key: string, byteLen: number, writer: (view: DataView, index: number, value: bigint) => void): CPtr {
// Idempotence: if arr is already a CPtr (from the earlier SML
// array-to-DataView IIFE), pass it through unchanged. Re-encoding
// would walk arr.length (undefined on a CPtr) and emit a zero-length
// buffer, then DataView.getBigInt64 throws RangeError at the read.
if (arr && arr.buf && typeof arr.off !== "undefined") return arr;
const existing = arr?.[key];
if (existing?.buf) return existing;
const b = new Uint8Array(byteLen);
const v = new DataView(b.buffer);
for (let i = 0; i < arr.length; i++) {
const x = arr[i];
writer(v, i, typeof x === "bigint" ? x : BigInt(Math.trunc(Number(x ?? 0))));
}
const ptr = { buf: b, off: 0 };
if (arr && typeof arr === "object") {
try { Object.defineProperty(arr, key, { value: ptr, enumerable: false, configurable: true, writable: true }); } catch { (arr as any)[key] = ptr; }
}
return ptr;
}
function cptr_from_uint64_array(arr: any[]): CPtr { return __cptr_cached_array_bigint(arr, "__cptr_uint64", arr.length * 8, (v, i, x) => v.setBigUint64(i * 8, BigInt.asUintN(64, x), true)); }
function cptr_from_int64_array(arr: any[]): CPtr { return __cptr_cached_array_bigint(arr, "__cptr_int64", arr.length * 8, (v, i, x) => v.setBigInt64(i * 8, BigInt.asIntN(64, x), true)); }
function cptr_offset(ptr: any, n: number): any { if (typeof ptr === 'string') { /* C17 §6.5.6 pointer arithmetic chains: s+ls-lp lowers to cptr_offset(cptr_offset(s,ls),-lp). On a JS string the first substring drops absolute position; convert to CPtr so the chain composes. */ const __b = new Uint8Array(ptr.length + 1); for (let __i = 0; __i < ptr.length; __i++) __b[__i] = ptr.charCodeAt(__i); return { buf: __b, off: Number(n) }; } if (ptr && ptr.__field_ref === true) { return { __field_ref: true, __owner: ptr.__owner, __owner_type: ptr.__owner_type, __field_name: ptr.__field_name, __field_offset: ptr.__field_offset, __byte_delta: (ptr.__byte_delta ?? 0) + Number(n) }; } if (ptr && ptr.__field_at_offset === true) { return { __field_at_offset: true, __owner: ptr.__owner, __byte_offset: (ptr.__byte_offset ?? 0) + Number(n) }; } /* BRIDGE: pointer-array — C17 §6.7.6.2 array-of-pointers (T*[N]) decays to T** (§6.3.2.1). When a slot-bearing CPtr (slots+__ptr_arr) is incremented, scale n by 8 (LLP64 sizeof(void*)) so cptr_read_ptr's off>>3 advances slot-by-slot, not byte-by-byte. */ if (ptr?.buf && ptr.__ptr_arr === true) return { buf: ptr.buf, off: (ptr.off ?? 0) + Number(n) * 8, slots: ptr.slots, __ptr_arr: true }; if (ptr?.buf) return { buf: ptr.buf, off: (ptr.off ?? 0) + n, __src_arr: ptr.__src_arr, __src_writer: ptr.__src_writer, __elem_size: ptr.__elem_size, __class_byte_view: ptr.__class_byte_view, __instance: ptr.__instance, __layout: ptr.__layout }; if (Array.isArray(ptr)) { /* BRIDGE: pointer-array — C17 §6.7.9 + §6.3.2.1: const T *arr[N] init-then-decay produces a T** that survives cptr_offset/cptr_read_ptr. Detect "JS array of pointers" by element shape (CPtr-like {buf,...} or null) and lift to a slot-bearing CPtr. Plain numeric arrays fall through to the int32-DataView path. */ const isPtrArr = ptr.length > 0 && ptr.some((e: any) => e == null || (typeof e === 'object' && (e?.buf || e?.slots))); if (isPtrArr) { return { buf: new Uint8Array(ptr.length * 8), off: Number(n) * 8, slots: ptr.slice(), __ptr_arr: true }; } const b = new Uint8Array(ptr.length * 4); const v = new DataView(b.buffer); for (let i = 0; i < ptr.length; i++) v.setInt32(i * 4, ptr[i], true); return { buf: b, off: n }; } if (ptr && typeof ptr === 'object' && !ptr.__cptr_overlay && !ptr.__arr && ptr.constructor && (ptr.constructor as any).__fieldNames) { return { __field_at_offset: true, __owner: ptr, __byte_offset: Number(n) }; } return ptr; }
// C17 §6.5.16.1: writes through a CPtr derived from a JS array must mirror
// to the source array so subsequent arr[i] reads see the written value.
function __cptr_writeback(ptr: any, byteOff: number): void { const arr = ptr.__src_arr; if (!arr) return; const es = ptr.__elem_size ?? 1; if (byteOff % es !== 0) return; const idx = byteOff / es; if (idx < 0 || idx >= arr.length) return; const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); if (es === 1) arr[idx] = dv.getInt8(byteOff); else if (es === 2) arr[idx] = dv.getInt16(byteOff, true); else if (es === 4) arr[idx] = dv.getInt32(byteOff, true); else if (es === 8) arr[idx] = dv.getFloat64(byteOff, true); }
function cptr_read(ptr: any, i: number = 0): any {
if (typeof ptr === 'string') ptr = cptr_from_string(ptr);
if (Array.isArray(ptr)) return ptr[i]; if (!ptr?.buf) return 0; return ptr.buf[ptr.off + i] ?? 0; }
function cptr_write(ptr: any, i: number, val: number): void {
if (typeof ptr === 'string') ptr = cptr_from_string(ptr);
if (!ptr?.buf) return; ptr.buf[ptr.off + i] = val & 0xFF; }
function cptr_to_string(ptr: any | null): string {
if (typeof ptr === 'string') ptr = cptr_from_string(ptr);
if (!ptr) return ''; const bytes: number[] = []; for (let i = ptr.off; i < ptr.buf.length; i++) { if (ptr.buf[i] === 0) break; bytes.push(ptr.buf[i]); } return String.fromCharCode(...bytes); }
function cptr_from_string(str: string): CPtr { const buf = new Uint8Array(str.length + 1); for (let i = 0; i < str.length; i++) buf[i] = str.charCodeAt(i); buf[str.length] = 0; return { buf, off: 0 }; }
function cptr_strlen(ptr: any | null): number {
if (typeof ptr === 'string') ptr = cptr_from_string(ptr);
if (!ptr) return 0; let i = 0; while (ptr.off + i < ptr.buf.length && ptr.buf[ptr.off + i] !== 0) i++; return i; }
function cptr_memset(ptr: any, val: number, n: number): void {
if (typeof ptr === 'string') ptr = cptr_from_string(ptr);
for (let i = 0; i < n; i++) ptr.buf[ptr.off + i] = val & 0xFF; }
function cptr_copy(dst: any, src: any, n: number): void {
if (typeof dst === 'string') dst = cptr_from_string(dst);
if (typeof src === 'string') src = cptr_from_string(src);
for (let i = 0; i < n; i++) dst.buf[dst.off + i] = src.buf[src.off + i] ?? 0; }
function cptr_realloc(ptr: any, newSize: any): CPtr { const sz = typeof newSize === "bigint" ? Number(newSize) : Number(newSize ?? 0); const n = new Uint8Array(sz); if (ptr) { const copyLen = Math.min(ptr.buf.length - ptr.off, sz); n.set(ptr.buf.subarray(ptr.off, ptr.off + copyLen)); } const r: any = { buf: n, off: 0 }; if (ptr && (ptr as any).slots) r.slots = (ptr as any).slots.slice(); return r; }
function cptr_clone(ptr: any): any { if (ptr == null) return null; if (ptr?.buf) { const c: any = { buf: ptr.buf, off: ptr.off }; if (ptr.slots) c.slots = ptr.slots; if (ptr.__ptr_arr) c.__ptr_arr = true; return c; } /* BRIDGE: pointer-array — C17 §6.7.9 + §6.3.2.1: cloning a JS array-of-pointers (T*[N]) at a call boundary lifts it to a slot-bearing CPtr so callee-side cptr_offset/cptr_read_ptr operate on a T** view rather than treating it as an int32 array. */ if (Array.isArray(ptr)) { const isPtrArr = ptr.length > 0 && ptr.some((e: any) => e == null || (typeof e === 'object' && (e?.buf || e?.slots))); if (isPtrArr) { return { buf: new Uint8Array(ptr.length * 8), off: 0, slots: ptr.slice(), __ptr_arr: true }; } return ptr; } if (typeof ptr === 'string') return cptr_from_string(ptr); return ptr; }
function cptr_eq(a: any, b: any): boolean {
if (typeof a === 'string') a = cptr_from_string(a);
if (typeof b === 'string') b = cptr_from_string(b);
if (a === b) return true; if (!a || !b) return false; if (!a.buf && !b.buf) return false; return a.buf === b.buf && a.off === b.off; }
function cptr_read_int8(ptr: any, i: number = 0): number { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) return ptr.value; return typeof ptr === 'number' ? ptr : (Array.isArray(ptr) ? ptr[i] : 0); } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); return dv.getInt8(ptr.off + i); }
function cptr_write_int8(ptr: any, i: number, val: number): void { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) { ptr.value = val; return; } if (Array.isArray(ptr)) ptr[i] = val; return; } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); dv.setInt8(ptr.off + i, val); if (ptr.__src_arr) __cptr_writeback(ptr, ptr.off + i); }
function cptr_read_uint8(ptr: any, i: number = 0): number {
if (typeof ptr === 'string') ptr = cptr_from_string(ptr);
if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) return ptr.value; return typeof ptr === 'number' ? ptr : (Array.isArray(ptr) ? ptr[i] : 0); } return ptr.buf[ptr.off + i] ?? 0; }
function cptr_write_uint8(ptr: any, i: number, val: number): void {
if (typeof ptr === 'string') ptr = cptr_from_string(ptr);
if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) { ptr.value = val; return; } if (Array.isArray(ptr)) ptr[i] = val; return; } ptr.buf[ptr.off + i] = val & 0xFF; if (ptr.__src_arr) __cptr_writeback(ptr, ptr.off + i); }
function cptr_read_int16(ptr: any, i: number = 0): number { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) return ptr.value; return typeof ptr === 'number' ? ptr : (Array.isArray(ptr) ? ptr[i] : 0); } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); return dv.getInt16(ptr.off + i * 2, __LITTLE_ENDIAN); }
function cptr_write_int16(ptr: any, i: number, val: number): void { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) { ptr.value = val; return; } if (Array.isArray(ptr)) ptr[i] = val; return; } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); dv.setInt16(ptr.off + i * 2, val, __LITTLE_ENDIAN); if (ptr.__src_arr) __cptr_writeback(ptr, ptr.off + i * 2); }
function cptr_read_uint16(ptr: any, i: number = 0): number { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) return ptr.value; return typeof ptr === 'number' ? ptr : (Array.isArray(ptr) ? ptr[i] : 0); } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); return dv.getUint16(ptr.off + i * 2, __LITTLE_ENDIAN); }
function cptr_write_uint16(ptr: any, i: number, val: number): void { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) { ptr.value = val; return; } if (Array.isArray(ptr)) ptr[i] = val; return; } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); dv.setUint16(ptr.off + i * 2, val, __LITTLE_ENDIAN); if (ptr.__src_arr) __cptr_writeback(ptr, ptr.off + i * 2); }
function cptr_read_int32(ptr: any, i: number = 0): number {
if (typeof ptr === 'string') ptr = cptr_from_string(ptr);
if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) return ptr.value; return typeof ptr === 'number' ? ptr : (Array.isArray(ptr) ? ptr[i] : 0); } if (Array.isArray(ptr.buf)) { const idx = (ptr.off ?? 0) / 4 + i; return Number(ptr.buf[idx] ?? 0); } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); return dv.getInt32(ptr.off + i * 4, __LITTLE_ENDIAN); }
function cptr_write_int32(ptr: any, i: number, val: number): void { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) { ptr.value = val; return; } if (Array.isArray(ptr)) ptr[i] = val; return; } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); dv.setInt32(ptr.off + i * 4, val, __LITTLE_ENDIAN); if (ptr.__src_arr) __cptr_writeback(ptr, ptr.off + i * 4); }
function cptr_read_uint32(ptr: any, i: number = 0): number { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) return ptr.value; return typeof ptr === 'number' ? ptr : (Array.isArray(ptr) ? ptr[i] : 0); } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); return dv.getUint32(ptr.off + i * 4, __LITTLE_ENDIAN); }
function cptr_write_uint32(ptr: any, i: number, val: number): void { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) { ptr.value = val; return; } if (Array.isArray(ptr)) ptr[i] = val; return; } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); dv.setUint32(ptr.off + i * 4, val, __LITTLE_ENDIAN); if (ptr.__src_arr) __cptr_writeback(ptr, ptr.off + i * 4); }
function cptr_read_int64(ptr: any, i: number = 0): bigint { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) { const v = ptr.value; return typeof v === 'bigint' ? v : BigInt(Math.trunc(Number(v ?? 0))); } if (typeof ptr === 'bigint') return ptr; if (typeof ptr === 'number') return BigInt(Math.trunc(ptr)); if (Array.isArray(ptr)) { const x = ptr[i]; return typeof x === 'bigint' ? x : BigInt(Math.trunc(Number(x ?? 0))); } return 0n; } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); return dv.getBigInt64(ptr.off + i * 8, __LITTLE_ENDIAN); }
function cptr_write_int64(ptr: any, i: number, val: bigint | number): void { const v = typeof val === 'bigint' ? val : BigInt(Math.trunc(Number(val ?? 0))); if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) { ptr.value = v; return; } if (Array.isArray(ptr)) ptr[i] = v; return; } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); dv.setBigInt64(ptr.off + i * 8, BigInt.asIntN(64, v), __LITTLE_ENDIAN); }
function cptr_read_uint64(ptr: any, i: number = 0): bigint { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) { const v = ptr.value; return typeof v === 'bigint' ? BigInt.asUintN(64, v) : BigInt(Math.trunc(Number(v ?? 0))); } if (typeof ptr === 'bigint') return BigInt.asUintN(64, ptr); if (typeof ptr === 'number') return BigInt(Math.trunc(ptr)); if (Array.isArray(ptr)) { const x = ptr[i]; return typeof x === 'bigint' ? BigInt.asUintN(64, x) : BigInt(Math.trunc(Number(x ?? 0))); } return 0n; } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); return dv.getBigUint64(ptr.off + i * 8, __LITTLE_ENDIAN); }
function cptr_write_uint64(ptr: any, i: number, val: bigint | number): void { const v = typeof val === 'bigint' ? val : BigInt(Math.trunc(Number(val ?? 0))); if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) { ptr.value = v; return; } if (Array.isArray(ptr)) ptr[i] = v; return; } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); dv.setBigUint64(ptr.off + i * 8, BigInt.asUintN(64, v), __LITTLE_ENDIAN); }
function cptr_read_float32(ptr: any, i: number = 0): number { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) return ptr.value; return typeof ptr === 'number' ? ptr : (Array.isArray(ptr) ? ptr[i] : 0); } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); return dv.getFloat32(ptr.off + i * 4, __LITTLE_ENDIAN); }
function cptr_write_float32(ptr: any, i: number, val: number): void { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) { ptr.value = val; return; } if (Array.isArray(ptr)) ptr[i] = val; return; } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); dv.setFloat32(ptr.off + i * 4, val, __LITTLE_ENDIAN); if (ptr.__src_arr) __cptr_writeback(ptr, ptr.off + i * 4); }
function cptr_read_float64(ptr: any, i: number = 0): number { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) return ptr.value; return typeof ptr === 'number' ? ptr : (Array.isArray(ptr) ? ptr[i] : 0); } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); return dv.getFloat64(ptr.off + i * 8, __LITTLE_ENDIAN); }
function cptr_write_float64(ptr: any, i: number, val: number): void { if (!ptr?.buf) { if (ptr && typeof ptr === 'object' && 'value' in ptr) { ptr.value = val; return; } if (Array.isArray(ptr)) ptr[i] = val; return; } const dv = new DataView(ptr.buf.buffer, ptr.buf.byteOffset); dv.setFloat64(ptr.off + i * 8, val, __LITTLE_ENDIAN); if (ptr.__src_arr) __cptr_writeback(ptr, ptr.off + i * 8); }
// C17 6.7.6.1 / 6.7.6.2: pointer-to-pointer (T**) read/write helpers.
// CPtr buf/off carries an optional parallel slots[] array of (CPtr | null)
// entries. cptr_write_ptr lazily attaches slots[] and stores the pointer
// reference at slots[idx]; it also stamps a non-zero sentinel into the byte
// view at idx*8 so byte-level scans (e.g. p->items[i] truthiness) still see
// the slot as truthy. cptr_read_ptr returns slots[idx] (or null when not yet
// written). memcpy/memmove of a slot-bearing CPtr copies the slot references
// alongside the bytes so a re-allocated buffer preserves pointer identity.
// Slot offset within the source CPtr is (off/8) so cptr_offset by 8*N
// preserves the slot view consistently.
function cptr_read_ptr(ptr: any, idx: number = 0): any { if (ptr == null) return null; if (Array.isArray(ptr)) { const v = ptr[idx]; return v ?? null; } if (typeof ptr === 'object' && (ptr as any).slots) { const slotIdx = (((ptr as any).off ?? 0) >> 3) + Number(idx); return (ptr as any).slots[slotIdx] ?? null; } return null; }
function cptr_write_ptr(ptr: any, idx: number, val: any): void { if (ptr == null) return; if (Array.isArray(ptr)) { ptr[Number(idx)] = val; return; } if (typeof ptr !== 'object') return; if (!(ptr as any).slots) (ptr as any).slots = []; const slotIdx = (((ptr as any).off ?? 0) >> 3) + Number(idx); (ptr as any).slots[slotIdx] = val ?? null; if ((ptr as any).buf) { const byteOff = (((ptr as any).off ?? 0) + Number(idx) * 8); const buf = (ptr as any).buf; if (buf && buf.length >= byteOff + 1) { buf[byteOff] = val == null ? 0 : 0xFF; } } }
function malloc(size: any): CPtr { return cptr_create(size); }
function __strto_source(s: any): string { return typeof s === 'string' ? s : (s?.buf ? cptr_to_string(s) : String(s ?? '')); }
function __strto_set_end(src: any, endptr: any, consumed: number): void {
if (!endptr) return;
if (typeof endptr === 'object' && 'value' in endptr) {
/* C17 §7.22.1.4: *endptr := pointer to first unparsed char.
* If src is a CPtr, advance off by consumed. If src is a JS
* string, hand back the suffix string so subsequent %s prints
* the unparsed portion. */
if (consumed === 0) endptr.value = src;
else if (src?.buf) endptr.value = cptr_offset(src, consumed);
else if (typeof src === 'string') endptr.value = src.substring(consumed);
else endptr.value = consumed;
return;
}
if (endptr?.buf) {
if (src?.buf) { endptr.off = (src.off ?? 0) + consumed; }
}
}
function __strto_space(c: string | undefined): boolean { return c === ' ' || c === '\t' || c === '\n' || c === '\v' || c === '\f' || c === '\r'; }
function __strto_digit(ch: string | undefined, base: number): number {
if (!ch) return -1;
const code = ch.charCodeAt(0);
let value = -1;
if (code >= 48 && code <= 57) value = code - 48;
else if (code >= 65 && code <= 90) value = code - 65 + 10;
else if (code >= 97 && code <= 122) value = code - 97 + 10;
return value >= 0 && value < base ? value : -1;
}
function __strto_int_core(src: any, base: number, unsigned: boolean, bits: number, preferBigInt = false): any {
const ss = __strto_source(src);
let p = 0;
while (p < ss.length && __strto_space(ss[p])) p++;
let negative = false;
if (ss[p] === '+' || ss[p] === '-') { negative = ss[p] === '-'; p++; }
let b = base | 0;
if ((b === 0 || b === 16) && ss[p] === '0' && (ss[p + 1] === 'x' || ss[p + 1] === 'X') && __strto_digit(ss[p + 2], 16) >= 0) { b = 16; p += 2; }
else if (b === 0 && ss[p] === '0') { b = 8; }
else if (b === 0) { b = 10; }
if (b < 2 || b > 36) { __strto_set_end(src, null, 0); return { value: 0, endIndex: 0 }; }
const digitsStart = p;
let acc = 0n;
const bitsBig = BigInt(bits);
const maxBig = unsigned ? ((1n << bitsBig) - 1n) : ((1n << (bitsBig - 1n)) - 1n);
const minBig = unsigned ? 0n : -(1n << (bitsBig - 1n));
const limit = unsigned ? maxBig : (negative ? -minBig : maxBig);
let overflow = false;
while (p < ss.length) {
const d = __strto_digit(ss[p], b);
if (d < 0) break;
if (!overflow) {
const digitBig = BigInt(d);
if (acc > (limit - digitBig) / BigInt(b)) overflow = true;
else acc = acc * BigInt(b) + digitBig;
}
p++;
}
if (p === digitsStart) return { value: 0, endIndex: 0 };
const finish = (value: bigint): any => {
if (preferBigInt) {
const asNum = Number(value);
return Number.isSafeInteger(asNum) ? asNum : value;
}
return Number(value);
};
if (overflow) {
if (typeof errno !== 'undefined') errno = typeof ERANGE !== 'undefined' ? ERANGE : 34;
return { value: finish(unsigned ? maxBig : (negative ? minBig : maxBig)), endIndex: p };
}
let signed = negative ? -acc : acc;
if (!unsigned && (signed < minBig || signed > maxBig)) {
if (typeof errno !== 'undefined') errno = typeof ERANGE !== 'undefined' ? ERANGE : 34;
return { value: finish(negative ? minBig : maxBig), endIndex: p };
}
if (unsigned && negative) {
const modulo = 1n << bitsBig;
signed = (modulo - (acc % modulo)) % modulo;
}
return { value: finish(signed), endIndex: p };
}
function __strto_float_core(src: any): { value: number; endIndex: number } {
const ss = __strto_source(src);
let p = 0;
while (p < ss.length && __strto_space(ss[p])) p++;
const start = p;
let sign = 1;
if (ss[p] === '+' || ss[p] === '-') { if (ss[p] === '-') sign = -1; p++; }
const rest = ss.slice(p).toLowerCase();
if (rest.startsWith('nan')) {
let end = p + 3;
if (ss[end] === '(') { const close = ss.indexOf(')', end); if (close !== -1) end = close + 1; }
return { value: NaN, endIndex: end };
}
if (rest.startsWith('infinity')) return { value: sign * Infinity, endIndex: p + 8 };
if (rest.startsWith('inf')) return { value: sign * Infinity, endIndex: p + 3 };
const m = ss.slice(p).match(/^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/);
if (!m) return { value: 0, endIndex: 0 };
const parsed = sign * parseFloat(m[0]);
return { value: parsed, endIndex: p + m[0].length };
}
function atoi(s: string): number { return __strto_int_core(s, 10, false, 32).value | 0; }
function atol(s: string): number { return __strto_int_core(s, 10, false, 32).value | 0; }
function atoll(s: string): number { return __strto_int_core(s, 10, false, 64, true).value; }
function atof(s: string): number { return __strto_float_core(s).value; }
function strtol(s: any, endptr: any, base: number): number { const r = __strto_int_core(s, base, false, 32); __strto_set_end(s, endptr, r.endIndex); return r.value | 0; }
function strtoul(s: any, endptr: any, base: number): number { const r = __strto_int_core(s, base, true, 32); __strto_set_end(s, endptr, r.endIndex); return r.value >>> 0; }
function strtoll(s: any, endptr: any, base: number): number { const r = __strto_int_core(s, base, false, 64, true); __strto_set_end(s, endptr, r.endIndex); return r.value; }
function strtoull(s: any, endptr: any, base: number): number { const r = __strto_int_core(s, base, true, 64, true); __strto_set_end(s, endptr, r.endIndex); return r.value; }
function strtod(s: any, endptr: any): number { const r = __strto_float_core(s); __strto_set_end(s, endptr, r.endIndex); return r.value; }
function strtof(s: any, endptr: any): number { const r = __strto_float_core(s); __strto_set_end(s, endptr, r.endIndex); return Math.fround(r.value); }
function memcpy(dst: any, src: any, n: number): any {
if (typeof dst === 'string') dst = cptr_from_string(dst);
if (dst?.buf && src?.buf) { cptr_copy(dst, src, n); /* C17 §6.7.6.1: when src is a slot-bearing CPtr (T** array), copy the parallel slot references into dst so pointer identity survives the byte-copy. Slot stride is 8 bytes (LLP64 sizeof(void*)); slot indices align with byte offset >> 3. */ if ((src as any).slots) { const dstAny: any = dst; if (!dstAny.slots) dstAny.slots = []; const srcSlotBase = ((src.off ?? 0) >> 3); const dstSlotBase = ((dst.off ?? 0) >> 3); const slotCount = Math.floor(n / 8); for (let i = 0; i < slotCount; i++) dstAny.slots[dstSlotBase + i] = (src as any).slots[srcSlotBase + i] ?? null; } return dst; } if (dst?.buf && typeof src === 'string') { for (let i = 0; i < n && i < src.length; i++) dst.buf[dst.off + i] = src.charCodeAt(i); return dst; } if (dst?.buf && src && typeof src === 'object' && 'value' in src && typeof src.value === 'number') { const dv = new DataView(dst.buf.buffer, dst.buf.byteOffset + dst.off); if (n >= 4) dv.setInt32(0, src.value, true); else if (n >= 2) dv.setInt16(0, src.value, true); else dv.setInt8(0, src.value); return dst; } if (dst && typeof dst === 'object' && 'value' in dst && src?.buf) { /* BRIDGE: memcpy(box, cptr, n) — read N bytes from a CPtr into a {value} box. C17 §7.24.2.1. n=8 → bigint64 (signed). n=4 → int32. n=2 → int16. n=1 → int8. */ const dv = new DataView(src.buf.buffer, src.buf.byteOffset); const off = src.off ?? 0; if (n >= 8) { const bv = dv.getBigInt64(off, true); dst.value = (typeof dst.value === 'bigint') ? bv : Number(bv); } else if (n >= 4) dst.value = dv.getInt32(off, true); else if (n >= 2) dst.value = dv.getInt16(off, true); else dst.value = dv.getInt8(off); return dst; } if (dst && typeof dst === 'object' && 'value' in dst && src && typeof src === 'object' && 'value' in src) { /* C17 §6.5 type-pun via memcpy: reinterpret src.value bytes as dst's type. n=4: int32<->float32. n=8: int64<->float64 (via bigint). */ const __b = new Uint8Array(8); const __dv = new DataView(__b.buffer); const __s = src.value; const __d = dst.value; if (n === 4) { if (Number.isInteger(__s) && !Number.isInteger(__d) && typeof __d === 'number') { __dv.setInt32(0, __s | 0, true); dst.value = __dv.getFloat32(0, true); } else if (!Number.isInteger(__s) && Number.isInteger(__d)) { __dv.setFloat32(0, __s, true); dst.value = __dv.getInt32(0, true); } else { dst.value = __s; } } else if (n === 8) { if (typeof __s === 'bigint' && typeof __d !== 'bigint') { __dv.setBigInt64(0, __s, true); dst.value = __dv.getFloat64(0, true); } else if (typeof __s !== 'bigint' && typeof __d === 'bigint') { __dv.setFloat64(0, Number(__s), true); dst.value = __dv.getBigInt64(0, true); } else if (Number.isInteger(__s) && !Number.isInteger(__d)) { __dv.setBigInt64(0, BigInt(Math.trunc(__s)), true); dst.value = __dv.getFloat64(0, true); } else if (!Number.isInteger(__s) && Number.isInteger(__d)) { __dv.setFloat64(0, __s, true); dst.value = Number(__dv.getBigInt64(0, true)); } else { dst.value = __s; } } else { dst.value = __s; } return dst; } if (Array.isArray(dst) && src && src.buf) { /* BRIDGE: memcpy(Array, CPtr, n) — destination is a JS Array decayed from a struct/array of i64/i32/etc., source is a CPtr backed by a Uint8Array. Read element-wise via DataView using src.__elem_size when available, defaulting to 8 (int64 — covers curve25519 fcontract / fmonty origx<-x and BLAKE2 buffer staging). C17 §7.24.2.1: memcpy copies n bytes; element-size routing is the byte-addressable lowering for an i64 destination. */ const dv = new DataView(src.buf.buffer, src.buf.byteOffset); const baseOff = src.off ?? 0; const elemSize = (src.__elem_size as number) || 8; const count = Math.floor(n / elemSize); for (let i = 0; i < count; i++) { const eoff = baseOff + i * elemSize; if (elemSize === 8) dst[i] = dv.getBigInt64(eoff, true); else if (elemSize === 4) dst[i] = dv.getInt32(eoff, true); else if (elemSize === 2) dst[i] = dv.getInt16(eoff, true); else dst[i] = dv.getInt8(eoff); } return dst; } if (Array.isArray(dst) && Array.isArray(src)) { for (let i = 0; i < n; i++) dst[i] = src[i]; } else if (typeof dst === 'object' && typeof src === 'object') Object.assign(dst, src); return dst; }
function memset(dst: any, val: number, n: number): any { const __zeroObject = (obj: any): void => { for (const k of Object.keys(obj)) { const v = obj[k]; if (typeof v === 'number') obj[k] = val | 0; else if (typeof v === 'boolean') obj[k] = val !== 0; else if (typeof v === 'string') obj[k] = ''; else if (v && typeof v === 'object' && v.buf) cptr_memset(v, val, v.buf.length); else if (Array.isArray(v) && v.length > 0 && typeof Object.values(v).find(x => x !== null && typeof x === 'object') !== 'undefined') { for (const item of v) { if (item && typeof item === 'object') __zeroObject(item); } } else if (Array.isArray(v)) { for (let i = 0; i < Math.min(n, v.length); i++) v[i] = val; } else if (v && typeof v === 'object') __zeroObject(v); else if (v != null) obj[k] = null; } }; if (dst?.buf) { cptr_memset(dst, val, n); return dst; } if (Array.isArray(dst) && dst.length > 0 && typeof Object.values(dst).find(x => x !== null && typeof x === 'object') !== 'undefined') { for (const obj of dst) { if (obj && typeof obj === 'object') __zeroObject(obj); } return dst; } if (Array.isArray(dst)) { for (let _mi = 0; _mi < Math.min(n, dst.length); _mi++) dst[_mi] = val; return dst; } if (dst && typeof dst === 'object') { __zeroObject(dst); return dst; } return dst; }
function strcpy(dst: any, src: any): any {
if (typeof dst === 'string') dst = cptr_from_string(dst);
const srcStr = typeof src === 'string' ? src : src?.buf ? cptr_to_string(src) : src?.toString?.() ?? ''; if (dst?.buf) { for (let i = 0; i < srcStr.length; i++) dst.buf[dst.off + i] = srcStr.charCodeAt(i); dst.buf[dst.off + srcStr.length] = 0; return dst; } if (Array.isArray(dst)) { for (let i = 0; i < srcStr.length; i++) dst[i] = srcStr.charCodeAt(i); dst[srcStr.length] = 0; return dst; } if (dst && typeof dst === 'object' && 'value' in dst) dst.value = srcStr; return srcStr; }
// C++20 iterator helpers — shared by <algorithm> / <numeric>.
// Lowering: `v[Symbol.iterator]()` to `v.values()` (C++20 §22.3.11). We patch
// Array.prototype.values once so the returned iterator carries __arr/__pos and
// coerces to its position via valueOf, so iterator arithmetic expressions like
// `it - v[Symbol.iterator]()` (from std::distance lowerings) evaluate to a position index
// instead of NaN.
if (!(Array.prototype as any).__cpp_values_patched) {
Object.defineProperty(Array.prototype, '__cpp_values_patched', { value: true, enumerable: false });
const __origValues = Array.prototype.values;
(Array.prototype as any).values = function () {
const arr: any[] = this as any;
let pos = 0;
const it: any = {
__arr: arr,
get __pos() { return pos; },
set __pos(v: number) { pos = v; },
next() { if (pos < arr.length) return { value: arr[pos++], done: false }; return { value: undefined, done: true }; },
[Symbol.iterator]() { return this; },
valueOf() { return pos; },
return(v: any) { pos = arr.length; return { value: v, done: true }; },
};
return it;
};
void __origValues;
}
function __cpp_arr(first: any, last?: any): { arr: any[]; start: number; end: number } {
if (first == null) return { arr: [], start: 0, end: 0 };
if (Array.isArray(first)) {
const end = (last != null && typeof last === 'number') ? last
: (last && last.__arr === first) ? last.__pos
: first.length;
return { arr: first, start: 0, end };
}
if (first && first.__arr !== undefined && Array.isArray(first.__arr)) {
const arr = first.__arr;
const start = first.__pos ?? 0;
const end = (last && last.__arr === arr) ? (last.__pos ?? arr.length)
: (last == null) ? arr.length
: (typeof last === 'number') ? last
: arr.length;
return { arr, start, end };
}
// Fallback: any iterable — materialise
const arr = Array.from(first as Iterable<any>);
return { arr, start: 0, end: arr.length };
}
function __cpp_iter(arr: any[], pos: number): any {
return { __arr: arr, __pos: pos, valueOf() { return this.__pos; }, [Symbol.iterator](): any { let i = this.__pos; const self = this; return { next() { if (i < self.__arr.length) return { value: self.__arr[i++], done: false }; return { value: undefined, done: true }; } }; } };
}
// C++20 27.2.3 [iterator.requirements]: iterator equality compares position
// within the same range. Lowering: it == __cpp_iter(v, v.length) and similar
// patterns through this helper because strict object-identity is meaningless
// across distinct iterator literals: __cpp_iter(v, n) === __cpp_iter(v, n)
// is false even when the positions are equal.
function __cpp_iter_eq(a: any, b: any): boolean {
const ap = (a && typeof a === 'object' && '__pos' in a) ? a.__pos : (typeof a === 'number' ? a : Number(a));
const bp = (b && typeof b === 'object' && '__pos' in b) ? b.__pos : (typeof b === 'number' ? b : Number(b));
return ap === bp;
}
// back_inserter: C++20 §25.5.2.1. Accepts a ref-box { value: array } or the
// raw array. Produces a sink object with __push(x) and __arr pointing at the
// destination so algorithm shims that append do so via __push.
function back_inserter(c: any): any {
const target: any[] = (c && 'value' in c) ? c.value : c;
return { __arr: target, __push(x: any) { target.push(x); }, __isBackInserter: true };
}
function front_inserter(c: any): any {
const target: any[] = (c && 'value' in c) ? c.value : c;
return { __arr: target, __push(x: any) { target.unshift(x); }, __isBackInserter: true };
}
function inserter(c: any, pos: any): any {
const target: any[] = (c && 'value' in c) ? c.value : c;
let idx = (pos && pos.__pos !== undefined) ? pos.__pos : (typeof pos === 'number' ? pos : target.length);
return { __arr: target, __push(x: any) { target.splice(idx++, 0, x); }, __isBackInserter: true };
}
function __cpp_write(out: any, values: any[]): any {
if (out == null) return null;
if (out.__isBackInserter) { for (const v of values) out.__push(v); return out; }
if (Array.isArray(out)) { for (let i = 0; i < values.length; i++) out[i] = values[i]; return __cpp_iter(out, values.length); }
if (out.__arr !== undefined && Array.isArray(out.__arr)) {
const a = out.__arr; let p = out.__pos ?? 0;
for (const v of values) a[p++] = v;
return __cpp_iter(a, p);
}
return null;
}
function reduce(first: any, last: any, init?: any, op?: Function): any { const A = __cpp_arr(first, last); const f = op ?? ((a: any, b: any) => a + b); let acc = init ?? 0; for (let i = A.start; i < A.end; i++) acc = f(acc, A.arr[i]); return acc; }
function prev(it: any, n: number = 1): any { if (it == null) return null; if (it && it.__arr !== undefined) return __cpp_iter(it.__arr, (it.__pos ?? 0) - n); if (typeof it === 'number') return it - n; return it; }
function count(first: any, last: any, value: any): number { const A = __cpp_arr(first, last); let n = 0; for (let i = A.start; i < A.end; i++) if (A.arr[i] === value) n++; return n; }
function strncmp(a: any, b: any, n: number): number { const sa = ((typeof a === 'string') ? a : (a?.buf ? cptr_to_string(a) : a?.toString?.() ?? '')).substring(0, n); const sb = ((typeof b === 'string') ? b : (b?.buf ? cptr_to_string(b) : b?.toString?.() ?? '')).substring(0, n); return sa < sb ? -1 : sa > sb ? 1 : 0; }
function fabs(x: number): number { return Math.abs(x); }
function tolower(c: number): number { if (c == null) return 0; const ch = String.fromCharCode(c); return ch.toLowerCase().charCodeAt(0); }
function write(fd: any, buf: any, count: number): number { if (fd === 1) { const s = (buf?.buf) ? cptr_to_string(buf) : (typeof buf === 'string' ? buf : String.fromCharCode(...new Uint8Array(buf, 0, count))); process.stdout.write(s.substring(0, count)); return count; } if (fd === 2) { const s = (buf?.buf) ? cptr_to_string(buf) : (typeof buf === 'string' ? buf : String(buf)); process.stderr.write(s.substring(0, count)); return count; } try { const data = (buf?.buf) ? Buffer.from(buf.buf.buffer, buf.buf.byteOffset + buf.off, count) : (typeof buf === 'string' ? Buffer.from(buf) : Buffer.from(buf)); require('fs').writeSync(fd, data, 0, count); return count; } catch { return -1; } }
function abs(x: number): number { return Math.abs(x); }
function includes(first1: any, last1: any, first2: any, last2: any, comp?: Function): boolean { const A = __cpp_arr(first1, last1); const B = __cpp_arr(first2, last2); const lt = comp ?? ((a: any, b: any) => a < b); let i = A.start, j = B.start; while (i < A.end && j < B.end) { if (lt(B.arr[j], A.arr[i])) return false; if (lt(A.arr[i], B.arr[j])) i++; else { i++; j++; } } return j === B.end; }
function max(a: any, b?: any, comp?: Function): any { if (b === undefined) { if (Array.isArray(a)) return a.reduce((m, x) => x > m ? x : m, a[0]); return a; } const lt = comp ?? ((x: any, y: any) => x < y); return lt(a, b) ? b : a; }
function trunc(x: number): number { return Math.trunc(x); }
/* stdbool: true/false are native in TypeScript */
const stdin = { __fd: 0, __name: 'stdin' }, stdout = { __fd: 1, __name: 'stdout' }, stderr = { __fd: 2, __name: 'stderr' };
const NULL = null;
const NAN = NaN, INFINITY_C = Infinity, HUGE_VAL = Infinity, HUGE_VALF = Infinity, HUGE_VALL = Infinity, M_PI = 3.141592653589793, M_PI_2 = 1.5707963267948966, M_PI_4 = 0.7853981633974483, M_1_PI = 0.3183098861837907, M_2_PI = 0.6366197723675814, M_2_SQRTPI = 1.1283791670955126, M_E = 2.718281828459045, M_LOG2E = 1.4426950408889634, M_LOG10E = 0.4342944819032518, M_LN2 = 0.6931471805599453, M_LN10 = 2.302585092994046, M_SQRT2 = 1.4142135623730951, M_SQRT1_2 = 0.7071067811865476;
function i32(x: number) { return x | 0; }
function u32(x: number) { return x >>> 0; }
function __as_bigint(x: any): bigint { if (typeof x === 'bigint') return x; if (typeof x === 'number') return BigInt(Math.trunc(x)); if (x && typeof x === 'object' && 'value' in x) { const v = (x as any).value; return typeof v === 'bigint' ? v : BigInt(Math.trunc(Number(v ?? 0))); } if (typeof x === 'boolean') return x ? 1n : 0n; return BigInt(Math.trunc(Number(x ?? 0))); }
function __u64(x: bigint): bigint { return BigInt.asUintN(64, x); }
function __i64(x: bigint): bigint { return BigInt.asIntN(64, x); }
function __safe_div_i64(a: bigint, b: bigint): bigint { if (b === 0n) throw new Error('Division by zero'); return a / b; }
function __safe_mod_i64(a: bigint, b: bigint): bigint { if (b === 0n) throw new Error('Division by zero'); return a % b; }
const __rt_objId_map = new WeakMap<object, number>(); const __rt_objId_inverse = new Map<number, any>(); let __rt_objId_next = 64; function __rt_objId(o: any): number { if (o == null || typeof o !== 'object') return 0; let id = __rt_objId_map.get(o); if (id === undefined) { id = __rt_objId_next; __rt_objId_next += 64; __rt_objId_map.set(o, id); __rt_objId_inverse.set(id, o); } return id; } const __rt_cptrInt_byBuf = new WeakMap<object, Map<number, number>>(); const __rt_cptrInt_inverse = new Map<number, any>(); let __rt_cptrInt_next = -64; function __rt_ptr_to_intptr(p: any): number {
if (typeof p === 'string') p = cptr_from_string(p);
if (p == null) return 0; if (p && p.buf && typeof p.off !== 'undefined') { let m = __rt_cptrInt_byBuf.get(p.buf); if (!m) { m = new Map(); __rt_cptrInt_byBuf.set(p.buf, m); } const off = p.off ?? 0; let id = m.get(off); if (id === undefined) { id = __rt_cptrInt_next; __rt_cptrInt_next -= 64; m.set(off, id); __rt_cptrInt_inverse.set(id, { buf: p.buf, off }); } return id; } return __rt_objId(p); } function __rt_intptr_to_ptr(i: any): any { if (i === 0 || i === 0n || i == null) return null; const n = typeof i === 'bigint' ? Number(i) : i; if (__rt_cptrInt_inverse.has(n)) return __rt_cptrInt_inverse.get(n); if (__rt_objId_inverse.has(n)) return __rt_objId_inverse.get(n); return n; }
function __struct_ptr_at(p: any, i: any): any { if (p == null) return p; const idx = Number(i) | 0; if (Array.isArray(p)) return p[idx]; if (p && p.__arr !== undefined) return p.__arr[(p.__idx ?? 0) + idx]; if (p && p.__cptr_overlay === true && idx !== 0) { return cptr_struct_overlay(p.__structT, p.__cptr, (p.__byteOff ?? 0) + idx * (p.__layout?.totalSize ?? 0)); } if (p && p.__field_ref === true && idx === 0) { /* C17 §6.3.2.3 p7: container_of round-trip recovery. Fire ONLY when explicit pointer arithmetic happened (byte_delta != 0) and the accumulated delta + field_offset cancels to 0. The byte_delta=0 case is direct field-ref dereference (`(&t.f)->subfield`) — the field-ref Proxy itself handles sub-field access via property forwarding, so returning the owner here would incorrectly resolve `(g.nilvalue_field_ref)->value_` to `g.value_` (undefined) instead of `g.nilvalue.value_`. The cast-back form `(T*)((char*)&t.m - offsetof(T,m))` still works through cptr_struct_overlay's separate round-trip path. */ const bd = p.__byte_delta ?? 0; if (bd !== 0 && bd + (p.__field_offset ?? 0) === 0) return p.__owner; } if (p && p.__field_at_offset === true && idx === 0) { /* C17 §6.3.2.3 p7 + §7.19: resolve inverse-container_of shape. byte_offset 0 with cast target == owner's type is round-trip back to owner; otherwise look up the field at byte offset on the owner's class. */ const ctor = p.__owner ? p.__owner.constructor : null; const target = p.__byte_offset ?? 0; if (target === 0 && p.__cast_target === ctor) return p.__owner; if (ctor && ctor.__fieldNames) { if (ctor.__fieldOffsets) { for (let k = 0; k < ctor.__fieldNames.length; k++) { if (ctor.__fieldOffsets[k] === target) return p.__owner[ctor.__fieldNames[k]]; } } else if (ctor.__fieldTypes) { const SZ: any = { bool:1, int8:1, uint8:1, char:1, bytes:1, int16:2, uint16:2, int32:4, uint32:4, float:4, int64:8, uint64:8, double:8, ptr:8 }; let off = 0; for (let k = 0; k < ctor.__fieldNames.length; k++) { if (off === target) return p.__owner[ctor.__fieldNames[k]]; off += SZ[ctor.__fieldTypes[k]] ?? 4; } } } if (target === 0) return p.__owner; } return p; }
function __struct_array_with_tail(n: number, ctor: () => any, tail: number): any { const a: any = Array.from({ length: n }, ctor); a[n] = { buf: new Uint8Array(Math.max(0, tail | 0)), off: 0 }; return a; }
function __cptr_overlay_layout(T: any): any {
if (T.__overlay_layout) return T.__overlay_layout;
const types: string[] = T.__fieldTypes ?? [];
const names: string[] = T.__fieldNames ?? [];
const SZ: Record<string, number> = { 'bool':1,'int8':1,'int16':2,'int32':4,'int64':8,'float':4,'double':8,'bytes':0 };
const AL: Record<string, number> = { 'bool':1,'int8':1,'int16':2,'int32':4,'int64':8,'float':4,'double':8,'bytes':1 };
const isPacked = T.__packed === true;
const isUnion = T.__union === true;
const fields: any[] = []; let off = 0; let maxAl = 1;
for (let i = 0; i < types.length; i++) {
const ty = types[i]; const sz = SZ[ty] ?? 4; const al = AL[ty] ?? sz;
const isLast = i === types.length - 1;
if (isUnion) {
// C17 §6.7.2.1 p16: every union member shares offset 0.
fields.push({ name: names[i], type: ty, offset: 0, size: sz });
if (sz > off) off = sz;
continue;
}
if (ty === 'bytes' && isLast) { fields.push({ name: names[i], type: ty, offset: off, size: 0 }); continue; }
if (!isPacked) { const pad = (al - (off % al)) % al; off += pad; if (al > maxAl) maxAl = al; }
fields.push({ name: names[i], type: ty, offset: off, size: sz });
off += sz;
}
T.__overlay_layout = { fields, totalSize: off };
return T.__overlay_layout;
}
function cptr_struct_overlay(T: any, p: any, byteOff?: number): any {
if (typeof p === 'string') p = cptr_from_string(p);
if (p == null) return p;
// C17 §6.3.2.3 p7 + §7.19: inverse-container_of bridge. When p was
// produced by `(InnerT*)((char*)container + offsetof(ContainerT, f))`
// (the inverse of container_of, used by intrusive-list libs like
// uthash's HH_FROM_ELMT, Linux hlist, BSD sys/queue.h), resolve the
// byte offset to the named field on the JS-class-backed container
// and return the live nested struct. This makes writes through the
// resulting pointer propagate to container.field.
if (p && p.__field_at_offset === true) {
const newOff = (p.__byte_offset ?? 0) + (byteOff ?? 0);
const ownerCtor = p.__owner ? p.__owner.constructor : null;
// Round-trip recovery: when the cast target matches the owner's
// class and the accumulated offset is 0, return the owner directly
// so pointer-equality (recovered == original) holds.
if (newOff === 0 && T === ownerCtor) return p.__owner;
// Tag with the cast target type and accumulate byteOff. Resolution
// for non-round-trip cases happens in __struct_ptr_at when the
// consumer dereferences. This preserves the back-reference chain
// so a subsequent cptr_offset (the reverse direction in a
// forward+reverse round-trip) can still recover the container.
return { __field_at_offset: true, __owner: p.__owner, __byte_offset: newOff, __cast_target: T };
}
// C17 §6.5 p7 + §7.19: inverse-container_of via class-byte-view.
// When p was produced by `(unsigned char *)container_ptr` followed
// by `cptr_offset(view, off)` and is now being recast to a struct
// pointer, route to the live container's field at byte offset `off`
// — same recovery semantics as the __field_at_offset path. This
// keeps writes through the resulting pointer propagating to the
// original container.field instead of dead-ending on the snapshot
// buffer. Round-trip when off === 0 and T === container's class.
if (p && p.__class_byte_view === true && p.__instance) {
const totalOff = (p.off ?? 0) + (byteOff ?? 0);
const ownerCtor2 = p.__instance.constructor;
if (totalOff === 0 && T === ownerCtor2) return p.__instance;
return { __field_at_offset: true, __owner: p.__instance, __byte_offset: totalOff, __cast_target: T };
}
// C17 §6.3.2.3 p7 + §7.19: container_of round-trip recovery. If p
// is a field reference whose accumulated byte_delta exactly cancels
// its field_offset (`(T*)((char*)&t.m - offsetof(T, m))`), return
// the containing struct. Otherwise the cast is UB per §6.3.2.3 p7;
// best-effort: still return owner so misshapen code at least
// doesn't crash. Future: emit a compile-time diagnostic.
if (p && p.__field_ref === true) {
return p.__owner;
}
if (Array.isArray(p)) return p[0];
if (p && p.__arr !== undefined) return p.__arr[(p.__idx ?? 0)];
if (!(p && p.buf !== undefined)) return p;
// Bit-field struct: the class encodes per-field shift+mask; route the
// class's internal DataView at the external buffer so its accessors
// operate directly on the caller's bytes. C17 §6.7.2.1 p11.
if (T.__bitfield === true && p.buf && (p.buf.buffer instanceof ArrayBuffer)) {
return new T(p.buf, (p.off ?? 0) + (byteOff ?? 0));
}
const layout = __cptr_overlay_layout(T);
const baseByteOff = byteOff ?? 0;
const view: any = { __cptr_overlay: true, __cptr: p, __layout: layout, __byteOff: baseByteOff, __structT: T };
for (const f of layout.fields) {
const off = f.offset, ty = f.type, name = f.name;
Object.defineProperty(view, name, {
enumerable: true, configurable: false,
get(): any {
const buf = p.buf; const at = (p.off ?? 0) + baseByteOff + off;
switch (ty) {
case 'bool': case 'int8': { const v = buf[at] & 0xFF; return (v << 24) >> 24; }
case 'int16': { const v = (buf[at] & 0xFF) | ((buf[at+1] & 0xFF) << 8); return (v << 16) >> 16; }
case 'int32': { return ((buf[at] & 0xFF) | ((buf[at+1] & 0xFF) << 8) | ((buf[at+2] & 0xFF) << 16) | ((buf[at+3] & 0xFF) << 24)) | 0; }
case 'int64': { const lo = ((buf[at] & 0xFF) | ((buf[at+1] & 0xFF) << 8) | ((buf[at+2] & 0xFF) << 16)) + ((buf[at+3] & 0xFF) * 0x1000000); const hi = ((buf[at+4] & 0xFF) | ((buf[at+5] & 0xFF) << 8) | ((buf[at+6] & 0xFF) << 16)) + ((buf[at+7] & 0xFF) * 0x1000000); return lo + hi * 0x100000000; }
case 'float': { const dv = new DataView(new ArrayBuffer(4)); for (let k = 0; k < 4; k++) dv.setUint8(k, buf[at+k] & 0xFF); return dv.getFloat32(0, true); }
case 'double': { const dv = new DataView(new ArrayBuffer(8)); for (let k = 0; k < 8; k++) dv.setUint8(k, buf[at+k] & 0xFF); return dv.getFloat64(0, true); }
case 'bytes': { return new Proxy({} as any, { get: (_t, k) => { if (k === 'buf') return buf; if (k === 'off') return at; const ii = Number(k); if (!isNaN(ii)) return buf[at + ii] & 0xFF; return undefined; }, set: (_t, k, val) => { const ii = Number(k); if (!isNaN(ii)) buf[at + ii] = Number(val) & 0xFF; return true; } }); }
}
return undefined;
},
set(val: any): void {
const buf = p.buf; const at = (p.off ?? 0) + baseByteOff + off;
switch (ty) {
case 'bool': case 'int8': { const v = Number(val) | 0; buf[at] = v & 0xFF; return; }
case 'int16': { const v = Number(val) | 0; buf[at] = v & 0xFF; buf[at+1] = (v >> 8) & 0xFF; return; }
case 'int32': { const v = Number(val) | 0; buf[at] = v & 0xFF; buf[at+1] = (v >> 8) & 0xFF; buf[at+2] = (v >> 16) & 0xFF; buf[at+3] = (v >> 24) & 0xFF; return; }
case 'int64': { let big = typeof val === 'bigint' ? val : BigInt(Math.trunc(Number(val))); for (let k = 0; k < 8; k++) { buf[at+k] = Number(big & 0xFFn) & 0xFF; big = big >> 8n; } return; }
case 'float': { const dv = new DataView(new ArrayBuffer(4)); dv.setFloat32(0, Number(val), true); for (let k = 0; k < 4; k++) buf[at+k] = dv.getUint8(k); return; }
case 'double': { const dv = new DataView(new ArrayBuffer(8)); dv.setFloat64(0, Number(val), true); for (let k = 0; k < 8; k++) buf[at+k] = dv.getUint8(k); return; }
}
},
});
}
return view;
}
function __field_ref_scalar(getOwner: () => any, ownerType: string, fieldName: string, fieldOffset: number): any {
let _buf: Uint8Array | null = null;
let _view: DataView | null = null;
let _proxy: any = null;
function _width(): number {
const o = getOwner(); if (!o || !o.constructor) return 4;
const ft: string[] | undefined = (o.constructor as any).__fieldTypes;
const fn: string[] | undefined = (o.constructor as any).__fieldNames;
if (!ft || !fn) return 4;
const i = fn.indexOf(fieldName); if (i < 0) return 4;
const t = ft[i] || '';
if (/int8|uint8|^char$|^bool$|bytes/.test(t)) return 1;
if (/int16|uint16|short/.test(t)) return 2;
if (/int64|uint64|long\s*long|double/.test(t)) return 8;
return 4;
}
function _ensureBuf(): void {
if (_buf != null) return;
const w = _width();
_buf = new Uint8Array(w);
_view = new DataView(_buf.buffer);
const v = (getOwner() as any)?.[fieldName];
if (w === 1) _buf[0] = (Number(v) | 0) & 0xFF;
else if (w === 2) _view.setUint16(0, Number(v ?? 0) & 0xFFFF, true);
else if (w === 4) _view.setUint32(0, (Number(v ?? 0)) >>> 0, true);
else { const bv = typeof v === 'bigint' ? v : BigInt(Math.trunc(Number(v ?? 0))); _view.setBigUint64(0, BigInt.asUintN(64, bv), true); }
}
function _unpack(): void {
if (_buf == null || _view == null) return;
const w = _width(); let nv: any;
if (w === 1) nv = _buf[0];
else if (w === 2) nv = _view.getUint16(0, true);
else if (w === 4) nv = _view.getUint32(0, true);
else nv = _view.getBigUint64(0, true);
(getOwner() as any)[fieldName] = nv;
}
return {
__field_ref: true,
__owner_type: ownerType, __field_name: fieldName,
__field_offset: fieldOffset, __byte_delta: 0,
off: 0,
get __owner() { return getOwner(); },
get value() { return getOwner()[fieldName]; },
set value(v: any) { getOwner()[fieldName] = v; },
get buf() {
_ensureBuf();
if (_proxy == null) {
_proxy = new Proxy(_buf!, {
get(t, p) { return (t as any)[p]; },
set(t, p, v) {
const isIdx = typeof p === 'string' && /^\d+$/.test(p);
(t as any)[p] = isIdx ? (Number(v) & 0xFF) : v;
if (isIdx) _unpack();
return true;
},
});
}
return _proxy;
},
};
}
function __field_ref_aggregate(getOwner: () => any, ownerType: string, fieldName: string, fieldOffset: number): any {
const meta: any = {
__field_ref: true,
__owner_type: ownerType, __field_name: fieldName,
__field_offset: fieldOffset, __byte_delta: 0,
};
return new Proxy({} as any, {
get(_t, prop) {
if (prop === '__owner') return getOwner();
if (prop in meta) return meta[prop];
const inner = getOwner()[fieldName];
return inner == null ? undefined : (inner as any)[prop];
},
set(_t, prop, val) {
if (prop in meta) { meta[prop] = val; return true; }
const inner = getOwner()[fieldName];
if (inner != null) (inner as any)[prop] = val;
return true;
},
has(_t, prop) { return prop in meta || (prop in (getOwner()[fieldName] ?? {})); },
});
}
function container_of(p: any, _T: any, _member: string): any {
if (p == null) return null;
if (p.__field_ref === true) return p.__owner;
return p; /* best-effort identity; UB per C17 §6.3.2.3 p7 */
}
// BRIDGE: c-out-pointer alias — C17 §6.5.3.2 + §6.7.6.1; structurally `{ value: T }`.
type COutParam<T> = { value: T };
function printf(fmt: string, ...args: any[]): number {
let result = "", argIdx = 0, i = 0;
while (i < fmt.length) {
if (fmt[i] === "%" && i + 1 < fmt.length) {
i++;
let flags = ""; while ("-+ 0#".includes(fmt[i])) flags += fmt[i++];
let width = ""; if (fmt[i] === "*") { width = String(args[argIdx++]); i++; } else { while (fmt[i] >= "0" && fmt[i] <= "9") width += fmt[i++]; }
let prec = ""; if (fmt[i] === ".") { i++; if (fmt[i] === "*") { prec = String(args[argIdx++]); i++; } else { while (fmt[i] >= "0" && fmt[i] <= "9") prec += fmt[i++]; } }
let lenMod = ""; if ("hlLzjt".includes(fmt[i])) { lenMod = fmt[i]; i++; if (fmt[i] === fmt[i-1]) { lenMod += fmt[i]; i++; } }
const is64 = (lenMod === "z" || lenMod === "ll" || lenMod === "j" || lenMod === "L");
const spec = fmt[i++], a = args[argIdx++], w = width ? parseInt(width) : 0;
const av = (a && typeof a === "object" && a.__arr !== undefined) ? a.__arr[a.__pos ?? 0] : a;
let s: string;
// C17 7.21.6.1: negative values under u/x/X/o with z, ll, j length modifiers
// render with full 64-bit unsigned wrap so size_t(-1) prints as 18446744073709551615.
const toUnsignedStr = (v: any, radix: number, upper: boolean): string => {
if (typeof v === "bigint") {
const r = BigInt.asUintN(is64 ? 64 : 32, v).toString(radix);
return upper ? r.toUpperCase() : r;
}
const n = Number(v);
if (is64 && n < 0) {
let big = BigInt.asUintN(64, BigInt(Math.trunc(n)));
let r = big.toString(radix);
return upper ? r.toUpperCase() : r;
}
let r = (Math.trunc(n) >>> 0).toString(radix);
return upper ? r.toUpperCase() : r;
};
switch (spec) {
case "d": case "i": { if (typeof av === "bigint") { const n = is64 ? BigInt.asIntN(64, av) : av; let mag = (n < 0n ? -n : n).toString(); if (prec) { const p = parseInt(prec); if (mag.length < p) mag = mag.padStart(p, "0"); } s = (n < 0n ? "-" : "") + mag; if (n >= 0n && flags.includes("+")) s = "+" + s; else if (n >= 0n && flags.includes(" ")) s = " " + s; break; } const n = Math.trunc(Number(av)); let mag = Math.abs(n).toString(); if (prec) { const p = parseInt(prec); if (mag.length < p) mag = mag.padStart(p, "0"); } s = (n < 0 ? "-" : "") + mag; if (n >= 0 && flags.includes("+")) s = "+" + s; else if (n >= 0 && flags.includes(" ")) s = " " + s; break; }
case "u": s = toUnsignedStr(av, 10, false); if (prec) { const p = parseInt(prec); if (s.length < p) s = s.padStart(p, "0"); } break;
case "x": s = toUnsignedStr(av, 16, false); if (prec) { const p = parseInt(prec); if (s.length < p) s = s.padStart(p, "0"); } if (flags.includes("#") && s !== "0") s = "0x" + s; break;
case "X": s = toUnsignedStr(av, 16, true); if (prec) { const p = parseInt(prec); if (s.length < p) s = s.padStart(p, "0"); } if (flags.includes("#") && s !== "0") s = "0X" + s; break;
case "o": s = toUnsignedStr(av, 8, false); if (prec) { const p = parseInt(prec); if (s.length < p) s = s.padStart(p, "0"); } if (flags.includes("#") && !s.startsWith("0")) s = "0" + s; break;
case "f": case "F": { const aObj: any = av; const nn = Number(aObj); if (Number.isNaN(nn)) { s = spec === "F" ? "NAN" : "nan"; break; } if (!Number.isFinite(nn)) { s = (nn < 0 ? "-" : (flags.includes("+") ? "+" : (flags.includes(" ") ? " " : ""))) + (spec === "F" ? "INF" : "inf"); break; } const isDec = !!(aObj && typeof aObj.toFixed === "function" && typeof aObj.toNumber === "function"); const p = prec ? parseInt(prec) : 6; if (isDec) { s = aObj.toFixed(p); } else { s = nn.toFixed(p); } const isNegZero = !isDec && Object.is(nn, -0); const sign = isDec ? (aObj.isNegative && aObj.isNegative() ? -1 : 1) : (nn < 0 || isNegZero ? -1 : 1); if (isNegZero && !s.startsWith("-")) s = "-" + s; if (sign >= 0 && flags.includes("+")) s = "+" + s; else if (sign >= 0 && flags.includes(" ")) s = " " + s; break; }
case "e": { const aObj: any = av; const nn = Number(aObj); if (Number.isNaN(nn)) { s = "nan"; break; } if (!Number.isFinite(nn)) { s = (nn < 0 ? "-" : (flags.includes("+") ? "+" : (flags.includes(" ") ? " " : ""))) + "inf"; break; } const isDec = !!(aObj && typeof aObj.toExponential === "function" && typeof aObj.toNumber === "function"); const p = prec ? parseInt(prec) : 6; if (isDec) { s = aObj.toExponential(p); } else { s = nn.toExponential(p); } s = s.replace(/e([+-])(\d)$/, "e$1" + "0$2"); const sign = isDec ? (aObj.isNegative && aObj.isNegative() ? -1 : 1) : (nn < 0 ? -1 : 1); if (sign >= 0 && flags.includes("+")) s = "+" + s; else if (sign >= 0 && flags.includes(" ")) s = " " + s; break; }
case "E": { const aObj: any = av; const nn = Number(aObj); if (Number.isNaN(nn)) { s = "NAN"; break; } if (!Number.isFinite(nn)) { s = (nn < 0 ? "-" : (flags.includes("+") ? "+" : (flags.includes(" ") ? " " : ""))) + "INF"; break; } const isDec = !!(aObj && typeof aObj.toExponential === "function" && typeof aObj.toNumber === "function"); const p = prec ? parseInt(prec) : 6; if (isDec) { s = aObj.toExponential(p); } else { s = nn.toExponential(p); } s = s.replace(/e([+-])(\d)$/, "e$1" + "0$2").toUpperCase(); const sign = isDec ? (aObj.isNegative && aObj.isNegative() ? -1 : 1) : (nn < 0 ? -1 : 1); if (sign >= 0 && flags.includes("+")) s = "+" + s; else if (sign >= 0 && flags.includes(" ")) s = " " + s; break; }
case "g": case "G": { const aObj: any = av; const nn = Number(aObj); if (Number.isNaN(nn)) { s = spec === "G" ? "NAN" : "nan"; break; } if (!Number.isFinite(nn)) { s = (nn < 0 ? "-" : (flags.includes("+") ? "+" : (flags.includes(" ") ? " " : ""))) + (spec === "G" ? "INF" : "inf"); break; } const isDec = !!(aObj && typeof aObj.toPrecision === "function" && typeof aObj.toNumber === "function"); const gPrec = prec ? parseInt(prec) : 6; if (isDec) { s = aObj.toPrecision(gPrec); } else { s = nn.toPrecision(gPrec); } s = s.replace(/(\.\d*?)0+(?=e|$)/, "$1").replace(/\.(?=e|$)/, "").replace(/e([+-])(\d)$/, "e$1" + "0$2"); if (spec === "G") s = s.toUpperCase(); const sign = isDec ? (aObj.isNegative && aObj.isNegative() ? -1 : 1) : (nn < 0 ? -1 : 1); if (sign >= 0 && flags.includes("+")) s = "+" + s; else if (sign >= 0 && flags.includes(" ")) s = " " + s; break; }
case "s": {
// C17 §7.21.6.1: %s prints a char string; %ls (lenMod 'l') prints
// a wchar_t string. For wide strings, decode the wchar_t array to
// UTF-16 code points (null-terminated). Plain JS array of numbers
// = wchar_t buffer; CPtr or string = char string.
if (lenMod === "l" && Array.isArray(a)) {
let r = "";
for (let i = 0; i < a.length; i++) {
const cp = Number(a[i] ?? 0);
if (cp === 0) break;
r += String.fromCodePoint(cp);
}
s = r;
} else if (a?.buf) {
s = cptr_to_string(a);
} else if (a && typeof a === "object" && typeof a.c_str === "function") {
s = a;
} else {
s = "" + (a ?? "");
}
if (prec) s = s.slice(0, parseInt(prec));
break;
}
case "a": case "A": { const v = Number(av); if (v === 0) { s = (spec === "A" ? "0X0P+0" : "0x0p+0"); break; } const __bb = new ArrayBuffer(8); new DataView(__bb).setFloat64(0, v, true); const __dv = new DataView(__bb); const __lo = __dv.getUint32(0, true), __hi = __dv.getUint32(4, true); const __sg = (__hi >>> 31) & 1; const __ex = ((__hi >>> 20) & 0x7FF) - 1023; let __m = (__hi & 0xFFFFF).toString(16).padStart(5, "0") + __lo.toString(16).padStart(8, "0"); __m = __m.replace(/0+$/, ""); const __exStr = __ex >= 0 ? ("+" + __ex) : String(__ex); const __head = spec === "A" ? "0X1" : "0x1"; const __mid = __m ? ("." + (spec === "A" ? __m.toUpperCase() : __m)) : ""; const __p = spec === "A" ? "P" : "p"; s = (__sg ? "-" : "") + __head + __mid + __p + __exStr; break; }
case "c": s = typeof av === "string" ? av.charAt(0) : String.fromCharCode(Number(av)); break;
case "p": s = "0x" + (Number(av) >>> 0).toString(16); break;
case "n": { if (a?.buf) new DataView(a.buf.buffer, a.buf.byteOffset).setInt32(a.off ?? 0, result.length, true); else if (a && typeof a === "object" && "value" in a) a.value = result.length; s = ""; break; }
case "%": s = "%"; argIdx--; break;
default: s = "%" + spec; argIdx--;
}
{ let ww = w; let leftAlign = flags.includes("-"); if (ww < 0) { leftAlign = true; ww = -ww; } if (ww > s.length) { const zero = flags.includes("0") && !leftAlign && "diouxXeEfFgG".includes(spec); const padChar = zero ? "0" : " "; const padLen = ww - s.length; const pad = padChar.repeat(padLen); /* C17 §7.21.6.1: zero-pad goes BETWEEN the sign and the magnitude, not before the sign. Same for 0x/0X prefixes added by # flag. */ if (zero && !leftAlign && (s.startsWith("-") || s.startsWith("+") || s.startsWith(" "))) { s = s[0] + pad + s.slice(1); } else if (zero && !leftAlign && (s.startsWith("0x") || s.startsWith("0X"))) { s = s.slice(0, 2) + pad + s.slice(2); } else { s = leftAlign ? s + pad : pad + s; } } }
result += s;
} else { result += fmt[i++]; }
}
// Reference _fileHandles via globalThis to avoid TS2304 in TUs that don't
// include the file-IO injection block (no fopen/fclose/fgets in the source).
// The runtime check still works either way.
const __fh: any = (globalThis as any)._fileHandles;
if (typeof stdout === "object" && stdout && typeof (stdout as any).__fd === "number" && __fh) {
const h = __fh.get((stdout as any).__fd);
if (h) {
const buf = Buffer.from(result);
require("fs").writeSync(h.fd, buf, 0, buf.length, h.pos);
h.pos += buf.length;
return result.length;
}
}
process.stdout.write(result);
return result.length;
}
function strlen(s: any): number { if (s == null) return 0; if (typeof s === 'string') return s.length; if (s.buf) return cptr_strlen(s); if (Array.isArray(s)) { let i = 0; while (s[i] !== 0 && s[i] !== undefined && i < s.length) i++; return i; } return s?.length ?? 0; }
function strcmp(a: any, b: any): number { const sa = (typeof a === 'string') ? a : (a?.buf ? cptr_to_string(a) : a?.toString?.() ?? ''); const sb = (typeof b === 'string') ? b : (b?.buf ? cptr_to_string(b) : b?.toString?.() ?? ''); return sa < sb ? -1 : sa > sb ? 1 : 0; }
// Static local variables
let _static_version_0: CPtr = cptr_create(15);
let _static_default_buffer_size_1: number = ((256) >>> 0);
// BRIDGE: struct-as-class — C17 §6.7.2.1 / C++20 [class]
export class cJSON {
next: cJSON | null;
prev: cJSON | null;
child: cJSON | null;
type: number;
valuestring: string;
valueint: number;
valuedouble: number;
string: string;
constructor() {
this.next = null;
this.prev = null;
this.child = null;
this.type = 0;
this.valuestring = null;
this.valueint = 0;
this.valuedouble = 0.0;
this.string = null;
}
}
(cJSON as any).__fieldTypes = ["int64","int64","int64","int32","int64","int32","double","int64"];
(cJSON as any).__fieldNames = ["next","prev","child","type","valuestring","valueint","valuedouble","string"];
(cJSON as any).__fieldOffsets = [0,8,16,24,32,40,48,56];
// BRIDGE: struct-as-class — C17 §6.7.2.1 / C++20 [class]
export class cJSON_Hooks {
malloc_fn: any;
free_fn: any;
constructor() {
this.malloc_fn = null;
this.free_fn = null;
}
}
(cJSON_Hooks as any).__fieldTypes = ["int64","int32"];
(cJSON_Hooks as any).__fieldNames = ["malloc_fn","free_fn"];
(cJSON_Hooks as any).__fieldOffsets = [0,8];
type cJSON_bool = number;
// BRIDGE: struct-as-class — C17 §6.7.2.1 / C++20 [class]
export class error {
json: any | null;
position: number;
constructor() {
this.json = null;
this.position = 0;
}
}
(error as any).__fieldTypes = ["int64","int64"];
(error as any).__fieldNames = ["json","position"];
(error as any).__fieldOffsets = [0,8];
let global_error = Object.assign(new error(), { json: null, position: ((0) >>> 0) });
export function cJSON_GetErrorPtr(): CPtr {
return cptr_clone(((cptr_offset(global_error.json, ((global_error.position) >>> 0)))));
}
export function cJSON_GetStringValue(item: cJSON | null): CPtr {
if ((!cJSON_IsString(item) ? 1 : 0)) {
return null;
}
return cptr_clone((__struct_ptr_at(item, 0)).valuestring);
}
export function cJSON_GetNumberValue(item: cJSON | null): number {
if ((!cJSON_IsNumber(item) ? 1 : 0)) {
return ((__builtin_nanf("")));
}
return (__struct_ptr_at(item, 0)).valuedouble;
}
export function cJSON_Version(): CPtr {
(() => { const __s = printf_format("%i.%i.%i", 1, 7, 19); strcpy(_static_version_0, __s); return __s.length; })();
return cptr_clone(_static_version_0);
}
function case_insensitive_strcmp(string1: any | null, string2: any | null): number {
if (typeof string1 === 'string') string1 = cptr_from_string(string1);
if (typeof string2 === 'string') string2 = cptr_from_string(string2);
if (((((cptr_eq(string1, (null)) ? 1 : 0)) || ((cptr_eq(string2, (null)) ? 1 : 0))) ? 1 : 0)) {
return 1;
}
if ((cptr_eq(string1, string2) ? 1 : 0)) {
return 0;
}
for (; (tolower(((string1.buf[string1.off]) & 0xFF)) == tolower(((string2.buf[string2.off]) & 0xFF)) ? 1 : 0); (string1.off++), string2.off++) {
if ((((string1.buf[string1.off]) & 0xFF) == 0 ? 1 : 0)) {
return 0;
}
}
return i32(tolower(((string1.buf[string1.off]) & 0xFF)) - tolower(((string2.buf[string2.off]) & 0xFF)));
}
// BRIDGE: struct-as-class — C17 §6.7.2.1 / C++20 [class]
export class internal_hooks {
allocate: any;
deallocate: any;
reallocate: any;
constructor() {
this.allocate = null;
this.deallocate = null;
this.reallocate = null;
}
}
(internal_hooks as any).__fieldTypes = ["int64","int32","int64"];
(internal_hooks as any).__fieldNames = ["allocate","deallocate","reallocate"];
(internal_hooks as any).__fieldOffsets = [0,8,16];
function internal_malloc(size: number): any | null {
return cptr_clone(malloc(((size) >>> 0)));
}
function internal_free(pointer: any | null): void {
free(pointer);
}
function internal_realloc(pointer: any | null, size: number): any | null {
return cptr_clone(realloc(pointer, ((size) >>> 0)));
}
let global_hooks = Object.assign(new internal_hooks(), { allocate: internal_malloc, deallocate: internal_free, reallocate: internal_realloc });
function cJSON_strdup(string: any | null, hooks: internal_hooks | null): any | null {
let length = ((0) >>> 0);
let copy = null; /* &ref */
if ((cptr_eq(string, (null)) ? 1 : 0)) {
return null;
}
length = strlen(cptr_clone((string))) + 1;
copy = ((__struct_ptr_at(hooks, 0)).allocate(((length) >>> 0)));
if ((cptr_eq(copy, (null)) ? 1 : 0)) {
return null;
}
memcpy(copy, string, ((length) >>> 0));
return cptr_clone(copy);
}
export function cJSON_InitHooks(hooks: cJSON_Hooks | null): void {
if ((hooks == (null) ? 1 : 0)) {
global_hooks.allocate = malloc;
global_hooks.deallocate = free;
global_hooks.reallocate = realloc;
return;
}
global_hooks.allocate = malloc;
if (((__struct_ptr_at(hooks, 0)).malloc_fn != (null) ? 1 : 0)) {
global_hooks.allocate = (__struct_ptr_at(hooks, 0)).malloc_fn;
}
global_hooks.deallocate = free;
if (((__struct_ptr_at(hooks, 0)).free_fn != (null) ? 1 : 0)) {
global_hooks.deallocate = (__struct_ptr_at(hooks, 0)).free_fn;
}
global_hooks.reallocate = null;
if (((((global_hooks.allocate == malloc ? 1 : 0)) && ((global_hooks.deallocate == free ? 1 : 0))) ? 1 : 0)) {
global_hooks.reallocate = realloc;
}
}
function cJSON_New_Item(hooks: internal_hooks | null): cJSON | null {
let node = (new cJSON()); /* &ref */
if (node) {
memset(node, 0, 64);
}
return node;
}
export function cJSON_Delete(item: cJSON | null): void {
let next = null; /* &ref */
while ((item != (null) ? 1 : 0)) {
next = (__struct_ptr_at(item, 0)).next;
if ((((!((__struct_ptr_at(item, 0)).type & 256) ? 1 : 0) && (((__struct_ptr_at(item, 0)).child != (null) ? 1 : 0))) ? 1 : 0)) {
cJSON_Delete((__struct_ptr_at(item, 0)).child);
}
if ((((!((__struct_ptr_at(item, 0)).type & 256) ? 1 : 0) && ((!cptr_eq((__struct_ptr_at(item, 0)).valuestring, (null)) ? 1 : 0))) ? 1 : 0)) {
global_hooks.deallocate((__struct_ptr_at(item, 0)).valuestring);
(__struct_ptr_at(item, 0)).valuestring = null;
}
if ((((!((__struct_ptr_at(item, 0)).type & 512) ? 1 : 0) && ((!cptr_eq((__struct_ptr_at(item, 0)).string, (null)) ? 1 : 0))) ? 1 : 0)) {
global_hooks.deallocate((__struct_ptr_at(item, 0)).string);
(__struct_ptr_at(item, 0)).string = null;
}
global_hooks.deallocate(item);
item = next;
}
}
function get_decimal_point(): number {
return ((46) & 0xFF);
}
// BRIDGE: struct-as-class — C17 §6.7.2.1 / C++20 [class]
export class parse_buffer {
content: any | null;
length: number;
offset: number;
depth: number;
hooks: internal_hooks;
constructor() {
this.content = null;
this.length = 0;
this.offset = 0;
this.depth = 0;
this.hooks = new internal_hooks();
}
}
(parse_buffer as any).__fieldTypes = ["int64","int64","int64","int64","int32"];
(parse_buffer as any).__fieldNames = ["content","length","offset","depth","hooks"];
(parse_buffer as any).__fieldOffsets = [0,8,16,24,32];
function parse_number(item: cJSON | null, input_buffer: parse_buffer | null): cJSON_bool {
let number: number = 0.0;
let after_end: any | null = null;
let number_c_string: any | null = null;
let decimal_point: number = 0;
let i: number = 0;
let number_string_length: number = 0;
let has_decimal_point: cJSON_bool = 0;
let _state = 0;
_sm: while (true) {
switch (_state) {
case 0:
number = 0;
after_end = null; /* &ref */
number_c_string = null;
decimal_point = get_decimal_point();
i = ((0) >>> 0);
number_string_length = ((0) >>> 0);
has_decimal_point = (Math.trunc(+(0)));
if (((((input_buffer == (null) ? 1 : 0)) || ((cptr_eq((__struct_ptr_at(input_buffer, 0)).content, (null)) ? 1 : 0))) ? 1 : 0)) {
return (Math.trunc(+(0)));
}
for (i = ((0) >>> 0); (((((input_buffer != (null) ? 1 : 0)) && ((((((__struct_ptr_at((input_buffer), 0)).offset) >>> 0) + ((i) >>> 0)) < (((__struct_ptr_at((input_buffer), 0)).length) >>> 0) ? 1 : 0))) ? 1 : 0)); (() => { const _t = i; i = u32(i + 1); return _t; })()) {