capnstruct 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1076 @@
1
+ import { generateGo, generateRust, toGoStruct, toRustReprC, } from './codegen.js';
2
+ export { generateGo, generateRust, toGoStruct, toRustReprC, };
3
+ const textDecoder = new TextDecoder();
4
+ const textEncoder = new TextEncoder();
5
+ const oob = () => {
6
+ throw new RangeError('Out of bounds');
7
+ };
8
+ const al = (x, a) => (x + a - 1) & ~(a - 1);
9
+ const u8s = (d, o = 0, l = d.byteLength - o) => new Uint8Array(d.buffer, d.byteOffset + o, l);
10
+ const N = Number;
11
+ const chkLen = (n) => {
12
+ if (!N.isInteger(n) || n < 0)
13
+ oob();
14
+ };
15
+ let sBuf = new ArrayBuffer(65536), sDv = new DataView(sBuf), sU8 = new Uint8Array(sBuf), tail = 0;
16
+ function hid(value) {
17
+ return { value, writable: true, enumerable: false, configurable: true };
18
+ }
19
+ const BASE_DESCS = Object.fromEntries('_d _b _o _m _a _ws _tl _dead _dirty'.split(' ').map((k) => [k, hid()]));
20
+ const dvP = DataView.prototype;
21
+ function prim(type) {
22
+ const c = type[0], bits = +type.slice(1) || 8, size = bits >> 3, float = c === 'f', big = size === 8 && !float, m = (float ? 'Float' : (big ? 'Big' : '') + (c === 'i' ? 'Int' : 'Uint')) + bits, g = dvP['get' + m], s = dvP['set' + m];
23
+ return {
24
+ kind: 'primitive',
25
+ type,
26
+ rustType: (type === 'f16' ? 'u16' : type),
27
+ size,
28
+ align: size,
29
+ signed: c === 'i' || float,
30
+ float,
31
+ bigint: big,
32
+ _C: globalThis[m + 'Array'] ?? Uint16Array,
33
+ _g: (d, o) => g.call(d, o, true),
34
+ _s: (d, o, v) => s.call(d, o, big ? BigInt(v) : N(v), true),
35
+ };
36
+ }
37
+ /** Unsigned 8-bit integer (`0..255`, 1 byte, 1-byte aligned). */
38
+ export const u8 = /* @__PURE__ */ prim('u8');
39
+ /** Signed 8-bit integer (`-128..127`, 1 byte, 1-byte aligned). */
40
+ export const i8 = /* @__PURE__ */ prim('i8');
41
+ /** Little-endian unsigned 16-bit integer (`0..65535`, 2 bytes, 2-byte aligned). */
42
+ export const u16 = /* @__PURE__ */ prim('u16');
43
+ /** Little-endian signed 16-bit integer (`-32768..32767`, 2 bytes, 2-byte aligned). */
44
+ export const i16 = /* @__PURE__ */ prim('i16');
45
+ /** Little-endian unsigned 32-bit integer (4 bytes, 4-byte aligned). */
46
+ export const u32 = /* @__PURE__ */ prim('u32');
47
+ /** Little-endian signed 32-bit integer (4 bytes, 4-byte aligned). */
48
+ export const i32 = /* @__PURE__ */ prim('i32');
49
+ /** Little-endian unsigned 64-bit integer (`bigint`, 8 bytes, 8-byte aligned). */
50
+ export const u64 = /* @__PURE__ */ prim('u64');
51
+ /** Little-endian signed 64-bit integer (`bigint`, 8 bytes, 8-byte aligned). */
52
+ export const i64 = /* @__PURE__ */ prim('i64');
53
+ /** IEEE 754 16-bit half-precision float (2 bytes, 2-byte aligned). */
54
+ export const f16 = /* @__PURE__ */ prim('f16');
55
+ /** IEEE 754 32-bit float (4 bytes, 4-byte aligned). */
56
+ export const f32 = /* @__PURE__ */ prim('f32');
57
+ /** IEEE 754 64-bit float (8 bytes, 8-byte aligned). */
58
+ export const f64 = /* @__PURE__ */ prim('f64');
59
+ /** 1-byte boolean (`0` or `1`, 1-byte aligned). */
60
+ export const bool = {
61
+ ... /* @__PURE__ */prim('bool'),
62
+ _g: (d, o) => d.getUint8(o) !== 0,
63
+ _s: (d, o, v) => d.setUint8(o, v ? 1 : 0),
64
+ };
65
+ /** Inline fixed-length null-padded UTF-8 string `[u8; N]` (`align: 1, size: length`) with zero tail indirection. */
66
+ export function fixedStr(length) {
67
+ return {
68
+ ...fixedBytes(length),
69
+ type: 'fixedStr',
70
+ _g(d, o) {
71
+ let end = 0;
72
+ while (end < length && d.getUint8(o + end))
73
+ end++;
74
+ return textDecoder.decode(u8s(d, o, end));
75
+ },
76
+ _s(d, o, v) {
77
+ const u = u8s(d, o, length);
78
+ u.fill(0);
79
+ textEncoder.encodeInto(String(v), u);
80
+ },
81
+ };
82
+ }
83
+ /** Inline fixed-length byte array `[u8; N]` (`align: 1, size: length`) read as a zero-copy `Uint8Array`. */
84
+ export function fixedBytes(length) {
85
+ chkLen(length);
86
+ return {
87
+ kind: 'primitive',
88
+ type: 'fixedBytes',
89
+ length,
90
+ size: length,
91
+ align: 1,
92
+ rustType: `[u8; ${length}]`,
93
+ _C: undefined,
94
+ _g: (d, o) => u8s(d, o, length),
95
+ _s(d, o, v) {
96
+ const u = u8s(d, o, length);
97
+ u.fill(0);
98
+ if (v)
99
+ u.set(ArrayBuffer.isView(v) ? u8s(v, 0, Math.min(v.byteLength, length)) : Array.from(v).slice(0, length));
100
+ },
101
+ };
102
+ }
103
+ /** Maps an inline sentinel value (e.g. `-32768` for `i16` or `NaN` for `f32`) to `null` in JS with 0 extra wire bytes. */
104
+ export function sentinel(primDesc, nullValue) {
105
+ return {
106
+ ...primDesc,
107
+ nullable: true,
108
+ _null: nullValue,
109
+ _C: undefined,
110
+ _g: (d, o) => { const v = primDesc._g(d, o); return Object.is(v, nullValue) ? null : v; },
111
+ _s: (d, o, v) => primDesc._s(d, o, (v ?? nullValue)),
112
+ };
113
+ }
114
+ /** Alias for `sentinel(primDesc, nullValue)`. */
115
+ export const nullable = sentinel;
116
+ export function scaled(primDesc, factor, nullOpt) {
117
+ const nv = typeof nullOpt === 'number' ? nullOpt : nullOpt?.null;
118
+ return {
119
+ ...sentinel(primDesc, nv),
120
+ type: 'f64',
121
+ float: true,
122
+ nullable: (nv !== undefined),
123
+ _g: (d, o) => {
124
+ const r = primDesc._g(d, o);
125
+ return Object.is(r, nv) ? null : r / factor;
126
+ },
127
+ _s: (d, o, v) => primDesc._s(d, o, v == null ? (nv ?? 0) : Math.round(+v * factor)),
128
+ };
129
+ }
130
+ /** Variable-length UTF-8 string stored in the tail arena via an 8-byte `[u32 off, u32 len]` descriptor. */
131
+ export const str = {
132
+ kind: 'str',
133
+ size: 8,
134
+ align: 4,
135
+ rustType: 'CapnStr',
136
+ };
137
+ export function fixedArray(element, length) {
138
+ chkLen(length);
139
+ return {
140
+ kind: 'array',
141
+ element,
142
+ length,
143
+ size: element.size * length,
144
+ align: element.align,
145
+ rustType: `[${element.rustType}; ${length}]`,
146
+ };
147
+ }
148
+ /** Alias for `fixedArray(element, length)`. */
149
+ export const array = fixedArray;
150
+ /** Variable-length slice `CapnSlice<T>` stored in the tail arena via an 8-byte `[u32 off, u32 len]` descriptor. */
151
+ const _reg = {};
152
+ function ptrDesc(kind, target) {
153
+ const getEl = () => _reg[target] ?? (typeof target === 'function' ? target() : target);
154
+ return {
155
+ kind,
156
+ get element() { return getEl(); },
157
+ size: 8,
158
+ align: 4,
159
+ get rustType() {
160
+ return `Capn${kind === 'ref' ? 'Ref' : 'Slice'}<${getEl().rustType}>`;
161
+ },
162
+ };
163
+ }
164
+ export function slice(element, kind = 'slice') { return ptrDesc(kind, element); }
165
+ /** Alias for `slice(element)`. */
166
+ export const list = slice;
167
+ export function ref(target) { return ptrDesc('ref', target); }
168
+ function ensureScratch(minBytes) {
169
+ if (minBytes > sBuf.byteLength) {
170
+ const nb = new ArrayBuffer(Math.max(minBytes, sBuf.byteLength * 2));
171
+ sDv = new DataView((sBuf = nb));
172
+ const nu = new Uint8Array(nb);
173
+ nu.set(sU8);
174
+ sU8 = nu;
175
+ }
176
+ }
177
+ function growMem(m, end) {
178
+ if (end > m.buffer.byteLength)
179
+ m.grow(Math.ceil((end - m.buffer.byteLength) / 65536));
180
+ }
181
+ function resolveSource(s, byteOffset = 0) {
182
+ const v = ArrayBuffer.isView(s), m = !v && s?.buffer ? s : null, b = v ? s.buffer : m ? m.buffer : s, len = v ? s.byteLength : b.byteLength;
183
+ if (byteOffset < 0 || byteOffset > len)
184
+ oob();
185
+ return {
186
+ d: m && '_d' in m ? m.sync()._d : new DataView(b, v ? s.byteOffset : 0, len),
187
+ b: v ? s.byteOffset : 0,
188
+ o: byteOffset,
189
+ max: len - byteOffset,
190
+ m,
191
+ };
192
+ }
193
+ function defVal(desc, plain) {
194
+ const d = new DataView(new ArrayBuffer(desc.size));
195
+ return readVal({ def: desc, _d: d, _b: 0, _o: 0, _ws: desc.size, _m: null, _k: () => d }, desc, 0, plain);
196
+ }
197
+ function allocTail(v, bytes, align) {
198
+ const root = v._a ?? v, m = root._m;
199
+ if (m && '_u8' in m) {
200
+ const p = m._alloc(bytes, align, true);
201
+ if (root._tl !== undefined && m.offset > root._tl)
202
+ root._tl = m.offset;
203
+ v._d = root._d = m._d;
204
+ return p;
205
+ }
206
+ const d = root._k(), cur = Math.max(root._tl ?? root._o + al(root.byteLength, 8), m?.offset ?? 0), p = al(cur, align), end = p + bytes;
207
+ if (end > d.byteLength) {
208
+ if (m) {
209
+ growMem(m, end);
210
+ root._d = new DataView(m.buffer);
211
+ }
212
+ else {
213
+ const nb = new ArrayBuffer(Math.max(al(end, 8), d.byteLength * 2, 64));
214
+ new Uint8Array(nb).set(u8s(d, 0, cur));
215
+ root._d = new DataView(nb);
216
+ }
217
+ v._d = root._d;
218
+ }
219
+ else if (bytes) {
220
+ u8s(d, p, bytes).fill(0);
221
+ }
222
+ root._tl = end;
223
+ if (m)
224
+ m.offset = end;
225
+ return p;
226
+ }
227
+ function mutVar(v, off, base, count, elSize, align) {
228
+ const bytes = count * elSize;
229
+ if (!v) {
230
+ const st = count ? al(tail, align) : tail;
231
+ ensureScratch((tail = st + bytes) + 64);
232
+ sU8.fill(0, st, tail);
233
+ setDesc(off, count ? st - base : 0, count);
234
+ return st;
235
+ }
236
+ const root = v._a ?? v, d = v._k(), oldP = d.getUint32(off, true), oldB = d.getUint32(off + 4, true) * elSize, st0 = base + oldP, inTail = oldP > 0 && st0 >= root._o + root.byteLength, atTip = inTail && oldB > 0 && st0 + oldB === (root._tl ?? root._o + root.byteLength);
237
+ let st = st0;
238
+ if (inTail && bytes <= oldB) {
239
+ if (atTip)
240
+ root._tl = st0 + bytes;
241
+ if (oldB > bytes)
242
+ root._dead = (root._dead ?? 0) + (oldB - bytes);
243
+ }
244
+ else {
245
+ if (atTip && !root._m)
246
+ root._tl = st0;
247
+ else if (inTail && oldB)
248
+ root._dead = (root._dead ?? 0) + oldB;
249
+ st = allocTail(root, bytes, align);
250
+ if (root.def && off === root._b + root.def._fv && st - base !== al(root.byteLength, 8))
251
+ root._dirty = true;
252
+ }
253
+ if (bytes)
254
+ u8s(root._d, st, bytes).fill(0);
255
+ setDesc(off, count ? st - base : 0, count, root._d);
256
+ return st;
257
+ }
258
+ function upgradeView(v) {
259
+ if (v._ws < v.def.size)
260
+ (v._a ?? v).compact();
261
+ }
262
+ let _budget = 0;
263
+ let _rSeen = null;
264
+ let _wSeen = null;
265
+ let _wActive = null;
266
+ let _wFix = null;
267
+ function readVal(v, desc, off, plain) {
268
+ const d = v._k(), k = desc.kind;
269
+ if (k === 'primitive') {
270
+ const r = desc._g(d, off);
271
+ return plain && r instanceof Uint8Array ? Array.from(r) : r;
272
+ }
273
+ const minP = v._o === v._b ? v._o + v._ws : v._b;
274
+ if (k === 'str') {
275
+ const p = v._b + d.getUint32(off, true), l = d.getUint32(off + 4, true);
276
+ if (!l)
277
+ return '';
278
+ if (p < minP || p + l > d.byteLength || (plain && (_budget -= l) < 0))
279
+ oob();
280
+ return textDecoder.decode(u8s(d, p, l));
281
+ }
282
+ if (k === 'array' || k === 'slice' || k === 'ref') {
283
+ const el = desc.element, sz = el.size, n = k === 'array' ? desc.length : d.getUint32(off + 4, true);
284
+ let p = off;
285
+ if (k !== 'array') {
286
+ if (!n && k === 'ref')
287
+ return null;
288
+ p = n ? v._b + d.getUint32(off, true) : v._b;
289
+ const bl = (k === 'ref' ? 1 : n) * sz, inTbl = el === v.def && p >= v._b && p < minP && (p - v._b) % (v._ws || v.def.size) === 0;
290
+ if (n && ((!inTbl && p < minP) || p + bl > d.byteLength || (!inTbl && p < off + 8 && p + bl > off)))
291
+ oob();
292
+ }
293
+ if (k === 'ref')
294
+ return readVal(v, el, p, plain);
295
+ const tot = d.byteOffset + p;
296
+ if (!plain && el.kind === 'primitive' && el._C && el.type !== 'bool' && tot % sz === 0)
297
+ return new el._C(d.buffer, tot, n);
298
+ if (!plain && el.kind === 'struct') {
299
+ const sav = new StructArrayView(el, d, p, n, v._b);
300
+ sav._m = v._m;
301
+ sav._a = v._a ?? v;
302
+ return sav;
303
+ }
304
+ if (plain && (_budget -= n * sz) < 0)
305
+ oob();
306
+ return Array.from({ length: n }, (_, i) => readVal(v, el, p + i * sz, plain));
307
+ }
308
+ if (!plain) {
309
+ if (desc === v.def && v === v._a?._c) {
310
+ v._o = off;
311
+ return v;
312
+ }
313
+ const nv = new desc._V(d, v._b, off, v._m);
314
+ nv._ws = desc === v.def ? v._ws : desc.size;
315
+ nv._a = v._a ?? v;
316
+ return nv;
317
+ }
318
+ const prev = _rSeen?.get(off);
319
+ if (prev)
320
+ return prev;
321
+ const ws = desc === v.def ? (v._ws ?? desc.size) : desc.size;
322
+ if ((_budget -= ws) < 0)
323
+ oob();
324
+ const out = {};
325
+ _rSeen?.set(off, out);
326
+ for (const f of desc.fieldList) {
327
+ out[f.name] =
328
+ f.offset + f.size > ws
329
+ ? defVal(f.desc, true)
330
+ : readVal(v, f.desc, off + f.offset, true);
331
+ }
332
+ return out;
333
+ }
334
+ function readPlain(v, o = v._o, multi = false) {
335
+ _budget = Math.max(v._k().byteLength * 8, 65536);
336
+ _rSeen = new Map();
337
+ try {
338
+ return multi
339
+ ? Array.from({ length: v.length }, (_, i) => readVal(v, v.def, o + i * v.stride, true))
340
+ : readVal(v, v.def, o, true);
341
+ }
342
+ finally {
343
+ _rSeen = null;
344
+ }
345
+ }
346
+ function setDesc(off, ptr, len, d = sDv) {
347
+ d.setUint32(off, ptr, true);
348
+ d.setUint32(off + 4, len, true);
349
+ }
350
+ function writeVal(v, desc, val, base, off) {
351
+ if (val === undefined || (val === null && desc.kind !== 'ref' && desc._null === undefined))
352
+ return;
353
+ const top = _wSeen === null && desc.kind !== 'primitive' && desc.kind !== 'str';
354
+ if (top) {
355
+ _wSeen = new Map();
356
+ _wActive = new Set();
357
+ _wFix = [];
358
+ }
359
+ try {
360
+ let d = v ? v._k() : sDv;
361
+ const k = desc.kind;
362
+ if (k === 'primitive') {
363
+ desc._s(d, off, val);
364
+ }
365
+ else if (k === 'str') {
366
+ const b = textEncoder.encode(String(val)), st = mutVar(v, off, base, b.byteLength, 1, 1);
367
+ u8s(v ? v._k() : sDv, st, b.byteLength).set(b);
368
+ }
369
+ else if (k === 'ref') {
370
+ const el = desc.element;
371
+ if (val === null)
372
+ mutVar(v, off, base, 0, el.size, el.align);
373
+ else {
374
+ const sv = val instanceof MemView && val._k().buffer === d.buffer && val._d.byteOffset === d.byteOffset
375
+ ? val._o
376
+ : _wSeen?.get(val);
377
+ if (sv !== undefined)
378
+ setDesc(off, sv - base, 1, d);
379
+ else
380
+ writeVal(v, el, val, base, mutVar(v, off, base, 1, el.size, el.align));
381
+ }
382
+ }
383
+ else if (k === 'array' || k === 'slice') {
384
+ const el = desc.element, isSav = val instanceof StructArrayView, isRaw = el.kind === 'struct' && el._fv < 0 && ArrayBuffer.isView(val), src = isSav || isRaw || 'length' in val ? val : Array.from(val), rawLen = isRaw ? (val.byteLength / el.size) | 0 : src.length, n = k === 'array' ? desc.length : rawLen, cp = Math.min(n, rawLen) * el.size, st = k === 'slice' ? mutVar(v, off, base, n, el.size, el.align) : off;
385
+ d = v ? v._k() : sDv;
386
+ if (v && k !== 'slice' && n)
387
+ u8s(d, st, n * el.size).fill(0);
388
+ const sb = isRaw || (el.kind === 'primitive' && el._C && val instanceof el._C)
389
+ ? u8s(val, 0, cp)
390
+ : isSav && el._fv < 0 && val.stride === el.size && val._ws === el.size
391
+ ? u8s(val._k(), val._o, cp)
392
+ : null;
393
+ if (sb) {
394
+ if (cp)
395
+ u8s(d, st, cp).set(sb);
396
+ }
397
+ else {
398
+ const m = Math.min(n, src.length);
399
+ if (el.kind === 'struct' && _wSeen && !isSav)
400
+ for (let i = 0; i < m; i++) {
401
+ const it = src[i];
402
+ if (it && typeof it === 'object' && !Array.isArray(it) && !_wSeen.has(it))
403
+ _wSeen.set(it, st + i * el.size);
404
+ }
405
+ const savCur = isSav ? val._mv(0) : null;
406
+ for (let i = 0; i < m; i++)
407
+ writeVal(v, el, savCur ? val._mv(i, savCur) : src[i], base, st + i * el.size);
408
+ }
409
+ if (el._null !== undefined)
410
+ for (let i = Math.min(n, rawLen); i < n; i++)
411
+ el._s(d, st + i * el.size, null);
412
+ }
413
+ else if (k === 'struct') {
414
+ const rec = val;
415
+ const isTuple = Array.isArray(rec);
416
+ const trackObj = Boolean(rec && typeof rec === 'object' && !isTuple && !(rec instanceof StructViewBase));
417
+ if (trackObj) {
418
+ if (_wActive?.has(rec)) {
419
+ _wFix.push([off, _wSeen.get(rec), desc.size]);
420
+ return;
421
+ }
422
+ if (_wSeen && !_wSeen.has(rec))
423
+ _wSeen.set(rec, off);
424
+ _wActive?.add(rec);
425
+ }
426
+ if (v && v._ws < desc.size)
427
+ upgradeView(v);
428
+ for (let i = 0; i < desc.fieldList.length; i++) {
429
+ const f = desc.fieldList[i], fv = isTuple ? rec[i] : rec[f.name];
430
+ if (fv !== undefined) {
431
+ writeVal(v, f.desc, fv, base, off + f.offset);
432
+ }
433
+ else if ((!v || off !== v._o) && f.desc._null !== undefined) {
434
+ f.desc._s(v ? v._k() : sDv, off + f.offset, null);
435
+ }
436
+ else if (!v && off === base && off + f.offset === desc._fv) {
437
+ setDesc(off + f.offset, tail - base, 0);
438
+ }
439
+ }
440
+ if (trackObj)
441
+ _wActive?.delete(rec);
442
+ }
443
+ }
444
+ finally {
445
+ if (top) {
446
+ const dEnd = v ? v._k() : sDv;
447
+ for (const [dst, src, sz] of _wFix)
448
+ u8s(dEnd, dst, sz).set(u8s(dEnd, src, sz));
449
+ _wSeen = _wActive = _wFix = null;
450
+ }
451
+ }
452
+ }
453
+ function initNulls(def, d, o, n = 1, st = def.size) {
454
+ for (const f of def.fieldList)
455
+ if (f.desc._null !== undefined)
456
+ for (let i = 0; i < n; i++)
457
+ f.desc._s(d, o + i * st + f.offset, null);
458
+ }
459
+ class MemView {
460
+ /** @internal */
461
+ _set(d, b, o, m) {
462
+ this._d = d;
463
+ this._b = b;
464
+ this._o = o;
465
+ this._m = m;
466
+ return this;
467
+ }
468
+ /** @internal */
469
+ _k() {
470
+ const a = this._a;
471
+ if (a)
472
+ return (this._d = a._k());
473
+ const m = this._m;
474
+ if (m) {
475
+ const b = (m.memory ?? m).buffer ?? m._buf;
476
+ if (b !== this._d.buffer)
477
+ this._d = m.sync ? m.sync()._d : new DataView(b);
478
+ }
479
+ return this._d;
480
+ }
481
+ /** Underlying `ArrayBuffer` (automatically re-bound if backed by a growing `WebAssembly.Memory` or `WasmArena`). */
482
+ get buffer() {
483
+ return this._k().buffer;
484
+ }
485
+ /** Byte offset of this view inside `buffer`. */
486
+ get byteOffset() {
487
+ return this._k().byteOffset + this._o;
488
+ }
489
+ /** Total active + dead bytes occupied by this view's fixed table and tail arena. */
490
+ get usedByteLength() {
491
+ const r = this._a ?? this;
492
+ return r._tl !== undefined ? Math.max(r.byteLength, r._tl - r._o) : r.byteLength;
493
+ }
494
+ /** Dead bytes in the tail arena reclaimable via `.compact()`. */
495
+ get deadByteLength() {
496
+ const r = this._a ?? this;
497
+ return r._dead ?? 0;
498
+ }
499
+ /** Ratio (`0..1`) of dead tail bytes to total used bytes. */
500
+ get compactionRatio() {
501
+ const used = this.usedByteLength;
502
+ return used > 0 ? Math.min(1, this.deadByteLength / used) : 0;
503
+ }
504
+ /** Returns a structured inspection summary (`{ schema, stride, rowCount, usedByteLength, deadByteLength, compactionRatio, data }`). */
505
+ toDebugObject() {
506
+ const a = this;
507
+ return {
508
+ schema: this.def.rustType,
509
+ stride: a.stride ?? this.def.size,
510
+ rowCount: a.length ?? 1,
511
+ usedByteLength: this.usedByteLength,
512
+ deadByteLength: this.deadByteLength,
513
+ compactionRatio: this.compactionRatio,
514
+ data: a.toJSON(),
515
+ };
516
+ }
517
+ /** Re-packs only live fields and tail data into a tight `Uint8Array` and rebinds this view in-place. */
518
+ compact() {
519
+ const a = this, isArr = 'length' in a, p = pack(this.def, (isArr ? a.toJSON() : [a.toJSON()])), o0 = this._o, sz = this.def.size;
520
+ this.byteLength = (isArr ? a.length : 1) * sz;
521
+ this._tl = p.byteLength;
522
+ this._ws = sz;
523
+ this._dead = 0;
524
+ this._dirty = false;
525
+ this._set(new DataView(p.buffer, p.byteOffset, p.byteLength), 0, 0, null);
526
+ if (isArr) {
527
+ a.stride = sz;
528
+ a._cap = a.length;
529
+ for (const pv of [a._c, ...(a._p ?? [])])
530
+ if (pv) {
531
+ pv._set(this._d, 0, pv._o - o0, a);
532
+ pv._ws = sz;
533
+ }
534
+ }
535
+ return p;
536
+ }
537
+ /** Wire-ready `Uint8Array` view over the underlying bytes (automatically compacts dead tail bytes if dirty). */
538
+ get bytes() {
539
+ if (this._dirty || this._dead || (this.def._fv >= 0 && this._b !== this._o))
540
+ return this.compact();
541
+ const d = this._k(), rawEnd = Math.max(this.byteLength, (this._tl ?? this._o + this.byteLength) - this._o), end = !this._m && this._tl !== undefined ? Math.min(d.byteLength - this._o, al(rawEnd, 8)) : rawEnd;
542
+ if (this.byteLength && this.def._fv >= 0) {
543
+ const ts = al(this.byteLength, 8), f = this._b + this.def._fv, p0 = d.getUint32(f, true);
544
+ if (this._tl !== undefined && p0 > ts)
545
+ return this.compact();
546
+ if (p0 < ts && end >= ts) {
547
+ const h = p0 || d.getUint32(f + 4, true) ? 4 : 0;
548
+ d.setUint32(f + h, ts | (h >> 2), true);
549
+ }
550
+ }
551
+ return u8s(d, this._o, end);
552
+ }
553
+ }
554
+ export class StructViewBase extends MemView {
555
+ /** @internal */
556
+ constructor(descs, dv, base, off, mem = null) {
557
+ super();
558
+ Object.defineProperties(this, descs);
559
+ if (dv)
560
+ this._set(dv, base, off, mem);
561
+ }
562
+ /** Re-positions this flyweight cursor to row `index` (supports negative indices from the end). */
563
+ seek(index) {
564
+ const a = this._a;
565
+ if (a !== undefined)
566
+ return a.at(index, this);
567
+ const st = this._ws || this.def.size, o = this._b + index * st;
568
+ if (o < 0 || o + st > this._k().byteLength)
569
+ oob();
570
+ this._o = o;
571
+ return this;
572
+ }
573
+ set(fieldOrValues, value) {
574
+ if (typeof fieldOrValues === 'string')
575
+ this[fieldOrValues] = value;
576
+ else
577
+ writeVal(this, this.def, fieldOrValues, this._b, this._o);
578
+ return this;
579
+ }
580
+ toObject() {
581
+ return readPlain(this);
582
+ }
583
+ }
584
+ const kInspect = /* @__PURE__ */ Symbol.for('nodejs.util.inspect.custom');
585
+ StructViewBase.prototype.at = StructViewBase.prototype.seek;
586
+ StructViewBase.prototype.setAll = StructViewBase.prototype.set;
587
+ StructViewBase.prototype.toJSON = StructViewBase.prototype[kInspect] = StructViewBase.prototype.toObject;
588
+ function normOpts(b = 0, c, bo, s) {
589
+ return typeof b === 'number'
590
+ ? { o: b, c, b: bo, s }
591
+ : { o: b.byteOffset ?? 0, c: b.count, b: b.baseOffset, s: b.stride };
592
+ }
593
+ export function structView(def, source, byteOffset = 0, baseOffset, wireStride) {
594
+ const n = normOpts(byteOffset, undefined, baseOffset, wireStride);
595
+ const r = resolveSource(source, n.o), ws = n.s ?? (r.max < def.size ? r.max : def.size);
596
+ if (r.o < 0 || r.max < ws)
597
+ oob();
598
+ const v = new def._V(r.d, n.b ?? r.o, r.o, r.m);
599
+ v._ws = ws;
600
+ v._tl = r.o + Math.max(ws, r.max);
601
+ return v;
602
+ }
603
+ export class StructArrayView extends MemView {
604
+ constructor(def, source, byteOffset = 0, count, baseOffset, wireStride) {
605
+ super();
606
+ const n = normOpts(byteOffset, count, baseOffset, wireStride);
607
+ const sz = n.s ?? def.size, r = resolveSource(source, n.o), hasVar = def._fv >= 0 && def._fv < sz, f = n.c === undefined && r.max >= sz && hasVar
608
+ ? (def._fvr && r.d.getUint32(r.o + def._fv + 4, true) & ~7) || r.d.getUint32(r.o + def._fv, true)
609
+ : 0, len = n.c ?? (f >= sz && f <= r.max ? f / sz : r.max / sz) | 0, tot = len * sz;
610
+ if (len < 0 || r.o < 0 || r.max < tot)
611
+ oob();
612
+ Object.assign(this, {
613
+ def,
614
+ stride: sz,
615
+ length: len,
616
+ byteLength: tot,
617
+ _ws: sz,
618
+ _tl: r.o + (!hasVar && n.c !== undefined ? tot : Math.max(tot, r.max)),
619
+ _cap: len,
620
+ _dead: 0,
621
+ _dirty: false,
622
+ });
623
+ this._set(r.d, n.b ?? r.o, r.o, r.m);
624
+ }
625
+ /** @internal */
626
+ _mv(index, v) {
627
+ const d = this._k(), o = this._o + index * this.stride, nv = v ? v._set(d, this._b, o, this._m) : new this.def._V(d, this._b, o, this._m);
628
+ nv._ws = this._ws;
629
+ nv._a = this._a ?? this;
630
+ return nv;
631
+ }
632
+ /** Returns a reusable flyweight cursor positioned at `index`. */
633
+ cursor(index = 0) {
634
+ return (this._c = this._mv(index, this._c));
635
+ }
636
+ /** Returns a `StructView<F>` at `index` (supports negative indices from the end, e.g. `rows.at(-1)`). */
637
+ at(index, out) {
638
+ if (index < 0)
639
+ index += this.length;
640
+ if (index < 0 || index >= this.length)
641
+ oob();
642
+ if (out)
643
+ return this._mv(index, out);
644
+ const p = this._p ?? (this._p = []);
645
+ const s = (this._pi = ((this._pi ?? 0) + 1) & 255);
646
+ return (p[s] = this._mv(index, p[s]));
647
+ }
648
+ /** Writes `value` into the struct at `index` (supports negative indices from the end). */
649
+ set(index, value) {
650
+ this.at(index).set(value);
651
+ return this;
652
+ }
653
+ /** Appends one or more rows to the binary array, automatically growing capacity if needed. */
654
+ push(...items) {
655
+ const def = this.def, st = this.stride, need = this.length + items.length, hasVar = def._fv >= 0;
656
+ if (need > this._cap) {
657
+ const curEnd = this._tl ?? this._o + this.byteLength, tableEnd = this._o + this._cap * st;
658
+ if ((!hasVar || !this.length) && tableEnd === curEnd) {
659
+ allocTail(this, (need - this._cap) * st, def.align);
660
+ this._cap = need;
661
+ }
662
+ else {
663
+ const newCap = Math.max(need, (this._cap || 2) * 2), newO = allocTail(this, al(newCap * st, 8), def.align), d = this._k(), dO = newO - this._o;
664
+ if (this.byteLength > 0) {
665
+ u8s(d, newO, this.byteLength).set(u8s(d, this._o, this.byteLength));
666
+ this._dead = (this._dead ?? 0) + this.byteLength;
667
+ }
668
+ this._o = newO;
669
+ this._cap = newCap;
670
+ for (const pv of [this._c, ...(this._p ?? [])])
671
+ if (pv)
672
+ pv._o += dO;
673
+ }
674
+ }
675
+ initNulls(def, this._k(), this._o + this.length * st, items.length, st);
676
+ for (const item of items) {
677
+ const idx = this.length++;
678
+ this.byteLength = this.length * st;
679
+ writeVal(this, def, item, this._b, this._o + idx * st);
680
+ if (hasVar)
681
+ this._dirty = true;
682
+ }
683
+ return this.length;
684
+ }
685
+ pop() {
686
+ if (!this.length)
687
+ return undefined;
688
+ const lastIdx = --this.length, val = readPlain(this, this._o + lastIdx * this.stride);
689
+ this.byteLength = this.length * this.stride;
690
+ if (this.def._fv >= 0) {
691
+ this._dirty = true;
692
+ this._dead = (this._dead ?? 0) + this.stride;
693
+ }
694
+ else if (this._tl === this._o + (lastIdx + 1) * this.stride) {
695
+ this._tl -= this.stride;
696
+ this._cap = this.length;
697
+ }
698
+ return val;
699
+ }
700
+ /** Returns a zero-copy `StructArrayView` over `[begin, end)` without copying bytes. */
701
+ subarray(begin = 0, end = this.length) {
702
+ const len = this.length, cl = (i) => Math.max(0, Math.min(len, i < 0 ? len + i : i)), s = cl(begin), e = cl(end), sub = new StructArrayView(this.def, this._k(), this._o + s * this.stride, Math.max(0, e - s), this._b, this._ws);
703
+ sub._m = this._m;
704
+ sub._a = this._a ?? this;
705
+ sub._dirty = (this.def._fv >= 0 && (s > 0 || e < len)) || Boolean(this._dirty || this._dead);
706
+ return sub;
707
+ }
708
+ lowerBound(field, value) {
709
+ return bsearch(this, field, value, false);
710
+ }
711
+ /** Binary search: first row index `i` in `[0..length]` where `row[i][field] > value` ($O(\log N)$, 0 allocations). */
712
+ upperBound(field, value) {
713
+ return bsearch(this, field, value, true);
714
+ }
715
+ /** Returns a zero-copy `StructArrayView` slice over the sorted range `min <= row[field] <= max` in $O(\log N)$. */
716
+ rangeBy(field, min, max) {
717
+ return this.subarray(this.lowerBound(field, min), this.upperBound(field, max));
718
+ }
719
+ /** Filters rows with a reusable flyweight cursor (0 per-row JS objects) and copies matching binary rows into a `Uint8Array`. */
720
+ filterBytes(predicate) {
721
+ const len = this.length, c = this.cursor(0), def = this.def, st = this.stride, rows = [];
722
+ ensureScratch(len * st);
723
+ let outOff = 0;
724
+ for (let i = 0; i < len; i++)
725
+ if (predicate(c.seek(i), i))
726
+ def._fv < 0 && st === def.size && this._ws === st
727
+ ? (sU8.set(u8s(this._k(), this._o + i * st, st), outOff), (outOff += st))
728
+ : rows.push(c.toObject());
729
+ return rows.length ? pack(def, rows) : sU8.slice(0, outOff);
730
+ }
731
+ /** Extracts a `TypedArray` column for primitive `field` (zero-copy when `stride === field.size`). */
732
+ column(field) {
733
+ const lay = colDesc(this, field), desc = lay.desc, n = this.length, st = this.stride, fo = lay.offset, d = this._k(), start = d.byteOffset + this._o + fo, out = new desc._C(n);
734
+ if (fo + desc.size <= this._ws) {
735
+ if (desc.type !== 'bool' && (st === desc.size || n <= 1) && !(start % desc.align))
736
+ return new desc._C(d.buffer, start, n);
737
+ for (let i = 0, off = this._o + fo; i < n; i++, off += st)
738
+ out[i] = desc._g(d, off);
739
+ }
740
+ return out;
741
+ }
742
+ /** Bulk-writes a primitive column from `values` into `field` across all rows. */
743
+ setColumn(field, values) {
744
+ const lay = colDesc(this, field);
745
+ if (lay.offset + lay.size > this._ws)
746
+ this.compact();
747
+ const desc = lay.desc, d = this._k(), st = this.stride, n = Math.min(this.length, values.length);
748
+ for (let i = 0, off = this._o + lay.offset; i < n; i++, off += st) {
749
+ desc._s(d, off, values[i]);
750
+ }
751
+ return this;
752
+ }
753
+ /** Materializes all rows into an array of plain JavaScript objects. */
754
+ toObjects() {
755
+ return readPlain(this, this._o, true);
756
+ }
757
+ *[Symbol.iterator]() {
758
+ for (let i = 0, c = this.cursor(0), b = this._o, st = this.stride, n = this.length; i < n; i++) {
759
+ c._o = b + i * st;
760
+ yield c;
761
+ }
762
+ }
763
+ }
764
+ StructArrayView.prototype.toJSON = StructArrayView.prototype[kInspect] = StructArrayView.prototype.toObjects;
765
+ function colDesc(a, k) {
766
+ const lay = a.def.fields[k];
767
+ if (!lay?.desc._C)
768
+ oob();
769
+ return lay;
770
+ }
771
+ function bsearch(a, k, v, eq) {
772
+ const lay = colDesc(a, k), g = lay.desc._g, d = a._k(), b = a._o + lay.offset, st = a.stride;
773
+ let lo = 0, hi = a.length;
774
+ while (lo < hi) {
775
+ const mid = (lo + hi) >>> 1, x = g(d, b + mid * st);
776
+ if (eq ? x <= v : x < v)
777
+ lo = mid + 1;
778
+ else
779
+ hi = mid;
780
+ }
781
+ return lo;
782
+ }
783
+ export class WasmArena {
784
+ constructor(backing = 65536, baseOffset = 0) {
785
+ this.memory = backing?.buffer ? backing : null;
786
+ this.baseOffset = this.offset = baseOffset;
787
+ this._rebind(this.memory
788
+ ? this.memory.buffer
789
+ : backing instanceof ArrayBuffer
790
+ ? backing
791
+ : new ArrayBuffer(Math.max(backing, baseOffset)));
792
+ }
793
+ /** @internal */
794
+ _rebind(buf) {
795
+ this._buf = buf;
796
+ this._u8 = u8s((this._d = new DataView(buf)));
797
+ return this;
798
+ }
799
+ sync() {
800
+ if (this.memory !== null && this.memory.buffer !== this._buf) {
801
+ this._rebind(this.memory.buffer);
802
+ }
803
+ return this;
804
+ }
805
+ get buffer() {
806
+ return this.sync()._buf;
807
+ }
808
+ get byteLength() {
809
+ return this.sync()._buf.byteLength;
810
+ }
811
+ get bytesUsed() {
812
+ return this.offset - this.baseOffset;
813
+ }
814
+ get u8() {
815
+ return this.sync()._u8;
816
+ }
817
+ get dataView() {
818
+ return this.sync()._d;
819
+ }
820
+ alignTo(align) {
821
+ return (this.offset = al(this.offset, align));
822
+ }
823
+ ensureCapacity(requiredByteLength) {
824
+ this.sync();
825
+ if (requiredByteLength <= this._buf.byteLength)
826
+ return this;
827
+ if (this.memory !== null) {
828
+ growMem(this.memory, requiredByteLength);
829
+ return this._rebind(this.memory.buffer);
830
+ }
831
+ const nb = new ArrayBuffer(Math.max(requiredByteLength, this._buf.byteLength * 2, 64));
832
+ new Uint8Array(nb).set(this._u8);
833
+ return this._rebind(nb);
834
+ }
835
+ /** @internal */
836
+ _alloc(bytes, align, zero = false) {
837
+ const p = this.alignTo(align), end = (this.offset = p + bytes);
838
+ this.ensureCapacity(end);
839
+ if (zero && bytes > 0)
840
+ this._u8.fill(0, p, end);
841
+ return p;
842
+ }
843
+ alloc(def, count = 1, zero = false) {
844
+ const p = this._alloc(count * def.size, def.align, zero);
845
+ initNulls(def, this._d, p, count);
846
+ const v = new StructArrayView(def, this, p, count, p);
847
+ v._tl = p + count * def.size;
848
+ return v;
849
+ }
850
+ allocOne(def, init) {
851
+ const p = this._alloc(def.size, def.align, true), v = new def._V(this._d, p, p, this);
852
+ initNulls(def, this._d, p);
853
+ return init !== undefined ? v.setAll(init) : v;
854
+ }
855
+ placeBytes(bytes, alignOrDef = 8) {
856
+ const u = u8s(bytes), p = this._alloc(u.byteLength, typeof alignOrDef === 'number' ? alignOrDef : alignOrDef.align);
857
+ this._u8.set(u, p);
858
+ return Object.defineProperties(new Uint8Array(this._buf, p, u.byteLength), {
859
+ ptr: hid(p),
860
+ as: hid((def, count = def.array(u).length) => {
861
+ const v = new StructArrayView(def, this, p, count, p);
862
+ v._tl = p + u.byteLength;
863
+ return v;
864
+ }),
865
+ });
866
+ }
867
+ view(def, byteOffset, baseOffset = byteOffset) {
868
+ return structView(def, this, byteOffset, baseOffset);
869
+ }
870
+ viewArray(def, byteOffset, count, baseOffset = byteOffset) {
871
+ return new StructArrayView(def, this, byteOffset, count, baseOffset);
872
+ }
873
+ reset(baseOffset = this.baseOffset) {
874
+ this.offset = baseOffset;
875
+ return this;
876
+ }
877
+ }
878
+ export const Arena = WasmArena;
879
+ export class StructDef {
880
+ constructor(name, schemaOrBuilder) {
881
+ if (name)
882
+ _reg[name] = this;
883
+ const schema = typeof schemaOrBuilder === 'function' ? schemaOrBuilder((() => this)) : schemaOrBuilder;
884
+ if (!schema)
885
+ oob();
886
+ let off = 0, maxA = 1;
887
+ let firstV = -1, fvr = false;
888
+ const fObj = {};
889
+ const descs = { ...BASE_DESCS };
890
+ for (const [k, d] of Object.entries(schema)) {
891
+ const a = d.align;
892
+ maxA = Math.max(maxA, a);
893
+ const fo = (off = al(off, a));
894
+ fObj[k] = {
895
+ name: k,
896
+ desc: d,
897
+ offset: fo,
898
+ size: d.size,
899
+ align: a,
900
+ };
901
+ off += d.size;
902
+ const dk = d.kind;
903
+ if ((dk === 'str' || dk === 'slice' || dk === 'ref' || (dk === 'struct' && d._fv >= 0)) && firstV < 0) {
904
+ firstV = dk === 'struct' ? fo + d._fv : fo;
905
+ fvr = dk === 'ref';
906
+ }
907
+ const end = fo + d.size;
908
+ descs[k] = {
909
+ enumerable: true,
910
+ configurable: true,
911
+ get() {
912
+ return end > this._ws
913
+ ? defVal(d, false)
914
+ : dk === 'primitive'
915
+ ? d._g(this._k(), this._o + fo)
916
+ : readVal(this, d, this._o + fo, false);
917
+ },
918
+ set(v) {
919
+ if (end > this._ws)
920
+ upgradeView(this);
921
+ writeVal(this, d, v, this._b, this._o + fo);
922
+ },
923
+ };
924
+ }
925
+ const sz = al(off, maxA);
926
+ descs._ws = hid(sz);
927
+ class SpecializedStructView extends StructViewBase {
928
+ constructor(dv, b, o, m) {
929
+ super(descs, dv, b, o, m);
930
+ }
931
+ }
932
+ SpecializedStructView.prototype.def = this;
933
+ SpecializedStructView.prototype.byteLength = sz;
934
+ Object.assign(this, {
935
+ kind: 'struct',
936
+ name,
937
+ rustType: name || 'AnonStruct',
938
+ schema,
939
+ size: sz,
940
+ stride: sz,
941
+ align: maxA,
942
+ fields: fObj,
943
+ fieldList: Object.values(fObj),
944
+ _fv: firstV,
945
+ _fvr: fvr,
946
+ _V: SpecializedStructView,
947
+ });
948
+ }
949
+ offsetOf(field) {
950
+ return this.fields[field].offset;
951
+ }
952
+ /** Allocates a single `StructView<F>` backed by a fresh buffer and optionally initializes fields. */
953
+ create(init) {
954
+ const v = this.view(new ArrayBuffer(this.size));
955
+ initNulls(this, v._d, 0);
956
+ return init !== undefined ? v.setAll(init) : v;
957
+ }
958
+ /** Infers `Partial<StructInput<F>>` on a plain JS object literal (for building typed cyclic JS graphs without `any`). */
959
+ item(init) {
960
+ return init;
961
+ }
962
+ view(source, byteOffset, baseOffset, wireStride) {
963
+ return structView(this, source, byteOffset, baseOffset, wireStride);
964
+ }
965
+ /** Wraps a binary buffer in a zero-copy `StructArrayView<F>`. */
966
+ array(source, byteOffset, count, baseOffset, wireStride) {
967
+ return new StructArrayView(this, source, byteOffset, count, baseOffset, wireStride);
968
+ }
969
+ /** Allocates a growable `StructArrayView<F>` for `count` rows (pass `0` for an empty growable array). */
970
+ alloc(count, Ctor = ArrayBuffer) {
971
+ const a = this.array(new Ctor(count * this.size), 0, count);
972
+ initNulls(this, a._d, 0, count);
973
+ return a;
974
+ }
975
+ from(sourceOrRows) {
976
+ if (typeof sourceOrRows === 'number')
977
+ return this.alloc(sourceOrRows);
978
+ if (sourceOrRows instanceof StructArrayView)
979
+ return sourceOrRows;
980
+ if ('byteLength' in sourceOrRows || sourceOrRows?.buffer) {
981
+ return this.array(sourceOrRows);
982
+ }
983
+ return this.array(this.pack(Array.isArray(sourceOrRows)
984
+ ? sourceOrRows
985
+ : Array.from(sourceOrRows)));
986
+ }
987
+ shared(rowsOrCount) {
988
+ const B = typeof SharedArrayBuffer !== 'undefined'
989
+ ? SharedArrayBuffer
990
+ : ArrayBuffer;
991
+ if (typeof rowsOrCount === 'number')
992
+ return this.alloc(rowsOrCount, B);
993
+ const p = this.pack(rowsOrCount), sb = new B(p.byteLength);
994
+ new Uint8Array(sb).set(p);
995
+ return this.array(sb);
996
+ }
997
+ /** Allocates or packs a `StructArrayView<F>` directly inside `WebAssembly.Memory` (via `WasmArena` or exported `capn_alloc`/`alloc`) and returns `{ view, ptr, len, byteLength }`. */
998
+ inWasm(wasmMemoryOrExports, rowsOrCount) {
999
+ const exp = wasmMemoryOrExports?.exports ?? wasmMemoryOrExports, src = typeof rowsOrCount === 'number' ? null : this.from(rowsOrCount), u = src?.bytes, len = src ? src.length : rowsOrCount, byteLength = u ? u.byteLength : len * this.size, mem = exp._d ? exp : exp.memory ?? exp, fn = exp.capn_alloc ?? exp.alloc, ptr = exp._alloc
1000
+ ? exp._alloc(byteLength, this.align)
1001
+ : fn
1002
+ ? byteLength && fn.call(exp, byteLength) >>> 0
1003
+ : al(mem.offset ?? 64, this.align), end = (mem.offset = Math.max(mem.offset ?? 0, ptr + byteLength));
1004
+ if (!exp._d)
1005
+ growMem(mem, end);
1006
+ const view = this.array(mem, ptr, len, ptr);
1007
+ view._tl = end;
1008
+ u ? u8s(view._d, ptr, byteLength).set(u) : (u8s(view._d, ptr, byteLength).fill(0), initNulls(this, view._d, ptr, len));
1009
+ return { view, ptr, len, byteLength };
1010
+ }
1011
+ /** Packs an array of plain JavaScript objects or positional tuples into an 8-byte-aligned `Uint8Array`. */
1012
+ pack(rows) {
1013
+ return pack(this, rows);
1014
+ }
1015
+ concatBytes(chunks) {
1016
+ return concatBytes(this, chunks);
1017
+ }
1018
+ }
1019
+ /** Concatenates multiple `StructArrayView<F>` or `Uint8Array` chunks into a single packed `Uint8Array` via bulk `memcpy` when fixed-size. */
1020
+ export function concatBytes(def, chunks) {
1021
+ if (def._fv >= 0)
1022
+ return pack(def, chunks.flatMap((c) => def.from(c).toObjects()));
1023
+ const slices = chunks.map((c) => c instanceof Uint8Array ? (c.byteLength % def.size && oob(), c) : c.stride === def.size ? c.bytes : c.compact());
1024
+ const out = new Uint8Array(slices.reduce((s, b) => s + b.byteLength, 0));
1025
+ let off = 0;
1026
+ for (const s of slices)
1027
+ (out.set(s, off), (off += s.byteLength));
1028
+ return out;
1029
+ }
1030
+ /** Packs an array of plain JavaScript objects into an 8-byte-aligned `Uint8Array`. */
1031
+ export function pack(def, rows) {
1032
+ const n = rows.length;
1033
+ const st = def.size;
1034
+ const tb = n * st;
1035
+ const ts = def._fv >= 0 ? al(tb, 8) : tb;
1036
+ ensureScratch(ts + n * 64 + 64);
1037
+ sU8.fill(0, 0, ts);
1038
+ tail = ts;
1039
+ writeVal(null, { kind: 'array', element: def, length: n }, rows, 0, 0);
1040
+ if (n && def._fv >= 0 && sDv.getUint32(def._fv, true) < ts) {
1041
+ const h = sDv.getUint32(def._fv + 4, true) ? 4 : 0;
1042
+ sDv.setUint32(def._fv + h, ts | (h >> 2), true);
1043
+ }
1044
+ const end = al(tail, 8);
1045
+ sU8.fill(0, tail, end);
1046
+ return sU8.slice(0, end);
1047
+ }
1048
+ export function defineStruct(nameOrFields, maybeFields) {
1049
+ return typeof nameOrFields === 'string'
1050
+ ? new StructDef(nameOrFields, maybeFields)
1051
+ : new StructDef('', nameOrFields);
1052
+ }
1053
+ /** Alias for `defineStruct`. */
1054
+ export const struct = defineStruct;
1055
+ const _dtf = {
1056
+ header(x) {
1057
+ if (!(x instanceof MemView))
1058
+ return null;
1059
+ const n = x.def?.name || 'Struct';
1060
+ if ('length' in x)
1061
+ return ['span', {}, `${n}[${x.length}] (${x.usedByteLength} B)`];
1062
+ const ks = Object.keys(x);
1063
+ return ['span', {}, `${n} { ${ks.slice(0, 4).map((k) => `${k}: ${JSON.stringify(x[k])}`).join(', ')}${ks.length > 4 ? ', ...' : ''} }`];
1064
+ },
1065
+ hasBody: (x) => x instanceof MemView,
1066
+ body: (x) => ['div', {}, ['object', { object: x.toJSON() }]],
1067
+ };
1068
+ /** Registers a lazy Chrome/Edge/Firefox DevTools custom formatter (`globalThis.devtoolsFormatters`) for `StructView` and `StructArrayView`. */
1069
+ export function installDevtoolsFormatter() {
1070
+ const g = globalThis;
1071
+ const list = (g.devtoolsFormatters ??= []);
1072
+ if (!list.includes(_dtf))
1073
+ list.push(_dtf);
1074
+ return _dtf;
1075
+ }
1076
+ //# sourceMappingURL=index.js.map