balloc 1.4.0 → 2.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.MD +157 -334
  3. package/docs/API /342/200/224 balloc.en.md" +478 -1217
  4. package/docs/MIGRATION /342/200/224 balloc.en.md" +208 -0
  5. package/package.json +2 -44
  6. package/src/README.MD +0 -0
  7. package/src/en/balloc.cjs +510 -960
  8. package/src/en/balloc.js +1 -1
  9. package/src/en/balloc.mjs +551 -1099
  10. package/types/README.MD +0 -0
  11. package/types/en/balloc.d.mts +275 -583
  12. package/README.ar.md +0 -439
  13. package/README.en.md +0 -467
  14. package/README.es.md +0 -439
  15. package/README.jp.md +0 -438
  16. package/README.pt.md +0 -462
  17. package/README.zh.md +0 -438
  18. package/docs/API /342/200/224 balloc.ar.md" +0 -1509
  19. package/docs/API /342/200/224 balloc.es.md" +0 -1325
  20. package/docs/API /342/200/224 balloc.jp.md" +0 -1264
  21. package/docs/API /342/200/224 balloc.pt.md" +0 -1395
  22. package/docs/API /342/200/224 balloc.zh.md" +0 -1324
  23. package/src/ar/balloc.cjs +0 -1303
  24. package/src/ar/balloc.js +0 -2
  25. package/src/ar/balloc.mjs +0 -1591
  26. package/src/es/balloc.cjs +0 -1320
  27. package/src/es/balloc.js +0 -2
  28. package/src/es/balloc.mjs +0 -1608
  29. package/src/jp/balloc.cjs +0 -1260
  30. package/src/jp/balloc.js +0 -2
  31. package/src/jp/balloc.mjs +0 -1548
  32. package/src/pt/balloc.cjs +0 -1326
  33. package/src/pt/balloc.js +0 -2
  34. package/src/pt/balloc.mjs +0 -1619
  35. package/src/zh/balloc.cjs +0 -1205
  36. package/src/zh/balloc.js +0 -2
  37. package/src/zh/balloc.mjs +0 -1493
  38. package/types/ar/balloc.d.mts +0 -793
  39. package/types/es/balloc.d.mts +0 -810
  40. package/types/jp/balloc.d.mts +0 -750
  41. package/types/pt/balloc.d.mts +0 -818
  42. package/types/zh/balloc.d.mts +0 -695
