balloc 0.0.0-stage → 1.0.1

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,1360 @@
1
+ import { encode, decode } from 'cbor-x';
2
+
3
+ /**
4
+ * Indicador que representa un valor inválido o desconocido.
5
+ */
6
+ const UNKNOWN = 0xFFFFFFFF >>> 0;
7
+
8
+ /**
9
+ * Tamaños y tipos de bucket válidos.
10
+ * Solo se admiten tamaños de 8, 16, 32 y 64 bits para tipos enteros y
11
+ * solo se admiten tamaños de 16, 32 y 64 bits para flotantes.
12
+ * Tipos de datos admitidos:
13
+ * u = entero sin signo
14
+ * i = entero con signo
15
+ * f = flotante
16
+ *
17
+ * Sintaxis del identificador de bucket:
18
+ *
19
+ * [Tamaño en bits][tipo de dato]
20
+ *
21
+ * Ejemplos:
22
+ * Un bucket de enteros sin signo de 32 bits: 32u
23
+ * Un bucket de enteros con signo de 64 bits: 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
+ * Tipos de bucket admitidos por el asignador:
42
+ * - Enteros sin signo: '8u', '16u', '32u', '64u'
43
+ * - Enteros con signo: '8i', '16i', '32i', '64i'
44
+ * - Punto flotante: '16f', '32f', '64f'
45
+ *
46
+ * @typedef {'8u'|'16u'|'32u'|'64u'|'8i'|'16i'|'32i'|'64i'|'16f'|'32f'|'64f'} BucketType
47
+ */
48
+
49
+ /**
50
+ * Indicador de ordenamiento de bytes (endianness) del sistema.
51
+ *
52
+ * Detecta si el sistema es Little Endian, lo cual afecta
53
+ * el orden de los bytes en las operaciones de DataView.
54
+ */
55
+ const IS_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
56
+
57
+
58
+ /**
59
+ * Formato de los metadatos.
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
+ * Estructura que contiene los metadatos codificados dentro de un identificador.
78
+ *
79
+ * @typedef {Object} Metadata
80
+ * @property {number} byteCapacity - Capacidad del bloque de memoria en bytes.
81
+ * @property {number} capacityExponent - Capacidad del bloque de memoria expresada como exponente de base dos.
82
+ * @property {number} dataAddress - Dirección del bloque de memoria dentro del dataBus.
83
+ * @property {number} generation - Generación a la que pertenece el identificador.
84
+ * @property {number} headerAddress - Dirección de la cabecera dentro del controlBus.
85
+ * @property {number} occupied - Número de elementos ocupados en el bloque.
86
+ */
87
+
88
+ /**
89
+ * Comprueba si un valor es una instancia de TypedArray.
90
+ *
91
+ * @param {any} val - Valor a comprobar.
92
+ * @returns {boolean} `true` si el valor es un TypedArray, de lo contrario `false`.
93
+ */
94
+ const isTypedArray = (val) => ArrayBuffer.isView(val) && !(val instanceof DataView);
95
+
96
+ /**
97
+ * Asignador de tipo Bump de doble bus con pila Echo y GC ReBump.
98
+ */
99
+ export default class Balloc {
100
+
101
+ /**
102
+ * Crea una instancia del asignador de memoria `Balloc`.
103
+ *
104
+ * El asignador mantiene dos bústeres independientes:
105
+ * - `dataBus`: almacena los datos de los bloques asignados;
106
+ * - `controlBus`: almacena las cabeceras y otros metadatos de control.
107
+ *
108
+ * Cada bloque posee una cabecera de tamaño fijo (`HEADER_SIZE`) y se
109
+ * identifica externamente mediante un identificador lógico de 43 bits, compuesto
110
+ * por una generación de 11 bits y la dirección de su cabecera en 32 bits.
111
+ *
112
+ * La capacidad de cada bloque se redondea hacia arriba a la siguiente potencia de
113
+ * dos en elementos, respetando el ancho del bucket configurado.
114
+ *
115
+ * @param {number} [size=65535] - Capacidad inicial del `dataBus`, en bytes.
116
+ * Debe ser un entero seguro en el rango [2, 0x80000000].
117
+ * @param {BucketType} [bucketSize="32u"] - Identificador del tipo y tamaño del bucket
118
+ * (ej.: '32u' para Uint32, '64f' para Float64, '8i' para Int8).
119
+ * @param {number} [metadataSize=1024] - Capacidad inicial del `controlBus`,
120
+ * en bytes. Debe ser un entero seguro en el rango
121
+ * [HEADER_SIZE, 0x80000000].
122
+ *
123
+ * @throws {RangeError} Si `size` se encuentra fuera del rango permitido.
124
+ * @throws {RangeError} Si `bucketSize` no es un identificador de bucket válido.
125
+ * @throws {RangeError} Si `metadataSize` se encuentra fuera del rango permitido.
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
+ // ========== ASIGNACIÓN ==========
172
+
173
+ /**
174
+ * Asigna un nuevo bloque de memoria.
175
+ *
176
+ * La capacidad solicitada se convierte a la potencia de dos más pequeña que
177
+ * admita `size` elementos. El bloque se obtiene preferentemente de la lista
178
+ * de regiones reciclables con la capacidad correspondiente; si no existe
179
+ * una región compatible, el bloque se reserva en la parte superior del `dataBus`.
180
+ *
181
+ * A continuación, se obtiene una cabecera del espacio de control. Las cabeceras
182
+ * liberadas previamente pueden reutilizarse mediante la pila interna de reciclaje;
183
+ * de lo contrario, el `controlBus` se expande cuando es necesario.
184
+ *
185
+ * La cabecera recibe la dirección, la capacidad, la ocupación inicial (cero) y
186
+ * un cookie de validación. El valor devuelto codifica la generación de la asignación
187
+ * y la dirección de la cabecera:
188
+ *
189
+ * [11 bits de generación][32 bits de dirección de cabecera]
190
+ *
191
+ * @param {number} [size=16] - Número mínimo de elementos que el bloque debe
192
+ * alojar. Debe ser un entero seguro en el rango [2, 0x80000000].
193
+ * @returns {number} Identificador que identifica el bloque asignado.
194
+ * @throws {RangeError} Si `size` se encuentra fuera del rango permitido.
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
+ * Expande la capacidad de un bloque a la siguiente potencia de dos.
233
+ *
234
+ * Cuando el bloque se encuentra en la parte superior actual del `dataBus`, la expansión
235
+ * se realiza in situ: solo se actualizan su capacidad y el `dataPointer`.
236
+ *
237
+ * En caso de existir otra región después del bloque, se obtiene una nueva región con el doble
238
+ * de capacidad del espacio reciclable o se asigna en la parte superior del `dataBus`.
239
+ * Los elementos ocupados actualmente se copian a la nueva región,
240
+ * y la región anterior se devuelve a la lista de reciclaje.
241
+ *
242
+ * El identificador permanece válido, ya que su cabecera se conserva y solo se
243
+ * actualizan la dirección y la capacidad registradas en él.
244
+ *
245
+ * @param {number} handler - Identificador del bloque a expandir.
246
+ * @returns {void}
247
+ * @throws {Error} Si el identificador es inválido o está corrupto.
248
+ * @throws {AggregateError} Si la capacidad ha alcanzado su límite
249
+ * máximo soportado.
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
+ * Libera un bloque de memoria.
299
+ *
300
+ * La cabecera del bloque se invalida poniendo su cookie a cero y su
301
+ * dirección se registra para su reutilización posterior. La región de datos
302
+ * también se devuelve al sistema de reciclaje, excepto cuando el bloque está
303
+ * exactamente en la parte superior del `dataBus`; en ese caso, el `dataPointer` simplemente
304
+ * retrocede, eliminando la región sin crear una entrada en la lista de
305
+ * reciclaje.
306
+ *
307
+ * @param {number} handler - Identificador del bloque a liberar.
308
+ * @returns {void}
309
+ * @throws {Error} Si el identificador es inválido o está corrupto.
310
+ */
311
+ free(handler) {
312
+ const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
313
+ let headerAddress = handler >>> 0;
314
+
315
+ const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
316
+ const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
317
+ const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
318
+
319
+
320
+ if (cookie !== this.bakeCookie(headerAddress, generation)) {
321
+ throw new Error("Invalid or corrupted handle");
322
+ }
323
+
324
+ const blockSize = (1 << capacity >>> 0) * this.wordSize;
325
+
326
+ this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
327
+
328
+ if (this.echoPointer + 4 <= this.controlBus.byteLength) {
329
+ this.controlAdapter.setUint32(this.echoPointer, headerAddress, IS_LITTLE_ENDIAN);
330
+ this.echoPointer += 4;
331
+ }
332
+
333
+
334
+ if (dataAddress + blockSize === this.dataPointer) {
335
+ this.dataPointer = dataAddress;
336
+ } else {
337
+ this.recyclePush(blockSize, dataAddress);
338
+ }
339
+
340
+ }
341
+
342
+ // ========== RECICLAJE ==========
343
+
344
+ /**
345
+ * [USO INTERNO]
346
+ * Inserta una región libre en la lista de reciclaje.
347
+ *
348
+ * La lista se organiza por capacidad en bytes. Para cada capacidad, el
349
+ * valor almacenado es un `Uint32Array` cuya posición cero contiene la cantidad
350
+ * de direcciones registradas y las posiciones siguientes contienen las direcciones
351
+ * de las regiones libres:
352
+ *
353
+ * [count, address1, address2, ...]
354
+ *
355
+ * Cuando la página se llena, su búster se expande al doble de la
356
+ * capacidad actual.
357
+ *
358
+ * @param {number} capacity - Capacidad de la región libre, en bytes.
359
+ * @param {number} address - Dirección inicial de la región en el `dataBus`.
360
+ * @returns {void}
361
+ * @private
362
+ */
363
+ recyclePush(capacity, address) {
364
+ if (this.recycle.has(capacity)) {
365
+ let page = this.recycle.get(capacity);
366
+ const count = page[0];
367
+
368
+ if (count === page.length - 1) {
369
+ const newBuffer = page.buffer.transfer(page.buffer.byteLength * 2);
370
+ page = new Uint32Array(newBuffer);
371
+ this.recycle.set(capacity, page);
372
+ }
373
+
374
+ page[count + 1] = address;
375
+ page[0] = count + 1;
376
+ } else {
377
+ this.recycle.set(capacity, new Uint32Array([1, address]));
378
+ }
379
+ }
380
+
381
+ /**
382
+ * [USO INTERNO]
383
+ * Elimina una región libre de la lista de reciclaje.
384
+ *
385
+ * La búsqueda se realiza por la capacidad exacta solicitada. Cuando existe una
386
+ * página correspondiente, la última dirección registrada se elimina de la
387
+ * página y se devuelve, implementando el reciclaje como una pila LIFO.
388
+ *
389
+ * @param {number} capacity - Capacidad deseada, en bytes.
390
+ * @returns {number} Dirección inicial de una región reciclable o `UNKNOWN`
391
+ * cuando no existe una región con la capacidad solicitada.
392
+ * @private
393
+ */
394
+ recyclePop(capacity) {
395
+ if (!this.recycle.has(capacity)) return UNKNOWN;
396
+
397
+ const page = this.recycle.get(capacity);
398
+ const count = page[0];
399
+
400
+ if (count === 0) return UNKNOWN;
401
+
402
+ const address = page[count];
403
+ page[0] = count - 1;
404
+
405
+ return address;
406
+ }
407
+
408
+ // ========== RECOLECCIÓN DE BASURA ==========
409
+ /**
410
+ * Compacta el `dataBus` mediante el algoritmo ReBump.
411
+ *
412
+ * Recorre secuencialmente las cabeceras registradas en el `controlBus` y copia
413
+ * las regiones que aún son válidas a un nuevo `dataBus`, eliminando los espacios
414
+ * libres existentes entre ellas. La dirección de cada bloque superviviente se
415
+ * actualiza en su respectiva cabecera.
416
+ *
417
+ * Se preserva el orden de los bloques en el `controlBus`. Los datos internos de
418
+ * cada bloque también se conservan íntegramente, incluyendo su capacidad
419
+ * reservada y su ocupación actual.
420
+ *
421
+ * Al finalizar la compactación:
422
+ * - se eliminan todas las regiones reciclables;
423
+ * - `dataPointer` apunta al primer byte después del último bloque
424
+ * activo;
425
+ * - el `dataBus` pasa a representar un montón contiguo para los bloques activos.
426
+ *
427
+ * La complejidad de control es O(n), donde `n` es el número de cabeceras
428
+ * recorridas. El coste efectivo del movimiento de memoria también depende
429
+ * del volumen de bytes pertenecientes a los bloques activos.
430
+ *
431
+ * @returns {void}
432
+ */
433
+ gc() {
434
+ const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
435
+ this.recycle.clear();
436
+ this.dataPointer = 0 >>> 0;
437
+ for (let i = 0; i < this.controlPointer; i+= HEADER_SIZE) {
438
+ if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
439
+ const start = this.controlAdapter.getUint32(i + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
440
+ const size = (1 << this.controlBus[i + CAPACITY_OFFSET] >>> 0) * this.wordSize;
441
+ const end = start + size;
442
+ newDataBus.set(this.dataBus.subarray(start, end), this.dataPointer);
443
+ this.controlAdapter.setUint32(i + ADDRESS_OFFSET, this.dataPointer, IS_LITTLE_ENDIAN);
444
+ this.dataPointer += size;
445
+ }
446
+ this.dataBus = newDataBus;
447
+ this.dataAdapter = new DataView(this.dataBus.buffer);
448
+ this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
449
+ this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
450
+ this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
451
+ }
452
+
453
+ // ========== ESCALADO ==========
454
+ /**
455
+ * [!!! USO INTERNO, NO USAR EN TU CÓDIGO !!!]
456
+ * Expande el `dataBus` al doble de su capacidad actual.
457
+ *
458
+ * El búster subyacente se transfiere a un `ArrayBuffer` mayor, preservando
459
+ * los datos existentes. Todas las vistas asociadas al búster se recrean
460
+ * para hacer referencia al nuevo almacenamiento.
461
+ *
462
+ * @returns {void}
463
+ * @throws {RangeError} Si la capacidad del `dataBus` ha excedido el
464
+ * límite máximo soportado.
465
+ * @private
466
+ */
467
+ grow() {
468
+ if (this.size > 0x80000000) throw new RangeError("Data bus capacity exceeded");
469
+
470
+ const newSize = (this.size * 2) >>> 0;
471
+ const newBuffer = this.dataBus.buffer.transfer(newSize);
472
+
473
+ this.size = newSize;
474
+ this.dataBus = new Uint8Array(newBuffer);
475
+ this.dataAdapter = new DataView(newBuffer);
476
+ this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
477
+ this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
478
+ this.auxiliary = new this.bucketArray(newBuffer);
479
+ }
480
+
481
+ /**
482
+ * [!!! USO INTERNO, NO USAR EN TU CÓDIGO !!!]
483
+ * Expande el `controlBus` al doble de su capacidad actual.
484
+ *
485
+ * El búster subyacente se transfiere a un `ArrayBuffer` mayor, preservando
486
+ * las cabeceras existentes. El `controlAdapter` se recrea para hacer referencia
487
+ * al nuevo almacenamiento.
488
+ *
489
+ * @returns {void}
490
+ * @throws {RangeError} Si la capacidad actual del `controlBus` ha
491
+ * excedido el límite máximo soportado.
492
+ * @private
493
+ */
494
+ headerGrow() {
495
+ if (this.controlBus.byteLength > 0x80000000) throw new RangeError("Control bus capacity exceeded");
496
+ const newSize = (this.controlBus.byteLength * 2) >>> 0;
497
+ const newBuffer = this.controlBus.buffer.transfer(newSize);
498
+
499
+ this.controlBus = new Uint8Array(newBuffer);
500
+ this.controlAdapter = new DataView(newBuffer);
501
+ }
502
+
503
+ // ========== OPERACIONES DE PILA ==========
504
+
505
+ /**
506
+ * Añade un elemento al final de la secuencia ocupada por el bloque.
507
+ *
508
+ * El elemento se graba en la primera posición libre tras el último elemento
509
+ * ocupado. La ocupación del bloque se incrementa solo cuando existe espacio
510
+ * disponible en su capacidad.
511
+ *
512
+ * @param {number} handler - Identificador del bloque.
513
+ * @param {number} value - Valor a insertar.
514
+ * @returns {boolean} `true` si el valor fue insertado; `false` si el bloque
515
+ * ya no dispone de espacio libre.
516
+ * @throws {Error} Si el identificador es inválido o está corrupto.
517
+ */
518
+ push(handler, value) {
519
+
520
+ const meta = this.extractMetadata(handler, this.metadata);
521
+
522
+ if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
523
+
524
+ this.writer(meta.dataAddress + meta.occupied * this.wordSize , value, IS_LITTLE_ENDIAN);
525
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1,IS_LITTLE_ENDIAN);
526
+
527
+ return true;
528
+ }
529
+
530
+ /**
531
+ * Elimina el último elemento ocupado del bloque y lo devuelve.
532
+ *
533
+ * La ocupación se decrementa antes de leer el elemento eliminado. Los
534
+ * bytes correspondientes no se limpian y permanecen en la región asignada,
535
+ * pero dejan de formar parte de la secuencia ocupada.
536
+ *
537
+ * @param {number} handler - Identificador del bloque.
538
+ * @returns {number|undefined} Valor eliminado o `undefined` si el bloque
539
+ * está vacío.
540
+ * @throws {Error} Si el identificador es inválido o está corrupto.
541
+ */
542
+ pop(handler) {
543
+ const meta = this.extractMetadata(handler, this.metadata);
544
+
545
+ if (meta.occupied === 0) return undefined;
546
+
547
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1,IS_LITTLE_ENDIAN);
548
+ return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
549
+ }
550
+
551
+ /**
552
+ * Devuelve el último elemento ocupado sin eliminarlo.
553
+ *
554
+ * @param {number} handler - Identificador del bloque.
555
+ * @returns {number|undefined} Último valor ocupado o `undefined` si el
556
+ * bloque está vacío.
557
+ * @throws {Error} Si el identificador es inválido o está corrupto.
558
+ */
559
+ peek(handler) {
560
+ const meta = this.extractMetadata(handler, this.metadata);
561
+
562
+ if (meta.occupied === 0) return undefined;
563
+
564
+ return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
565
+ }
566
+
567
+ // ========== OPERACIONES DE COLA ==========
568
+
569
+ /**
570
+ * Inserta un elemento al inicio de la secuencia ocupada.
571
+ *
572
+ * Los elementos ocupados actualmente se desplazan una posición hacia
573
+ * adelante y `value` se graba en la primera posición. La operación exige una
574
+ * posición libre en la capacidad del bloque.
575
+ *
576
+ * El coste de la operación es proporcional al número de elementos ocupados,
577
+ * ya que los datos deben desplazarse.
578
+ *
579
+ * @param {number} handler - Identificador del bloque.
580
+ * @param {number} value - Valor a insertar.
581
+ * @returns {boolean} `true` si el valor fue insertado; `false` si el bloque
582
+ * está lleno.
583
+ * @throws {Error} Si el identificador es inválido o está corrupto.
584
+ */
585
+ nudge(handler, value) {
586
+ const meta = this.extractMetadata(handler, this.metadata);
587
+
588
+ if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
589
+
590
+ this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
591
+ this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
592
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1,IS_LITTLE_ENDIAN);
593
+
594
+ return true;
595
+ }
596
+
597
+ /**
598
+ * Elimina el primer elemento ocupado del bloque y lo devuelve.
599
+ *
600
+ * Los elementos restantes se desplazan una posición hacia el inicio
601
+ * de la región ocupada. La capacidad física del bloque permanece inalterada.
602
+ *
603
+ * El coste de la operación es proporcional al número de elementos desplazados.
604
+ *
605
+ * @param {number} handler - Identificador del bloque.
606
+ * @returns {number|undefined} Primer valor eliminado o `undefined` si el
607
+ * bloque está vacío.
608
+ * @throws {Error} Si el identificador es inválido o está corrupto.
609
+ */
610
+ pull(handler) {
611
+ const meta = this.extractMetadata(handler, this.metadata);
612
+
613
+ if (meta.occupied === 0) return undefined;
614
+
615
+ const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
616
+ this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
617
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
618
+ return result;
619
+ }
620
+
621
+ /**
622
+ * Devuelve el primer elemento ocupado sin eliminarlo.
623
+ *
624
+ * @param {number} handler - Identificador del bloque.
625
+ * @returns {number|undefined} Primer valor ocupado o `undefined` si el
626
+ * bloque está vacío.
627
+ * @throws {Error} Si el identificador es inválido o está corrupto.
628
+ */
629
+ head(handler) {
630
+ const meta = this.extractMetadata(handler, this.metadata);
631
+
632
+ if (meta.occupied === 0) return undefined;
633
+
634
+ return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
635
+ }
636
+
637
+ // ========== ACCESO ALEATORIO ==========
638
+
639
+ /**
640
+ * Comprueba si un valor está presente entre los elementos ocupados del bloque.
641
+ *
642
+ * La búsqueda se realiza directamente sobre el `TypedArray` auxiliar y considera
643
+ * únicamente el intervalo ocupado actualmente, no toda la capacidad física
644
+ * reservada.
645
+ *
646
+ * @param {number} handler - Identificador del bloque.
647
+ * @param {number} value - Valor a buscar.
648
+ * @returns {boolean} `true` si `value` está presente entre los elementos
649
+ * ocupados; de lo contrario, `false`.
650
+ * @throws {Error} Si el identificador es inválido o está corrupto.
651
+ */
652
+ has(handler, value) {
653
+ const meta = this.extractMetadata(handler, this.metadata);
654
+
655
+ if (meta.occupied === 0) return false;
656
+
657
+ const rawAddres = meta.dataAddress >>> this.wordShift;
658
+
659
+ return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
660
+ }
661
+
662
+ /**
663
+ * Devuelve el elemento ocupado en un índice basado en cero.
664
+ *
665
+ * Los índices fuera del rango `[0, occupied)` no se consideran un error y
666
+ * dan como resultado `undefined`.
667
+ *
668
+ * @param {number} handler - Identificador del bloque.
669
+ * @param {number} index - Índice basado en cero del elemento.
670
+ * @returns {number|undefined} Valor almacenado en el índice o `undefined` si
671
+ * el índice está fuera de la región ocupada.
672
+ * @throws {Error} Si el identificador es inválido o está corrupto.
673
+ */
674
+ get(handler, index) {
675
+
676
+ const meta = this.extractMetadata(handler, this.metadata);
677
+
678
+ if (index < 0 || index >= meta.occupied) return undefined;
679
+
680
+ return this.reader(meta.dataAddress + index * this.wordSize, IS_LITTLE_ENDIAN);
681
+ }
682
+
683
+ /**
684
+ * Sustituye el valor almacenado en un índice ocupado.
685
+ *
686
+ * La operación no altera la ocupación del bloque. Los índices fuera del rango
687
+ * `[0, occupied)` se ignoran y dan como resultado `false`.
688
+ *
689
+ * @param {number} handler - Identificador del bloque.
690
+ * @param {number} index - Índice basado en cero del elemento.
691
+ * @param {number} value - Nuevo valor.
692
+ * @returns {boolean} `true` si el valor fue grabado; `false` si el índice
693
+ * está fuera de la región ocupada.
694
+ * @throws {Error} Si el identificador es inválido o está corrupto.
695
+ */
696
+ set(handler, index, value) {
697
+ const meta = this.extractMetadata(handler, this.metadata);
698
+
699
+ if (index < 0 || index >= meta.occupied) return false;
700
+
701
+ this.writer(meta.dataAddress + index * this.wordSize, value, IS_LITTLE_ENDIAN);
702
+ return true;
703
+ }
704
+
705
+ // ============= MISCELÁNEA ===============
706
+
707
+ /**
708
+ * Pone a cero la ocupación del bloque y llena toda su capacidad física con
709
+ * un mismo valor.
710
+ *
711
+ * El relleno abarca todas las ranuras disponibles, no solo los
712
+ * elementos ocupados actualmente. Tras la operación, el bloque se considera
713
+ * vacío independientemente del valor utilizado en el relleno.
714
+ *
715
+ * @param {number} handler - Identificador del bloque.
716
+ * @param {number} [value=0] - Valor utilizado para rellenar todas las ranuras.
717
+ * @returns {void}
718
+ * @throws {Error} Si el identificador es inválido o está corrupto.
719
+ */
720
+ clear(handler, value=0) {
721
+ const meta = this.extractMetadata(handler, this.metadata);
722
+
723
+ const slots = meta.byteCapacity / this.wordSize;
724
+ const rawAddress = meta.dataAddress >>> this.wordShift;
725
+
726
+ this.auxiliary.fill(value, rawAddress, rawAddress + slots);
727
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
728
+ }
729
+
730
+
731
+ /**
732
+ * Rellena un intervalo de ranuras del bloque con un valor.
733
+ *
734
+ * El intervalo utiliza índices basados en cero y sigue la convención
735
+ * `[start, end)`, por lo que `start` es inclusivo y `end` es exclusivo.
736
+ * Cuando no se proporciona `end`, el relleno se extiende hasta el final de la
737
+ * capacidad física del bloque.
738
+ *
739
+ * La ocupación del bloque pasa a ser `end`, incluso cuando el intervalo
740
+ * rellenado se extiende más allá de la ocupación anterior.
741
+ *
742
+ * @param {number} handler - Identificador del bloque.
743
+ * @param {number} value - Valor utilizado en el relleno.
744
+ * @param {number} [start=0] - Índice inicial, inclusivo.
745
+ * @param {number|null} [end=null] - Índice final, exclusivo. Cuando se
746
+ * omite o es `null`, utiliza la capacidad total del bloque.
747
+ * @returns {void}
748
+ * @throws {Error} Si el identificador es inválido o está corrupto.
749
+ * @throws {RangeError} Si `start` o `end` están fuera de los límites de
750
+ * capacidad, o si `start > end`.
751
+ */
752
+ fill(handler, value, start = 0, end = null) {
753
+ const meta = this.extractMetadata(handler, this.metadata);
754
+
755
+ const slots = meta.byteCapacity / this.wordSize;
756
+ const lastIndex = end ?? slots;
757
+
758
+ if (start > lastIndex) {
759
+ throw new RangeError(`start ${start} must be less or equal than end ${lastIndex}.`);
760
+ }
761
+ if (start < 0 || start > slots) {
762
+ throw new RangeError(`start ${start} out of range [0, ${slots}].`);
763
+ }
764
+ if (lastIndex < 0 || lastIndex > slots) {
765
+ throw new RangeError(`end ${lastIndex} out of range [0, ${slots}].`);
766
+ }
767
+
768
+ const rawAddress = meta.dataAddress >>> this.wordShift;
769
+
770
+ this.auxiliary.fill(value, rawAddress + start, rawAddress + lastIndex);
771
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, lastIndex, IS_LITTLE_ENDIAN);
772
+ }
773
+
774
+ /**
775
+ * Rellena todas las ranuras físicas del bloque con un valor y marca toda la
776
+ * capacidad como ocupada.
777
+ *
778
+ * A diferencia de `clear()`, la operación da como resultado un bloque totalmente
779
+ * ocupado.
780
+ *
781
+ * @param {number} handler - Identificador del bloque.
782
+ * @param {number} value - Valor utilizado en el relleno.
783
+ * @returns {void}
784
+ * @throws {Error} Si el identificador es inválido o está corrupto.
785
+ */
786
+ fillAll(handler, value) {
787
+ const meta = this.extractMetadata(handler, this.metadata);
788
+
789
+ const rawAddress = meta.dataAddress >>> this.wordShift;
790
+ const capacityElements = meta.byteCapacity / this.wordSize;
791
+
792
+ this.auxiliary.fill(value, rawAddress, rawAddress + capacityElements);
793
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, capacityElements, IS_LITTLE_ENDIAN);
794
+ }
795
+
796
+ /**
797
+ * Copia los elementos de un `Array` o `TypedArray` al inicio del bloque.
798
+ *
799
+ * La cantidad copiada está limitada por la capacidad del bloque. La ocupación se
800
+ * actualiza al mayor valor entre la ocupación anterior y la cantidad
801
+ * copiada efectivamente; por lo tanto, una llamada a `put()` no reduce la
802
+ * ocupación existente cuando recibe una secuencia menor.
803
+ *
804
+ * Para `Array`, solo se copian los primeros elementos que quepan.
805
+ * Para `TypedArray`, se utiliza un subarreglo del origen sin copia
806
+ * intermedia.
807
+ *
808
+ * @param {number} handler - Identificador del bloque.
809
+ * @param {Array|TypedArray} data - Secuencia de valores a copiar.
810
+ * @returns {void}
811
+ * @throws {Error} Si el identificador es inválido o está corrupto.
812
+ * @throws {TypeError} Si `data` no es ni un `Array` ni un `TypedArray`.
813
+ */
814
+ put(handler, data) {
815
+ const meta = this.extractMetadata(handler, this.metadata);
816
+
817
+ const rawAddress = meta.dataAddress >>> this.wordShift;
818
+ const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
819
+
820
+ meta.occupied = Math.max(length, meta.occupied);
821
+
822
+ if (Array.isArray(data)) {
823
+ this.auxiliary.set(data.slice(0, length), rawAddress);
824
+ } else if (isTypedArray(data)) {
825
+ this.auxiliary.set(data.subarray(0, length), rawAddress);
826
+ } else {
827
+ const actual = data?.constructor?.name ?? (data === null ? 'null' : typeof data);
828
+ throw new TypeError(`data must be Array or TypedArray, but ${actual} was given.`);
829
+ }
830
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
831
+ }
832
+
833
+ /**
834
+ * Devuelve una copia de los elementos ocupados actualmente por el bloque.
835
+ *
836
+ * El resultado es un `TypedArray` del mismo tipo configurado por
837
+ * `bucketSize`. La capacidad física no ocupada no se incluye en el resultado.
838
+ *
839
+ * La operación no expone directamente el almacenamiento interno: el método
840
+ * utiliza `TypedArray.prototype.slice()`, produciendo una nueva vista con
841
+ * almacenamiento independiente.
842
+ *
843
+ * @param {number} handler - Identificador del bloque.
844
+ * @returns {TypedArray} Copia de los elementos ocupados por el bloque. Cuando
845
+ * el bloque está vacío, devuelve un `TypedArray` vacío del tipo configurado.
846
+ * @throws {Error} Si el identificador es inválido o está corrupto.
847
+ */
848
+ pick(handler) {
849
+ const meta = this.extractMetadata(handler, this.metadata);
850
+
851
+ const rawAddress = meta.dataAddress >>> this.wordShift;
852
+
853
+ if (meta.occupied === 0) {
854
+ return this.auxiliary.slice(rawAddress, rawAddress);
855
+ }
856
+
857
+ return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
858
+ }
859
+
860
+ // ======== CAPACIDAD EN RANURAS ==========
861
+
862
+ /**
863
+ * Devuelve la capacidad física del bloque en bytes.
864
+ *
865
+ * La capacidad corresponde al espacio reservado para todas las ranuras del
866
+ * bloque, independientemente de cuántos elementos estén ocupados actualmente.
867
+ *
868
+ * @param {number} handler - Identificador del bloque.
869
+ * @returns {number} Capacidad física del bloque, en bytes.
870
+ * @throws {Error} Si el identificador es inválido o está corrupto.
871
+ */
872
+ byteSize(handler) {
873
+ const meta = this.extractMetadata(handler, this.metadata);
874
+ return meta.byteCapacity;
875
+ }
876
+
877
+ /**
878
+ * Devuelve la cantidad de elementos ocupados actualmente en el bloque.
879
+ *
880
+ * @param {number} handler - Identificador del bloque.
881
+ * @returns {number} Número de elementos ocupados.
882
+ * @throws {Error} Si el identificador es inválido o está corrupto.
883
+ */
884
+ occupied(handler){
885
+ const meta = this.extractMetadata(handler, this.metadata);
886
+ return meta.occupied;
887
+
888
+ }
889
+
890
+ /**
891
+ * Devuelve la capacidad del bloque en número de elementos.
892
+ *
893
+ * El valor corresponde a la cantidad total de ranuras reservadas físicamente,
894
+ * y no a la cantidad ocupada actualmente.
895
+ *
896
+ * @param {number} handler - Identificador del bloque.
897
+ * @returns {number} Número total de ranuras disponibles en el bloque.
898
+ * @throws {Error} Si el identificador es inválido o está corrupto.
899
+ */
900
+ length(handler) {
901
+ const meta = this.extractMetadata(handler, this.metadata);
902
+ return 1 << meta.capacityExponent >>> 0;
903
+ }
904
+
905
+ // ========== Operaciones entre bloques=============
906
+
907
+ /**
908
+ * Copia elementos ocupados de un bloque a otro.
909
+ *
910
+ * La copia comienza en el primer elemento de `source` y la primera ranura de
911
+ * `destiny`. La cantidad copiada de forma efectiva está limitada por el número de
912
+ * elementos ocupados en el origen, la capacidad física del destino y el límite
913
+ * especificado en `slots`.
914
+ *
915
+ * La ocupación del destino se incrementa, cuando es necesario, para abarcar los
916
+ * elementos copiados. La capacidad del destino no se altera.
917
+ *
918
+ * La operación utiliza `Uint8Array.prototype.copyWithin()` sobre el `dataBus`,
919
+ * por lo tanto el valor devuelto es el propio `Uint8Array` que representa el bus de datos.
920
+ *
921
+ * @param {number} source - Identificador del bloque de origen.
922
+ * @param {number} destiny - Identificador del bloque de destino.
923
+ * @param {number} [slots=UNKNOWN] - Número máximo de elementos a copiar.
924
+ * `UNKNOWN` representa el valor centinela utilizado para no imponer un
925
+ * límite adicional.
926
+ * @returns {Uint8Array} El `dataBus` después de la operación.
927
+ * @throws {Error} Si `source` o `destiny` son inválidos o están corruptos.
928
+ */
929
+ copy(source, destiny, slots = UNKNOWN){
930
+ /** @type {Metadata} */
931
+ const metaA = {};
932
+ /** @type {Metadata} */
933
+ const metaB = {};
934
+
935
+ this.extractMetadata(source, metaA);
936
+ this.extractMetadata(destiny, metaB);
937
+
938
+ const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
939
+ const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
940
+ const newOccupied = Math.max(metaB.occupied, slotsToCopy);
941
+
942
+ this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
943
+
944
+ return this.dataBus.copyWithin(metaB.dataAddress, metaA.dataAddress, metaA.dataAddress + slotsToCopy * this.wordSize);
945
+ }
946
+
947
+ /**
948
+ * Copia una región de elementos dentro del propio bloque.
949
+ *
950
+ * Los índices están basados en cero y siguen la semántica de
951
+ * `Array.prototype.copyWithin()`: `target` identifica la posición de destino,
952
+ * `start` la posición inicial del origen y `length` la cantidad máxima de
953
+ * elementos a copiar.
954
+ *
955
+ * Los índices negativos se interpretan a partir del final de la capacidad del
956
+ * bloque. Tras dicha normalización, los índices se limitan a la capacidad
957
+ * física. La cantidad copiada también se ve limitada por los elementos
958
+ * ocupados efectivamente y el espacio disponible a partir de `target`.
959
+ *
960
+ * La operación admite regiones superpuestas y puede incrementar la ocupación del
961
+ * bloque cuando el intervalo de destino supera la ocupación actual.
962
+ *
963
+ * @param {number} handler - Identificador del bloque.
964
+ * @param {number} target - Índice inicial del destino.
965
+ * @param {number} start - Índice inicial del origen.
966
+ * @param {number} length - Número máximo de elementos a copiar.
967
+ * @returns {Uint8Array} El `dataBus` después de la operación.
968
+ * @throws {Error} Si el identificador es inválido o está corrupto.
969
+ */
970
+ copyWithin(handler, target, start, length) {
971
+ const meta = this.extractMetadata(handler, this.metadata);
972
+ const slots = Math.floor(meta.byteCapacity / this.wordSize);
973
+
974
+ target = Math.trunc(target);
975
+ start = Math.trunc(start);
976
+ length = Math.trunc(length);
977
+
978
+ if (target < 0) target += slots;
979
+ if (start < 0) start += slots;
980
+
981
+ // Limita los índices dentro de los límites de capacidad
982
+ target = Math.max(0, Math.min(target, slots));
983
+ start = Math.max(0, Math.min(start, slots));
984
+
985
+ // Limita la copia al espacio disponible a partir de target
986
+ // y a los elementos ocupados efectivamente a partir de start
987
+ const maxRead = Math.max(0, meta.occupied - start);
988
+ const maxWrite = slots - target;
989
+ length = Math.max(0, Math.min(length, maxRead, maxWrite));
990
+
991
+ if (length === 0) return this.dataBus;
992
+
993
+ const targetAddress = meta.dataAddress + target * this.wordSize;
994
+ const sourceAddress = meta.dataAddress + start * this.wordSize;
995
+
996
+ // Actualiza la ocupación en caso de que la copia expanda la parte superior ocupada del bloque
997
+ const newOccupied = Math.max(meta.occupied, target + length);
998
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
999
+
1000
+ return this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + length * this.wordSize);
1001
+ }
1002
+
1003
+ /**
1004
+ * Añade los elementos ocupados de `source` al final de `target`.
1005
+ *
1006
+ * La cantidad copiada está limitada por el número de elementos ocupados en el
1007
+ * origen y el espacio libre restante en la capacidad del destino.
1008
+ *
1009
+ * La operación admite que `target` y `source` hagan referencia al mismo bloque.
1010
+ * En ese caso, la copia se realiza sobre la propia región del bloque y
1011
+ * preserva la semántica de superposición de `copyWithin()`.
1012
+ *
1013
+ * @param {number} target - Identificador del bloque que recibirá los elementos.
1014
+ * @param {number} source - Identificador del bloque cuyos elementos serán
1015
+ * añadidos.
1016
+ * @returns {number} Número de elementos añadidos efectivamente.
1017
+ * @throws {Error} Si `target` o `source` son inválidos o están corruptos.
1018
+ */
1019
+ append(target, source) {
1020
+ const metaTarget = {};
1021
+ const metaSource = {};
1022
+
1023
+ this.extractMetadata(target, metaTarget);
1024
+ this.extractMetadata(source, metaSource);
1025
+
1026
+ const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
1027
+ const count = Math.min(available, metaSource.occupied);
1028
+
1029
+ if (count === 0) return 0;
1030
+
1031
+ const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
1032
+ const sourceAddress = metaSource.dataAddress;
1033
+
1034
+ if (target === source) {
1035
+ this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
1036
+ } else {
1037
+ this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
1038
+ }
1039
+
1040
+ this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
1041
+
1042
+ return count;
1043
+ }
1044
+
1045
+ /**
1046
+ * Crea una copia independiente de un bloque.
1047
+ *
1048
+ * El nuevo bloque posee la misma capacidad física y la misma ocupación del
1049
+ * bloque original. Se copian todos los bytes de la región reservada, incluyendo
1050
+ * las posiciones no ocupadas actualmente.
1051
+ *
1052
+ * El nuevo bloque recibe un nuevo identificador y permanece sujeto a las reglas
1053
+ * normales de asignación y reciclaje.
1054
+ *
1055
+ * @param {number} handler - Identificador del bloque a clonar.
1056
+ * @returns {number} Identificador del nuevo bloque.
1057
+ * @throws {Error} Si el identificador es inválido o está corrupto.
1058
+ */
1059
+ clone(handler) {
1060
+ const meta = this.extractMetadata(handler, this.metadata);
1061
+ const cloned = this.alloc(meta.byteCapacity / this.wordSize);
1062
+
1063
+ const cloneMeta = {};
1064
+ this.extractMetadata(cloned, cloneMeta);
1065
+
1066
+ this.dataBus.copyWithin(cloneMeta.dataAddress, meta.dataAddress, meta.dataAddress + meta.byteCapacity);
1067
+ this.controlAdapter.setUint32(cloneMeta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
1068
+
1069
+ return cloned;
1070
+ }
1071
+
1072
+ /**
1073
+ * Intercambia las regiones de datos asociadas a dos bloques.
1074
+ *
1075
+ * La operación intercambia entre las cabeceras las direcciones de las regiones, sus
1076
+ * capacidades y sus ocupaciones. Los identificadores permanecen inalterados:
1077
+ * después de la operación, cada identificador continúa identificando su propia
1078
+ * cabecera, pero dicha cabecera pasa a describir la región que pertenecía
1079
+ * anteriormente al otro bloque.
1080
+ *
1081
+ * No se copia ningún dato en el `dataBus`; solo se modifican los metadatos de ambas
1082
+ * cabeceras.
1083
+ *
1084
+ * @param {number} source - Identificador del primer bloque.
1085
+ * @param {number} target - Identificador del segundo bloque.
1086
+ * @returns {void}
1087
+ * @throws {Error} Si `source` o `target` son inválidos o están corruptos.
1088
+ */
1089
+ swap(source, target) {
1090
+ /** @type {Metadata} */
1091
+ const metaA = {};
1092
+ /** @type {Metadata} */
1093
+ const metaB = {};
1094
+
1095
+ this.extractMetadata(source, metaA);
1096
+ this.extractMetadata(target, metaB);
1097
+
1098
+ this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
1099
+ this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
1100
+
1101
+ this.controlAdapter.setUint8(metaA.headerAddress + CAPACITY_OFFSET, metaB.capacityExponent);
1102
+ this.controlAdapter.setUint8(metaB.headerAddress + CAPACITY_OFFSET, metaA.capacityExponent);
1103
+
1104
+ this.controlAdapter.setUint32(metaA.headerAddress + OCCUPIED_OFFSET, metaB.occupied, IS_LITTLE_ENDIAN);
1105
+ this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, metaA.occupied, IS_LITTLE_ENDIAN);
1106
+ }
1107
+
1108
+
1109
+ // ============= SERIALIZACIÓN ==============
1110
+
1111
+ /**
1112
+ * Serializa el contenido y los metadatos de un bloque de memoria.
1113
+ *
1114
+ * El método extrae los datos ocupados del bloque mediante `pick()`,
1115
+ * los agrupa junto con la información de capacidad y tipo de palabra
1116
+ * en un sobre de datos y los codifica utilizando el formato CBOR.
1117
+ *
1118
+ * @param {number} handler - Identificador del bloque a serializar.
1119
+ * @returns {Uint8Array} Un búster que contiene los datos serializados del bloque.
1120
+ * @throws {Error} Si el identificador es inválido o está corrupto.
1121
+ */
1122
+ dump(handler) {
1123
+ const meta = this.extractMetadata(handler, this.metadata);
1124
+ const capacity = meta.capacityExponent;
1125
+ const capacityElements = 2 ** capacity;
1126
+
1127
+ if (!Number.isInteger(capacity) || capacity < 1 || capacity > 31 || meta.occupied > capacityElements) {
1128
+ throw new Error("Cannot serialize a block with invalid metadata");
1129
+ }
1130
+
1131
+ const payload = this.pick(handler);
1132
+
1133
+ if (payload.length !== meta.occupied || payload.constructor !== this.bucketArray) {
1134
+ throw new Error("Cannot serialize a block with an invalid payload");
1135
+ }
1136
+
1137
+ return encode({
1138
+ v: 1,
1139
+ wordType: this.wordType,
1140
+ capacity,
1141
+ occupied: meta.occupied,
1142
+ le: IS_LITTLE_ENDIAN,
1143
+ payload
1144
+ });
1145
+ }
1146
+
1147
+ /**
1148
+ * Restaura un bloque de memoria a partir de datos serializados.
1149
+ *
1150
+ * Decodifica el sobre CBOR, valida si el tipo de palabra del dato
1151
+ * serializado es compatible con la instancia actual del asignador y asigna
1152
+ * un nuevo bloque con la capacidad necesaria para alojar el contenido.
1153
+ * A continuación, se restauran los datos y la ocupación original en el nuevo bloque.
1154
+ *
1155
+ * @param {Uint8Array|ArrayBuffer} serialized - Búster que contiene los datos serializados.
1156
+ * @returns {number} Identificador del nuevo bloque recreado.
1157
+ * @throws {Error} Si el tipo de palabra del dato decodificado difiere del configurado en el asignador.
1158
+ */
1159
+ load(serialized) {
1160
+ if (!(serialized instanceof ArrayBuffer) && !(serialized instanceof Uint8Array)) {
1161
+ throw new TypeError("serialized must be an ArrayBuffer or Uint8Array");
1162
+ }
1163
+
1164
+ const envelope = decode(serialized);
1165
+
1166
+ if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)) {
1167
+ throw new TypeError("Invalid serialized block envelope");
1168
+ }
1169
+
1170
+ if (envelope.v !== 1) {
1171
+ throw new Error(`Unsupported serialized block version: ${envelope.v}`);
1172
+ }
1173
+
1174
+ if (envelope.wordType !== this.wordType) {
1175
+ throw new Error(`Can't load data, ${this.wordType} expected but ${envelope.wordType} found.`);
1176
+ }
1177
+
1178
+ if (!Number.isInteger(envelope.capacity) || envelope.capacity < 1 || envelope.capacity > 31) {
1179
+ throw new RangeError("Invalid serialized block capacity");
1180
+ }
1181
+
1182
+ const capacityElements = 2 ** envelope.capacity;
1183
+
1184
+ if (!Number.isSafeInteger(envelope.occupied) || envelope.occupied < 0 || envelope.occupied > capacityElements) {
1185
+ throw new RangeError("Invalid serialized block occupancy");
1186
+ }
1187
+
1188
+ if (typeof envelope.le !== "boolean") {
1189
+ throw new TypeError("Invalid serialized endianness flag");
1190
+ }
1191
+
1192
+ const payload = envelope.payload;
1193
+
1194
+ if (!isTypedArray(payload) || payload.constructor !== this.bucketArray || payload.length !== envelope.occupied) {
1195
+ throw new TypeError(`Invalid payload: expected ${this.bucketType}Array with ${envelope.occupied} elements`);
1196
+ }
1197
+
1198
+ if (payload.BYTES_PER_ELEMENT !== this.wordSize || payload.byteLength !== envelope.occupied * this.wordSize) {
1199
+ throw new TypeError("Serialized payload has an invalid element size");
1200
+ }
1201
+
1202
+ const handler = this.alloc(capacityElements);
1203
+ const meta = this.extractMetadata(handler, this.metadata);
1204
+ this.put(handler, payload);
1205
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, envelope.occupied, IS_LITTLE_ENDIAN);
1206
+
1207
+ return handler;
1208
+ }
1209
+
1210
+ // ============= UTILIDADES ==============
1211
+
1212
+ /**
1213
+ * [USO INTERNO]
1214
+ * Decodifica los metadatos asociados a un identificador.
1215
+ *
1216
+ * El identificador se divide en generación y dirección de la cabecera. El cookie almacenado
1217
+ * en la cabecera se recalcula para validar la combinación; solo tras
1218
+ * dicha validación se leen los metadatos.
1219
+ *
1220
+ * Los campos decodificados se escriben en el objeto `out`, el cual es devuelto
1221
+ * por la propia función. El objeto se puede reutilizar entre llamadas para
1222
+ * evitar nuevas asignaciones.
1223
+ *
1224
+ * @param {number} handler - Identificador a decodificar y validar.
1225
+ * @param {Metadata} out - Objeto que recibirá los metadatos decodificados.
1226
+ * @returns {Metadata} La misma referencia proporcionada en `out`.
1227
+ * @throws {Error} Si el cookie de la cabecera no coincide con el identificador o
1228
+ * si el identificador no identifica una cabecera válida.
1229
+ * @private
1230
+ */
1231
+ extractMetadata(handler, out) {
1232
+ out.generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
1233
+ out.headerAddress = handler >>> 0;
1234
+
1235
+ const cookie = this.controlAdapter.getUint8(out.headerAddress + COOKIE_OFFSET);
1236
+
1237
+
1238
+ if (cookie !== this.bakeCookie(out.headerAddress, out.generation)) {
1239
+ throw new Error("Invalid or corrupted handle");
1240
+ }
1241
+
1242
+ out.dataAddress = this.controlAdapter.getUint32(out.headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
1243
+ out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1244
+ out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
1245
+ out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
1246
+
1247
+ return out;
1248
+ }
1249
+
1250
+
1251
+ /**
1252
+ * [USO INTERNO]
1253
+ * Calcula el cookie de validación de una cabecera.
1254
+ *
1255
+ * El cookie se deriva de la dirección de la cabecera y de los 11 bits de la generación mediante
1256
+ * un hash rápido.
1257
+ * El resultado se reduce a 8 bits.
1258
+ *
1259
+ * El valor cero se reserva como indicador de cabecera inválida; por este motivo,
1260
+ * cuando el cálculo produce cero, el método devuelve `1`.
1261
+ *
1262
+ * El cookie no constituye un mecanismo criptográfico. Su finalidad es
1263
+ * detectar identificadores inválidos, obsoletos o corruptos dentro del modelo de
1264
+ * gestión de memoria del asignador.
1265
+ *
1266
+ * @param {number} addr - Dirección de la cabecera.
1267
+ * @param {number} gen - Generación asociada al identificador. Solo se consideran los 11 bits
1268
+ * menos significativos.
1269
+ * @returns {number} Cookie de 8 bits en el rango [1, 255].
1270
+ * @private
1271
+ */
1272
+ bakeCookie(addr, gen) {
1273
+ return (addr ^ (gen & 0x7FF * 0x9e3779b1)) & 0xff || 1;
1274
+ }
1275
+
1276
+ /**
1277
+ * Devuelve la cantidad de regiones almacenadas actualmente en la lista de
1278
+ * reciclaje.
1279
+ *
1280
+ * Cada región corresponde a un bloque liberado que no pudo devolverse
1281
+ * directamente a la parte superior del `dataBus` y, por tanto, permanece disponible para
1282
+ * su reutilización en una asignación futura de capacidad idéntica.
1283
+ *
1284
+ * @returns {number} Número de regiones libres mantenidas en `recycle`.
1285
+ */
1286
+ recycleCount() {
1287
+ let count = 0;
1288
+
1289
+ for (const [, page] of this.recycle) {
1290
+ count += page[0];
1291
+ }
1292
+
1293
+ return count;
1294
+ }
1295
+
1296
+ /**
1297
+ * Devuelve el total de bytes pertenecientes a las regiones almacenadas
1298
+ * actualmente en la lista de reciclaje.
1299
+ *
1300
+ * El valor se calcula sumando la capacidad de cada región libre multiplicada
1301
+ * por la cantidad de regiones registradas para dicha capacidad.
1302
+ *
1303
+ * @returns {number} Número de bytes ocupados por regiones reciclables.
1304
+ */
1305
+ get recycleBytes() {
1306
+ let total = 0;
1307
+
1308
+ for (const [capacity, page] of this.recycle) {
1309
+ total += page[0] * capacity;
1310
+ }
1311
+
1312
+ return total;
1313
+ }
1314
+
1315
+ /**
1316
+ * Devuelve la cantidad de bytes asignados que no pertenecen a las regiones
1317
+ * reciclables actualmente.
1318
+ *
1319
+ * El valor se obtiene restando del avance total del `dataPointer` los bytes
1320
+ * pertenecientes a las regiones libres mantenidas en `recycle`.
1321
+ *
1322
+ * @returns {number} Número de bytes asociados a regiones no reciclables
1323
+ * dentro del área ya utilizada por el `dataBus`.
1324
+ */
1325
+ get allocatedBytes() {
1326
+ return this.dataPointer - this.recycleBytes;
1327
+ }
1328
+
1329
+ /**
1330
+ * Devuelve la cantidad de bytes que aún no se han utilizado en la parte superior del `dataBus`.
1331
+ *
1332
+ * Este espacio corresponde a la región comprendida entre `dataPointer` y el final de la
1333
+ * capacidad reservada actualmente para el búster.
1334
+ *
1335
+ * @returns {number} Número de bytes disponibles después de `dataPointer`.
1336
+ */
1337
+ get unallocatedBytes() {
1338
+ return this.size - this.dataPointer;
1339
+ }
1340
+
1341
+ /**
1342
+ * Devuelve la razón entre la memoria reciclable y el área de montón utilizada.
1343
+ *
1344
+ * La métrica considera como fragmentación las regiones libres mantenidas en
1345
+ * `recycle` y utiliza `dataPointer` como denominador. Cuando no se ha utilizado
1346
+ * ningún byte por el montón, el resultado es cero.
1347
+ *
1348
+ * El valor no representa la fracción de toda la capacidad del `dataBus`, sino
1349
+ * específicamente la proporción de bytes reciclables dentro del área ya
1350
+ * recorrida por el puntero de tipo bump.
1351
+ *
1352
+ * @returns {number} Razón de fragmentación en el rango [0, 1] bajo condiciones
1353
+ * normales de operación.
1354
+ */
1355
+ get fragmentationRatio() {
1356
+ if (this.dataPointer === 0) return 0;
1357
+ return this.recycleBytes / this.dataPointer;
1358
+ }
1359
+
1360
+ }