balloc 0.0.0-stage → 1.0.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.
@@ -0,0 +1,1091 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/en/balloc.mjs
20
+ var balloc_exports = {};
21
+ __export(balloc_exports, {
22
+ default: () => Balloc
23
+ });
24
+ module.exports = __toCommonJS(balloc_exports);
25
+ var import_cbor_x = require("cbor-x");
26
+ var UNKNOWN = 4294967295 >>> 0;
27
+ var BUCKET_MAPPING = Object.freeze({
28
+ "8u": { type: "Uint8", bits: 8 },
29
+ "16u": { type: "Uint16", bits: 16 },
30
+ "32u": { type: "Uint32", bits: 32 },
31
+ "64u": { type: "BigUint64", bits: 64 },
32
+ "8i": { type: "Int8", bits: 8 },
33
+ "16i": { type: "Int16", bits: 16 },
34
+ "32i": { type: "Int32", bits: 32 },
35
+ "64i": { type: "BigInt64", bits: 64 },
36
+ "16f": { type: "Float16", bits: 16 },
37
+ "32f": { type: "Float32", bits: 32 },
38
+ "64f": { type: "Float64", bits: 64 }
39
+ });
40
+ var IS_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
41
+ var HEADER_SIZE = 16 >>> 0;
42
+ var ADDRESS_OFFSET = 0 >>> 0;
43
+ var OCCUPIED_OFFSET = 4 >>> 0;
44
+ var CAPACITY_OFFSET = 8 >>> 0;
45
+ var COOKIE_OFFSET = 9 >>> 0;
46
+ var ROTATE_32BITS = 4294967296;
47
+ var CLAMP_11BITS = 2047 >>> 0;
48
+ var isTypedArray = (val) => ArrayBuffer.isView(val) && !(val instanceof DataView);
49
+ var Balloc = class {
50
+ /**
51
+ * Creates an instance of the `Balloc` memory allocator.
52
+ *
53
+ * The allocator maintains two independent buffers:
54
+ * - `dataBus`: stores the data of allocated blocks;
55
+ * - `controlBus`: stores headers and other control metadata.
56
+ *
57
+ * Each block has a fixed-size header (`HEADER_SIZE`) and is externally
58
+ * identified by a 43-bit logical handle, composed of an 11-bit generation
59
+ * and a 32-bit header address.
60
+ *
61
+ * The capacity of each block is rounded up to the next power of two
62
+ * in elements, respecting the configured bucket width.
63
+ *
64
+ * @param {number} [size=65535] - Initial capacity of the `dataBus`, in bytes.
65
+ * Must be a safe integer in the range [2, 0x80000000].
66
+ * @param {BucketType} [bucketSize="32u"] - Bucket type and size identifier
67
+ * (e.g., '32u' for Uint32, '64f' for Float64, '8i' for Int8).
68
+ * @param {number} [metadataSize=1024] - Initial capacity of the `controlBus`,
69
+ * in bytes. Must be a safe integer in the range
70
+ * [HEADER_SIZE, 0x80000000].
71
+ *
72
+ * @throws {RangeError} If `size` is out of the allowed range.
73
+ * @throws {RangeError} If `bucketSize` is not a valid bucket identifier.
74
+ * @throws {RangeError} If `metadataSize` is out of the allowed range.
75
+ */
76
+ constructor(size = 65535, bucketSize = "32u", metadataSize = 1024) {
77
+ if (!Number.isSafeInteger(size) || size < 2 || size > 2147483648) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
78
+ if (!BUCKET_MAPPING[bucketSize]) {
79
+ throw new RangeError(`bucketSize must be in ([ 8 || 16 || 32 || 64][ u || i ]) || ([ 16 || 32 || 64][ f ]) but I found ${bucketSize}`);
80
+ }
81
+ if (!Number.isSafeInteger(metadataSize) || metadataSize < HEADER_SIZE || metadataSize > 2147483648) throw new RangeError(`Parameter metadataSize must be in range [HEADER_SIZE, 0x80000000] but metadataSize is ${metadataSize}`);
82
+ this.wordType = bucketSize;
83
+ this.bucketType = BUCKET_MAPPING[bucketSize].type;
84
+ this.bucketSize = BUCKET_MAPPING[bucketSize].bits >>> 0;
85
+ this.bucketArray = globalThis[`${this.bucketType}Array`];
86
+ this.wordSize = this.bucketSize >>> 3;
87
+ this.wordShift = this.bucketSize >>> 4;
88
+ this.size = Math.max(1 << 32 - Math.clz32(size) >>> 0, this.wordSize);
89
+ this.headerSize = 1 << 32 - Math.clz32(metadataSize) >>> 0;
90
+ this.dataPointer = 0 >>> 0;
91
+ this.controlPointer = 0 >>> 0;
92
+ this.echoPointer = 0 >>> 0;
93
+ this.generation = 0 >>> 0;
94
+ this.dataBus = new Uint8Array(this.size);
95
+ this.controlBus = new Uint8Array(this.headerSize);
96
+ this.dataAdapter = new DataView(this.dataBus.buffer);
97
+ this.controlAdapter = new DataView(this.controlBus.buffer);
98
+ this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
99
+ this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
100
+ this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
101
+ this.recycle = /* @__PURE__ */ new Map();
102
+ this.metadata = {
103
+ generation: 0 >>> 0,
104
+ headerAddress: 0 >>> 0,
105
+ dataAddress: 0 >>> 0,
106
+ capacityExponent: 0 >>> 0,
107
+ byteCapacity: 0 >>> 0,
108
+ occupied: 0 >>> 0
109
+ };
110
+ }
111
+ // ========== ALLOCATION ==========
112
+ /**
113
+ * Allocates a new memory block.
114
+ *
115
+ * The requested capacity is converted to the smallest power of two that
116
+ * accommodates `size` elements. The block is preferably obtained from the list
117
+ * of recyclable regions with the corresponding capacity; if no compatible
118
+ * region exists, the block is reserved at the top of the `dataBus`.
119
+ *
120
+ * Next, a header is obtained from the control space. Previously freed headers
121
+ * can be reused via the internal recycling stack; otherwise, the `controlBus`
122
+ * is expanded when necessary.
123
+ *
124
+ * The header receives the address, capacity, initial occupancy (zero), and
125
+ * a validation cookie. The returned value encodes the allocation generation
126
+ * and the header address:
127
+ *
128
+ * [11 bits generation][32 bits header address]
129
+ *
130
+ * @param {number} [size=16] - Minimum number of elements the block must
131
+ * accommodate. Must be a safe integer in the range [2, 0x80000000].
132
+ * @returns {number} Handle identifying the allocated block.
133
+ * @throws {RangeError} If `size` is out of the allowed range.
134
+ */
135
+ alloc(size = 16) {
136
+ if (!Number.isSafeInteger(size) || size < 2 || size > 2147483648) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
137
+ const capacity = 32 - Math.clz32(size - 1);
138
+ const blockSize = (1 << capacity >>> 0) * this.wordSize;
139
+ let dataAddress = this.recyclePop(blockSize);
140
+ if (dataAddress === UNKNOWN) {
141
+ while (this.dataPointer + blockSize > this.size) this.grow();
142
+ dataAddress = this.dataPointer;
143
+ this.dataPointer += blockSize;
144
+ }
145
+ let headerAddress = 0 >>> 0;
146
+ if (this.echoPointer > this.controlPointer) {
147
+ this.echoPointer -= 4;
148
+ headerAddress = this.controlAdapter.getUint32(this.echoPointer, IS_LITTLE_ENDIAN);
149
+ } else {
150
+ if (this.controlPointer + HEADER_SIZE > this.controlAdapter.byteLength) this.headerGrow();
151
+ headerAddress = this.controlPointer;
152
+ this.controlPointer += HEADER_SIZE;
153
+ this.echoPointer += HEADER_SIZE;
154
+ }
155
+ this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, dataAddress, IS_LITTLE_ENDIAN);
156
+ this.controlAdapter.setUint32(headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
157
+ this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, capacity);
158
+ this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, this.bakeCookie(headerAddress, ++this.generation));
159
+ return (this.generation & CLAMP_11BITS) * ROTATE_32BITS + headerAddress;
160
+ }
161
+ /**
162
+ * Expands a block's capacity to the next power of two.
163
+ *
164
+ * When the block is located at the current top of the `dataBus`, expansion
165
+ * occurs in-place: only its capacity and `dataPointer` are updated.
166
+ *
167
+ * If another region exists after the block, a new region with double the
168
+ * capacity is obtained from the recyclable space or allocated at the top of
169
+ * the `dataBus`. Currently occupied elements are then copied to the new region,
170
+ * and the previous region is returned to the recycling list.
171
+ *
172
+ * The handle remains valid because its header is preserved, and only the
173
+ * address and capacity recorded within it are updated.
174
+ *
175
+ * @param {number} handler - Handle of the block to expand.
176
+ * @returns {void}
177
+ * @throws {Error} If the handle is invalid or corrupted.
178
+ * @throws {AggregateError} If the capacity has reached its maximum
179
+ * supported limit.
180
+ */
181
+ realloc(handler) {
182
+ const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
183
+ let headerAddress = handler >>> 0;
184
+ const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
185
+ const occupied = this.controlAdapter.getUint32(headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
186
+ const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
187
+ const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
188
+ if (cookie !== this.bakeCookie(headerAddress, generation)) {
189
+ throw new Error("Invalid or corrupted handle");
190
+ }
191
+ if (capacity >= 31) throw new AggregateError([new Error("Can\xB4t reallocate handler."), new RangeError("Capacity has reached its limit.")], "Internal Error.");
192
+ const newCapacity = capacity + 1;
193
+ const newBlockSize = (1 << newCapacity >>> 0) * this.wordSize;
194
+ const oldBlockSize = (1 << capacity >>> 0) * this.wordSize;
195
+ if (dataAddress + oldBlockSize === this.dataPointer) {
196
+ while (dataAddress + newBlockSize > this.size) this.grow();
197
+ this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity, IS_LITTLE_ENDIAN);
198
+ this.dataPointer = dataAddress + newBlockSize;
199
+ return;
200
+ }
201
+ this.recyclePush(oldBlockSize, dataAddress);
202
+ let newAddress = this.recyclePop(newBlockSize);
203
+ if (newAddress === UNKNOWN) {
204
+ while (this.dataPointer + newBlockSize > this.size) this.grow();
205
+ newAddress = this.dataPointer;
206
+ this.dataPointer += newBlockSize;
207
+ }
208
+ this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
209
+ this.dataBus.copyWithin(newAddress, dataAddress, dataAddress + occupied * this.wordSize);
210
+ this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, newAddress, IS_LITTLE_ENDIAN);
211
+ }
212
+ /**
213
+ * Frees a memory block.
214
+ *
215
+ * The block's header is invalidated by zeroing its cookie, and its address
216
+ * is registered for later reuse. The data region is also returned to the
217
+ * recycling system, except when the block is exactly at the top of the
218
+ * `dataBus`; in that case, `dataPointer` is simply rolled back, eliminating
219
+ * the region without creating an entry in the recycling list.
220
+ *
221
+ * @param {number} handler - Handle of the block to free.
222
+ * @returns {void}
223
+ * @throws {Error} If the handle is invalid or corrupted.
224
+ */
225
+ free(handler) {
226
+ const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
227
+ let headerAddress = handler >>> 0;
228
+ const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
229
+ const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
230
+ const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
231
+ if (cookie !== this.bakeCookie(headerAddress, generation)) {
232
+ throw new Error("Invalid or corrupted handle");
233
+ }
234
+ const blockSize = (1 << capacity >>> 0) * this.wordSize;
235
+ this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
236
+ if (this.echoPointer + 4 <= this.controlBus.byteLength) {
237
+ this.controlAdapter.setUint32(this.echoPointer, headerAddress, IS_LITTLE_ENDIAN);
238
+ this.echoPointer += 4;
239
+ }
240
+ if (dataAddress + blockSize === this.dataPointer) {
241
+ this.dataPointer = dataAddress;
242
+ } else {
243
+ this.recyclePush(blockSize, dataAddress);
244
+ }
245
+ }
246
+ // ========== RECYCLING ==========
247
+ /**
248
+ * [INTERNAL USE]
249
+ * Inserts a free region into the recycling list.
250
+ *
251
+ * The list is organized by capacity in bytes. For each capacity, the
252
+ * stored value is a `Uint32Array` whose zero position contains the number
253
+ * of registered addresses, and subsequent positions contain the addresses
254
+ * of the free regions:
255
+ *
256
+ * [count, address1, address2, ...]
257
+ *
258
+ * When the page becomes full, its buffer is expanded to double the current
259
+ * capacity.
260
+ *
261
+ * @param {number} capacity - Capacity of the free region, in bytes.
262
+ * @param {number} address - Initial address of the region in the `dataBus`.
263
+ * @returns {void}
264
+ * @private
265
+ */
266
+ recyclePush(capacity, address) {
267
+ if (this.recycle.has(capacity)) {
268
+ let page = this.recycle.get(capacity);
269
+ const count = page[0];
270
+ if (count === page.length - 1) {
271
+ const newBuffer = page.buffer.transfer(page.buffer.byteLength * 2);
272
+ page = new Uint32Array(newBuffer);
273
+ this.recycle.set(capacity, page);
274
+ }
275
+ page[count + 1] = address;
276
+ page[0] = count + 1;
277
+ } else {
278
+ this.recycle.set(capacity, new Uint32Array([1, address]));
279
+ }
280
+ }
281
+ /**
282
+ * [INTERNAL USE]
283
+ * Removes a free region from the recycling list.
284
+ *
285
+ * The search is performed by the exact requested capacity. When a corresponding
286
+ * page exists, the last registered address is removed from the page and returned,
287
+ * implementing recycling as a LIFO stack.
288
+ *
289
+ * @param {number} capacity - Desired capacity, in bytes.
290
+ * @returns {number} Initial address of a recyclable region or `UNKNOWN`
291
+ * when no region exists with the requested capacity.
292
+ * @private
293
+ */
294
+ recyclePop(capacity) {
295
+ if (!this.recycle.has(capacity)) return UNKNOWN;
296
+ const page = this.recycle.get(capacity);
297
+ const count = page[0];
298
+ if (count === 0) return UNKNOWN;
299
+ const address = page[count];
300
+ page[0] = count - 1;
301
+ return address;
302
+ }
303
+ // ========== GARBAGE COLLECTION ==========
304
+ /**
305
+ * Compacts the `dataBus` using the ReBump algorithm.
306
+ *
307
+ * Sequentially traverses the headers registered in the `controlBus` and copies
308
+ * still-valid regions to a new `dataBus`, eliminating free spaces between them.
309
+ * The address of each surviving block is updated in its respective header.
310
+ *
311
+ * The order of blocks in the `controlBus` is preserved. Internal data of each
312
+ * block is also fully preserved, including its reserved capacity and current
313
+ * occupancy.
314
+ *
315
+ * At the end of compaction:
316
+ * - all recyclable regions are eliminated;
317
+ * - `dataPointer` points to the first byte after the last live block;
318
+ * - `dataBus` represents a contiguous heap for active blocks.
319
+ *
320
+ * Control complexity is O(n), where `n` is the number of headers traversed.
321
+ * The effective cost of memory movement also depends on the volume of bytes
322
+ * belonging to live blocks.
323
+ *
324
+ * @returns {void}
325
+ */
326
+ gc() {
327
+ const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
328
+ this.recycle.clear();
329
+ this.dataPointer = 0 >>> 0;
330
+ for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
331
+ if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
332
+ const start = this.controlAdapter.getUint32(i + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
333
+ const size = (1 << this.controlBus[i + CAPACITY_OFFSET] >>> 0) * this.wordSize;
334
+ const end = start + size;
335
+ newDataBus.set(this.dataBus.subarray(start, end), this.dataPointer);
336
+ this.controlAdapter.setUint32(i + ADDRESS_OFFSET, this.dataPointer, IS_LITTLE_ENDIAN);
337
+ this.dataPointer += size;
338
+ }
339
+ this.dataBus = newDataBus;
340
+ this.dataAdapter = new DataView(this.dataBus.buffer);
341
+ this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
342
+ this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
343
+ this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
344
+ }
345
+ // ========== SCALING ==========
346
+ /**
347
+ * [!!! INTERNAL USE, DO NOT USE IN YOUR CODE !!!]
348
+ * Expands the `dataBus` to double its current capacity.
349
+ *
350
+ * The underlying buffer is transferred to a larger `ArrayBuffer`, preserving
351
+ * existing data. All views associated with the buffer are recreated to reference
352
+ * the new storage.
353
+ *
354
+ * @returns {void}
355
+ * @throws {RangeError} If the `dataBus` capacity has exceeded the maximum
356
+ * supported limit.
357
+ * @private
358
+ */
359
+ grow() {
360
+ if (this.size > 2147483648) throw new RangeError("Data bus capacity exceeded");
361
+ const newSize = this.size * 2 >>> 0;
362
+ const newBuffer = this.dataBus.buffer.transfer(newSize);
363
+ this.size = newSize;
364
+ this.dataBus = new Uint8Array(newBuffer);
365
+ this.dataAdapter = new DataView(newBuffer);
366
+ this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
367
+ this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
368
+ this.auxiliary = new this.bucketArray(newBuffer);
369
+ }
370
+ /**
371
+ * [!!! INTERNAL USE, DO NOT USE IN YOUR CODE !!!]
372
+ * Expands the `controlBus` to double its current capacity.
373
+ *
374
+ * The underlying buffer is transferred to a larger `ArrayBuffer`, preserving
375
+ * existing headers. The `controlAdapter` is recreated to reference the new
376
+ * storage.
377
+ *
378
+ * @returns {void}
379
+ * @throws {RangeError} If the current `controlBus` capacity has exceeded
380
+ * the maximum supported limit.
381
+ * @private
382
+ */
383
+ headerGrow() {
384
+ if (this.controlBus.byteLength > 2147483648) throw new RangeError("Control bus capacity exceeded");
385
+ const newSize = this.controlBus.byteLength * 2 >>> 0;
386
+ const newBuffer = this.controlBus.buffer.transfer(newSize);
387
+ this.controlBus = new Uint8Array(newBuffer);
388
+ this.controlAdapter = new DataView(newBuffer);
389
+ }
390
+ // ========== STACK OPERATIONS ==========
391
+ /**
392
+ * Appends an element to the end of the block's occupied sequence.
393
+ *
394
+ * The element is written at the first free position after the last occupied
395
+ * element. Block occupancy is incremented only when space is available within
396
+ * its capacity.
397
+ *
398
+ * @param {number} handler - Block handle.
399
+ * @param {number} value - Value to insert.
400
+ * @returns {boolean} `true` if the value was inserted; `false` if the block
401
+ * has no available space.
402
+ * @throws {Error} If the handle is invalid or corrupted.
403
+ */
404
+ push(handler, value) {
405
+ const meta = this.extractMetadata(handler, this.metadata);
406
+ if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
407
+ this.writer(meta.dataAddress + meta.occupied * this.wordSize, value, IS_LITTLE_ENDIAN);
408
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
409
+ return true;
410
+ }
411
+ /**
412
+ * Removes and returns the last occupied element from the block.
413
+ *
414
+ * Occupancy is decremented before reading the removed element. Corresponding
415
+ * bytes are not cleared and remain in the allocated region, but cease to be
416
+ * part of the occupied sequence.
417
+ *
418
+ * @param {number} handler - Block handle.
419
+ * @returns {number|undefined} Removed value or `undefined` if the block
420
+ * is empty.
421
+ * @throws {Error} If the handle is invalid or corrupted.
422
+ */
423
+ pop(handler) {
424
+ const meta = this.extractMetadata(handler, this.metadata);
425
+ if (meta.occupied === 0) return void 0;
426
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
427
+ return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
428
+ }
429
+ /**
430
+ * Returns the last occupied element without removing it.
431
+ *
432
+ * @param {number} handler - Block handle.
433
+ * @returns {number|undefined} Last occupied value or `undefined` if the
434
+ * block is empty.
435
+ * @throws {Error} If the handle is invalid or corrupted.
436
+ */
437
+ peek(handler) {
438
+ const meta = this.extractMetadata(handler, this.metadata);
439
+ if (meta.occupied === 0) return void 0;
440
+ return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
441
+ }
442
+ // ========== QUEUE OPERATIONS ==========
443
+ /**
444
+ * Inserts an element at the beginning of the occupied sequence.
445
+ *
446
+ * Currently occupied elements are shifted one position forward and `value`
447
+ * is written to the first position. The operation requires a free position
448
+ * within the block's capacity.
449
+ *
450
+ * The operation's cost is proportional to the number of occupied elements,
451
+ * as data needs to be shifted.
452
+ *
453
+ * @param {number} handler - Block handle.
454
+ * @param {number} value - Value to insert.
455
+ * @returns {boolean} `true` if the value was inserted; `false` if the block
456
+ * is full.
457
+ * @throws {Error} If the handle is invalid or corrupted.
458
+ */
459
+ nudge(handler, value) {
460
+ const meta = this.extractMetadata(handler, this.metadata);
461
+ if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
462
+ this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
463
+ this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
464
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
465
+ return true;
466
+ }
467
+ /**
468
+ * Removes and returns the first occupied element from the block.
469
+ *
470
+ * Remaining elements are shifted one position toward the beginning of the
471
+ * occupied region. The block's physical capacity remains unchanged.
472
+ *
473
+ * The operation's cost is proportional to the number of shifted elements.
474
+ *
475
+ * @param {number} handler - Block handle.
476
+ * @returns {number|undefined} First removed value or `undefined` if the
477
+ * block is empty.
478
+ * @throws {Error} If the handle is invalid or corrupted.
479
+ */
480
+ pull(handler) {
481
+ const meta = this.extractMetadata(handler, this.metadata);
482
+ if (meta.occupied === 0) return void 0;
483
+ const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
484
+ this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
485
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
486
+ return result;
487
+ }
488
+ /**
489
+ * Returns the first occupied element without removing it.
490
+ *
491
+ * @param {number} handler - Block handle.
492
+ * @returns {number|undefined} First occupied value or `undefined` if the
493
+ * block is empty.
494
+ * @throws {Error} If the handle is invalid or corrupted.
495
+ */
496
+ head(handler) {
497
+ const meta = this.extractMetadata(handler, this.metadata);
498
+ if (meta.occupied === 0) return void 0;
499
+ return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
500
+ }
501
+ // ========== RANDOM ACCESS ==========
502
+ /**
503
+ * Checks if a value is present among the block's occupied elements.
504
+ *
505
+ * The search is performed directly on the auxiliary `TypedArray` and considers
506
+ * only the currently occupied range, not the entire reserved physical capacity.
507
+ *
508
+ * @param {number} handler - Block handle.
509
+ * @param {number} value - Value to search for.
510
+ * @returns {boolean} `true` if `value` is present among the occupied elements;
511
+ * otherwise, `false`.
512
+ * @throws {Error} If the handle is invalid or corrupted.
513
+ */
514
+ has(handler, value) {
515
+ const meta = this.extractMetadata(handler, this.metadata);
516
+ if (meta.occupied === 0) return false;
517
+ const rawAddres = meta.dataAddress >>> this.wordShift;
518
+ return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
519
+ }
520
+ /**
521
+ * Returns the occupied element at a zero-based index.
522
+ *
523
+ * Indices outside the range `[0, occupied)` are not considered an error and
524
+ * result in `undefined`.
525
+ *
526
+ * @param {number} handler - Block handle.
527
+ * @param {number} index - Zero-based index of the element.
528
+ * @returns {number|undefined} Value stored at the index or `undefined` if
529
+ * the index is outside the occupied region.
530
+ * @throws {Error} If the handle is invalid or corrupted.
531
+ */
532
+ get(handler, index) {
533
+ const meta = this.extractMetadata(handler, this.metadata);
534
+ if (index < 0 || index >= meta.occupied) return void 0;
535
+ return this.reader(meta.dataAddress + index * this.wordSize, IS_LITTLE_ENDIAN);
536
+ }
537
+ /**
538
+ * Replaces the value stored at an occupied index.
539
+ *
540
+ * The operation does not alter block occupancy. Indices outside the range
541
+ * `[0, occupied)` are ignored and result in `false`.
542
+ *
543
+ * @param {number} handler - Block handle.
544
+ * @param {number} index - Zero-based index of the element.
545
+ * @param {number} value - New value.
546
+ * @returns {boolean} `true` if the value was written; `false` if the index
547
+ * is outside the occupied region.
548
+ * @throws {Error} If the handle is invalid or corrupted.
549
+ */
550
+ set(handler, index, value) {
551
+ const meta = this.extractMetadata(handler, this.metadata);
552
+ if (index < 0 || index >= meta.occupied) return false;
553
+ this.writer(meta.dataAddress + index * this.wordSize, value, IS_LITTLE_ENDIAN);
554
+ return true;
555
+ }
556
+ // ============= MISCELLANEOUS ===============
557
+ /**
558
+ * Clears block occupancy and fills its entire physical capacity with a single value.
559
+ *
560
+ * Filling covers all available slots, not just currently occupied elements.
561
+ * After the operation, the block is considered empty regardless of the value
562
+ * used for filling.
563
+ *
564
+ * @param {number} handler - Block handle.
565
+ * @param {number} [value=0] - Value used to fill all slots.
566
+ * @returns {void}
567
+ * @throws {Error} If the handle is invalid or corrupted.
568
+ */
569
+ clear(handler, value = 0) {
570
+ const meta = this.extractMetadata(handler, this.metadata);
571
+ const slots = meta.byteCapacity / this.wordSize;
572
+ const rawAddress = meta.dataAddress >>> this.wordShift;
573
+ this.auxiliary.fill(value, rawAddress, rawAddress + slots);
574
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
575
+ }
576
+ /**
577
+ * Fills a range of block slots with a value.
578
+ *
579
+ * The range uses zero-based indices and follows the convention `[start, end)`,
580
+ * meaning `start` is inclusive and `end` is exclusive. When `end` is not provided,
581
+ * filling extends to the end of the block's physical capacity.
582
+ *
583
+ * Block occupancy becomes `end`, including when the filled range extends beyond
584
+ * the previous occupancy.
585
+ *
586
+ * @param {number} handler - Block handle.
587
+ * @param {number} value - Value used for filling.
588
+ * @param {number} [start=0] - Initial index, inclusive.
589
+ * @param {number|null} [end=null] - Final index, exclusive. When omitted or
590
+ * `null`, uses the total block capacity.
591
+ * @returns {void}
592
+ * @throws {Error} If the handle is invalid or corrupted.
593
+ * @throws {RangeError} If `start` or `end` is out of capacity bounds, or if
594
+ * `start > end`.
595
+ */
596
+ fill(handler, value, start = 0, end = null) {
597
+ const meta = this.extractMetadata(handler, this.metadata);
598
+ const slots = meta.byteCapacity / this.wordSize;
599
+ const lastIndex = end ?? slots;
600
+ if (start > lastIndex) {
601
+ throw new RangeError(`start ${start} must be less or equal than end ${lastIndex}.`);
602
+ }
603
+ if (start < 0 || start > slots) {
604
+ throw new RangeError(`start ${start} out of range [0, ${slots}].`);
605
+ }
606
+ if (lastIndex < 0 || lastIndex > slots) {
607
+ throw new RangeError(`end ${lastIndex} out of range [0, ${slots}].`);
608
+ }
609
+ const rawAddress = meta.dataAddress >>> this.wordShift;
610
+ this.auxiliary.fill(value, rawAddress + start, rawAddress + lastIndex);
611
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, lastIndex, IS_LITTLE_ENDIAN);
612
+ }
613
+ /**
614
+ * Fills all physical slots of the block with a value and marks the entire
615
+ * capacity as occupied.
616
+ *
617
+ * Unlike `clear()`, the operation results in a fully occupied block.
618
+ *
619
+ * @param {number} handler - Block handle.
620
+ * @param {number} value - Value used for filling.
621
+ * @returns {void}
622
+ * @throws {Error} If the handle is invalid or corrupted.
623
+ */
624
+ fillAll(handler, value) {
625
+ const meta = this.extractMetadata(handler, this.metadata);
626
+ const rawAddress = meta.dataAddress >>> this.wordShift;
627
+ const capacityElements = meta.byteCapacity / this.wordSize;
628
+ this.auxiliary.fill(value, rawAddress, rawAddress + capacityElements);
629
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, capacityElements, IS_LITTLE_ENDIAN);
630
+ }
631
+ /**
632
+ * Copies elements from an `Array` or `TypedArray` to the beginning of the block.
633
+ *
634
+ * The copied quantity is limited by the block's capacity. Occupancy is updated
635
+ * to the greater value between the previous occupancy and the quantity effectively
636
+ * copied; therefore, a call to `put()` does not reduce existing occupancy when
637
+ * receiving a smaller sequence.
638
+ *
639
+ * For `Array`, only the first fitting elements are copied. For `TypedArray`,
640
+ * a source subarray is used without intermediate copying.
641
+ *
642
+ * @param {number} handler - Block handle.
643
+ * @param {Array|TypedArray} data - Sequence of values to copy.
644
+ * @returns {void}
645
+ * @throws {Error} If the handle is invalid or corrupted.
646
+ * @throws {TypeError} If `data` is neither an `Array` nor a `TypedArray`.
647
+ */
648
+ put(handler, data) {
649
+ const meta = this.extractMetadata(handler, this.metadata);
650
+ const rawAddress = meta.dataAddress >>> this.wordShift;
651
+ const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
652
+ meta.occupied = Math.max(length, meta.occupied);
653
+ if (Array.isArray(data)) {
654
+ this.auxiliary.set(data.slice(0, length), rawAddress);
655
+ } else if (isTypedArray(data)) {
656
+ this.auxiliary.set(data.subarray(0, length), rawAddress);
657
+ } else {
658
+ const actual = data?.constructor?.name ?? (data === null ? "null" : typeof data);
659
+ throw new TypeError(`data must be Array or TypedArray, but ${actual} was given.`);
660
+ }
661
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
662
+ }
663
+ /**
664
+ * Returns a copy of the elements currently occupied by the block.
665
+ *
666
+ * The result is a `TypedArray` of the same type configured by `bucketSize`.
667
+ * Unoccupied physical capacity is not included in the result.
668
+ *
669
+ * The operation does not directly expose internal storage: the method uses
670
+ * `TypedArray.prototype.slice()`, producing a new view with independent storage.
671
+ *
672
+ * @param {number} handler - Block handle.
673
+ * @returns {TypedArray} Copy of the elements occupied by the block. When the
674
+ * block is empty, returns an empty `TypedArray` of the configured type.
675
+ * @throws {Error} If the handle is invalid or corrupted.
676
+ */
677
+ pick(handler) {
678
+ const meta = this.extractMetadata(handler, this.metadata);
679
+ const rawAddress = meta.dataAddress >>> this.wordShift;
680
+ if (meta.occupied === 0) {
681
+ return this.auxiliary.slice(rawAddress, rawAddress);
682
+ }
683
+ return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
684
+ }
685
+ // ======== CAPACITY IN SLOTS ==========
686
+ /**
687
+ * Returns the physical capacity of the block in bytes.
688
+ *
689
+ * Capacity corresponds to the space reserved for all slots in the block,
690
+ * regardless of how many elements are currently occupied.
691
+ *
692
+ * @param {number} handler - Block handle.
693
+ * @returns {number} Physical capacity of the block, in bytes.
694
+ * @throws {Error} If the handle is invalid or corrupted.
695
+ */
696
+ byteSize(handler) {
697
+ const meta = this.extractMetadata(handler, this.metadata);
698
+ return meta.byteCapacity;
699
+ }
700
+ /**
701
+ * Returns the number of elements currently occupied in the block.
702
+ *
703
+ * @param {number} handler - Block handle.
704
+ * @returns {number} Number of occupied elements.
705
+ * @throws {Error} If the handle is invalid or corrupted.
706
+ */
707
+ occupied(handler) {
708
+ const meta = this.extractMetadata(handler, this.metadata);
709
+ return meta.occupied;
710
+ }
711
+ /**
712
+ * Returns the capacity of the block in number of elements.
713
+ *
714
+ * The value corresponds to the total quantity of physically reserved slots,
715
+ * not the currently occupied quantity.
716
+ *
717
+ * @param {number} handler - Block handle.
718
+ * @returns {number} Total number of slots available in the block.
719
+ * @throws {Error} If the handle is invalid or corrupted.
720
+ */
721
+ length(handler) {
722
+ const meta = this.extractMetadata(handler, this.metadata);
723
+ return 1 << meta.capacityExponent >>> 0;
724
+ }
725
+ // ========== Inter-block Operations =============
726
+ /**
727
+ * Copies occupied elements from one block to another.
728
+ *
729
+ * Copying begins at the first element of `source` and the first slot of
730
+ * `destiny`. The effectively copied quantity is limited by the number of occupied
731
+ * elements in the source, the destination's physical capacity, and the limit
732
+ * specified in `slots`.
733
+ *
734
+ * Destination occupancy is increased, when necessary, to cover the copied
735
+ * elements. Destination capacity is not changed.
736
+ *
737
+ * The operation uses `Uint8Array.prototype.copyWithin()` on the `dataBus`,
738
+ * therefore the return value is the `Uint8Array` representing the data bus.
739
+ *
740
+ * @param {number} source - Source block handle.
741
+ * @param {number} destiny - Destination block handle.
742
+ * @param {number} [slots=UNKNOWN] - Maximum number of elements to copy.
743
+ * `UNKNOWN` represents the sentinel value used not to impose an additional limit.
744
+ * @returns {Uint8Array} The `dataBus` after the operation.
745
+ * @throws {Error} If `source` or `destiny` is invalid or corrupted.
746
+ */
747
+ copy(source, destiny, slots = UNKNOWN) {
748
+ const metaA = {};
749
+ const metaB = {};
750
+ this.extractMetadata(source, metaA);
751
+ this.extractMetadata(destiny, metaB);
752
+ const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
753
+ const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
754
+ const newOccupied = Math.max(metaB.occupied, slotsToCopy);
755
+ this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
756
+ return this.dataBus.copyWithin(metaB.dataAddress, metaA.dataAddress, metaA.dataAddress + slotsToCopy * this.wordSize);
757
+ }
758
+ /**
759
+ * Copies a region of elements within the same block.
760
+ *
761
+ * Indices are zero-based and follow the semantics of `Array.prototype.copyWithin()`:
762
+ * `target` identifies the destination position, `start` the source starting
763
+ * position, and `length` the maximum number of elements to copy.
764
+ *
765
+ * Negative indices are interpreted from the end of the block's capacity. After
766
+ * this normalization, indices are clamped to physical capacity. The copied quantity
767
+ * is also limited by effectively occupied elements and available space from `target`.
768
+ *
769
+ * The operation supports overlapping regions and can increase block occupancy
770
+ * when the target range exceeds current occupancy.
771
+ *
772
+ * @param {number} handler - Block handle.
773
+ * @param {number} target - Initial destination index.
774
+ * @param {number} start - Initial source index.
775
+ * @param {number} length - Maximum number of elements to copy.
776
+ * @returns {Uint8Array} The `dataBus` after the operation.
777
+ * @throws {Error} If the handle is invalid or corrupted.
778
+ */
779
+ copyWithin(handler, target, start, length) {
780
+ const meta = this.extractMetadata(handler, this.metadata);
781
+ const slots = Math.floor(meta.byteCapacity / this.wordSize);
782
+ target = Math.trunc(target);
783
+ start = Math.trunc(start);
784
+ length = Math.trunc(length);
785
+ if (target < 0) target += slots;
786
+ if (start < 0) start += slots;
787
+ target = Math.max(0, Math.min(target, slots));
788
+ start = Math.max(0, Math.min(start, slots));
789
+ const maxRead = Math.max(0, meta.occupied - start);
790
+ const maxWrite = slots - target;
791
+ length = Math.max(0, Math.min(length, maxRead, maxWrite));
792
+ if (length === 0) return this.dataBus;
793
+ const targetAddress = meta.dataAddress + target * this.wordSize;
794
+ const sourceAddress = meta.dataAddress + start * this.wordSize;
795
+ const newOccupied = Math.max(meta.occupied, target + length);
796
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
797
+ return this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + length * this.wordSize);
798
+ }
799
+ /**
800
+ * Appends occupied elements of `source` to the end of `target`.
801
+ *
802
+ * The copied quantity is limited by the number of occupied elements in the
803
+ * source and the remaining free space in the destination's capacity.
804
+ *
805
+ * The operation supports `target` and `source` referencing the same block.
806
+ * In that case, the copy is performed on the block's own region and preserves
807
+ * `copyWithin()` overlap semantics.
808
+ *
809
+ * @param {number} target - Handle of the block that will receive the elements.
810
+ * @param {number} source - Handle of the block whose elements will be appended.
811
+ * @returns {number} Number of elements effectively appended.
812
+ * @throws {Error} If `target` or `source` is invalid or corrupted.
813
+ */
814
+ append(target, source) {
815
+ const metaTarget = {};
816
+ const metaSource = {};
817
+ this.extractMetadata(target, metaTarget);
818
+ this.extractMetadata(source, metaSource);
819
+ const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
820
+ const count = Math.min(available, metaSource.occupied);
821
+ if (count === 0) return 0;
822
+ const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
823
+ const sourceAddress = metaSource.dataAddress;
824
+ if (target === source) {
825
+ this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
826
+ } else {
827
+ this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
828
+ }
829
+ this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
830
+ return count;
831
+ }
832
+ /**
833
+ * Creates an independent copy of a block.
834
+ *
835
+ * The new block has the same physical capacity and occupancy as the original block.
836
+ * All bytes in the reserved region, including currently unoccupied positions,
837
+ * are copied.
838
+ *
839
+ * The new block receives a new handle and remains subject to normal allocation
840
+ * and recycling rules.
841
+ *
842
+ * @param {number} handler - Handle of the block to clone.
843
+ * @returns {number} Handle of the new block.
844
+ * @throws {Error} If the handle is invalid or corrupted.
845
+ */
846
+ clone(handler) {
847
+ const meta = this.extractMetadata(handler, this.metadata);
848
+ const cloned = this.alloc(meta.byteCapacity / this.wordSize);
849
+ const cloneMeta = {};
850
+ this.extractMetadata(cloned, cloneMeta);
851
+ this.dataBus.copyWithin(cloneMeta.dataAddress, meta.dataAddress, meta.dataAddress + meta.byteCapacity);
852
+ this.controlAdapter.setUint32(cloneMeta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
853
+ return cloned;
854
+ }
855
+ /**
856
+ * Swaps the data regions associated with two blocks.
857
+ *
858
+ * The operation swaps region addresses, capacities, and occupancies between headers.
859
+ * Handles remain unchanged: after the operation, each handle continues identifying
860
+ * its own header, but that header now describes the region previously belonging
861
+ * to the other block.
862
+ *
863
+ * No data is copied in the `dataBus`; only the metadata of the two headers
864
+ * is modified.
865
+ *
866
+ * @param {number} source - Handle of the first block.
867
+ * @param {number} target - Handle of the second block.
868
+ * @returns {void}
869
+ * @throws {Error} If `source` or `target` is invalid or corrupted.
870
+ */
871
+ swap(source, target) {
872
+ const metaA = {};
873
+ const metaB = {};
874
+ this.extractMetadata(source, metaA);
875
+ this.extractMetadata(target, metaB);
876
+ this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
877
+ this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
878
+ this.controlAdapter.setUint8(metaA.headerAddress + CAPACITY_OFFSET, metaB.capacityExponent);
879
+ this.controlAdapter.setUint8(metaB.headerAddress + CAPACITY_OFFSET, metaA.capacityExponent);
880
+ this.controlAdapter.setUint32(metaA.headerAddress + OCCUPIED_OFFSET, metaB.occupied, IS_LITTLE_ENDIAN);
881
+ this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, metaA.occupied, IS_LITTLE_ENDIAN);
882
+ }
883
+ // ============= SERIALIZATION ==============
884
+ /**
885
+ * Serializes the content and metadata of a memory block.
886
+ *
887
+ * The method extracts occupied data from the block via `pick()`, groups them
888
+ * along with capacity and word type information into a data envelope, and encodes
889
+ * them using the CBOR format.
890
+ *
891
+ * @param {number} handler - Handle of the block to serialize.
892
+ * @returns {Uint8Array} A buffer containing the serialized block data.
893
+ * @throws {Error} If the handle is invalid or corrupted.
894
+ */
895
+ dump(handler) {
896
+ const meta = this.extractMetadata(handler, this.metadata);
897
+ const capacity = meta.capacityExponent;
898
+ const capacityElements = 2 ** capacity;
899
+ if (!Number.isInteger(capacity) || capacity < 1 || capacity > 31 || meta.occupied > capacityElements) {
900
+ throw new Error("Cannot serialize a block with invalid metadata");
901
+ }
902
+ const payload = this.pick(handler);
903
+ if (payload.length !== meta.occupied || payload.constructor !== this.bucketArray) {
904
+ throw new Error("Cannot serialize a block with an invalid payload");
905
+ }
906
+ return (0, import_cbor_x.encode)({
907
+ v: 1,
908
+ wordType: this.wordType,
909
+ capacity,
910
+ occupied: meta.occupied,
911
+ le: IS_LITTLE_ENDIAN,
912
+ payload
913
+ });
914
+ }
915
+ /**
916
+ * Restores a memory block from serialized data.
917
+ *
918
+ * Decodes the CBOR envelope, validates whether the word type of the serialized
919
+ * data is compatible with the current allocator instance, and allocates a new
920
+ * block with the necessary capacity to accommodate the content. Then, the original
921
+ * data and occupancy are restored in the new block.
922
+ *
923
+ * @param {Uint8Array|ArrayBuffer} serialized - Buffer containing serialized data.
924
+ * @returns {number} Handle of the newly recreated block.
925
+ * @throws {Error} If the decoded data's word type differs from the one configured in the allocator.
926
+ */
927
+ load(serialized) {
928
+ if (!(serialized instanceof ArrayBuffer) && !(serialized instanceof Uint8Array)) {
929
+ throw new TypeError("serialized must be an ArrayBuffer or Uint8Array");
930
+ }
931
+ const envelope = (0, import_cbor_x.decode)(serialized);
932
+ if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)) {
933
+ throw new TypeError("Invalid serialized block envelope");
934
+ }
935
+ if (envelope.v !== 1) {
936
+ throw new Error(`Unsupported serialized block version: ${envelope.v}`);
937
+ }
938
+ if (envelope.wordType !== this.wordType) {
939
+ throw new Error(`Can't load data, ${this.wordType} expected but ${envelope.wordType} found.`);
940
+ }
941
+ if (!Number.isInteger(envelope.capacity) || envelope.capacity < 1 || envelope.capacity > 31) {
942
+ throw new RangeError("Invalid serialized block capacity");
943
+ }
944
+ const capacityElements = 2 ** envelope.capacity;
945
+ if (!Number.isSafeInteger(envelope.occupied) || envelope.occupied < 0 || envelope.occupied > capacityElements) {
946
+ throw new RangeError("Invalid serialized block occupancy");
947
+ }
948
+ if (typeof envelope.le !== "boolean") {
949
+ throw new TypeError("Invalid serialized endianness flag");
950
+ }
951
+ const payload = envelope.payload;
952
+ if (!isTypedArray(payload) || payload.constructor !== this.bucketArray || payload.length !== envelope.occupied) {
953
+ throw new TypeError(`Invalid payload: expected ${this.bucketType}Array with ${envelope.occupied} elements`);
954
+ }
955
+ if (payload.BYTES_PER_ELEMENT !== this.wordSize || payload.byteLength !== envelope.occupied * this.wordSize) {
956
+ throw new TypeError("Serialized payload has an invalid element size");
957
+ }
958
+ const handler = this.alloc(capacityElements);
959
+ const meta = this.extractMetadata(handler, this.metadata);
960
+ this.put(handler, payload);
961
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, envelope.occupied, IS_LITTLE_ENDIAN);
962
+ return handler;
963
+ }
964
+ // ============= UTILITIES ==============
965
+ /**
966
+ * [INTERNAL USE]
967
+ * Decodes the metadata associated with a handle.
968
+ *
969
+ * The handle is split into generation and header address. The cookie stored
970
+ * in the header is then recalculated to validate the combination; only after
971
+ * this validation is metadata read.
972
+ *
973
+ * Decoded fields are written to the `out` object, which is returned by the function
974
+ * itself. The object can be reused across calls to avoid new allocations.
975
+ *
976
+ * @param {number} handler - Handle to decode and validate.
977
+ * @param {Metadata} out - Object that will receive the decoded metadata.
978
+ * @returns {Metadata} The same reference provided in `out`.
979
+ * @throws {Error} If the header cookie does not match the handle or if the
980
+ * handle does not identify a valid header.
981
+ * @private
982
+ */
983
+ extractMetadata(handler, out) {
984
+ out.generation = handler / ROTATE_32BITS & CLAMP_11BITS;
985
+ out.headerAddress = handler >>> 0;
986
+ const cookie = this.controlAdapter.getUint8(out.headerAddress + COOKIE_OFFSET);
987
+ if (cookie !== this.bakeCookie(out.headerAddress, out.generation)) {
988
+ throw new Error("Invalid or corrupted handle");
989
+ }
990
+ out.dataAddress = this.controlAdapter.getUint32(out.headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
991
+ out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
992
+ out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
993
+ out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
994
+ return out;
995
+ }
996
+ /**
997
+ * [INTERNAL USE]
998
+ * Calculates the validation cookie of a header.
999
+ *
1000
+ * The cookie is derived from the header address and the 11-bit generation via
1001
+ * fast hash. The result is reduced to 8 bits.
1002
+ *
1003
+ * The value zero is reserved as an invalid header indicator; therefore, when
1004
+ * the calculation yields zero, the method returns `1`.
1005
+ *
1006
+ * The cookie is not a cryptographic mechanism. Its purpose is to detect invalid,
1007
+ * stale, or corrupted handles within the allocator's memory management model.
1008
+ *
1009
+ * @param {number} addr - Header address.
1010
+ * @param {number} gen - Generation associated with the handle. Only the 11 least
1011
+ * significant bits are considered.
1012
+ * @returns {number} 8-bit cookie in the range [1, 255].
1013
+ * @private
1014
+ */
1015
+ bakeCookie(addr, gen) {
1016
+ return (addr ^ gen & 2047 * 2654435761) & 255 || 1;
1017
+ }
1018
+ /**
1019
+ * Returns the number of regions currently stored in the recycling list.
1020
+ *
1021
+ * Each region corresponds to a freed block that could not be returned directly
1022
+ * to the top of the `dataBus` and therefore remains available for reuse by a
1023
+ * future allocation of identical capacity.
1024
+ *
1025
+ * @returns {number} Number of free regions maintained in `recycle`.
1026
+ */
1027
+ recycleCount() {
1028
+ let count = 0;
1029
+ for (const [, page] of this.recycle) {
1030
+ count += page[0];
1031
+ }
1032
+ return count;
1033
+ }
1034
+ /**
1035
+ * Returns the total bytes belonging to regions currently stored in the recycling list.
1036
+ *
1037
+ * The value is calculated by summing the capacity of each free region multiplied
1038
+ * by the number of regions registered for that capacity.
1039
+ *
1040
+ * @returns {number} Number of bytes occupied by recyclable regions.
1041
+ */
1042
+ get recycleBytes() {
1043
+ let total = 0;
1044
+ for (const [capacity, page] of this.recycle) {
1045
+ total += page[0] * capacity;
1046
+ }
1047
+ return total;
1048
+ }
1049
+ /**
1050
+ * Returns the amount of allocated bytes that do not belong to currently recyclable regions.
1051
+ *
1052
+ * The value is obtained by subtracting the bytes belonging to free regions maintained
1053
+ * in `recycle` from the total advance of `dataPointer`.
1054
+ *
1055
+ * @returns {number} Number of bytes associated with non-recyclable regions within
1056
+ * the area already used by the `dataBus`.
1057
+ */
1058
+ get allocatedBytes() {
1059
+ return this.dataPointer - this.recycleBytes;
1060
+ }
1061
+ /**
1062
+ * Returns the amount of bytes not yet used at the top of the `dataBus`.
1063
+ *
1064
+ * This space corresponds to the region between `dataPointer` and the end of the
1065
+ * capacity currently reserved for the buffer.
1066
+ *
1067
+ * @returns {number} Number of available bytes after `dataPointer`.
1068
+ */
1069
+ get unallocatedBytes() {
1070
+ return this.size - this.dataPointer;
1071
+ }
1072
+ /**
1073
+ * Returns the ratio between recyclable memory and the used heap area.
1074
+ *
1075
+ * The metric considers free regions maintained in `recycle` as fragmentation
1076
+ * and uses `dataPointer` as the denominator. When no bytes have been used by the heap,
1077
+ * the result is zero.
1078
+ *
1079
+ * The value does not represent the fraction of the entire `dataBus` capacity,
1080
+ * but specifically the proportion of recyclable bytes within the area already
1081
+ * traversed by the bump pointer.
1082
+ *
1083
+ * @returns {number} Fragmentation ratio in the range [0, 1] under normal
1084
+ * operating conditions.
1085
+ */
1086
+ get fragmentationRatio() {
1087
+ if (this.dataPointer === 0) return 0;
1088
+ return this.recycleBytes / this.dataPointer;
1089
+ }
1090
+ };
1091
+ module.exports = { Balloc };