package/src/es/balloc.cjs DELETED
@@ -1,1320 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __export = (target, all) => {
6
- for (var name in all)
7
- __defProp(target, name, { get: all[name], enumerable: true });
8
- };
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") {
11
- for (let key of __getOwnPropNames(from))
12
- if (!__hasOwnProp.call(to, key) && key !== except)
13
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
- }
15
- return to;
16
- };
17
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
-
19
- // src/es/balloc.mjs
20
- var balloc_exports = {};
21
- __export(balloc_exports, {
22
- default: () => Balloc
23
- });
24
- module.exports = __toCommonJS(balloc_exports);
25
- var import_cbor_x = require("cbor-x");
26
- var UNKNOWN = 4294967295 >>> 0;
27
- var BUCKET_MAPPING = Object.freeze({
28
- "8u": { type: "Uint8", bits: 8 },
29
- "16u": { type: "Uint16", bits: 16 },
30
- "32u": { type: "Uint32", bits: 32 },
31
- "64u": { type: "BigUint64", bits: 64 },
32
- "8i": { type: "Int8", bits: 8 },
33
- "16i": { type: "Int16", bits: 16 },
34
- "32i": { type: "Int32", bits: 32 },
35
- "64i": { type: "BigInt64", bits: 64 },
36
- "16f": { type: "Float16", bits: 16 },
37
- "32f": { type: "Float32", bits: 32 },
38
- "64f": { type: "Float64", bits: 64 }
39
- });
40
- var IS_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
41
- var HEADER_SIZE = 16 >>> 0;
42
- var ADDRESS_OFFSET = 0 >>> 0;
43
- var OCCUPIED_OFFSET = 4 >>> 0;
44
- var CAPACITY_OFFSET = 8 >>> 0;
45
- var COOKIE_OFFSET = 9 >>> 0;
46
- var FLAGS_OFFSET = 10 >>> 0;
47
- var VIEW_LOCK = 1 >>> 0;
48
- var ROTATE_32BITS = 4294967296;
49
- var CLAMP_11BITS = 2047 >>> 0;
50
- var isTypedArray = (val) => ArrayBuffer.isView(val) && !(val instanceof DataView);
51
- var Balloc = class {
52
- /**
53
- * Crea una instancia del asignador de memoria `Balloc`.
54
- *
55
- * El asignador mantiene dos búferes independientes:
56
- * - `dataBus`: almacena los datos de los bloques asignados;
57
- * - `controlBus`: almacena las cabeceras y demás metadatos de control.
58
- *
59
- * Cada bloque posee una cabecera de tamaño fijo (`HEADER_SIZE`) y se
60
- * identifica externamente mediante un descriptor (handle) lógico de 43 bits, compuesto
61
- * por una generación de 11 bits y la dirección de su cabecera en 32 bits.
62
- *
63
- * La capacidad de cada bloque se redondea hacia arriba a la siguiente potencia de
64
- * dos en elementos, respetando el ancho del bucket configurado.
65
- *
66
- * @param {number} [size=65535] - Capacidad inicial del `dataBus`, en bytes.
67
- * Debe ser un entero seguro en el rango [2, 0x80000000].
68
- * @param {BucketType} [bucketSize="32u"] - Identificador del tipo y tamaño del bucket
69
- * (ej.: '32u' para Uint32, '64f' para Float64, '8i' para Int8).
70
- * @param {number} [metadataSize=1024] - Capacidad inicial del `controlBus`,
71
- * en bytes. Debe ser un entero seguro en el rango
72
- * [HEADER_SIZE, 0x80000000].
73
- *
74
- * @throws {RangeError} Si `size` se encuentra fuera del rango permitido.
75
- * @throws {RangeError} Si `bucketSize` no es un identificador de bucket válido.
76
- * @throws {RangeError} Si `metadataSize` se encuentra fuera del rango permitido.
77
- */
78
- constructor(size = 65535, bucketSize = "32u", metadataSize = 1024) {
79
- if (!Number.isSafeInteger(size) || size < 2 || size > 2147483648) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
80
- if (!BUCKET_MAPPING[bucketSize]) {
81
- throw new RangeError(`bucketSize must be in ([ 8 || 16 || 32 || 64][ u || i ]) || ([ 16 || 32 || 64][ f ]) but I found ${bucketSize}`);
82
- }
83
- if (!Number.isSafeInteger(metadataSize) || metadataSize < HEADER_SIZE || metadataSize > 2147483648) throw new RangeError(`Parameter metadataSize must be in range [HEADER_SIZE, 0x80000000] but metadataSize is ${metadataSize}`);
84
- this.wordType = bucketSize;
85
- this.bucketType = BUCKET_MAPPING[bucketSize].type;
86
- this.bucketSize = BUCKET_MAPPING[bucketSize].bits >>> 0;
87
- this.bucketArray = globalThis[`${this.bucketType}Array`];
88
- this.wordSize = this.bucketSize >>> 3;
89
- this.wordShift = this.bucketSize >>> 4;
90
- this.size = Math.max(1 << 32 - Math.clz32(size - 1) >>> 0, this.wordSize);
91
- this.headerSize = 1 << 32 - Math.clz32(metadataSize - 1) >>> 0;
92
- this.dataPointer = 0 >>> 0;
93
- this.controlPointer = 0 >>> 0;
94
- this.echoPointer = 0 >>> 0;
95
- this.generation = 0 >>> 0;
96
- this.dataBus = new Uint8Array(this.size);
97
- this.controlBus = new Uint8Array(this.headerSize);
98
- this.dataAdapter = new DataView(this.dataBus.buffer);
99
- this.controlAdapter = new DataView(this.controlBus.buffer);
100
- this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
101
- this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
102
- this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
103
- this.recycle = /* @__PURE__ */ new Map();
104
- this.metadata = {
105
- generation: 0 >>> 0,
106
- headerAddress: 0 >>> 0,
107
- dataAddress: 0 >>> 0,
108
- capacityExponent: 0 >>> 0,
109
- byteCapacity: 0 >>> 0,
110
- occupied: 0 >>> 0
111
- };
112
- }
113
- // ========== ASIGNACIÓN (ALLOCATION) ==========
114
- /**
115
- * Asigna un nuevo bloque de memoria.
116
- *
117
- * La capacidad solicitada se convierte a la menor potencia de dos que
118
- * pueda alojar `size` elementos. El bloque se obtiene preferentemente de la lista
119
- * de regiones reciclables con la capacidad correspondiente; si no existe
120
- * una región compatible, el bloque se reserva en la cima del `dataBus`.
121
- *
122
- * A continuación, se obtiene una cabecera del espacio de control. Las cabeceras previamente
123
- * liberadas se pueden reutilizar mediante la pila interna de reciclaje;
124
- * de lo contrario, el `controlBus` se expande cuando es necesario.
125
- *
126
- * La cabecera recibe la dirección, la capacidad, la ocupación inicial (cero) y
127
- * una cookie de validación. El valor devuelto codifica la generación de la asignación
128
- * y la dirección de la cabecera:
129
- *
130
- * [11 bits de generación][32 bits de dirección de cabecera]
131
- *
132
- * @param {number} [size=16] - Número mínimo de elementos que el bloque debe
133
- * poder alojar. Debe ser un entero seguro en el rango [2, 0x80000000].
134
- * @returns {number} Descriptor (handle) que identifica el bloque asignado.
135
- * @throws {RangeError} Si `size` se encuentra fuera del rango permitido.
136
- * @throws {Error} Si es necesario expandir el `dataBus` mientras haya
137
- * algún bloque prestado mediante `withView()`.
138
- */
139
- alloc(size = 16) {
140
- if (!Number.isSafeInteger(size) || size < 2 || size > 2147483648) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
141
- const capacity = 32 - Math.clz32(size - 1);
142
- const blockSize = (1 << capacity >>> 0) * this.wordSize;
143
- let dataAddress = this.recyclePop(blockSize);
144
- if (dataAddress === UNKNOWN) {
145
- while (this.dataPointer + blockSize > this.size) this.grow();
146
- dataAddress = this.dataPointer;
147
- this.dataPointer += blockSize;
148
- }
149
- let headerAddress = 0 >>> 0;
150
- if (this.echoPointer > this.controlPointer) {
151
- this.echoPointer -= 4;
152
- headerAddress = this.controlAdapter.getUint32(this.echoPointer, IS_LITTLE_ENDIAN);
153
- } else {
154
- if (this.controlPointer + HEADER_SIZE > this.controlAdapter.byteLength) this.headerGrow();
155
- headerAddress = this.controlPointer;
156
- this.controlPointer += HEADER_SIZE;
157
- this.echoPointer += HEADER_SIZE;
158
- }
159
- this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, dataAddress, IS_LITTLE_ENDIAN);
160
- this.controlAdapter.setUint32(headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
161
- this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, capacity);
162
- this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, this.bakeCookie(headerAddress, ++this.generation));
163
- this.controlBus[headerAddress + FLAGS_OFFSET] = 0;
164
- return (this.generation & CLAMP_11BITS) * ROTATE_32BITS + headerAddress;
165
- }
166
- /**
167
- * Amplía la capacidad de un bloque a la siguiente potencia de dos.
168
- *
169
- * Cuando el bloque se encuentra en la cima actual del `dataBus`, la ampliación
170
- * se realiza in situ (in-place): solo se actualizan su capacidad y el puntero `dataPointer`.
171
- *
172
- * Si existe otra región después del bloque, se obtiene una nueva región con el doble de
173
- * capacidad del espacio reciclable o se asigna en la cima del `dataBus`.
174
- * Los elementos actualmente ocupados se copian entonces a la nueva región,
175
- * y la región anterior se devuelve a la lista de reciclaje.
176
- *
177
- * El descriptor permanece válido, ya que su cabecera se conserva y solo se actualizan
178
- * la dirección y la capacidad registradas en ella.
179
- *
180
- * @param {number} handler - Descriptor del bloque a ampliar.
181
- * @returns {void}
182
- * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque
183
- * está prestado mediante `withView()`. También se produce si la ampliación requiere
184
- * reasignar el `dataBus` mientras otro bloque está prestado.
185
- * @throws {AggregateError} Si la capacidad ha alcanzado el límite
186
- * máximo soportado.
187
- */
188
- realloc(handler) {
189
- const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
190
- const headerAddress = handler >>> 0;
191
- const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
192
- const occupied = this.controlAdapter.getUint32(headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
193
- const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
194
- const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
195
- const borrowed = this.controlAdapter.getUint8(headerAddress + FLAGS_OFFSET) & VIEW_LOCK;
196
- if (cookie !== this.bakeCookie(headerAddress, generation)) {
197
- throw new Error("Invalid or corrupted handle");
198
- }
199
- if (borrowed) {
200
- throw new Error("Block is borrowed");
201
- }
202
- if (capacity >= 31) throw new AggregateError([new Error("Can\xB4t reallocate handler."), new RangeError("Capacity has reached its limit.")], "Internal Error.");
203
- const newCapacity = capacity + 1;
204
- const newBlockSize = (1 << newCapacity >>> 0) * this.wordSize;
205
- const oldBlockSize = (1 << capacity >>> 0) * this.wordSize;
206
- if (dataAddress + oldBlockSize === this.dataPointer) {
207
- while (dataAddress + newBlockSize > this.size) this.grow();
208
- this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
209
- this.dataPointer = dataAddress + newBlockSize;
210
- return;
211
- }
212
- let newAddress = this.recyclePop(newBlockSize);
213
- if (newAddress === UNKNOWN) {
214
- while (this.dataPointer + newBlockSize > this.size) this.grow();
215
- newAddress = this.dataPointer;
216
- this.dataPointer += newBlockSize;
217
- }
218
- this.dataBus.copyWithin(newAddress, dataAddress, dataAddress + occupied * this.wordSize);
219
- this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, newAddress, IS_LITTLE_ENDIAN);
220
- this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
221
- this.recyclePush(oldBlockSize, dataAddress);
222
- }
223
- /**
224
- * Reduce un bloque a la menor capacidad potencia de dos que pueda contener
225
- * sus elementos ocupados, preservando su dirección y su handler.
226
- *
227
- * Si el bloque está en la parte superior de dataBus, dataPointer retrocede.
228
- * De lo contrario, la cola liberada se divide en regiones de potencias
229
- * de dos y cada región se devuelve a la lista de reciclaje.
230
- *
231
- * @param {number} handler - Handler del bloque que se va a reducir.
232
- * @returns {void}
233
- * @throws {Error} Si el handler no es válido, está dañado o está prestado
234
- * mediante withView().
235
- */
236
- shrink(handler) {
237
- const meta = this.extractMetadata(handler, this.metadata);
238
- if (meta.borrowed) throw new Error("Block is borrowed");
239
- const newCapacity = Math.max(1, 32 - Math.clz32(Math.max(2, meta.occupied) - 1));
240
- if (newCapacity >= meta.capacityExponent) return;
241
- const oldBlockSize = meta.byteCapacity;
242
- const newBlockSize = 2 ** newCapacity * this.wordSize;
243
- const oldEnd = meta.dataAddress + oldBlockSize;
244
- this.controlAdapter.setUint8(meta.headerAddress + CAPACITY_OFFSET, newCapacity);
245
- if (oldEnd === this.dataPointer) {
246
- this.dataPointer = meta.dataAddress + newBlockSize;
247
- return;
248
- }
249
- let address = meta.dataAddress + newBlockSize;
250
- for (let exponent = newCapacity; exponent < meta.capacityExponent; exponent++) {
251
- const segmentSize = 2 ** exponent * this.wordSize;
252
- this.recyclePush(segmentSize, address);
253
- address += segmentSize;
254
- }
255
- }
256
- free(handler) {
257
- const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
258
- const headerAddress = handler >>> 0;
259
- const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
260
- const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
261
- const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
262
- const borrowed = this.controlAdapter.getUint8(headerAddress + FLAGS_OFFSET) & VIEW_LOCK;
263
- if (cookie !== this.bakeCookie(headerAddress, generation)) {
264
- throw new Error("Invalid or corrupted handle");
265
- }
266
- if (borrowed) {
267
- throw new Error("Block is borrowed");
268
- }
269
- const blockSize = (1 << capacity >>> 0) * this.wordSize;
270
- this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
271
- if (this.echoPointer + 4 <= this.controlBus.byteLength) {
272
- this.controlAdapter.setUint32(this.echoPointer, headerAddress, IS_LITTLE_ENDIAN);
273
- this.echoPointer += 4;
274
- }
275
- if (dataAddress + blockSize === this.dataPointer) {
276
- this.dataPointer = dataAddress;
277
- } else {
278
- this.recyclePush(blockSize, dataAddress);
279
- }
280
- }
281
- // ========== RECICLAJE (RECYCLING) ==========
282
- /**
283
- * [USO INTERNO]
284
- * Inserta una región libre en la lista de reciclaje.
285
- *
286
- * La lista se organiza por capacidad en bytes. Para cada capacidad, el
287
- * valor almacenado es un `Uint32Array` cuya posición cero contiene la cantidad
288
- * de direcciones registradas y las posiciones subsiguientes contienen las direcciones de
289
- * las regiones libres:
290
- *
291
- * [count, address1, address2, ...]
292
- *
293
- * Cuando la página se llena, su búfer se expande al doble de su
294
- * capacidad actual.
295
- *
296
- * @param {number} capacity - Capacidad de la región libre, en bytes.
297
- * @param {number} address - Dirección inicial de la región en el `dataBus`.
298
- * @returns {void}
299
- * @private
300
- */
301
- recyclePush(capacity, address) {
302
- if (this.recycle.has(capacity)) {
303
- let page = this.recycle.get(capacity);
304
- const count = page[0];
305
- if (count === page.length - 1) {
306
- const newBuffer = page.buffer.transfer(page.buffer.byteLength * 2);
307
- page = new Uint32Array(newBuffer);
308
- this.recycle.set(capacity, page);
309
- }
310
- page[count + 1] = address;
311
- page[0] = count + 1;
312
- } else {
313
- this.recycle.set(capacity, new Uint32Array([1, address]));
314
- }
315
- }
316
- /**
317
- * [USO INTERNO]
318
- * Elimina una región libre de la lista de reciclaje.
319
- *
320
- * La búsqueda se realiza por la capacidad exacta solicitada. Cuando existe una
321
- * página correspondiente, se elimina de ella la última dirección registrada y se devuelve,
322
- * implementando el reciclaje como una pila LIFO.
323
- *
324
- * @param {number} capacity - Capacidad deseada, en bytes.
325
- * @returns {number} Dirección inicial de una región reciclable o `UNKNOWN`
326
- * cuando no existe una región con la capacidad solicitada.
327
- * @private
328
- */
329
- recyclePop(capacity) {
330
- if (!this.recycle.has(capacity)) return UNKNOWN;
331
- const page = this.recycle.get(capacity);
332
- const count = page[0];
333
- if (count === 0) return UNKNOWN;
334
- const address = page[count];
335
- page[0] = count - 1;
336
- return address;
337
- }
338
- // ========== RECOLECCIÓN DE BASURA (GARBAGE COLLECTION) ==========
339
- /**
340
- * Compacta el `dataBus` mediante el algoritmo ReBump.
341
- *
342
- * Recorre secuencialmente las cabeceras registradas en el `controlBus` y copia
343
- * las regiones aún válidas a un nuevo `dataBus`, eliminando los espacios
344
- * libres existentes entre ellas. La dirección de cada bloque superviviente se
345
- * actualiza en su cabecera respectiva.
346
- *
347
- * Se preserva el orden de los bloques en el `controlBus`. Los datos internos de
348
- * cada bloque también se conservan íntegramente, incluyendo su capacidad
349
- * reservada y su ocupación actual.
350
- *
351
- * Al finalizar la compactación:
352
- * - se eliminan todas las regiones reciclables;
353
- * - el puntero `dataPointer` apunta al primer byte posterior al último bloque
354
- * activo;
355
- * - el `dataBus` pasa a representar un montón (heap) contiguo para los bloques activos.
356
- *
357
- * La complejidad de control es O(n), donde `n` es el número de cabeceras
358
- * recorridas. El coste efectivo de movimiento de memoria también depende
359
- * del volumen de bytes pertenecientes a los bloques vivos.
360
- *
361
- * @returns {void}
362
- * @throws {Error} Si hay algún bloque prestado mediante `withView()`.
363
- */
364
- gc() {
365
- this.assertNoActiveViews();
366
- const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
367
- this.recycle.clear();
368
- this.dataPointer = 0 >>> 0;
369
- for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
370
- if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
371
- const start = this.controlAdapter.getUint32(i + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
372
- const size = (1 << this.controlBus[i + CAPACITY_OFFSET] >>> 0) * this.wordSize;
373
- const end = start + size;
374
- newDataBus.set(this.dataBus.subarray(start, end), this.dataPointer);
375
- this.controlAdapter.setUint32(i + ADDRESS_OFFSET, this.dataPointer, IS_LITTLE_ENDIAN);
376
- this.dataPointer += size;
377
- }
378
- this.dataBus = newDataBus;
379
- this.dataAdapter = new DataView(this.dataBus.buffer);
380
- this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
381
- this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
382
- this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
383
- }
384
- // ========== ESCALADO (SCALING) ==========
385
- /**
386
- * [!!! USO INTERNO, NO UTILIZAR EN SU CÓDIGO !!!]
387
- * Amplía el `dataBus` al doble de su capacidad actual.
388
- *
389
- * El búfer subyacente se transfiere a un `ArrayBuffer` mayor, preservando
390
- * los datos existentes. Todas las vistas asociadas al búfer se recrean
391
- * para hacer referencia al nuevo almacenamiento.
392
- *
393
- * @returns {void}
394
- * @throws {Error} Si hay algún bloque prestado mediante `withView()`.
395
- * @throws {RangeError} Si la capacidad del `dataBus` ya ha excedido el
396
- * límite máximo soportado.
397
- * @private
398
- */
399
- grow() {
400
- this.assertNoActiveViews();
401
- if (this.size > 2147483648) throw new RangeError("Data bus capacity exceeded");
402
- const newSize = this.size * 2 >>> 0;
403
- const newBuffer = this.dataBus.buffer.transfer(newSize);
404
- this.size = newSize;
405
- this.dataBus = new Uint8Array(newBuffer);
406
- this.dataAdapter = new DataView(newBuffer);
407
- this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
408
- this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
409
- this.auxiliary = new this.bucketArray(newBuffer);
410
- }
411
- /**
412
- * [!!! USO INTERNO, NO UTILIZAR EN SU CÓDIGO !!!]
413
- * Amplía el `controlBus` al doble de su capacidad actual.
414
- *
415
- * El búfer subyacente se transfiere a un `ArrayBuffer` mayor, preservando
416
- * las cabeceras existentes. El `controlAdapter` se recrea para hacer referencia
417
- * al nuevo almacenamiento.
418
- *
419
- * @returns {void}
420
- * @throws {RangeError} Si la capacidad actual del `controlBus` ya ha
421
- * excedido el límite máximo soportado.
422
- * @private
423
- */
424
- headerGrow() {
425
- if (this.controlBus.byteLength > 2147483648) throw new RangeError("Control bus capacity exceeded");
426
- const newSize = this.controlBus.byteLength * 2 >>> 0;
427
- const newBuffer = this.controlBus.buffer.transfer(newSize);
428
- this.controlBus = new Uint8Array(newBuffer);
429
- this.controlAdapter = new DataView(newBuffer);
430
- }
431
- // ========== OPERACIONES DE PILA (STACK OPERATIONS) ==========
432
- /**
433
- * Añade un elemento al final de la secuencia ocupada por el bloque.
434
- *
435
- * El elemento se escribe en la primera posición libre tras el último elemento
436
- * ocupado. La ocupación del bloque se incrementa únicamente cuando hay espacio
437
- * disponible dentro de su capacidad.
438
- *
439
- * @param {number} value - Valor que se va a insertar.
440
- * @returns {boolean} `true` si el valor fue insertado; `false` si el bloque
441
- * ya no dispone de espacio libre.
442
- * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque está prestado mediante `withView()`.
443
- *
444
- */
445
- push(handler, value) {
446
- const meta = this.extractMetadata(handler, this.metadata);
447
- if (meta.borrowed) throw new Error("Block is borrowed");
448
- if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
449
- this.writer(meta.dataAddress + meta.occupied * this.wordSize, value, IS_LITTLE_ENDIAN);
450
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
451
- return true;
452
- }
453
- /**
454
- * Elimina el último elemento ocupado del bloque y lo devuelve.
455
- *
456
- * La ocupación se decrementa antes de leer el elemento eliminado. Los
457
- * bytes correspondientes no se limpian y permanecen en la región asignada,
458
- * pero dejan de formar parte de la secuencia ocupada.
459
- *
460
- * @param {number} handler - Descriptor del bloque.
461
- * @returns {number|undefined} Valor eliminado o `undefined` si el bloque
462
- * está vacío.
463
- * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque está prestado mediante `withView()`.
464
- */
465
- pop(handler) {
466
- const meta = this.extractMetadata(handler, this.metadata);
467
- if (meta.borrowed) throw new Error("Block is borrowed");
468
- if (meta.occupied === 0) return void 0;
469
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
470
- return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
471
- }
472
- /**
473
- * Devuelve el último elemento ocupado sin eliminarlo.
474
- *
475
- * @param {number} handler - Descriptor del bloque.
476
- * @returns {number|undefined} Último valor ocupado o `undefined` si el
477
- * bloque está vacío.
478
- * @throws {Error} Si el descriptor no es válido o está corrupto.
479
- */
480
- peek(handler) {
481
- const meta = this.extractMetadata(handler, this.metadata);
482
- if (meta.occupied === 0) return void 0;
483
- return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
484
- }
485
- // ========== OPERACIONES DE COLA (QUEUE OPERATIONS) ==========
486
- /**
487
- * Inserta un elemento al principio de la secuencia ocupada.
488
- *
489
- * Los elementos actualmente ocupados se desplazan una posición hacia adelante
490
- * y `value` se escribe en la primera posición. La operación requiere una
491
- * posición libre en la capacidad del bloque.
492
- *
493
- * El coste de la operación es proporcional al número de elementos ocupados,
494
- * ya que es necesario desplazar los datos.
495
- *
496
- * @param {number} handler - Descriptor del bloque.
497
- * @param {number} value - Valor que se va a insertar.
498
- * @returns {boolean} `true` si el valor fue insertado; `false` si el bloque
499
- * está lleno.
500
- * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque está prestado mediante `withView()`.
501
- */
502
- nudge(handler, value) {
503
- const meta = this.extractMetadata(handler, this.metadata);
504
- if (meta.borrowed) throw new Error("Block is borrowed");
505
- if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
506
- this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
507
- this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
508
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
509
- return true;
510
- }
511
- /**
512
- * Elimina el primer elemento ocupado del bloque y lo devuelve.
513
- *
514
- * Los elementos restantes se desplazan una posición hacia el principio
515
- * de la región ocupada. La capacidad física del bloque permanece inalterada.
516
- *
517
- * El coste de la operación es proporcional al número de elementos desplazados.
518
- *
519
- * @param {number} handler - Descriptor del bloque.
520
- * @returns {number|undefined} Primer valor eliminado o `undefined` si el
521
- * bloque está vacío.
522
- * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque está prestado mediante `withView()`.
523
- */
524
- pull(handler) {
525
- const meta = this.extractMetadata(handler, this.metadata);
526
- if (meta.borrowed) throw new Error("Block is borrowed");
527
- if (meta.occupied === 0) return void 0;
528
- const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
529
- this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
530
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
531
- return result;
532
- }
533
- /**
534
- * Devuelve el primer elemento ocupado sin eliminarlo.
535
- *
536
- * @param {number} handler - Descriptor del bloque.
537
- * @returns {number|undefined} Primer valor ocupado o `undefined` si el
538
- * bloque está vacío.
539
- * @throws {Error} Si el descriptor no es válido o está corrupto.
540
- */
541
- head(handler) {
542
- const meta = this.extractMetadata(handler, this.metadata);
543
- if (meta.occupied === 0) return void 0;
544
- return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
545
- }
546
- // ========== ACCESO ALEATORIO (RANDOM ACCESS) ==========
547
- /**
548
- * Comprueba si un valor está presente entre los elementos ocupados del bloque.
549
- *
550
- * La búsqueda se realiza directamente sobre el `TypedArray` auxiliar y considera
551
- * únicamente el rango actualmente ocupado, no toda la capacidad física reservada.
552
- *
553
- * @param {number} handler - Descriptor del bloque.
554
- * @param {number} value - Valor que se busca.
555
- * @returns {boolean} `true` si `value` está presente entre los elementos
556
- * ocupados; de lo contrario, `false`.
557
- * @throws {Error} Si el descriptor no es válido o está corrupto.
558
- */
559
- has(handler, value) {
560
- const meta = this.extractMetadata(handler, this.metadata);
561
- if (meta.occupied === 0) return false;
562
- const rawAddres = meta.dataAddress >>> this.wordShift;
563
- return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
564
- }
565
- /**
566
- * Localiza la primera ocurrencia de un elemento en la secuencia ocupada del bloque.
567
- *
568
- * La búsqueda se realiza en orden ascendente de índices, utilizando la operación
569
- * `indexOf` del TypedArray subyacente. La exploración considera exclusivamente
570
- * los elementos ocupados, ignorando la capacidad no utilizada del bloque.
571
- *
572
- * La posición de inicio de la búsqueda se puede especificar mediante `fromIndex`,
573
- * siguiendo las reglas de indexación de TypedArray.
574
- *
575
- * @param {number} handler - Descriptor del bloque.
576
- * @param {number|bigint} searchElement - Elemento que se va a localizar.
577
- * @param {number} [fromIndex=0] - Índice a partir del cual se iniciará la búsqueda.
578
- * @returns {number} Índice de la primera ocurrencia o `-1` si el
579
- * elemento no se encuentra o si el bloque está vacío.
580
- * @throws {Error} Si el descriptor no es válido o está corrupto.
581
- */
582
- indexOf(handler, searchElement, fromIndex = 0) {
583
- const meta = this.extractMetadata(handler, this.metadata);
584
- if (meta.occupied === 0) return -1;
585
- const rawAddres = meta.dataAddress >>> this.wordShift;
586
- return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).indexOf(searchElement, fromIndex);
587
- }
588
- /**
589
- * Localiza la última ocurrencia de un elemento en la secuencia ocupada del bloque.
590
- *
591
- * La búsqueda se realiza en orden descendente de índices, utilizando la operación
592
- * `lastIndexOf` del TypedArray subyacente. La exploración considera exclusivamente
593
- * los elementos ocupados, ignorando la capacidad no utilizada del bloque.
594
- *
595
- * La posición de inicio de la búsqueda se puede especificar mediante `fromIndex`,
596
- * siguiendo las reglas de indexación de TypedArray. Por defecto, la búsqueda comienza
597
- * en el último elemento ocupado.
598
- *
599
- * @param {number} handler - Descriptor del bloque.
600
- * @param {number|bigint} searchElement - Elemento que se va a localizar.
601
- * @param {number} [fromIndex=-1] - Índice a partir del cual se iniciará la búsqueda.
602
- * @returns {number} Índice de la última ocurrencia o `-1` si el
603
- * elemento no se encuentra o si el bloque está vacío.
604
- * @throws {Error} Si el descriptor no es válido o está corrupto.
605
- */
606
- lastIndexOf(handler, searchElement, fromIndex = -1) {
607
- const meta = this.extractMetadata(handler, this.metadata);
608
- if (meta.occupied === 0) return -1;
609
- const rawAddres = meta.dataAddress >>> this.wordShift;
610
- return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).lastIndexOf(searchElement, fromIndex);
611
- }
612
- /**
613
- * Devuelve el elemento ocupado en un índice basado en cero.
614
- *
615
- * Los índices fuera del rango `[0, occupied)` no se consideran un error y
616
- * devuelven `undefined`.
617
- *
618
- * @param {number} handler - Descriptor del bloque.
619
- * @param {number} index - Índice basado en cero del elemento.
620
- * @returns {number|undefined} Valor almacenado en el índice o `undefined` si
621
- * el índice está fuera de la región ocupada.
622
- * @throws {Error} Si el descriptor no es válido o está corrupto.
623
- */
624
- get(handler, index) {
625
- const meta = this.extractMetadata(handler, this.metadata);
626
- if (index < 0 || index >= meta.occupied) return void 0;
627
- return this.reader(meta.dataAddress + index * this.wordSize, IS_LITTLE_ENDIAN);
628
- }
629
- /**
630
- * Reemplaza el valor almacenado en un índice ocupado.
631
- *
632
- * La operación no altera la ocupación del bloque. Los índices fuera del rango
633
- * `[0, occupied)` se ignoran y devuelven `false`.
634
- *
635
- * @param {number} handler - Descriptor del bloque.
636
- * @param {number} index - Índice basado en cero del elemento.
637
- * @param {number} value - Nuevo valor.
638
- * @returns {boolean} `true` si el valor fue escrito; `false` si el índice
639
- * está fuera de la región ocupada.
640
- * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque está prestado mediante `withView()`.
641
- */
642
- set(handler, index, value) {
643
- const meta = this.extractMetadata(handler, this.metadata);
644
- if (meta.borrowed) throw new Error("Block is borrowed");
645
- if (index < 0 || index >= meta.occupied) return false;
646
- this.writer(meta.dataAddress + index * this.wordSize, value, IS_LITTLE_ENDIAN);
647
- return true;
648
- }
649
- // ============= MISCELÁNEA (MISCELLANEOUS) ==============
650
- /**
651
- * Pone a cero la ocupación del bloque y rellena toda su capacidad física con
652
- * un mismo valor.
653
- *
654
- * El rellenado abarca todas las ranuras (slots) disponibles, no solo los
655
- * elementos actualmente ocupados. Tras la operación, el bloque se considera
656
- * vacío independientemente del valor utilizado para el rellenado.
657
- *
658
- * @param {number} handler - Descriptor del bloque.
659
- * @param {number} [value=0] - Valor utilizado para rellenar todas las ranuras.
660
- * @returns {void}
661
- * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque está prestado mediante `withView()`.
662
- */
663
- clear(handler, value = 0) {
664
- const meta = this.extractMetadata(handler, this.metadata);
665
- if (meta.borrowed) throw new Error("Block is borrowed");
666
- const slots = meta.byteCapacity / this.wordSize;
667
- const rawAddress = meta.dataAddress >>> this.wordShift;
668
- this.auxiliary.fill(value, rawAddress, rawAddress + slots);
669
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
670
- }
671
- /**
672
- * Rellena un intervalo de ranuras del bloque con un valor.
673
- *
674
- * El intervalo utiliza índices basados en cero y sigue la convención
675
- * `[start, end)`, por lo que `start` es inclusivo y `end` es exclusivo.
676
- * Cuando no se especifica `end`, el rellenado se extiende hasta el final de la
677
- * capacidad física del bloque.
678
- *
679
- * La ocupación del bloque pasa a ser `end`, incluso cuando el intervalo
680
- * rellenado se extiende más allá de la ocupación anterior.
681
- *
682
- * @param {number} handler - Descriptor del bloque.
683
- * @param {number} value - Valor utilizado en el rellenado.
684
- * @param {number} [start=0] - Índice inicial, inclusivo.
685
- * @param {number|null} [end=null] - Índice final, exclusivo. Cuando
686
- * se omite o es `null`, utiliza la capacidad total del bloque.
687
- * @returns {void}
688
- * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque está prestado mediante `withView()`.
689
- * @throws {RangeError} Si `start` o `end` están fuera de los límites de la
690
- * capacidad, o si `start > end`.
691
- */
692
- fill(handler, value, start = 0, end = null) {
693
- const meta = this.extractMetadata(handler, this.metadata);
694
- if (meta.borrowed) throw new Error("Block is borrowed");
695
- const slots = meta.byteCapacity / this.wordSize;
696
- const lastIndex = end ?? slots;
697
- if (start > lastIndex) {
698
- throw new RangeError(`start ${start} must be less or equal than end ${lastIndex}.`);
699
- }
700
- if (start < 0 || start > slots) {
701
- throw new RangeError(`start ${start} out of range [0, ${slots}].`);
702
- }
703
- if (lastIndex < 0 || lastIndex > slots) {
704
- throw new RangeError(`end ${lastIndex} out of range [0, ${slots}].`);
705
- }
706
- const rawAddress = meta.dataAddress >>> this.wordShift;
707
- this.auxiliary.fill(value, rawAddress + start, rawAddress + lastIndex);
708
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, lastIndex, IS_LITTLE_ENDIAN);
709
- }
710
- /**
711
- * Rellena todas las ranuras físicas del bloque con un valor y marca toda la
712
- * capacidad como ocupada.
713
- *
714
- * A diferencia de `clear()`, la operación da como resultado un bloque totalmente
715
- * ocupado.
716
- *
717
- * @param {number} handler - Descriptor del bloque.
718
- * @param {number} value - Valor utilizado en el rellenado.
719
- * @returns {void}
720
- * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque está prestado mediante `withView()`.
721
- */
722
- fillAll(handler, value) {
723
- const meta = this.extractMetadata(handler, this.metadata);
724
- if (meta.borrowed) throw new Error("Block is borrowed");
725
- const rawAddress = meta.dataAddress >>> this.wordShift;
726
- const capacityElements = meta.byteCapacity / this.wordSize;
727
- this.auxiliary.fill(value, rawAddress, rawAddress + capacityElements);
728
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, capacityElements, IS_LITTLE_ENDIAN);
729
- }
730
- /**
731
- * Copia los elementos de un `Array` o `TypedArray` al principio del bloque.
732
- *
733
- * La cantidad copiada está limitada por la capacidad del bloque. La ocupación se
734
- * actualiza al mayor valor entre la ocupación anterior y la cantidad
735
- * efectivamente copiada; por lo tanto, una llamada a `put()` no reduce la
736
- * ocupación existente cuando recibe una secuencia más pequeña.
737
- *
738
- * Para `Array`, solo se copian los primeros elementos que quepan.
739
- * Para `TypedArray`, se utiliza un subarreglo (subarray) de la fuente sin copia
740
- * intermedia.
741
- *
742
- * @param {number} handler - Descriptor del bloque.
743
- * @param {Array|TypedArray} data - Secuencia de valores que se van a copiar.
744
- * @returns {void}
745
- * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque está prestado mediante `withView()`.
746
- * @throws {TypeError} Si `data` no es ni un `Array` ni un `TypedArray`.
747
- */
748
- put(handler, data) {
749
- const meta = this.extractMetadata(handler, this.metadata);
750
- if (meta.borrowed) throw new Error("Block is borrowed");
751
- const rawAddress = meta.dataAddress >>> this.wordShift;
752
- const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
753
- if (Array.isArray(data)) {
754
- this.auxiliary.set(data.slice(0, length), rawAddress);
755
- } else if (isTypedArray(data)) {
756
- this.auxiliary.set(data.subarray(0, length), rawAddress);
757
- } else {
758
- const actual = data?.constructor?.name ?? (data === null ? "null" : typeof data);
759
- throw new TypeError(`data must be Array or TypedArray, but ${actual} was given.`);
760
- }
761
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, Math.max(length, meta.occupied), IS_LITTLE_ENDIAN);
762
- }
763
- /**
764
- * Devuelve una copia de los elementos ocupados actualmente por el bloque.
765
- *
766
- * El resultado es un `TypedArray` del mismo tipo configurado por
767
- * `bucketSize`. La capacidad física no ocupada no se incluye en el resultado.
768
- *
769
- * La operación no expone directamente el almacenamiento interno: el método
770
- * utiliza `TypedArray.prototype.slice()`, produciendo una nueva vista con
771
- * almacenamiento independiente.
772
- *
773
- * @param {number} handler - Descriptor del bloque.
774
- * @returns {TypedArray} Copia de los elementos ocupados por el bloque. Cuando
775
- * el bloque está vacío, devuelve un `TypedArray` vacío del tipo configurado.
776
- * @throws {Error} Si el descriptor no es válido o está corrupto.
777
- */
778
- pick(handler) {
779
- const meta = this.extractMetadata(handler, this.metadata);
780
- const rawAddress = meta.dataAddress >>> this.wordShift;
781
- if (meta.occupied === 0) {
782
- return this.auxiliary.slice(rawAddress, rawAddress);
783
- }
784
- return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
785
- }
786
- /**
787
- * Ejecuta una retrollamada (callback) sobre una vista directa de la región ocupada por el bloque.
788
- *
789
- * La vista comparte el almacenamiento interno de Balloc y no realiza copias.
790
- * El bloque queda protegido frente a operaciones incompatibles durante la ejecución de la retrollamada.
791
- *
792
- * La retrollamada debe ser síncrona. La vista recibida no debe almacenarse,
793
- * devolverse ni utilizarse una vez finalizada la retrollamada. Esta restricción
794
- * también se aplica a las subvistas derivadas de la vista original.
795
- *
796
- * @param {number} handler - Descriptor del bloque.
797
- * @param {...(number|Function)} args - Uno o más descriptores de bloque, seguidos de la retrollamada.
798
- * @returns {*} Valor devuelto por la retrollamada.
799
- * @throws {TypeError} Si no se proporciona ningún descriptor o la retrollamada no es una función.
800
- * @throws {Error} Si algún descriptor no es válido, está duplicado o ya está prestado.
801
- */
802
- withView(...args) {
803
- if (args.length < 2) throw new TypeError("At least one handler and one callback are required");
804
- const lastIndex = args.length - 1;
805
- const callback = args[lastIndex];
806
- if (typeof callback !== "function") throw new TypeError("callback must be a function");
807
- const lookup = /* @__PURE__ */ Object.create(null);
808
- const acquired = [];
809
- const views = [];
810
- try {
811
- for (let i = 0; i < lastIndex; i++) {
812
- const metadata = this.extractMetadata(args[i], this.metadata);
813
- const headerAddr = metadata.headerAddress;
814
- if (Object.hasOwn(lookup, headerAddr)) throw new Error("Duplicate handler");
815
- if (metadata.borrowed) throw new Error("Block is already borrowed");
816
- this.controlBus[headerAddr + FLAGS_OFFSET] |= VIEW_LOCK;
817
- const rawAddress = metadata.dataAddress >>> this.wordShift;
818
- lookup[headerAddr] = true;
819
- acquired.push(headerAddr);
820
- views.push(this.auxiliary.subarray(rawAddress, rawAddress + metadata.occupied));
821
- }
822
- return callback(...views);
823
- } finally {
824
- for (let i = 0; i < acquired.length; i++) {
825
- this.controlBus[acquired[i] + FLAGS_OFFSET] &= ~VIEW_LOCK;
826
- }
827
- }
828
- }
829
- // ======== CAPACIDAD EN RANURAS (CAPACITY IN SLOTS) ==========
830
- /**
831
- * Devuelve la capacidad física del bloque en bytes.
832
- *
833
- * La capacidad corresponde al espacio reservado para todas las ranuras del
834
- * bloque, independientemente de cuántos elementos estén ocupados actualmente.
835
- *
836
- * @param {number} handler - Descriptor del bloque.
837
- * @returns {number} Capacidad física del bloque, en bytes.
838
- * @throws {Error} Si el descriptor no es válido o está corrupto.
839
- */
840
- byteSize(handler) {
841
- const meta = this.extractMetadata(handler, this.metadata);
842
- return meta.byteCapacity;
843
- }
844
- /**
845
- * Devuelve la cantidad de elementos ocupados actualmente en el bloque.
846
- *
847
- * @param {number} handler - Descriptor del bloque.
848
- * @returns {number} Número de elementos ocupados.
849
- * @throws {Error} Si el descriptor no es válido o está corrupto.
850
- */
851
- occupied(handler) {
852
- const meta = this.extractMetadata(handler, this.metadata);
853
- return meta.occupied;
854
- }
855
- /**
856
- * Devuelve la capacidad del bloque en número de elementos.
857
- *
858
- * El valor corresponde a la cantidad total de ranuras reservadas físicamente,
859
- * y no a la cantidad ocupada actualmente.
860
- *
861
- * @param {number} handler - Descriptor del bloque.
862
- * @returns {number} Número total de ranuras disponibles en el bloque.
863
- * @throws {Error} Si el descriptor no es válido o está corrupto.
864
- */
865
- length(handler) {
866
- const meta = this.extractMetadata(handler, this.metadata);
867
- return 1 << meta.capacityExponent >>> 0;
868
- }
869
- /**
870
- * Comprueba si el bloque de memoria ha alcanzado su capacidad de asignación.
871
- *
872
- * Un bloque se considera lleno cuando la cantidad de elementos ocupados
873
- * es igual a su capacidad total asignada, sin quedar posiciones disponibles
874
- * para almacenar nuevos elementos.
875
- *
876
- * @param {number} handler - Descriptor del bloque.
877
- * @returns {boolean} `true` si el bloque está lleno; de lo contrario, `false`.
878
- * @throws {Error} Si el descriptor no es válido o está corrupto.
879
- */
880
- isFull(handler) {
881
- const meta = this.extractMetadata(handler, this.metadata);
882
- return (1 << meta.capacityExponent >>> 0) - meta.occupied === 0;
883
- }
884
- // ========== Operaciones entre bloques (Operations between blocks) =============
885
- /**
886
- * Copia elementos ocupados de un bloque a otro.
887
- *
888
- * La copia comienza en el primer elemento de la fuente (`source`) y en la primera ranura del
889
- * destino (`destination`). La cantidad efectivamente copiada está limitada por el número de
890
- * elementos ocupados en la fuente, la capacidad física del destino y el
891
- * límite especificado en `slots`.
892
- *
893
- * La ocupación del destino se incrementa, cuando es necesario, para abarcar los
894
- * elementos copiados. La capacidad del destino no se altera.
895
- *
896
- * La operación utiliza `Uint8Array.prototype.copyWithin()` sobre el `dataBus`,
897
- * por lo que el valor devuelto es el propio `Uint8Array` que representa el bus de datos.
898
- *
899
- * @param {number} source - Descriptor del bloque de origen.
900
- * @param {number} destination - Descriptor del bloque de destino.
901
- * @param {number} [slots=UNKNOWN] - Número máximo de elementos que se van a copiar.
902
- * `UNKNOWN` representa el valor centinela utilizado para no imponer un
903
- * límite adicional.
904
- * @returns {Uint8Array} El `dataBus` tras la operación.
905
- * @throws {Error} Si los descriptores no son válidos, están corruptos
906
- * o el bloque de destino está prestado mediante `withView()`.
907
- */
908
- copy(source, destination, slots = UNKNOWN) {
909
- const metaA = {};
910
- const metaB = {};
911
- this.extractMetadata(source, metaA);
912
- this.extractMetadata(destination, metaB);
913
- if (metaB.borrowed) throw new Error("Block is borrowed");
914
- const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
915
- const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
916
- const newOccupied = Math.max(metaB.occupied, slotsToCopy);
917
- this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
918
- return this.dataBus.copyWithin(metaB.dataAddress, metaA.dataAddress, metaA.dataAddress + slotsToCopy * this.wordSize);
919
- }
920
- /**
921
- * Copia una región de elementos dentro del propio bloque.
922
- *
923
- * Los índices están basados en cero y siguen la semántica de
924
- * `Array.prototype.copyWithin()`: `target` identifica la posición de destino,
925
- * `start` la posición inicial de origen y `length` la cantidad máxima de
926
- * elementos que se van a copiar.
927
- *
928
- * Los índices negativos se interpretan a partir del final de la capacidad del
929
- * bloque. Tras dicha normalización, los índices se limitan a la capacidad
930
- * física. La cantidad copiada también está limitada por los elementos
931
- * ocupados efectivamente y por el espacio disponible a partir de `target`.
932
- *
933
- * La operación admite regiones solapadas y puede incrementar la ocupación del
934
- * bloque cuando el intervalo de destino supera la ocupación actual.
935
- *
936
- * @param {number} handler - Descriptor del bloque.
937
- * @param {number} target - Índice inicial de destino.
938
- * @param {number} start - Índice inicial de origen.
939
- * @param {number} length - Número máximo de elementos que se van a copiar.
940
- * @returns {Uint8Array} El `dataBus` tras la operación.
941
- * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque está prestado mediante `withView()`.
942
- */
943
- copyWithin(handler, target, start, length) {
944
- const meta = this.extractMetadata(handler, this.metadata);
945
- if (meta.borrowed) throw new Error("Block is borrowed");
946
- const slots = Math.floor(meta.byteCapacity / this.wordSize);
947
- target = Math.trunc(target);
948
- start = Math.trunc(start);
949
- length = Math.trunc(length);
950
- if (target < 0) target += slots;
951
- if (start < 0) start += slots;
952
- target = Math.max(0, Math.min(target, slots));
953
- start = Math.max(0, Math.min(start, slots));
954
- const maxRead = Math.max(0, meta.occupied - start);
955
- const maxWrite = slots - target;
956
- length = Math.max(0, Math.min(length, maxRead, maxWrite));
957
- if (length === 0) return this.dataBus;
958
- const targetAddress = meta.dataAddress + target * this.wordSize;
959
- const sourceAddress = meta.dataAddress + start * this.wordSize;
960
- const newOccupied = Math.max(meta.occupied, target + length);
961
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
962
- return this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + length * this.wordSize);
963
- }
964
- /**
965
- * Añade los elementos ocupados de `source` al final de `target`.
966
- *
967
- * La cantidad copiada está limitada por el número de elementos ocupados en la
968
- * fuente y el espacio libre restante en la capacidad del destino.
969
- *
970
- * La operación permite que `target` y `source` hagan referencia al mismo bloque.
971
- * En ese caso, la copia se realiza sobre la propia región del bloque y
972
- * preserva la semántica de solapamiento de `copyWithin()`.
973
- *
974
- * @param {number} target - Descriptor del bloque que recibirá los elementos.
975
- * @param {number} source - Descriptor del bloque cuyos elementos se van a
976
- * añadir.
977
- * @returns {number} Número de elementos añadidos efectivamente.
978
- * @throws {Error} Si los descriptores no son válidos, están corruptos
979
- * o el bloque de destino está prestado mediante `withView()`.
980
- */
981
- append(target, source) {
982
- const metaTarget = {};
983
- const metaSource = {};
984
- this.extractMetadata(target, metaTarget);
985
- this.extractMetadata(source, metaSource);
986
- if (metaTarget.borrowed) throw new Error("Block is borrowed");
987
- const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
988
- const count = Math.min(available, metaSource.occupied);
989
- if (count === 0) return 0;
990
- const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
991
- const sourceAddress = metaSource.dataAddress;
992
- this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
993
- this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
994
- return count;
995
- }
996
- /**
997
- * Crea una copia independiente de un bloque.
998
- *
999
- * El nuevo bloque posee la misma capacidad física y la misma ocupación que el
1000
- * bloque original. Se copian todos los bytes de la región reservada, incluidas las posiciones
1001
- * no ocupadas actualmente.
1002
- *
1003
- * El nuevo bloque recibe un nuevo descriptor y sigue sujeto a las reglas
1004
- * normales de asignación y reciclaje.
1005
- *
1006
- * @param {number} handler - Descriptor del bloque que se va a clonar.
1007
- * @returns {number} Descriptor del nuevo bloque.
1008
- * @throws {Error} Si el descriptor no es válido o está corrupto.
1009
- */
1010
- clone(handler) {
1011
- const meta = this.extractMetadata(handler, this.metadata);
1012
- const cloned = this.alloc(meta.byteCapacity / this.wordSize);
1013
- const cloneMeta = {};
1014
- this.extractMetadata(cloned, cloneMeta);
1015
- this.dataBus.copyWithin(cloneMeta.dataAddress, meta.dataAddress, meta.dataAddress + meta.byteCapacity);
1016
- this.controlAdapter.setUint32(cloneMeta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
1017
- return cloned;
1018
- }
1019
- /**
1020
- * Intercambia las regiones de datos asociadas a dos bloques.
1021
- *
1022
- * La operación intercambia entre las cabeceras las direcciones de las regiones, sus
1023
- * capacidades y sus ocupaciones. Los descriptores permanecen inalterados:
1024
- * tras la operación, cada descriptor sigue identificando su propia
1025
- * cabecera, pero dicha cabecera pasa a describir la región que anteriormente
1026
- * pertenecía al otro bloque.
1027
- *
1028
- * No se copian datos en el `dataBus`; solo se modifican los metadatos de ambas
1029
- * cabeceras.
1030
- *
1031
- * @param {number} source - Descriptor del primer bloque.
1032
- * @param {number} target - Descriptor del segundo bloque.
1033
- * @returns {void}
1034
- * @throws {Error} Si los descriptores no son válidos, están corruptos
1035
- * o cualquiera de los bloques está prestado mediante `withView()`.
1036
- */
1037
- swap(source, target) {
1038
- const metaA = {};
1039
- const metaB = {};
1040
- this.extractMetadata(source, metaA);
1041
- this.extractMetadata(target, metaB);
1042
- if (metaA.borrowed) throw new Error("Block is borrowed");
1043
- if (metaB.borrowed) throw new Error("Block is borrowed");
1044
- this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
1045
- this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
1046
- this.controlAdapter.setUint8(metaA.headerAddress + CAPACITY_OFFSET, metaB.capacityExponent);
1047
- this.controlAdapter.setUint8(metaB.headerAddress + CAPACITY_OFFSET, metaA.capacityExponent);
1048
- this.controlAdapter.setUint32(metaA.headerAddress + OCCUPIED_OFFSET, metaB.occupied, IS_LITTLE_ENDIAN);
1049
- this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, metaA.occupied, IS_LITTLE_ENDIAN);
1050
- }
1051
- // ============= SERIALIZACIÓN (SERIALIZATION) ==============
1052
- /**
1053
- * Serializa el contenido y los metadatos de un bloque de memoria.
1054
- *
1055
- * El método extrae los datos ocupados del bloque mediante `pick()`,
1056
- * los agrupa junto con la información de capacidad y el tipo de palabra
1057
- * en un sobre de datos y los codifica utilizando el formato CBOR.
1058
- *
1059
- * @param {number} handler - Descriptor del bloque que se va a serializar.
1060
- * @returns {Uint8Array} Un búfer que contiene los datos serializados del bloque.
1061
- * @throws {Error} Si el descriptor no es válido o está corrupto.
1062
- */
1063
- dump(handler) {
1064
- const meta = this.extractMetadata(handler, this.metadata);
1065
- const capacity = meta.capacityExponent;
1066
- const capacityElements = 2 ** capacity;
1067
- if (!Number.isInteger(capacity) || capacity < 1 || capacity > 31 || meta.occupied > capacityElements) {
1068
- throw new Error("Cannot serialize a block with invalid metadata");
1069
- }
1070
- const payload = this.pick(handler);
1071
- if (payload.length !== meta.occupied || payload.constructor !== this.bucketArray) {
1072
- throw new Error("Cannot serialize a block with an invalid payload");
1073
- }
1074
- return (0, import_cbor_x.encode)({
1075
- v: 1,
1076
- wordType: this.wordType,
1077
- capacity,
1078
- occupied: meta.occupied,
1079
- le: IS_LITTLE_ENDIAN,
1080
- payload
1081
- });
1082
- }
1083
- /**
1084
- * Restaura un bloque de memoria a partir de datos serializados.
1085
- *
1086
- * Decodifica el sobre CBOR, valida si el tipo de palabra del dato
1087
- * serializado es compatible con la instancia actual del asignador y asigna
1088
- * un nuevo bloque con la capacidad necesaria para alojar el contenido.
1089
- * A continuación, se restauran los datos y la ocupación original en el nuevo bloque.
1090
- *
1091
- * @param {Uint8Array|ArrayBuffer} serialized - Búfer que contiene los datos serializados.
1092
- * @returns {number} Descriptor del nuevo bloque recreado.
1093
- * @throws {Error} Si el tipo de palabra del dato decodificado difiere del configurado en el asignador.
1094
- */
1095
- load(serialized) {
1096
- if (!(serialized instanceof ArrayBuffer) && !(serialized instanceof Uint8Array)) {
1097
- throw new TypeError("serialized must be an ArrayBuffer or Uint8Array");
1098
- }
1099
- const envelope = (0, import_cbor_x.decode)(serialized);
1100
- if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)) {
1101
- throw new TypeError("Invalid serialized block envelope");
1102
- }
1103
- if (envelope.v !== 1) {
1104
- throw new Error(`Unsupported serialized block version: ${envelope.v}`);
1105
- }
1106
- if (envelope.wordType !== this.wordType) {
1107
- throw new Error(`Can't load data, ${this.wordType} expected but ${envelope.wordType} found.`);
1108
- }
1109
- if (!Number.isInteger(envelope.capacity) || envelope.capacity < 1 || envelope.capacity > 31) {
1110
- throw new RangeError("Invalid serialized block capacity");
1111
- }
1112
- const capacityElements = 2 ** envelope.capacity;
1113
- if (!Number.isSafeInteger(envelope.occupied) || envelope.occupied < 0 || envelope.occupied > capacityElements) {
1114
- throw new RangeError("Invalid serialized block occupancy");
1115
- }
1116
- if (typeof envelope.le !== "boolean") {
1117
- throw new TypeError("Invalid serialized endianness flag");
1118
- }
1119
- const payload = envelope.payload;
1120
- if (!isTypedArray(payload) || payload.constructor !== this.bucketArray || payload.length !== envelope.occupied) {
1121
- throw new TypeError(`Invalid payload: expected ${this.bucketType}Array with ${envelope.occupied} elements`);
1122
- }
1123
- if (payload.BYTES_PER_ELEMENT !== this.wordSize || payload.byteLength !== envelope.occupied * this.wordSize) {
1124
- throw new TypeError("Serialized payload has an invalid element size");
1125
- }
1126
- const handler = this.alloc(capacityElements);
1127
- const meta = this.extractMetadata(handler, this.metadata);
1128
- this.put(handler, payload);
1129
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, envelope.occupied, IS_LITTLE_ENDIAN);
1130
- return handler;
1131
- }
1132
- // ========== INTEGRACIÓN E INGESTA DE DATOS ==========
1133
- /**
1134
- * Carga datos mediante un adaptador especializado.
1135
- *
1136
- * El adaptador recibe esta instancia y utiliza su API pública para asignar
1137
- * y completar los bloques necesarios. La organización y la interpretación
1138
- * de los datos son responsabilidad exclusiva del adaptador; Balloc solo
1139
- * delega la operación y devuelve el handler resultante.
1140
- *
1141
- * La operación es síncrona. El adaptador debe completar la ingesta antes
1142
- * de retornar y es responsable de revertir sus propias asignaciones si
1143
- * ocurre un error durante la carga.
1144
- *
1145
- * @param {FormatAdapter} adapter - Adaptador que implementa load(allocator).
1146
- * @returns {number} Handler devuelto por el adaptador.
1147
- * @throws {TypeError} Si el adaptador no implementa el método load().
1148
- * @throws {Error} Si el adaptador rechaza la infraestructura suscrita.
1149
- */
1150
- loadData(adapter) {
1151
- if (!adapter || typeof adapter.load !== "function") throw new TypeError("adapter must implement load(allocator)");
1152
- return adapter.load(this);
1153
- }
1154
- // ============= UTILIDADES (UTILITIES) ==============
1155
- /**
1156
- * Impide operaciones de modificación sobre un bloque prestado.
1157
- *
1158
- * Comprueba la bandera `VIEW_LOCK` en la cabecera asociada a la dirección proporcionada.
1159
- *
1160
- * @param {number} headerAddress - Dirección de la cabecera en el `controlBus`.
1161
- * @returns {void}
1162
- * @throws {Error} Si el bloque está prestado mediante `withView()`.
1163
- * @private
1164
- * @deprecated
1165
- */
1166
- assertNotBorrowed(headerAddress) {
1167
- if (this.controlBus[headerAddress + FLAGS_OFFSET] & VIEW_LOCK) {
1168
- throw new Error("Block is borrowed");
1169
- }
1170
- }
1171
- /**
1172
- * Impide operaciones que reemplazan o reasignan el `dataBus`
1173
- * mientras exista algún segmento prestado.
1174
- *
1175
- * @returns {void}
1176
- * @throws {Error} Si existe algún bloque prestado mediante `withView()`.
1177
- * @private
1178
- */
1179
- assertNoActiveViews() {
1180
- for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
1181
- if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
1182
- if (this.controlBus[i + FLAGS_OFFSET] & VIEW_LOCK) {
1183
- throw new Error("Cannot remap memory while a block is borrowed");
1184
- }
1185
- }
1186
- }
1187
- /**
1188
- * [USO INTERNO]
1189
- * Decodifica los metadatos asociados a un descriptor.
1190
- *
1191
- * El descriptor se divide en generación y dirección de la cabecera. La cookie almacenada
1192
- * en la cabecera se recalcula para validar la combinación; solo tras
1193
- * dicha validación se leen los metadatos.
1194
- *
1195
- * Los campos decodificados se escriben en el objeto `out`, que es devuelto
1196
- * por la propia función. El objeto se puede reutilizar entre llamadas para
1197
- * evitar nuevas asignaciones.
1198
- *
1199
- * @param {number} handler - Descriptor que se va a decodificar y validar.
1200
- * @param {Metadata} out - Objeto que recibirá los metadatos decodificados.
1201
- * @returns {Metadata} La misma referencia proporcionada en `out`.
1202
- * @throws {Error} Si la cookie de la cabecera no coincide con el descriptor o
1203
- * si el descriptor no identifica una cabecera válida.
1204
- * @private
1205
- */
1206
- extractMetadata(handler, out) {
1207
- out.generation = handler / ROTATE_32BITS & CLAMP_11BITS;
1208
- out.headerAddress = handler >>> 0;
1209
- const cookie = this.controlAdapter.getUint8(out.headerAddress + COOKIE_OFFSET);
1210
- if (cookie !== this.bakeCookie(out.headerAddress, out.generation)) {
1211
- throw new Error("Invalid or corrupted handle");
1212
- }
1213
- out.dataAddress = this.controlAdapter.getUint32(out.headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
1214
- out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1215
- out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
1216
- out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
1217
- out.borrowed = this.controlAdapter.getUint32(out.headerAddress + FLAGS_OFFSET, IS_LITTLE_ENDIAN) & VIEW_LOCK;
1218
- return out;
1219
- }
1220
- /**
1221
- * [USO INTERNO]
1222
- * Calcula la cookie de validación de una cabecera.
1223
- *
1224
- * La cookie se deriva de la dirección de la cabecera y de los 11 bits de la generación mediante
1225
- * un hash rápido (fast hash).
1226
- * El resultado se reduce a 8 bits.
1227
- *
1228
- * El valor cero se reserva como indicador de cabecera inválida; por tanto,
1229
- * cuando el cálculo produce cero, el método devuelve `1`.
1230
- *
1231
- * La cookie no constituye un mecanismo criptográfico. Su finalidad es
1232
- * detectar descriptores inválidos, obsoletos (stale) o corruptos dentro del modelo de
1233
- * gestión de memoria del asignador.
1234
- *
1235
- * @param {number} addr - Dirección de la cabecera.
1236
- * @param {number} gen - Generación asociada al descriptor. Solo se consideran los 11 bits
1237
- * menos significativos.
1238
- * @returns {number} Cookie de 8 bits en el rango [1, 255].
1239
- * @private
1240
- */
1241
- bakeCookie(addr, gen) {
1242
- return (addr ^ gen & 2047 * 2654435761) & 255 || 1;
1243
- }
1244
- /**
1245
- * Devuelve la cantidad de regiones almacenadas actualmente en la lista de
1246
- * reciclaje.
1247
- *
1248
- * Cada región corresponde a un bloque liberado que no pudo devolverse
1249
- * directamente a la cima del `dataBus` y, por tanto, permanece disponible para
1250
- * su reutilización en una futura asignación de capacidad idéntica.
1251
- *
1252
- * @returns {number} Número de regiones libres mantenidas en `recycle`.
1253
- */
1254
- recycleCount() {
1255
- let count = 0;
1256
- for (const [, page] of this.recycle) {
1257
- count += page[0];
1258
- }
1259
- return count;
1260
- }
1261
- /**
1262
- * Devuelve el total de bytes pertenecientes a las regiones almacenadas actualmente
1263
- * en la lista de reciclaje.
1264
- *
1265
- * El valor se calcula sumando la capacidad de cada región libre multiplicada
1266
- * por la cantidad de regiones registradas para dicha capacidad.
1267
- *
1268
- * @returns {number} Número de bytes ocupados por regiones reciclables.
1269
- */
1270
- get recycleBytes() {
1271
- let total = 0;
1272
- for (const [capacity, page] of this.recycle) {
1273
- total += page[0] * capacity;
1274
- }
1275
- return total;
1276
- }
1277
- /**
1278
- * Devuelve la cantidad de bytes asignados que no pertenecen a las regiones
1279
- * reciclables actualmente.
1280
- *
1281
- * El valor se obtiene restando del avance total del `dataPointer` los bytes
1282
- * pertenecientes a las regiones libres mantenidas en `recycle`.
1283
- *
1284
- * @returns {number} Número de bytes asociados a regiones no reciclables
1285
- * dentro del área ya utilizada por el `dataBus`.
1286
- */
1287
- get allocatedBytes() {
1288
- return this.dataPointer - this.recycleBytes;
1289
- }
1290
- /**
1291
- * Devuelve la cantidad de bytes aún no utilizada en la cima del `dataBus`.
1292
- *
1293
- * Dicho espacio corresponde a la región situada entre `dataPointer` y el final de la
1294
- * capacidad reservada actualmente para el búfer.
1295
- *
1296
- * @returns {number} Número de bytes disponibles después de `dataPointer`.
1297
- */
1298
- get unallocatedBytes() {
1299
- return this.size - this.dataPointer;
1300
- }
1301
- /**
1302
- * Devuelve la razón entre la memoria reciclable y el área de montón (heap) utilizada.
1303
- *
1304
- * La métrica considera como fragmentación las regiones libres mantenidas en
1305
- * `recycle` y utiliza `dataPointer` como denominador. Cuando ningún byte
1306
- * ha sido utilizado por el montón, el resultado es cero.
1307
- *
1308
- * El valor no representa la fracción de toda la capacidad del `dataBus`, sino
1309
- * específicamente la proporción de bytes reciclables dentro del área ya
1310
- * recorrida por el puntero bump (bump pointer).
1311
- *
1312
- * @returns {number} Razón de fragmentación en el rango [0, 1] en condiciones
1313
- * normales de operación.
1314
- */
1315
- get fragmentationRatio() {
1316
- if (this.dataPointer === 0) return 0;
1317
- return this.recycleBytes / this.dataPointer;
1318
- }
1319
- };
1320
- module.exports = { Balloc };