-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstruct.js
More file actions
1267 lines (1193 loc) · 46.8 KB
/
Copy pathstruct.js
File metadata and controls
1267 lines (1193 loc) · 46.8 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
/*
* Random-access struct encoding/decoding.
*
* Binary format is identical to msgpackr's struct.js:
* 0x20-0x2f record id 0-15 (1-byte header)
* 0x38 8-bit record id follows
* 0x39 16-bit record id follows (LE)
* 0x3a 24-bit record id follows (LE)
* 0x3b 32-bit record id follows (LE)
*
* Layout: [header][fixed-width fields][variable ref section]
* Fixed section: non-queued fields first (in enumeration order), then
* queued object/null/undefined fields.
* Ref section: string bytes first, then msgpack/cbor-encoded object bytes.
* String/object ref fields contain byte offsets relative to start of ref section.
*/
const ASCII = 3;
const NUMBER = 0;
const UTF8 = 2;
const OBJECT_DATA = 1;
const DATE = 16;
const TYPE_NAMES = ['num', 'object', 'string', 'ascii'];
TYPE_NAMES[DATE] = 'date';
const float32Headers = [false, true, true, false, false, true, true, false];
export const RECORD_SYMBOL = Symbol('record-id');
export const SOURCE_SYMBOL = Symbol.for('source');
// Tracks the source being decoded by a nested unpack call so that
// `saveState` can detach it from the parent decoder's buffer state.
let currentSource;
/**
* Called (bound to the decoder) when msgpackr saves its decoder state — e.g.
* during a nested unpack call. If we're in the middle of reading a struct's
* OBJECT_DATA field, slice the lazy struct's bytes so it remains self-contained
* after the parent decoder's globals are clobbered.
*/
export function saveState() {
if (currentSource) {
currentSource.bytes = Uint8Array.prototype.slice.call(currentSource.bytes, currentSource.position, currentSource.bytesEnd);
currentSource.position = 0;
currentSource.bytesEnd = currentSource.bytes.length;
currentSource = null;
}
}
// Multiplier table for float32 significant-digit rounding (matches msgpackr/unpack.js)
export const mult10 = new Array(256);
for (let i = 0; i < 256; i++) {
mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103));
}
let evalSupported;
try { new Function(''); evalSupported = true; } catch (e) { /* sandboxed */ }
let _textDecoder;
try { _textDecoder = new TextDecoder(); } catch (e) { /* not available */ }
// ── UTF-8 encoding helpers ────────────────────────────────────────────────────
const _hasNodeBuffer = typeof Buffer !== 'undefined';
// TextEncoder.encodeInto writes directly into a target buffer (no allocation).
const _encodeInto = (() => {
if (_hasNodeBuffer) return null; // prefer Buffer.utf8Write on Node.js
try {
const te = new TextEncoder();
return te.encodeInto ? (s, buf) => te.encodeInto(s, buf).written : null;
} catch (e) { return null; }
})();
function utf8EncodeFallback(str) {
const bytes = [];
for (let i = 0; i < str.length; i++) {
const c = str.charCodeAt(i);
if (c < 0x80) bytes.push(c);
else if (c < 0x800) bytes.push(c >> 6 | 0xc0, c & 0x3f | 0x80);
else bytes.push(c >> 12 | 0xe0, c >> 6 & 0x3f | 0x80, c & 0x3f | 0x80);
}
return new Uint8Array(bytes);
}
export function readString(src, start, length) {
if (_hasNodeBuffer) {
const b = Buffer.isBuffer(src)
? src
: Buffer.from(src.buffer, src.byteOffset, src.byteLength);
return b.toString('utf8', start, start + length);
}
if (_textDecoder) return _textDecoder.decode(src.subarray(start, start + length));
let s = '';
for (let i = start, end = start + length; i < end; i++) s += String.fromCharCode(src[i]);
return s;
}
function toConstant(code) {
switch (code) {
case 0xf6: return null;
case 0xf7: return undefined;
case 0xf8: return false;
case 0xf9: return true;
}
throw new Error('Unknown constant 0x' + code.toString(16));
}
function withSource(get) {
return function () { return get(this[SOURCE_SYMBOL]); };
}
function createBlankTransition(key, parent) {
return {
key, parent,
enumerationOffset: 0,
ascii0: null, ascii8: null, num8: null,
string16: null, object16: null, num32: null,
float64: null, date64: null,
};
}
// When the typed-structure dictionary reaches maxOwnStructures we stop minting new
// structures/transitions. typedStructs is append-only and pinned on the long-lived
// encoder (records reference structures by recordId), so an unbounded shape space —
// e.g. a wide, sparsely/variably-populated schema — would otherwise grow the
// dictionary + transition trie without limit. `frozen` is passed in (derived from the
// encoding instance's own typedStructs.length, never a shared global) so a re-entrant
// encode on another instance can't flip it; while frozen, a missing transition returns
// undefined so the caller bails and the record falls back to plain encoding.
function createTypeTransition(transition, type, size, frozen) {
const typeName = TYPE_NAMES[type] + (size << 3);
let t = transition[typeName];
if (t) return t;
if (frozen) return undefined;
t = transition[typeName] = Object.create(null);
t.__type = type;
t.__size = size;
t.__parent = transition;
return t;
}
// Unfrozen variant: always mints. Used on the fast path once a queued nested value has
// already been pack()ed — at that point pack() has advanced msgpackr's shared write
// position, so bailing with `return 0` would corrupt the fallback. We must finish the
// encode instead, even if that means minting a (bounded) handful of structures past the
// cap. The cap is still enforced up front, before the first pack().
function forceTypeTransition(transition, type, size) {
const typeName = TYPE_NAMES[type] + (size << 3);
let t = transition[typeName];
if (t) return t;
t = transition[typeName] = Object.create(null);
t.__type = type;
t.__size = size;
t.__parent = transition;
return t;
}
// ── Work-buffer pool (one pair per nesting depth) ─────────────────────────────
//
// Instead of allocating a new Uint8Array for each field value, we write
// directly into pre-allocated work buffers. A per-depth pool means nested
// struct encoding (from encodeNested) uses a separate set of buffers and
// never clobbers the outer call's state.
const INITIAL_FIXED = 4096;
const INITIAL_REFS = 65536;
const _pool = [];
let _depth = 0;
function _getWork() {
let w = _pool[_depth];
if (!w) {
const fb = _hasNodeBuffer ? Buffer.allocUnsafe(INITIAL_FIXED) : new Uint8Array(INITIAL_FIXED);
const rb = _hasNodeBuffer ? Buffer.allocUnsafe(INITIAL_REFS) : new Uint8Array(INITIAL_REFS);
_pool[_depth] = w = {
fixedBuf: fb,
fixedView: new DataView(fb.buffer, fb.byteOffset || 0, INITIAL_FIXED),
refsBuf: rb,
};
}
return w;
}
function _growFixed(w, need) {
const size = Math.max(w.fixedBuf.length * 2, need);
const nb = _hasNodeBuffer ? Buffer.allocUnsafe(size) : new Uint8Array(size);
nb.set(w.fixedBuf.subarray(0, w.fixedBuf.length));
w.fixedBuf = nb;
w.fixedView = new DataView(nb.buffer, nb.byteOffset || 0, size);
}
function _growRefs(w, need) {
const size = Math.max(w.refsBuf.length * 2, w.refsBuf.length + need);
const nb = _hasNodeBuffer ? Buffer.allocUnsafe(size) : new Uint8Array(size);
nb.set(w.refsBuf);
w.refsBuf = nb;
}
// Write a string directly into w.refsBuf at refsPos; return updated refsPos.
function _writeStr(w, refsPos, value) {
const need = value.length * 3;
if (refsPos + need > w.refsBuf.length) _growRefs(w, need);
if (_hasNodeBuffer) return refsPos + w.refsBuf.utf8Write(value, refsPos);
if (_encodeInto) return refsPos + _encodeInto(value, w.refsBuf.subarray(refsPos));
const bytes = utf8EncodeFallback(value);
w.refsBuf.set(bytes, refsPos);
return refsPos + bytes.length;
}
// Try to encode null/undefined into an existing fixed-width slot.
// Returns the matching transition node on success, null on failure.
// Updates _anyPos with the new fixedPos.
let _anyPos = 0;
function _anyTypeFixed(w, transition, fixedPos, value /* -10=null, -9=undefined */) {
let next;
if ((next = transition.ascii8 || transition.num8)) {
w.fixedView.setInt8(fixedPos, value);
_anyPos = fixedPos + 1;
return next;
}
if ((next = transition.string16 || transition.object16)) {
w.fixedView.setInt16(fixedPos, value, true);
_anyPos = fixedPos + 2;
return next;
}
if ((next = transition.num32)) {
w.fixedView.setUint32(fixedPos, 0xe0000100 + value, true);
_anyPos = fixedPos + 4;
return next;
}
if ((next = transition.num64)) {
w.fixedView.setFloat64(fixedPos, NaN, true);
w.fixedView.setInt8(fixedPos, value);
_anyPos = fixedPos + 8;
return next;
}
return null;
}
function _writeHeader(result, recordId, headerSize) {
switch (headerSize) {
case 1: result[0] = recordId + 0x20; break;
case 2: result[0] = 0x38; result[1] = recordId; break;
case 3: {
result[0] = 0x39;
new DataView(result.buffer, result.byteOffset || 0).setUint16(1, recordId, true);
break;
}
case 4: {
new DataView(result.buffer, result.byteOffset || 0).setUint32(0, (recordId << 8) + 0x3a, true);
break;
}
}
}
/**
* Fast path: writes a struct directly into the BaseClass's shared target
* buffer at the given position. Avoids the per-field allocations of the
* standalone writeStruct.
*
* Designed to be assigned to a Packr/Encoder instance as `_writeStruct`.
* The BaseClass's encode pipeline calls it as a method, so `this` is the
* encoder instance (provides `typedStructs`).
*
* @param {object} object
* @param {Uint8Array|Buffer} target - shared encoding buffer
* @param {number} encodingStart - start of this encoding within target
* @param {number} position - current write position in target
* @param {Array} structures - BaseClass's named-records array (unused)
* @param {function} makeRoom - grow target; returns new target
* @param {function} pack - pack a nested value at a given position
* @returns {number} new write position, or 0 to bail (fall back to plain object)
*/
export function writeStructInPlace(object, target, encodingStart, position, structures, makeRoom, pack, structureKnown) {
const packr = this;
let typedStructs = packr.typedStructs || (packr.typedStructs = []);
// structureKnown is set only on the internal layout-retry below: attempt 1 already minted
// this record's structure, so the retry re-encodes a known shape and must not re-apply the
// cap (which could otherwise bail after attempt 1 already packed refs → corrupt fallback).
// `frozen` is a local (from this instance's typedStructs) — never a shared global — so a
// re-entrant encode on another instance (e.g. via an enumerable getter) can't flip it.
const cap = packr.maxOwnStructures ?? Infinity;
const frozen = !structureKnown && typedStructs.length >= cap;
let targetView = target.dataView;
let refsStartPosition = (typedStructs.lastStringStart || 100) + position;
let safeEnd = target.length - 10;
let start = position;
if (position > safeEnd) {
target = makeRoom(position);
targetView = target.dataView;
position -= encodingStart;
start -= encodingStart;
refsStartPosition -= encodingStart;
encodingStart = 0;
safeEnd = target.length - 10;
}
let refOffset, refPosition = refsStartPosition;
let transition = typedStructs.transitions || (typedStructs.transitions = Object.create(null));
let nextId = typedStructs.length;
let headerSize =
nextId < 0xf ? 1 :
nextId < 0xf0 ? 2 :
nextId < 0xf000 ? 3 :
nextId < 0xf00000 ? 4 : 0;
if (headerSize === 0) return 0;
position += headerSize;
const queuedReferences = [];
let usedAscii0 = false;
let keyIndex = 0;
for (let key in object) {
let nextTransition = transition[key];
// Resolve the key transition BEFORE reading the value: when frozen and the key is new we
// bail here, so an enumerable getter isn't invoked during this (failed) struct attempt and
// then again by the plain fallback (which would double-read a side-effecting accessor).
if (!nextTransition) {
if (frozen) return 0;
transition[key] = nextTransition = {
key, parent: transition, enumerationOffset: 0,
ascii0: null, ascii8: null, num8: null,
string16: null, object16: null, num32: null,
float64: null, date64: null,
};
}
let value = object[key];
if (position > safeEnd) {
target = makeRoom(position);
targetView = target.dataView;
position -= encodingStart;
start -= encodingStart;
refsStartPosition -= encodingStart;
refPosition -= encodingStart;
encodingStart = 0;
safeEnd = target.length - 10;
}
switch (typeof value) {
case 'number': {
const number = value;
if (nextId < 200 || !nextTransition.num64) {
if (number >> 0 === number && number < 0x20000000 && number > -0x1f000000) {
if (
number < 0xf6 && number >= 0 &&
(nextTransition.num8 && !(nextId > 200 && nextTransition.num32) ||
number < 0x20 && !nextTransition.num32)
) {
transition = nextTransition.num8 || createTypeTransition(nextTransition, NUMBER, 1, frozen);
target[position++] = number;
} else {
transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4, frozen);
targetView.setUint32(position, number, true);
position += 4;
}
break;
} else if (number < 0x100000000 && number >= -0x80000000) {
targetView.setFloat32(position, number, true);
if (float32Headers[target[position + 3] >>> 5]) {
let xShifted;
if (((xShifted = number * mult10[((target[position + 3] & 0x7f) << 1) | (target[position + 2] >> 7)]) >> 0) === xShifted) {
transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4, frozen);
position += 4;
break;
}
}
}
}
transition = nextTransition.num64 || createTypeTransition(nextTransition, NUMBER, 8, frozen);
targetView.setFloat64(position, number, true);
position += 8;
break;
}
case 'string': {
const strLength = value.length;
refOffset = refPosition - refsStartPosition;
if ((strLength << 2) + refPosition > safeEnd) {
target = makeRoom((strLength << 2) + refPosition);
targetView = target.dataView;
position -= encodingStart;
start -= encodingStart;
refsStartPosition -= encodingStart;
refPosition -= encodingStart;
encodingStart = 0;
safeEnd = target.length - 10;
}
if (strLength > ((0xff00 + refOffset) >> 2)) {
queuedReferences.push(key, value, position - start);
break;
}
let isNotAscii;
let strStart = refPosition;
if (strLength < 0x40) {
let i, c1, c2;
for (i = 0; i < strLength; i++) {
c1 = value.charCodeAt(i);
if (c1 < 0x80) {
target[refPosition++] = c1;
} else if (c1 < 0x800) {
isNotAscii = true;
target[refPosition++] = c1 >> 6 | 0xc0;
target[refPosition++] = c1 & 0x3f | 0x80;
} else if (
(c1 & 0xfc00) === 0xd800 &&
((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00
) {
isNotAscii = true;
c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
i++;
target[refPosition++] = c1 >> 18 | 0xf0;
target[refPosition++] = c1 >> 12 & 0x3f | 0x80;
target[refPosition++] = c1 >> 6 & 0x3f | 0x80;
target[refPosition++] = c1 & 0x3f | 0x80;
} else {
isNotAscii = true;
target[refPosition++] = c1 >> 12 | 0xe0;
target[refPosition++] = c1 >> 6 & 0x3f | 0x80;
target[refPosition++] = c1 & 0x3f | 0x80;
}
}
} else if (_hasNodeBuffer) {
refPosition += target.utf8Write(value, refPosition, target.byteLength - refPosition);
isNotAscii = refPosition - strStart > strLength;
} else if (_encodeInto) {
refPosition += _encodeInto(value, target.subarray(refPosition));
isNotAscii = refPosition - strStart > strLength;
} else {
const bytes = utf8EncodeFallback(value);
target.set(bytes, refPosition);
refPosition += bytes.length;
isNotAscii = bytes.length > strLength;
}
if (refOffset < 0xa0 || (refOffset < 0xf6 && (nextTransition.ascii8 || nextTransition.string8))) {
if (isNotAscii) {
if (!(transition = nextTransition.string8)) {
if (typedStructs.length > 10 && (transition = nextTransition.ascii8)) {
transition.__type = UTF8;
nextTransition.ascii8 = null;
nextTransition.string8 = transition;
pack(null, 0, true); // notify structure update
} else {
transition = createTypeTransition(nextTransition, UTF8, 1, frozen);
}
}
} else if (refOffset === 0 && !usedAscii0) {
usedAscii0 = true;
transition = nextTransition.ascii0 || createTypeTransition(nextTransition, ASCII, 0, frozen);
break; // size=0: don't increment position
} else if (!(transition = nextTransition.ascii8) &&
!(typedStructs.length > 10 && (transition = nextTransition.string8))) {
transition = createTypeTransition(nextTransition, ASCII, 1, frozen);
}
target[position++] = refOffset;
} else {
transition = nextTransition.string16 || createTypeTransition(nextTransition, UTF8, 2, frozen);
targetView.setUint16(position, refOffset, true);
position += 2;
}
break;
}
case 'object': {
if (value) {
if (value.constructor === Date) {
transition = nextTransition.date64 || createTypeTransition(nextTransition, DATE, 8, frozen);
targetView.setFloat64(position, value.getTime(), true);
position += 8;
} else {
queuedReferences.push(key, value, keyIndex);
}
} else {
nextTransition = anyTypeInPlace(nextTransition, position, targetView, -10);
if (nextTransition) {
transition = nextTransition;
position = updatedPosition;
} else {
queuedReferences.push(key, value, keyIndex);
}
}
break;
}
case 'boolean':
transition = nextTransition.num8 || nextTransition.ascii8 || createTypeTransition(nextTransition, NUMBER, 1, frozen);
target[position++] = value ? 0xf9 : 0xf8;
break;
case 'undefined': {
nextTransition = anyTypeInPlace(nextTransition, position, targetView, -9);
if (nextTransition) {
transition = nextTransition;
position = updatedPosition;
} else {
queuedReferences.push(key, value, keyIndex);
}
break;
}
default:
queuedReferences.push(key, value, keyIndex);
}
if (transition === undefined) return 0; // frozen: structure cap reached
keyIndex++;
}
// Cap enforcement for queued (nested-object / null) references. pack() advances msgpackr's
// shared write position and we cannot cleanly bail afterward, so preflight the whole queued
// chain through EXISTING transitions first: if the cap is reached and any field would need a
// new structure, fall back to plain encoding now (return 0) — before touching the shared
// position. Uses a FRESH length read (not the entry-time `frozen`): a getter invoked while
// reading values above may have minted on this same instance since entry.
if (!structureKnown && queuedReferences.length > 0 && typedStructs.length >= cap) {
let t = transition;
for (let i = 0, l = queuedReferences.length; i < l; i += 3) {
// A non-null (object/Date) ref is pack()ed into the shared buffer, advancing
// msgpackr's write position. Its structure variant (object16 vs object32) depends on
// the runtime ref-section offset (inline strings + earlier refs), which we can't know
// before packing — and we can't bail after a pack without corrupting the fallback. So
// under the cap, any record with a packing ref falls back to plain encoding now,
// before any pack(). null/undefined refs don't pack, so they're walked normally.
if (queuedReferences[i + 1] != null) return 0;
const nt = t[queuedReferences[i]];
if (!nt) return 0;
const next = nt.object16; // null/undefined ref → OBJECT_DATA size 2
if (!next) return 0;
t = next;
}
if (t[RECORD_SYMBOL] == null) return 0; // exact structure not yet minted
}
// Past the preflight the chain is known, so no minting happens — except a rare offset
// divergence (a known shape whose ref section now crosses 0xff00 and needs object32 where
// the preflight matched object16). Once a ref is packed we can no longer bail, so we finish
// via the unfrozen forceTypeTransition: a bounded, self-converging overshoot for that one
// record. packedRef keeps the record-id mint from bailing after a pack.
let packedRef = false;
for (let i = 0, l = queuedReferences.length; i < l;) {
let key = queuedReferences[i++];
let value = queuedReferences[i++];
let propertyIndex = queuedReferences[i++];
let nextTransition = transition[key];
if (!nextTransition) {
transition[key] = nextTransition = {
key, parent: transition,
enumerationOffset: propertyIndex - keyIndex,
ascii0: null, ascii8: null, num8: null,
string16: null, object16: null, num32: null,
float64: null, date64: null,
};
}
let newPosition;
if (value) {
let size;
refOffset = refPosition - refsStartPosition;
if (refOffset < 0xff00) {
transition = nextTransition.object16;
if (transition) size = 2;
else if ((transition = nextTransition.object32)) size = 4;
else { transition = forceTypeTransition(nextTransition, OBJECT_DATA, 2); size = 2; }
} else {
transition = nextTransition.object32 || forceTypeTransition(nextTransition, OBJECT_DATA, 4);
size = 4;
}
newPosition = pack(value, refPosition);
packedRef = true;
if (typeof newPosition === 'object') {
// re-allocated buffer — refresh local refs
refPosition = newPosition.position;
targetView = newPosition.targetView;
target = newPosition.target;
refsStartPosition -= encodingStart;
position -= encodingStart;
start -= encodingStart;
encodingStart = 0;
} else {
refPosition = newPosition;
}
if (size === 2) { targetView.setUint16(position, refOffset, true); position += 2; }
else { targetView.setUint32(position, refOffset, true); position += 4; }
} else { // null or undefined
transition = nextTransition.object16 || forceTypeTransition(nextTransition, OBJECT_DATA, 2);
targetView.setInt16(position, value === null ? -10 : -9, true);
position += 2;
}
keyIndex++;
}
let recordId = transition[RECORD_SYMBOL];
if (recordId == null) {
// Flat records (no queued refs) reach here without packing, so the cap is enforced
// cleanly. Records that packed nested refs already passed the preflight (record id
// exists) or are completing a bounded overshoot; either way bailing now would corrupt.
if (!packedRef && packr.typedStructs.length >= (packr.maxOwnStructures ?? Infinity)) return 0;
recordId = packr.typedStructs.length;
const structure = [];
let nextTransition = transition;
let key, type;
while ((type = nextTransition.__type) !== undefined) {
let size = nextTransition.__size;
nextTransition = nextTransition.__parent;
key = nextTransition.key;
let property = [type, size, key];
if (nextTransition.enumerationOffset) property.push(nextTransition.enumerationOffset);
structure.push(property);
nextTransition = nextTransition.parent;
}
structure.reverse();
transition[RECORD_SYMBOL] = recordId;
packr.typedStructs[recordId] = structure;
pack(null, 0, true); // notify structure update
}
switch (headerSize) {
case 1:
if (recordId >= 0x10) return 0;
target[start] = recordId + 0x20;
break;
case 2:
if (recordId >= 0x100) return 0;
target[start] = 0x38;
target[start + 1] = recordId;
break;
case 3:
if (recordId >= 0x10000) return 0;
target[start] = 0x39;
targetView.setUint16(start + 1, recordId, true);
break;
case 4:
if (recordId >= 0x1000000) return 0;
targetView.setUint32(start, (recordId << 8) + 0x3a, true);
break;
}
if (position < refsStartPosition) {
if (refsStartPosition === refPosition) return position; // no refs
// compact: shift ref bytes left to immediately follow fixed section
target.copyWithin(position, refsStartPosition, refPosition);
refPosition += position - refsStartPosition;
typedStructs.lastStringStart = position - start;
} else if (position > refsStartPosition) {
if (refsStartPosition === refPosition) return position; // no refs
// fixed section overflowed our estimate — retry with the corrected size. The structure
// is already minted at this point, so pass structureKnown=true to skip the cap check
// (otherwise a record that became frozen during attempt 1 would bail mid-retry, after
// refs were already packed, and corrupt the fallback).
typedStructs.lastStringStart = position - start;
return writeStructInPlace.call(packr, object, target, encodingStart, start, structures, makeRoom, pack, true);
}
return refPosition;
}
let updatedPosition;
function anyTypeInPlace(transition, position, targetView, value) {
let next;
if ((next = transition.ascii8 || transition.num8)) {
targetView.setInt8(position, value, true);
updatedPosition = position + 1;
return next;
}
if ((next = transition.string16 || transition.object16)) {
targetView.setInt16(position, value, true);
updatedPosition = position + 2;
return next;
}
if ((next = transition.num32)) {
targetView.setUint32(position, 0xe0000100 + value, true);
updatedPosition = position + 4;
return next;
}
if ((next = transition.num64)) {
targetView.setFloat64(position, NaN, true);
targetView.setInt8(position, value);
updatedPosition = position + 8;
return next;
}
updatedPosition = position;
return null;
}
/**
* Encode `object` as a random-access struct (standalone path — used when the
* base encoder doesn't expose the writeStructSlots hook, e.g. cbor-x).
*
* @param {object} object
* @param {function} encodeNested - (value) => Uint8Array, for nested objects
* @param {object} packr - must have .typedStructs array (created if absent)
* @returns {Uint8Array|null}
*/
export function writeStruct(object, encodeNested, packr) {
// Grab work buffers for this nesting depth before incrementing so that
// any encodeNested call (which may re-enter writeStruct) uses the next slot.
const work = _getWork();
_depth++;
try {
return _encode(object, encodeNested, packr, work);
} finally {
_depth--;
}
}
function _encode(object, encodeNested, packr, work) {
let typedStructs = packr.typedStructs || (packr.typedStructs = []);
const cap = packr.maxOwnStructures ?? Infinity;
// Local (not a shared global), recomputed after each encodeNested below since a nested
// encode on this same instance can mint and grow typedStructs.
let frozen = typedStructs.length >= cap;
let transition = typedStructs.transitions || (typedStructs.transitions = Object.create(null));
const nextId = typedStructs.length;
const headerSize =
nextId < 0x10 ? 1 :
nextId < 0xf0 ? 2 :
nextId < 0xf000 ? 3 :
nextId < 0xf00000 ? 4 : 0;
if (headerSize === 0) return null;
let fixedPos = 0;
let refsPos = 0;
const queuedReferences = [];
let usedAscii0 = false;
let keyIndex = 0;
let structureUpdated = false;
for (const key in object) {
let nextTransition = transition[key];
// Resolve the key transition before reading the value, so a frozen miss on a new key bails
// without invoking an enumerable getter that the plain fallback would then read again.
if (!nextTransition) {
if (frozen) return null;
transition[key] = nextTransition = createBlankTransition(key, transition);
}
const value = object[key];
if (fixedPos + 8 > work.fixedBuf.length) _growFixed(work, fixedPos + 8);
switch (typeof value) {
case 'number': {
const number = value;
if (nextId < 200 || !nextTransition.num64) {
if (number >> 0 === number && number < 0x20000000 && number > -0x1f000000) {
if (
number < 0xf6 && number >= 0 &&
(nextTransition.num8 && !(nextId > 200 && nextTransition.num32) ||
number < 0x20 && !nextTransition.num32)
) {
transition = nextTransition.num8 || createTypeTransition(nextTransition, NUMBER, 1, frozen);
work.fixedBuf[fixedPos++] = number;
} else {
transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4, frozen);
work.fixedView.setUint32(fixedPos, number, true);
fixedPos += 4;
}
break;
} else if (number < 0x100000000 && number >= -0x80000000) {
work.fixedView.setFloat32(fixedPos, number, true);
if (float32Headers[work.fixedBuf[fixedPos + 3] >>> 5]) {
let xShifted;
if (((xShifted = number * mult10[((work.fixedBuf[fixedPos + 3] & 0x7f) << 1) | (work.fixedBuf[fixedPos + 2] >> 7)]) >> 0) === xShifted) {
transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4, frozen);
fixedPos += 4;
break;
}
}
}
}
transition = nextTransition.num64 || createTypeTransition(nextTransition, NUMBER, 8, frozen);
work.fixedView.setFloat64(fixedPos, number, true);
fixedPos += 8;
break;
}
case 'string': {
const strStart = refsPos;
refsPos = _writeStr(work, refsPos, value);
const isNotAscii = refsPos - strStart > value.length;
const curOffset = strStart;
if (fixedPos + 2 > work.fixedBuf.length) _growFixed(work, fixedPos + 2);
if (curOffset < 0xa0 || (curOffset < 0xf6 && (nextTransition.ascii8 || nextTransition.string8))) {
if (isNotAscii) {
if (!(transition = nextTransition.string8)) {
if (typedStructs.length > 10 && (transition = nextTransition.ascii8)) {
transition.__type = UTF8;
nextTransition.ascii8 = null;
nextTransition.string8 = transition;
structureUpdated = true;
} else {
transition = createTypeTransition(nextTransition, UTF8, 1, frozen);
}
}
work.fixedBuf[fixedPos++] = curOffset;
} else if (curOffset === 0 && !usedAscii0) {
usedAscii0 = true;
transition = nextTransition.ascii0 || createTypeTransition(nextTransition, ASCII, 0, frozen);
// size=0: no fixed byte written
} else {
if (!(transition = nextTransition.ascii8) &&
!(typedStructs.length > 10 && (transition = nextTransition.string8)))
transition = createTypeTransition(nextTransition, ASCII, 1, frozen);
work.fixedBuf[fixedPos++] = curOffset;
}
} else {
transition = nextTransition.string16 || createTypeTransition(nextTransition, UTF8, 2, frozen);
work.fixedView.setUint16(fixedPos, curOffset, true);
fixedPos += 2;
}
break;
}
case 'object': {
if (value && value.constructor === Date) {
transition = nextTransition.date64 || createTypeTransition(nextTransition, DATE, 8, frozen);
work.fixedView.setFloat64(fixedPos, value.getTime(), true);
fixedPos += 8;
} else if (value) {
queuedReferences.push(key, value, keyIndex);
} else {
// null
const any = _anyTypeFixed(work, nextTransition, fixedPos, -10);
if (any !== null) {
transition = any;
fixedPos = _anyPos;
} else {
queuedReferences.push(key, null, keyIndex);
}
}
break;
}
case 'boolean':
transition = nextTransition.num8 || nextTransition.ascii8 ||
createTypeTransition(nextTransition, NUMBER, 1, frozen);
work.fixedBuf[fixedPos++] = value ? 0xf9 : 0xf8;
break;
case 'undefined': {
const any = _anyTypeFixed(work, nextTransition, fixedPos, -9);
if (any !== null) {
transition = any;
fixedPos = _anyPos;
} else {
queuedReferences.push(key, undefined, keyIndex);
}
break;
}
default:
queuedReferences.push(key, value, keyIndex);
break;
}
if (transition === undefined) return null; // frozen: structure cap reached
keyIndex++;
}
// Queued objects/null/undefined — their fixed bytes (offsets into ref section)
// follow the primitive fixed bytes.
for (let i = 0, l = queuedReferences.length; i < l;) {
const key = queuedReferences[i++];
const value = queuedReferences[i++];
const propertyIndex = queuedReferences[i++];
let nextTransition = transition[key];
if (!nextTransition) {
if (frozen) return null;
transition[key] = nextTransition = {
key,
parent: transition,
enumerationOffset: propertyIndex - keyIndex,
ascii0: null, ascii8: null, num8: null,
string16: null, object16: null, num32: null,
float64: null, date64: null,
};
}
if (fixedPos + 4 > work.fixedBuf.length) _growFixed(work, fixedPos + 4);
if (value != null) {
const encoded = encodeNested(value);
// encodeNested may have minted on this same instance — refresh the cap state so a
// later missing transition still bails instead of minting past the cap.
frozen = typedStructs.length >= cap;
const curOffset = refsPos;
if (refsPos + encoded.length > work.refsBuf.length) _growRefs(work, encoded.length);
work.refsBuf.set(encoded, refsPos);
refsPos += encoded.length;
let size;
if (curOffset < 0xff00) {
transition = nextTransition.object16;
if (transition) size = 2;
else if ((transition = nextTransition.object32)) size = 4;
else { transition = createTypeTransition(nextTransition, OBJECT_DATA, 2, frozen); size = 2; }
} else {
transition = nextTransition.object32 || createTypeTransition(nextTransition, OBJECT_DATA, 4, frozen);
size = 4;
}
if (size === 2) { work.fixedView.setUint16(fixedPos, curOffset, true); fixedPos += 2; }
else { work.fixedView.setUint32(fixedPos, curOffset, true); fixedPos += 4; }
} else {
// null or undefined sentinel
transition = nextTransition.object16 || createTypeTransition(nextTransition, OBJECT_DATA, 2, frozen);
work.fixedView.setInt16(fixedPos, value === null ? -10 : -9, true);
fixedPos += 2;
}
if (transition === undefined) return null; // frozen: structure cap reached
keyIndex++;
}
// Build/retrieve structure definition from the transition chain.
let recordId = transition[RECORD_SYMBOL];
if (recordId == null) {
// Re-check the cap with a fresh length read: nested encodeNested() calls may have
// appended structures since entry, so this keeps typedStructs.length a hard bound.
if (typedStructs.length >= cap) return null;
recordId = typedStructs.length;
const structure = [];
let t = transition;
while (t.__type !== undefined) {
const type = t.__type;
const size = t.__size;
const keyTrans = t.__parent;
const entry = [type, size, keyTrans.key];
if (keyTrans.enumerationOffset) entry.push(keyTrans.enumerationOffset);
structure.push(entry);
t = keyTrans.parent;
}
structure.reverse();
transition[RECORD_SYMBOL] = recordId;
typedStructs[recordId] = structure;
structureUpdated = true;
}
if (structureUpdated && packr._onStructureAdded) packr._onStructureAdded();
// Assemble: [header][fixedSection][refsSection] — one allocation total.
const totalSize = headerSize + fixedPos + refsPos;
const result = new Uint8Array(totalSize);
_writeHeader(result, recordId, headerSize);
result.set(work.fixedBuf.subarray(0, fixedPos), headerSize);
if (refsPos > 0) result.set(work.refsBuf.subarray(0, refsPos), headerSize + fixedPos);
return result;
}
/**
* Decode a random-access struct.
*
* Designed to be assigned to a Packr/Unpackr instance as `_readStruct`. Call
* via `unpackr._readStruct(src, pos, end)` so that `this === unpackr`, or
* via `readStruct.call(unpackr, src, pos, end)` from the standalone path.
*
* @param {Uint8Array} src
* @param {number} position - byte offset of the struct header in src
* @param {number} srcEnd - exclusive end byte
* @returns lazy object with property getters
*/
export function readStruct(src, position, srcEnd) {
const unpackr = this;
let recordId = src[position++] - 0x20;
if (recordId >= 24) {
switch (recordId) {
case 24: recordId = src[position++]; break;
case 25: recordId = src[position++] + (src[position++] << 8); break;
case 26: recordId = src[position++] + (src[position++] << 8) + (src[position++] << 16); break;
case 27: recordId = src[position++] + (src[position++] << 8) + (src[position++] << 16) + (src[position++] << 24); break;
}
}
let structure = unpackr.typedStructs && unpackr.typedStructs[recordId];
if (!structure) {
if (typeof unpackr._loadStructures === 'function') {
// getStructures reads from the DB into the same reusable buffer — copy src first
src = Uint8Array.prototype.slice.call(src, 0, srcEnd);
unpackr._loadStructures();
structure = unpackr.typedStructs && unpackr.typedStructs[recordId];
}
if (!structure) throw new Error('Could not find typed structure ' + recordId);
}
if (!structure.construct) {
structure.construct = function LazyObject() {};
structure.fullConstruct = function LoadedObject() {};
structure.fullConstruct.prototype = unpackr.structPrototype || {};
const prototype = structure.construct.prototype = unpackr.structPrototype
? Object.create(unpackr.structPrototype) : {};
const properties = [];
let currentOffset = 0;
let lastRefProperty;
for (let i = 0, l = structure.length; i < l; i++) {
let [type, size, key, enumerationOffset] = structure[i];
if (key === '__proto__') key = '__proto_';
const property = { key, offset: currentOffset };
if (enumerationOffset) properties.splice(i + enumerationOffset, 0, property);
else properties.push(property);
let getRef;
switch (size) {
case 0: getRef = () => 0; break;
case 1:
getRef = (src, pos) => {
const v = src.bytes[pos + property.offset];
return v >= 0xf6 ? toConstant(v) : v;