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