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.
- package/LICENSE +7 -0
- package/README.MD +433 -0
- package/README.ar.md +405 -0
- package/README.en.md +433 -0
- package/README.es.md +405 -0
- package/README.jp.md +404 -0
- package/README.pt.md +433 -0
- package/README.zh.md +404 -0
- package/docs/API /342/200/224 balloc.ar.md" +1365 -0
- package/docs/API /342/200/224 balloc.en.md" +1264 -0
- package/docs/API /342/200/224 balloc.es.md" +1180 -0
- package/docs/API /342/200/224 balloc.jp.md" +1087 -0
- package/docs/API /342/200/224 balloc.pt.md" +1214 -0
- package/docs/API /342/200/224 balloc.zh.md" +1168 -0
- package/img/pix.png +0 -0
- package/package.json +109 -6
- package/src/ar/balloc.cjs +1079 -0
- package/src/ar/balloc.js +2 -0
- package/src/ar/balloc.mjs +1327 -0
- package/src/en/balloc.cjs +1091 -0
- package/src/en/balloc.js +2 -0
- package/src/en/balloc.mjs +1339 -0
- package/src/es/balloc.cjs +1111 -0
- package/src/es/balloc.js +2 -0
- package/src/es/balloc.mjs +1360 -0
- package/src/jp/balloc.cjs +1067 -0
- package/src/jp/balloc.js +2 -0
- package/src/jp/balloc.mjs +1315 -0
- package/src/pt/balloc.cjs +1114 -0
- package/src/pt/balloc.js +2 -0
- package/src/pt/balloc.mjs +1362 -0
- package/src/zh/balloc.cjs +1013 -0
- package/src/zh/balloc.js +2 -0
- package/src/zh/balloc.mjs +1262 -0
- package/types/ar/balloc.d.mts +647 -0
- package/types/en/balloc.d.mts +659 -0
- package/types/es/balloc.d.mts +679 -0
- package/types/jp/balloc.d.mts +635 -0
- package/types/pt/balloc.d.mts +682 -0
- package/types/zh/balloc.d.mts +581 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1111 @@
|
|
|
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 ROTATE_32BITS = 4294967296;
|
|
47
|
+
var CLAMP_11BITS = 2047 >>> 0;
|
|
48
|
+
var isTypedArray = (val) => ArrayBuffer.isView(val) && !(val instanceof DataView);
|
|
49
|
+
var Balloc = class {
|
|
50
|
+
/**
|
|
51
|
+
* Crea una instancia del asignador de memoria `Balloc`.
|
|
52
|
+
*
|
|
53
|
+
* El asignador mantiene dos bústeres independientes:
|
|
54
|
+
* - `dataBus`: almacena los datos de los bloques asignados;
|
|
55
|
+
* - `controlBus`: almacena las cabeceras y otros metadatos de control.
|
|
56
|
+
*
|
|
57
|
+
* Cada bloque posee una cabecera de tamaño fijo (`HEADER_SIZE`) y se
|
|
58
|
+
* identifica externamente mediante un identificador lógico de 43 bits, compuesto
|
|
59
|
+
* por una generación de 11 bits y la dirección de su cabecera en 32 bits.
|
|
60
|
+
*
|
|
61
|
+
* La capacidad de cada bloque se redondea hacia arriba a la siguiente potencia de
|
|
62
|
+
* dos en elementos, respetando el ancho del bucket configurado.
|
|
63
|
+
*
|
|
64
|
+
* @param {number} [size=65535] - Capacidad inicial del `dataBus`, en bytes.
|
|
65
|
+
* Debe ser un entero seguro en el rango [2, 0x80000000].
|
|
66
|
+
* @param {BucketType} [bucketSize="32u"] - Identificador del tipo y tamaño del bucket
|
|
67
|
+
* (ej.: '32u' para Uint32, '64f' para Float64, '8i' para Int8).
|
|
68
|
+
* @param {number} [metadataSize=1024] - Capacidad inicial del `controlBus`,
|
|
69
|
+
* en bytes. Debe ser un entero seguro en el rango
|
|
70
|
+
* [HEADER_SIZE, 0x80000000].
|
|
71
|
+
*
|
|
72
|
+
* @throws {RangeError} Si `size` se encuentra fuera del rango permitido.
|
|
73
|
+
* @throws {RangeError} Si `bucketSize` no es un identificador de bucket válido.
|
|
74
|
+
* @throws {RangeError} Si `metadataSize` se encuentra fuera del rango permitido.
|
|
75
|
+
*/
|
|
76
|
+
constructor(size = 65535, bucketSize = "32u", metadataSize = 1024) {
|
|
77
|
+
if (!Number.isSafeInteger(size) || size < 2 || size > 2147483648) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
|
|
78
|
+
if (!BUCKET_MAPPING[bucketSize]) {
|
|
79
|
+
throw new RangeError(`bucketSize must be in ([ 8 || 16 || 32 || 64][ u || i ]) || ([ 16 || 32 || 64][ f ]) but I found ${bucketSize}`);
|
|
80
|
+
}
|
|
81
|
+
if (!Number.isSafeInteger(metadataSize) || metadataSize < HEADER_SIZE || metadataSize > 2147483648) throw new RangeError(`Parameter metadataSize must be in range [HEADER_SIZE, 0x80000000] but metadataSize is ${metadataSize}`);
|
|
82
|
+
this.wordType = bucketSize;
|
|
83
|
+
this.bucketType = BUCKET_MAPPING[bucketSize].type;
|
|
84
|
+
this.bucketSize = BUCKET_MAPPING[bucketSize].bits >>> 0;
|
|
85
|
+
this.bucketArray = globalThis[`${this.bucketType}Array`];
|
|
86
|
+
this.wordSize = this.bucketSize >>> 3;
|
|
87
|
+
this.wordShift = this.bucketSize >>> 4;
|
|
88
|
+
this.size = Math.max(1 << 32 - Math.clz32(size) >>> 0, this.wordSize);
|
|
89
|
+
this.headerSize = 1 << 32 - Math.clz32(metadataSize) >>> 0;
|
|
90
|
+
this.dataPointer = 0 >>> 0;
|
|
91
|
+
this.controlPointer = 0 >>> 0;
|
|
92
|
+
this.echoPointer = 0 >>> 0;
|
|
93
|
+
this.generation = 0 >>> 0;
|
|
94
|
+
this.dataBus = new Uint8Array(this.size);
|
|
95
|
+
this.controlBus = new Uint8Array(this.headerSize);
|
|
96
|
+
this.dataAdapter = new DataView(this.dataBus.buffer);
|
|
97
|
+
this.controlAdapter = new DataView(this.controlBus.buffer);
|
|
98
|
+
this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
|
|
99
|
+
this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
|
|
100
|
+
this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
|
|
101
|
+
this.recycle = /* @__PURE__ */ new Map();
|
|
102
|
+
this.metadata = {
|
|
103
|
+
generation: 0 >>> 0,
|
|
104
|
+
headerAddress: 0 >>> 0,
|
|
105
|
+
dataAddress: 0 >>> 0,
|
|
106
|
+
capacityExponent: 0 >>> 0,
|
|
107
|
+
byteCapacity: 0 >>> 0,
|
|
108
|
+
occupied: 0 >>> 0
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
// ========== ASIGNACIÓN ==========
|
|
112
|
+
/**
|
|
113
|
+
* Asigna un nuevo bloque de memoria.
|
|
114
|
+
*
|
|
115
|
+
* La capacidad solicitada se convierte a la potencia de dos más pequeña que
|
|
116
|
+
* admita `size` elementos. El bloque se obtiene preferentemente de la lista
|
|
117
|
+
* de regiones reciclables con la capacidad correspondiente; si no existe
|
|
118
|
+
* una región compatible, el bloque se reserva en la parte superior del `dataBus`.
|
|
119
|
+
*
|
|
120
|
+
* A continuación, se obtiene una cabecera del espacio de control. Las cabeceras
|
|
121
|
+
* liberadas previamente pueden reutilizarse mediante la pila interna de reciclaje;
|
|
122
|
+
* de lo contrario, el `controlBus` se expande cuando es necesario.
|
|
123
|
+
*
|
|
124
|
+
* La cabecera recibe la dirección, la capacidad, la ocupación inicial (cero) y
|
|
125
|
+
* un cookie de validación. El valor devuelto codifica la generación de la asignación
|
|
126
|
+
* y la dirección de la cabecera:
|
|
127
|
+
*
|
|
128
|
+
* [11 bits de generación][32 bits de dirección de cabecera]
|
|
129
|
+
*
|
|
130
|
+
* @param {number} [size=16] - Número mínimo de elementos que el bloque debe
|
|
131
|
+
* alojar. Debe ser un entero seguro en el rango [2, 0x80000000].
|
|
132
|
+
* @returns {number} Identificador que identifica el bloque asignado.
|
|
133
|
+
* @throws {RangeError} Si `size` se encuentra fuera del rango permitido.
|
|
134
|
+
*/
|
|
135
|
+
alloc(size = 16) {
|
|
136
|
+
if (!Number.isSafeInteger(size) || size < 2 || size > 2147483648) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
|
|
137
|
+
const capacity = 32 - Math.clz32(size - 1);
|
|
138
|
+
const blockSize = (1 << capacity >>> 0) * this.wordSize;
|
|
139
|
+
let dataAddress = this.recyclePop(blockSize);
|
|
140
|
+
if (dataAddress === UNKNOWN) {
|
|
141
|
+
while (this.dataPointer + blockSize > this.size) this.grow();
|
|
142
|
+
dataAddress = this.dataPointer;
|
|
143
|
+
this.dataPointer += blockSize;
|
|
144
|
+
}
|
|
145
|
+
let headerAddress = 0 >>> 0;
|
|
146
|
+
if (this.echoPointer > this.controlPointer) {
|
|
147
|
+
this.echoPointer -= 4;
|
|
148
|
+
headerAddress = this.controlAdapter.getUint32(this.echoPointer, IS_LITTLE_ENDIAN);
|
|
149
|
+
} else {
|
|
150
|
+
if (this.controlPointer + HEADER_SIZE > this.controlAdapter.byteLength) this.headerGrow();
|
|
151
|
+
headerAddress = this.controlPointer;
|
|
152
|
+
this.controlPointer += HEADER_SIZE;
|
|
153
|
+
this.echoPointer += HEADER_SIZE;
|
|
154
|
+
}
|
|
155
|
+
this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, dataAddress, IS_LITTLE_ENDIAN);
|
|
156
|
+
this.controlAdapter.setUint32(headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
|
|
157
|
+
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, capacity);
|
|
158
|
+
this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, this.bakeCookie(headerAddress, ++this.generation));
|
|
159
|
+
return (this.generation & CLAMP_11BITS) * ROTATE_32BITS + headerAddress;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Expande la capacidad de un bloque a la siguiente potencia de dos.
|
|
163
|
+
*
|
|
164
|
+
* Cuando el bloque se encuentra en la parte superior actual del `dataBus`, la expansión
|
|
165
|
+
* se realiza in situ: solo se actualizan su capacidad y el `dataPointer`.
|
|
166
|
+
*
|
|
167
|
+
* En caso de existir otra región después del bloque, se obtiene una nueva región con el doble
|
|
168
|
+
* de capacidad del espacio reciclable o se asigna en la parte superior del `dataBus`.
|
|
169
|
+
* Los elementos ocupados actualmente se copian a la nueva región,
|
|
170
|
+
* y la región anterior se devuelve a la lista de reciclaje.
|
|
171
|
+
*
|
|
172
|
+
* El identificador permanece válido, ya que su cabecera se conserva y solo se
|
|
173
|
+
* actualizan la dirección y la capacidad registradas en él.
|
|
174
|
+
*
|
|
175
|
+
* @param {number} handler - Identificador del bloque a expandir.
|
|
176
|
+
* @returns {void}
|
|
177
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
178
|
+
* @throws {AggregateError} Si la capacidad ha alcanzado su límite
|
|
179
|
+
* máximo soportado.
|
|
180
|
+
*/
|
|
181
|
+
realloc(handler) {
|
|
182
|
+
const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
|
|
183
|
+
let headerAddress = handler >>> 0;
|
|
184
|
+
const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
185
|
+
const occupied = this.controlAdapter.getUint32(headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
|
|
186
|
+
const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
|
|
187
|
+
const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
|
|
188
|
+
if (cookie !== this.bakeCookie(headerAddress, generation)) {
|
|
189
|
+
throw new Error("Invalid or corrupted handle");
|
|
190
|
+
}
|
|
191
|
+
if (capacity >= 31) throw new AggregateError([new Error("Can\xB4t reallocate handler."), new RangeError("Capacity has reached its limit.")], "Internal Error.");
|
|
192
|
+
const newCapacity = capacity + 1;
|
|
193
|
+
const newBlockSize = (1 << newCapacity >>> 0) * this.wordSize;
|
|
194
|
+
const oldBlockSize = (1 << capacity >>> 0) * this.wordSize;
|
|
195
|
+
if (dataAddress + oldBlockSize === this.dataPointer) {
|
|
196
|
+
while (dataAddress + newBlockSize > this.size) this.grow();
|
|
197
|
+
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity, IS_LITTLE_ENDIAN);
|
|
198
|
+
this.dataPointer = dataAddress + newBlockSize;
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
this.recyclePush(oldBlockSize, dataAddress);
|
|
202
|
+
let newAddress = this.recyclePop(newBlockSize);
|
|
203
|
+
if (newAddress === UNKNOWN) {
|
|
204
|
+
while (this.dataPointer + newBlockSize > this.size) this.grow();
|
|
205
|
+
newAddress = this.dataPointer;
|
|
206
|
+
this.dataPointer += newBlockSize;
|
|
207
|
+
}
|
|
208
|
+
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
|
|
209
|
+
this.dataBus.copyWithin(newAddress, dataAddress, dataAddress + occupied * this.wordSize);
|
|
210
|
+
this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, newAddress, IS_LITTLE_ENDIAN);
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Libera un bloque de memoria.
|
|
214
|
+
*
|
|
215
|
+
* La cabecera del bloque se invalida poniendo su cookie a cero y su
|
|
216
|
+
* dirección se registra para su reutilización posterior. La región de datos
|
|
217
|
+
* también se devuelve al sistema de reciclaje, excepto cuando el bloque está
|
|
218
|
+
* exactamente en la parte superior del `dataBus`; en ese caso, el `dataPointer` simplemente
|
|
219
|
+
* retrocede, eliminando la región sin crear una entrada en la lista de
|
|
220
|
+
* reciclaje.
|
|
221
|
+
*
|
|
222
|
+
* @param {number} handler - Identificador del bloque a liberar.
|
|
223
|
+
* @returns {void}
|
|
224
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
225
|
+
*/
|
|
226
|
+
free(handler) {
|
|
227
|
+
const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
|
|
228
|
+
let headerAddress = handler >>> 0;
|
|
229
|
+
const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
230
|
+
const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
|
|
231
|
+
const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
|
|
232
|
+
if (cookie !== this.bakeCookie(headerAddress, generation)) {
|
|
233
|
+
throw new Error("Invalid or corrupted handle");
|
|
234
|
+
}
|
|
235
|
+
const blockSize = (1 << capacity >>> 0) * this.wordSize;
|
|
236
|
+
this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
|
|
237
|
+
if (this.echoPointer + 4 <= this.controlBus.byteLength) {
|
|
238
|
+
this.controlAdapter.setUint32(this.echoPointer, headerAddress, IS_LITTLE_ENDIAN);
|
|
239
|
+
this.echoPointer += 4;
|
|
240
|
+
}
|
|
241
|
+
if (dataAddress + blockSize === this.dataPointer) {
|
|
242
|
+
this.dataPointer = dataAddress;
|
|
243
|
+
} else {
|
|
244
|
+
this.recyclePush(blockSize, dataAddress);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
// ========== RECICLAJE ==========
|
|
248
|
+
/**
|
|
249
|
+
* [USO INTERNO]
|
|
250
|
+
* Inserta una región libre en la lista de reciclaje.
|
|
251
|
+
*
|
|
252
|
+
* La lista se organiza por capacidad en bytes. Para cada capacidad, el
|
|
253
|
+
* valor almacenado es un `Uint32Array` cuya posición cero contiene la cantidad
|
|
254
|
+
* de direcciones registradas y las posiciones siguientes contienen las direcciones
|
|
255
|
+
* de las regiones libres:
|
|
256
|
+
*
|
|
257
|
+
* [count, address1, address2, ...]
|
|
258
|
+
*
|
|
259
|
+
* Cuando la página se llena, su búster se expande al doble de la
|
|
260
|
+
* capacidad actual.
|
|
261
|
+
*
|
|
262
|
+
* @param {number} capacity - Capacidad de la región libre, en bytes.
|
|
263
|
+
* @param {number} address - Dirección inicial de la región en el `dataBus`.
|
|
264
|
+
* @returns {void}
|
|
265
|
+
* @private
|
|
266
|
+
*/
|
|
267
|
+
recyclePush(capacity, address) {
|
|
268
|
+
if (this.recycle.has(capacity)) {
|
|
269
|
+
let page = this.recycle.get(capacity);
|
|
270
|
+
const count = page[0];
|
|
271
|
+
if (count === page.length - 1) {
|
|
272
|
+
const newBuffer = page.buffer.transfer(page.buffer.byteLength * 2);
|
|
273
|
+
page = new Uint32Array(newBuffer);
|
|
274
|
+
this.recycle.set(capacity, page);
|
|
275
|
+
}
|
|
276
|
+
page[count + 1] = address;
|
|
277
|
+
page[0] = count + 1;
|
|
278
|
+
} else {
|
|
279
|
+
this.recycle.set(capacity, new Uint32Array([1, address]));
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* [USO INTERNO]
|
|
284
|
+
* Elimina una región libre de la lista de reciclaje.
|
|
285
|
+
*
|
|
286
|
+
* La búsqueda se realiza por la capacidad exacta solicitada. Cuando existe una
|
|
287
|
+
* página correspondiente, la última dirección registrada se elimina de la
|
|
288
|
+
* página y se devuelve, implementando el reciclaje como una pila LIFO.
|
|
289
|
+
*
|
|
290
|
+
* @param {number} capacity - Capacidad deseada, en bytes.
|
|
291
|
+
* @returns {number} Dirección inicial de una región reciclable o `UNKNOWN`
|
|
292
|
+
* cuando no existe una región con la capacidad solicitada.
|
|
293
|
+
* @private
|
|
294
|
+
*/
|
|
295
|
+
recyclePop(capacity) {
|
|
296
|
+
if (!this.recycle.has(capacity)) return UNKNOWN;
|
|
297
|
+
const page = this.recycle.get(capacity);
|
|
298
|
+
const count = page[0];
|
|
299
|
+
if (count === 0) return UNKNOWN;
|
|
300
|
+
const address = page[count];
|
|
301
|
+
page[0] = count - 1;
|
|
302
|
+
return address;
|
|
303
|
+
}
|
|
304
|
+
// ========== RECOLECCIÓN DE BASURA ==========
|
|
305
|
+
/**
|
|
306
|
+
* Compacta el `dataBus` mediante el algoritmo ReBump.
|
|
307
|
+
*
|
|
308
|
+
* Recorre secuencialmente las cabeceras registradas en el `controlBus` y copia
|
|
309
|
+
* las regiones que aún son válidas a un nuevo `dataBus`, eliminando los espacios
|
|
310
|
+
* libres existentes entre ellas. La dirección de cada bloque superviviente se
|
|
311
|
+
* actualiza en su respectiva cabecera.
|
|
312
|
+
*
|
|
313
|
+
* Se preserva el orden de los bloques en el `controlBus`. Los datos internos de
|
|
314
|
+
* cada bloque también se conservan íntegramente, incluyendo su capacidad
|
|
315
|
+
* reservada y su ocupación actual.
|
|
316
|
+
*
|
|
317
|
+
* Al finalizar la compactación:
|
|
318
|
+
* - se eliminan todas las regiones reciclables;
|
|
319
|
+
* - `dataPointer` apunta al primer byte después del último bloque
|
|
320
|
+
* activo;
|
|
321
|
+
* - el `dataBus` pasa a representar un montón contiguo para los bloques activos.
|
|
322
|
+
*
|
|
323
|
+
* La complejidad de control es O(n), donde `n` es el número de cabeceras
|
|
324
|
+
* recorridas. El coste efectivo del movimiento de memoria también depende
|
|
325
|
+
* del volumen de bytes pertenecientes a los bloques activos.
|
|
326
|
+
*
|
|
327
|
+
* @returns {void}
|
|
328
|
+
*/
|
|
329
|
+
gc() {
|
|
330
|
+
const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
|
|
331
|
+
this.recycle.clear();
|
|
332
|
+
this.dataPointer = 0 >>> 0;
|
|
333
|
+
for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
|
|
334
|
+
if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
|
|
335
|
+
const start = this.controlAdapter.getUint32(i + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
336
|
+
const size = (1 << this.controlBus[i + CAPACITY_OFFSET] >>> 0) * this.wordSize;
|
|
337
|
+
const end = start + size;
|
|
338
|
+
newDataBus.set(this.dataBus.subarray(start, end), this.dataPointer);
|
|
339
|
+
this.controlAdapter.setUint32(i + ADDRESS_OFFSET, this.dataPointer, IS_LITTLE_ENDIAN);
|
|
340
|
+
this.dataPointer += size;
|
|
341
|
+
}
|
|
342
|
+
this.dataBus = newDataBus;
|
|
343
|
+
this.dataAdapter = new DataView(this.dataBus.buffer);
|
|
344
|
+
this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
|
|
345
|
+
this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
|
|
346
|
+
this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
|
|
347
|
+
}
|
|
348
|
+
// ========== ESCALADO ==========
|
|
349
|
+
/**
|
|
350
|
+
* [!!! USO INTERNO, NO USAR EN TU CÓDIGO !!!]
|
|
351
|
+
* Expande el `dataBus` al doble de su capacidad actual.
|
|
352
|
+
*
|
|
353
|
+
* El búster subyacente se transfiere a un `ArrayBuffer` mayor, preservando
|
|
354
|
+
* los datos existentes. Todas las vistas asociadas al búster se recrean
|
|
355
|
+
* para hacer referencia al nuevo almacenamiento.
|
|
356
|
+
*
|
|
357
|
+
* @returns {void}
|
|
358
|
+
* @throws {RangeError} Si la capacidad del `dataBus` ha excedido el
|
|
359
|
+
* límite máximo soportado.
|
|
360
|
+
* @private
|
|
361
|
+
*/
|
|
362
|
+
grow() {
|
|
363
|
+
if (this.size > 2147483648) throw new RangeError("Data bus capacity exceeded");
|
|
364
|
+
const newSize = this.size * 2 >>> 0;
|
|
365
|
+
const newBuffer = this.dataBus.buffer.transfer(newSize);
|
|
366
|
+
this.size = newSize;
|
|
367
|
+
this.dataBus = new Uint8Array(newBuffer);
|
|
368
|
+
this.dataAdapter = new DataView(newBuffer);
|
|
369
|
+
this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
|
|
370
|
+
this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
|
|
371
|
+
this.auxiliary = new this.bucketArray(newBuffer);
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* [!!! USO INTERNO, NO USAR EN TU CÓDIGO !!!]
|
|
375
|
+
* Expande el `controlBus` al doble de su capacidad actual.
|
|
376
|
+
*
|
|
377
|
+
* El búster subyacente se transfiere a un `ArrayBuffer` mayor, preservando
|
|
378
|
+
* las cabeceras existentes. El `controlAdapter` se recrea para hacer referencia
|
|
379
|
+
* al nuevo almacenamiento.
|
|
380
|
+
*
|
|
381
|
+
* @returns {void}
|
|
382
|
+
* @throws {RangeError} Si la capacidad actual del `controlBus` ha
|
|
383
|
+
* excedido el límite máximo soportado.
|
|
384
|
+
* @private
|
|
385
|
+
*/
|
|
386
|
+
headerGrow() {
|
|
387
|
+
if (this.controlBus.byteLength > 2147483648) throw new RangeError("Control bus capacity exceeded");
|
|
388
|
+
const newSize = this.controlBus.byteLength * 2 >>> 0;
|
|
389
|
+
const newBuffer = this.controlBus.buffer.transfer(newSize);
|
|
390
|
+
this.controlBus = new Uint8Array(newBuffer);
|
|
391
|
+
this.controlAdapter = new DataView(newBuffer);
|
|
392
|
+
}
|
|
393
|
+
// ========== OPERACIONES DE PILA ==========
|
|
394
|
+
/**
|
|
395
|
+
* Añade un elemento al final de la secuencia ocupada por el bloque.
|
|
396
|
+
*
|
|
397
|
+
* El elemento se graba en la primera posición libre tras el último elemento
|
|
398
|
+
* ocupado. La ocupación del bloque se incrementa solo cuando existe espacio
|
|
399
|
+
* disponible en su capacidad.
|
|
400
|
+
*
|
|
401
|
+
* @param {number} handler - Identificador del bloque.
|
|
402
|
+
* @param {number} value - Valor a insertar.
|
|
403
|
+
* @returns {boolean} `true` si el valor fue insertado; `false` si el bloque
|
|
404
|
+
* ya no dispone de espacio libre.
|
|
405
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
406
|
+
*/
|
|
407
|
+
push(handler, value) {
|
|
408
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
409
|
+
if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
|
|
410
|
+
this.writer(meta.dataAddress + meta.occupied * this.wordSize, value, IS_LITTLE_ENDIAN);
|
|
411
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
|
|
412
|
+
return true;
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Elimina el último elemento ocupado del bloque y lo devuelve.
|
|
416
|
+
*
|
|
417
|
+
* La ocupación se decrementa antes de leer el elemento eliminado. Los
|
|
418
|
+
* bytes correspondientes no se limpian y permanecen en la región asignada,
|
|
419
|
+
* pero dejan de formar parte de la secuencia ocupada.
|
|
420
|
+
*
|
|
421
|
+
* @param {number} handler - Identificador del bloque.
|
|
422
|
+
* @returns {number|undefined} Valor eliminado o `undefined` si el bloque
|
|
423
|
+
* está vacío.
|
|
424
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
425
|
+
*/
|
|
426
|
+
pop(handler) {
|
|
427
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
428
|
+
if (meta.occupied === 0) return void 0;
|
|
429
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
|
|
430
|
+
return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Devuelve el último elemento ocupado sin eliminarlo.
|
|
434
|
+
*
|
|
435
|
+
* @param {number} handler - Identificador del bloque.
|
|
436
|
+
* @returns {number|undefined} Último valor ocupado o `undefined` si el
|
|
437
|
+
* bloque está vacío.
|
|
438
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
439
|
+
*/
|
|
440
|
+
peek(handler) {
|
|
441
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
442
|
+
if (meta.occupied === 0) return void 0;
|
|
443
|
+
return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
|
|
444
|
+
}
|
|
445
|
+
// ========== OPERACIONES DE COLA ==========
|
|
446
|
+
/**
|
|
447
|
+
* Inserta un elemento al inicio de la secuencia ocupada.
|
|
448
|
+
*
|
|
449
|
+
* Los elementos ocupados actualmente se desplazan una posición hacia
|
|
450
|
+
* adelante y `value` se graba en la primera posición. La operación exige una
|
|
451
|
+
* posición libre en la capacidad del bloque.
|
|
452
|
+
*
|
|
453
|
+
* El coste de la operación es proporcional al número de elementos ocupados,
|
|
454
|
+
* ya que los datos deben desplazarse.
|
|
455
|
+
*
|
|
456
|
+
* @param {number} handler - Identificador del bloque.
|
|
457
|
+
* @param {number} value - Valor a insertar.
|
|
458
|
+
* @returns {boolean} `true` si el valor fue insertado; `false` si el bloque
|
|
459
|
+
* está lleno.
|
|
460
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
461
|
+
*/
|
|
462
|
+
nudge(handler, value) {
|
|
463
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
464
|
+
if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
|
|
465
|
+
this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
|
|
466
|
+
this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
|
|
467
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
|
|
468
|
+
return true;
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Elimina el primer elemento ocupado del bloque y lo devuelve.
|
|
472
|
+
*
|
|
473
|
+
* Los elementos restantes se desplazan una posición hacia el inicio
|
|
474
|
+
* de la región ocupada. La capacidad física del bloque permanece inalterada.
|
|
475
|
+
*
|
|
476
|
+
* El coste de la operación es proporcional al número de elementos desplazados.
|
|
477
|
+
*
|
|
478
|
+
* @param {number} handler - Identificador del bloque.
|
|
479
|
+
* @returns {number|undefined} Primer valor eliminado o `undefined` si el
|
|
480
|
+
* bloque está vacío.
|
|
481
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
482
|
+
*/
|
|
483
|
+
pull(handler) {
|
|
484
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
485
|
+
if (meta.occupied === 0) return void 0;
|
|
486
|
+
const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
|
|
487
|
+
this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
|
|
488
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
|
|
489
|
+
return result;
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Devuelve el primer elemento ocupado sin eliminarlo.
|
|
493
|
+
*
|
|
494
|
+
* @param {number} handler - Identificador del bloque.
|
|
495
|
+
* @returns {number|undefined} Primer valor ocupado o `undefined` si el
|
|
496
|
+
* bloque está vacío.
|
|
497
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
498
|
+
*/
|
|
499
|
+
head(handler) {
|
|
500
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
501
|
+
if (meta.occupied === 0) return void 0;
|
|
502
|
+
return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
|
|
503
|
+
}
|
|
504
|
+
// ========== ACCESO ALEATORIO ==========
|
|
505
|
+
/**
|
|
506
|
+
* Comprueba si un valor está presente entre los elementos ocupados del bloque.
|
|
507
|
+
*
|
|
508
|
+
* La búsqueda se realiza directamente sobre el `TypedArray` auxiliar y considera
|
|
509
|
+
* únicamente el intervalo ocupado actualmente, no toda la capacidad física
|
|
510
|
+
* reservada.
|
|
511
|
+
*
|
|
512
|
+
* @param {number} handler - Identificador del bloque.
|
|
513
|
+
* @param {number} value - Valor a buscar.
|
|
514
|
+
* @returns {boolean} `true` si `value` está presente entre los elementos
|
|
515
|
+
* ocupados; de lo contrario, `false`.
|
|
516
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
517
|
+
*/
|
|
518
|
+
has(handler, value) {
|
|
519
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
520
|
+
if (meta.occupied === 0) return false;
|
|
521
|
+
const rawAddres = meta.dataAddress >>> this.wordShift;
|
|
522
|
+
return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* Devuelve el elemento ocupado en un índice basado en cero.
|
|
526
|
+
*
|
|
527
|
+
* Los índices fuera del rango `[0, occupied)` no se consideran un error y
|
|
528
|
+
* dan como resultado `undefined`.
|
|
529
|
+
*
|
|
530
|
+
* @param {number} handler - Identificador del bloque.
|
|
531
|
+
* @param {number} index - Índice basado en cero del elemento.
|
|
532
|
+
* @returns {number|undefined} Valor almacenado en el índice o `undefined` si
|
|
533
|
+
* el índice está fuera de la región ocupada.
|
|
534
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
535
|
+
*/
|
|
536
|
+
get(handler, index) {
|
|
537
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
538
|
+
if (index < 0 || index >= meta.occupied) return void 0;
|
|
539
|
+
return this.reader(meta.dataAddress + index * this.wordSize, IS_LITTLE_ENDIAN);
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Sustituye el valor almacenado en un índice ocupado.
|
|
543
|
+
*
|
|
544
|
+
* La operación no altera la ocupación del bloque. Los índices fuera del rango
|
|
545
|
+
* `[0, occupied)` se ignoran y dan como resultado `false`.
|
|
546
|
+
*
|
|
547
|
+
* @param {number} handler - Identificador del bloque.
|
|
548
|
+
* @param {number} index - Índice basado en cero del elemento.
|
|
549
|
+
* @param {number} value - Nuevo valor.
|
|
550
|
+
* @returns {boolean} `true` si el valor fue grabado; `false` si el índice
|
|
551
|
+
* está fuera de la región ocupada.
|
|
552
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
553
|
+
*/
|
|
554
|
+
set(handler, index, value) {
|
|
555
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
556
|
+
if (index < 0 || index >= meta.occupied) return false;
|
|
557
|
+
this.writer(meta.dataAddress + index * this.wordSize, value, IS_LITTLE_ENDIAN);
|
|
558
|
+
return true;
|
|
559
|
+
}
|
|
560
|
+
// ============= MISCELÁNEA ===============
|
|
561
|
+
/**
|
|
562
|
+
* Pone a cero la ocupación del bloque y llena toda su capacidad física con
|
|
563
|
+
* un mismo valor.
|
|
564
|
+
*
|
|
565
|
+
* El relleno abarca todas las ranuras disponibles, no solo los
|
|
566
|
+
* elementos ocupados actualmente. Tras la operación, el bloque se considera
|
|
567
|
+
* vacío independientemente del valor utilizado en el relleno.
|
|
568
|
+
*
|
|
569
|
+
* @param {number} handler - Identificador del bloque.
|
|
570
|
+
* @param {number} [value=0] - Valor utilizado para rellenar todas las ranuras.
|
|
571
|
+
* @returns {void}
|
|
572
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
573
|
+
*/
|
|
574
|
+
clear(handler, value = 0) {
|
|
575
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
576
|
+
const slots = meta.byteCapacity / this.wordSize;
|
|
577
|
+
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
578
|
+
this.auxiliary.fill(value, rawAddress, rawAddress + slots);
|
|
579
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Rellena un intervalo de ranuras del bloque con un valor.
|
|
583
|
+
*
|
|
584
|
+
* El intervalo utiliza índices basados en cero y sigue la convención
|
|
585
|
+
* `[start, end)`, por lo que `start` es inclusivo y `end` es exclusivo.
|
|
586
|
+
* Cuando no se proporciona `end`, el relleno se extiende hasta el final de la
|
|
587
|
+
* capacidad física del bloque.
|
|
588
|
+
*
|
|
589
|
+
* La ocupación del bloque pasa a ser `end`, incluso cuando el intervalo
|
|
590
|
+
* rellenado se extiende más allá de la ocupación anterior.
|
|
591
|
+
*
|
|
592
|
+
* @param {number} handler - Identificador del bloque.
|
|
593
|
+
* @param {number} value - Valor utilizado en el relleno.
|
|
594
|
+
* @param {number} [start=0] - Índice inicial, inclusivo.
|
|
595
|
+
* @param {number|null} [end=null] - Índice final, exclusivo. Cuando se
|
|
596
|
+
* omite o es `null`, utiliza la capacidad total del bloque.
|
|
597
|
+
* @returns {void}
|
|
598
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
599
|
+
* @throws {RangeError} Si `start` o `end` están fuera de los límites de
|
|
600
|
+
* capacidad, o si `start > end`.
|
|
601
|
+
*/
|
|
602
|
+
fill(handler, value, start = 0, end = null) {
|
|
603
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
604
|
+
const slots = meta.byteCapacity / this.wordSize;
|
|
605
|
+
const lastIndex = end ?? slots;
|
|
606
|
+
if (start > lastIndex) {
|
|
607
|
+
throw new RangeError(`start ${start} must be less or equal than end ${lastIndex}.`);
|
|
608
|
+
}
|
|
609
|
+
if (start < 0 || start > slots) {
|
|
610
|
+
throw new RangeError(`start ${start} out of range [0, ${slots}].`);
|
|
611
|
+
}
|
|
612
|
+
if (lastIndex < 0 || lastIndex > slots) {
|
|
613
|
+
throw new RangeError(`end ${lastIndex} out of range [0, ${slots}].`);
|
|
614
|
+
}
|
|
615
|
+
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
616
|
+
this.auxiliary.fill(value, rawAddress + start, rawAddress + lastIndex);
|
|
617
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, lastIndex, IS_LITTLE_ENDIAN);
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Rellena todas las ranuras físicas del bloque con un valor y marca toda la
|
|
621
|
+
* capacidad como ocupada.
|
|
622
|
+
*
|
|
623
|
+
* A diferencia de `clear()`, la operación da como resultado un bloque totalmente
|
|
624
|
+
* ocupado.
|
|
625
|
+
*
|
|
626
|
+
* @param {number} handler - Identificador del bloque.
|
|
627
|
+
* @param {number} value - Valor utilizado en el relleno.
|
|
628
|
+
* @returns {void}
|
|
629
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
630
|
+
*/
|
|
631
|
+
fillAll(handler, value) {
|
|
632
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
633
|
+
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
634
|
+
const capacityElements = meta.byteCapacity / this.wordSize;
|
|
635
|
+
this.auxiliary.fill(value, rawAddress, rawAddress + capacityElements);
|
|
636
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, capacityElements, IS_LITTLE_ENDIAN);
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Copia los elementos de un `Array` o `TypedArray` al inicio del bloque.
|
|
640
|
+
*
|
|
641
|
+
* La cantidad copiada está limitada por la capacidad del bloque. La ocupación se
|
|
642
|
+
* actualiza al mayor valor entre la ocupación anterior y la cantidad
|
|
643
|
+
* copiada efectivamente; por lo tanto, una llamada a `put()` no reduce la
|
|
644
|
+
* ocupación existente cuando recibe una secuencia menor.
|
|
645
|
+
*
|
|
646
|
+
* Para `Array`, solo se copian los primeros elementos que quepan.
|
|
647
|
+
* Para `TypedArray`, se utiliza un subarreglo del origen sin copia
|
|
648
|
+
* intermedia.
|
|
649
|
+
*
|
|
650
|
+
* @param {number} handler - Identificador del bloque.
|
|
651
|
+
* @param {Array|TypedArray} data - Secuencia de valores a copiar.
|
|
652
|
+
* @returns {void}
|
|
653
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
654
|
+
* @throws {TypeError} Si `data` no es ni un `Array` ni un `TypedArray`.
|
|
655
|
+
*/
|
|
656
|
+
put(handler, data) {
|
|
657
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
658
|
+
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
659
|
+
const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
|
|
660
|
+
meta.occupied = Math.max(length, meta.occupied);
|
|
661
|
+
if (Array.isArray(data)) {
|
|
662
|
+
this.auxiliary.set(data.slice(0, length), rawAddress);
|
|
663
|
+
} else if (isTypedArray(data)) {
|
|
664
|
+
this.auxiliary.set(data.subarray(0, length), rawAddress);
|
|
665
|
+
} else {
|
|
666
|
+
const actual = data?.constructor?.name ?? (data === null ? "null" : typeof data);
|
|
667
|
+
throw new TypeError(`data must be Array or TypedArray, but ${actual} was given.`);
|
|
668
|
+
}
|
|
669
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Devuelve una copia de los elementos ocupados actualmente por el bloque.
|
|
673
|
+
*
|
|
674
|
+
* El resultado es un `TypedArray` del mismo tipo configurado por
|
|
675
|
+
* `bucketSize`. La capacidad física no ocupada no se incluye en el resultado.
|
|
676
|
+
*
|
|
677
|
+
* La operación no expone directamente el almacenamiento interno: el método
|
|
678
|
+
* utiliza `TypedArray.prototype.slice()`, produciendo una nueva vista con
|
|
679
|
+
* almacenamiento independiente.
|
|
680
|
+
*
|
|
681
|
+
* @param {number} handler - Identificador del bloque.
|
|
682
|
+
* @returns {TypedArray} Copia de los elementos ocupados por el bloque. Cuando
|
|
683
|
+
* el bloque está vacío, devuelve un `TypedArray` vacío del tipo configurado.
|
|
684
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
685
|
+
*/
|
|
686
|
+
pick(handler) {
|
|
687
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
688
|
+
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
689
|
+
if (meta.occupied === 0) {
|
|
690
|
+
return this.auxiliary.slice(rawAddress, rawAddress);
|
|
691
|
+
}
|
|
692
|
+
return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
|
|
693
|
+
}
|
|
694
|
+
// ======== CAPACIDAD EN RANURAS ==========
|
|
695
|
+
/**
|
|
696
|
+
* Devuelve la capacidad física del bloque en bytes.
|
|
697
|
+
*
|
|
698
|
+
* La capacidad corresponde al espacio reservado para todas las ranuras del
|
|
699
|
+
* bloque, independientemente de cuántos elementos estén ocupados actualmente.
|
|
700
|
+
*
|
|
701
|
+
* @param {number} handler - Identificador del bloque.
|
|
702
|
+
* @returns {number} Capacidad física del bloque, en bytes.
|
|
703
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
704
|
+
*/
|
|
705
|
+
byteSize(handler) {
|
|
706
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
707
|
+
return meta.byteCapacity;
|
|
708
|
+
}
|
|
709
|
+
/**
|
|
710
|
+
* Devuelve la cantidad de elementos ocupados actualmente en el bloque.
|
|
711
|
+
*
|
|
712
|
+
* @param {number} handler - Identificador del bloque.
|
|
713
|
+
* @returns {number} Número de elementos ocupados.
|
|
714
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
715
|
+
*/
|
|
716
|
+
occupied(handler) {
|
|
717
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
718
|
+
return meta.occupied;
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* Devuelve la capacidad del bloque en número de elementos.
|
|
722
|
+
*
|
|
723
|
+
* El valor corresponde a la cantidad total de ranuras reservadas físicamente,
|
|
724
|
+
* y no a la cantidad ocupada actualmente.
|
|
725
|
+
*
|
|
726
|
+
* @param {number} handler - Identificador del bloque.
|
|
727
|
+
* @returns {number} Número total de ranuras disponibles en el bloque.
|
|
728
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
729
|
+
*/
|
|
730
|
+
length(handler) {
|
|
731
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
732
|
+
return 1 << meta.capacityExponent >>> 0;
|
|
733
|
+
}
|
|
734
|
+
// ========== Operaciones entre bloques=============
|
|
735
|
+
/**
|
|
736
|
+
* Copia elementos ocupados de un bloque a otro.
|
|
737
|
+
*
|
|
738
|
+
* La copia comienza en el primer elemento de `source` y la primera ranura de
|
|
739
|
+
* `destiny`. La cantidad copiada de forma efectiva está limitada por el número de
|
|
740
|
+
* elementos ocupados en el origen, la capacidad física del destino y el límite
|
|
741
|
+
* especificado en `slots`.
|
|
742
|
+
*
|
|
743
|
+
* La ocupación del destino se incrementa, cuando es necesario, para abarcar los
|
|
744
|
+
* elementos copiados. La capacidad del destino no se altera.
|
|
745
|
+
*
|
|
746
|
+
* La operación utiliza `Uint8Array.prototype.copyWithin()` sobre el `dataBus`,
|
|
747
|
+
* por lo tanto el valor devuelto es el propio `Uint8Array` que representa el bus de datos.
|
|
748
|
+
*
|
|
749
|
+
* @param {number} source - Identificador del bloque de origen.
|
|
750
|
+
* @param {number} destiny - Identificador del bloque de destino.
|
|
751
|
+
* @param {number} [slots=UNKNOWN] - Número máximo de elementos a copiar.
|
|
752
|
+
* `UNKNOWN` representa el valor centinela utilizado para no imponer un
|
|
753
|
+
* límite adicional.
|
|
754
|
+
* @returns {Uint8Array} El `dataBus` después de la operación.
|
|
755
|
+
* @throws {Error} Si `source` o `destiny` son inválidos o están corruptos.
|
|
756
|
+
*/
|
|
757
|
+
copy(source, destiny, slots = UNKNOWN) {
|
|
758
|
+
const metaA = {};
|
|
759
|
+
const metaB = {};
|
|
760
|
+
this.extractMetadata(source, metaA);
|
|
761
|
+
this.extractMetadata(destiny, metaB);
|
|
762
|
+
const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
|
|
763
|
+
const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
|
|
764
|
+
const newOccupied = Math.max(metaB.occupied, slotsToCopy);
|
|
765
|
+
this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
|
|
766
|
+
return this.dataBus.copyWithin(metaB.dataAddress, metaA.dataAddress, metaA.dataAddress + slotsToCopy * this.wordSize);
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Copia una región de elementos dentro del propio bloque.
|
|
770
|
+
*
|
|
771
|
+
* Los índices están basados en cero y siguen la semántica de
|
|
772
|
+
* `Array.prototype.copyWithin()`: `target` identifica la posición de destino,
|
|
773
|
+
* `start` la posición inicial del origen y `length` la cantidad máxima de
|
|
774
|
+
* elementos a copiar.
|
|
775
|
+
*
|
|
776
|
+
* Los índices negativos se interpretan a partir del final de la capacidad del
|
|
777
|
+
* bloque. Tras dicha normalización, los índices se limitan a la capacidad
|
|
778
|
+
* física. La cantidad copiada también se ve limitada por los elementos
|
|
779
|
+
* ocupados efectivamente y el espacio disponible a partir de `target`.
|
|
780
|
+
*
|
|
781
|
+
* La operación admite regiones superpuestas y puede incrementar la ocupación del
|
|
782
|
+
* bloque cuando el intervalo de destino supera la ocupación actual.
|
|
783
|
+
*
|
|
784
|
+
* @param {number} handler - Identificador del bloque.
|
|
785
|
+
* @param {number} target - Índice inicial del destino.
|
|
786
|
+
* @param {number} start - Índice inicial del origen.
|
|
787
|
+
* @param {number} length - Número máximo de elementos a copiar.
|
|
788
|
+
* @returns {Uint8Array} El `dataBus` después de la operación.
|
|
789
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
790
|
+
*/
|
|
791
|
+
copyWithin(handler, target, start, length) {
|
|
792
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
793
|
+
const slots = Math.floor(meta.byteCapacity / this.wordSize);
|
|
794
|
+
target = Math.trunc(target);
|
|
795
|
+
start = Math.trunc(start);
|
|
796
|
+
length = Math.trunc(length);
|
|
797
|
+
if (target < 0) target += slots;
|
|
798
|
+
if (start < 0) start += slots;
|
|
799
|
+
target = Math.max(0, Math.min(target, slots));
|
|
800
|
+
start = Math.max(0, Math.min(start, slots));
|
|
801
|
+
const maxRead = Math.max(0, meta.occupied - start);
|
|
802
|
+
const maxWrite = slots - target;
|
|
803
|
+
length = Math.max(0, Math.min(length, maxRead, maxWrite));
|
|
804
|
+
if (length === 0) return this.dataBus;
|
|
805
|
+
const targetAddress = meta.dataAddress + target * this.wordSize;
|
|
806
|
+
const sourceAddress = meta.dataAddress + start * this.wordSize;
|
|
807
|
+
const newOccupied = Math.max(meta.occupied, target + length);
|
|
808
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
|
|
809
|
+
return this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + length * this.wordSize);
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Añade los elementos ocupados de `source` al final de `target`.
|
|
813
|
+
*
|
|
814
|
+
* La cantidad copiada está limitada por el número de elementos ocupados en el
|
|
815
|
+
* origen y el espacio libre restante en la capacidad del destino.
|
|
816
|
+
*
|
|
817
|
+
* La operación admite que `target` y `source` hagan referencia al mismo bloque.
|
|
818
|
+
* En ese caso, la copia se realiza sobre la propia región del bloque y
|
|
819
|
+
* preserva la semántica de superposición de `copyWithin()`.
|
|
820
|
+
*
|
|
821
|
+
* @param {number} target - Identificador del bloque que recibirá los elementos.
|
|
822
|
+
* @param {number} source - Identificador del bloque cuyos elementos serán
|
|
823
|
+
* añadidos.
|
|
824
|
+
* @returns {number} Número de elementos añadidos efectivamente.
|
|
825
|
+
* @throws {Error} Si `target` o `source` son inválidos o están corruptos.
|
|
826
|
+
*/
|
|
827
|
+
append(target, source) {
|
|
828
|
+
const metaTarget = {};
|
|
829
|
+
const metaSource = {};
|
|
830
|
+
this.extractMetadata(target, metaTarget);
|
|
831
|
+
this.extractMetadata(source, metaSource);
|
|
832
|
+
const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
|
|
833
|
+
const count = Math.min(available, metaSource.occupied);
|
|
834
|
+
if (count === 0) return 0;
|
|
835
|
+
const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
|
|
836
|
+
const sourceAddress = metaSource.dataAddress;
|
|
837
|
+
if (target === source) {
|
|
838
|
+
this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
|
|
839
|
+
} else {
|
|
840
|
+
this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
|
|
841
|
+
}
|
|
842
|
+
this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
|
|
843
|
+
return count;
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* Crea una copia independiente de un bloque.
|
|
847
|
+
*
|
|
848
|
+
* El nuevo bloque posee la misma capacidad física y la misma ocupación del
|
|
849
|
+
* bloque original. Se copian todos los bytes de la región reservada, incluyendo
|
|
850
|
+
* las posiciones no ocupadas actualmente.
|
|
851
|
+
*
|
|
852
|
+
* El nuevo bloque recibe un nuevo identificador y permanece sujeto a las reglas
|
|
853
|
+
* normales de asignación y reciclaje.
|
|
854
|
+
*
|
|
855
|
+
* @param {number} handler - Identificador del bloque a clonar.
|
|
856
|
+
* @returns {number} Identificador del nuevo bloque.
|
|
857
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
858
|
+
*/
|
|
859
|
+
clone(handler) {
|
|
860
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
861
|
+
const cloned = this.alloc(meta.byteCapacity / this.wordSize);
|
|
862
|
+
const cloneMeta = {};
|
|
863
|
+
this.extractMetadata(cloned, cloneMeta);
|
|
864
|
+
this.dataBus.copyWithin(cloneMeta.dataAddress, meta.dataAddress, meta.dataAddress + meta.byteCapacity);
|
|
865
|
+
this.controlAdapter.setUint32(cloneMeta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
|
|
866
|
+
return cloned;
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* Intercambia las regiones de datos asociadas a dos bloques.
|
|
870
|
+
*
|
|
871
|
+
* La operación intercambia entre las cabeceras las direcciones de las regiones, sus
|
|
872
|
+
* capacidades y sus ocupaciones. Los identificadores permanecen inalterados:
|
|
873
|
+
* después de la operación, cada identificador continúa identificando su propia
|
|
874
|
+
* cabecera, pero dicha cabecera pasa a describir la región que pertenecía
|
|
875
|
+
* anteriormente al otro bloque.
|
|
876
|
+
*
|
|
877
|
+
* No se copia ningún dato en el `dataBus`; solo se modifican los metadatos de ambas
|
|
878
|
+
* cabeceras.
|
|
879
|
+
*
|
|
880
|
+
* @param {number} source - Identificador del primer bloque.
|
|
881
|
+
* @param {number} target - Identificador del segundo bloque.
|
|
882
|
+
* @returns {void}
|
|
883
|
+
* @throws {Error} Si `source` o `target` son inválidos o están corruptos.
|
|
884
|
+
*/
|
|
885
|
+
swap(source, target) {
|
|
886
|
+
const metaA = {};
|
|
887
|
+
const metaB = {};
|
|
888
|
+
this.extractMetadata(source, metaA);
|
|
889
|
+
this.extractMetadata(target, metaB);
|
|
890
|
+
this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
|
|
891
|
+
this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
|
|
892
|
+
this.controlAdapter.setUint8(metaA.headerAddress + CAPACITY_OFFSET, metaB.capacityExponent);
|
|
893
|
+
this.controlAdapter.setUint8(metaB.headerAddress + CAPACITY_OFFSET, metaA.capacityExponent);
|
|
894
|
+
this.controlAdapter.setUint32(metaA.headerAddress + OCCUPIED_OFFSET, metaB.occupied, IS_LITTLE_ENDIAN);
|
|
895
|
+
this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, metaA.occupied, IS_LITTLE_ENDIAN);
|
|
896
|
+
}
|
|
897
|
+
// ============= SERIALIZACIÓN ==============
|
|
898
|
+
/**
|
|
899
|
+
* Serializa el contenido y los metadatos de un bloque de memoria.
|
|
900
|
+
*
|
|
901
|
+
* El método extrae los datos ocupados del bloque mediante `pick()`,
|
|
902
|
+
* los agrupa junto con la información de capacidad y tipo de palabra
|
|
903
|
+
* en un sobre de datos y los codifica utilizando el formato CBOR.
|
|
904
|
+
*
|
|
905
|
+
* @param {number} handler - Identificador del bloque a serializar.
|
|
906
|
+
* @returns {Uint8Array} Un búster que contiene los datos serializados del bloque.
|
|
907
|
+
* @throws {Error} Si el identificador es inválido o está corrupto.
|
|
908
|
+
*/
|
|
909
|
+
dump(handler) {
|
|
910
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
911
|
+
const capacity = meta.capacityExponent;
|
|
912
|
+
const capacityElements = 2 ** capacity;
|
|
913
|
+
if (!Number.isInteger(capacity) || capacity < 1 || capacity > 31 || meta.occupied > capacityElements) {
|
|
914
|
+
throw new Error("Cannot serialize a block with invalid metadata");
|
|
915
|
+
}
|
|
916
|
+
const payload = this.pick(handler);
|
|
917
|
+
if (payload.length !== meta.occupied || payload.constructor !== this.bucketArray) {
|
|
918
|
+
throw new Error("Cannot serialize a block with an invalid payload");
|
|
919
|
+
}
|
|
920
|
+
return (0, import_cbor_x.encode)({
|
|
921
|
+
v: 1,
|
|
922
|
+
wordType: this.wordType,
|
|
923
|
+
capacity,
|
|
924
|
+
occupied: meta.occupied,
|
|
925
|
+
le: IS_LITTLE_ENDIAN,
|
|
926
|
+
payload
|
|
927
|
+
});
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Restaura un bloque de memoria a partir de datos serializados.
|
|
931
|
+
*
|
|
932
|
+
* Decodifica el sobre CBOR, valida si el tipo de palabra del dato
|
|
933
|
+
* serializado es compatible con la instancia actual del asignador y asigna
|
|
934
|
+
* un nuevo bloque con la capacidad necesaria para alojar el contenido.
|
|
935
|
+
* A continuación, se restauran los datos y la ocupación original en el nuevo bloque.
|
|
936
|
+
*
|
|
937
|
+
* @param {Uint8Array|ArrayBuffer} serialized - Búster que contiene los datos serializados.
|
|
938
|
+
* @returns {number} Identificador del nuevo bloque recreado.
|
|
939
|
+
* @throws {Error} Si el tipo de palabra del dato decodificado difiere del configurado en el asignador.
|
|
940
|
+
*/
|
|
941
|
+
load(serialized) {
|
|
942
|
+
if (!(serialized instanceof ArrayBuffer) && !(serialized instanceof Uint8Array)) {
|
|
943
|
+
throw new TypeError("serialized must be an ArrayBuffer or Uint8Array");
|
|
944
|
+
}
|
|
945
|
+
const envelope = (0, import_cbor_x.decode)(serialized);
|
|
946
|
+
if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)) {
|
|
947
|
+
throw new TypeError("Invalid serialized block envelope");
|
|
948
|
+
}
|
|
949
|
+
if (envelope.v !== 1) {
|
|
950
|
+
throw new Error(`Unsupported serialized block version: ${envelope.v}`);
|
|
951
|
+
}
|
|
952
|
+
if (envelope.wordType !== this.wordType) {
|
|
953
|
+
throw new Error(`Can't load data, ${this.wordType} expected but ${envelope.wordType} found.`);
|
|
954
|
+
}
|
|
955
|
+
if (!Number.isInteger(envelope.capacity) || envelope.capacity < 1 || envelope.capacity > 31) {
|
|
956
|
+
throw new RangeError("Invalid serialized block capacity");
|
|
957
|
+
}
|
|
958
|
+
const capacityElements = 2 ** envelope.capacity;
|
|
959
|
+
if (!Number.isSafeInteger(envelope.occupied) || envelope.occupied < 0 || envelope.occupied > capacityElements) {
|
|
960
|
+
throw new RangeError("Invalid serialized block occupancy");
|
|
961
|
+
}
|
|
962
|
+
if (typeof envelope.le !== "boolean") {
|
|
963
|
+
throw new TypeError("Invalid serialized endianness flag");
|
|
964
|
+
}
|
|
965
|
+
const payload = envelope.payload;
|
|
966
|
+
if (!isTypedArray(payload) || payload.constructor !== this.bucketArray || payload.length !== envelope.occupied) {
|
|
967
|
+
throw new TypeError(`Invalid payload: expected ${this.bucketType}Array with ${envelope.occupied} elements`);
|
|
968
|
+
}
|
|
969
|
+
if (payload.BYTES_PER_ELEMENT !== this.wordSize || payload.byteLength !== envelope.occupied * this.wordSize) {
|
|
970
|
+
throw new TypeError("Serialized payload has an invalid element size");
|
|
971
|
+
}
|
|
972
|
+
const handler = this.alloc(capacityElements);
|
|
973
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
974
|
+
this.put(handler, payload);
|
|
975
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, envelope.occupied, IS_LITTLE_ENDIAN);
|
|
976
|
+
return handler;
|
|
977
|
+
}
|
|
978
|
+
// ============= UTILIDADES ==============
|
|
979
|
+
/**
|
|
980
|
+
* [USO INTERNO]
|
|
981
|
+
* Decodifica los metadatos asociados a un identificador.
|
|
982
|
+
*
|
|
983
|
+
* El identificador se divide en generación y dirección de la cabecera. El cookie almacenado
|
|
984
|
+
* en la cabecera se recalcula para validar la combinación; solo tras
|
|
985
|
+
* dicha validación se leen los metadatos.
|
|
986
|
+
*
|
|
987
|
+
* Los campos decodificados se escriben en el objeto `out`, el cual es devuelto
|
|
988
|
+
* por la propia función. El objeto se puede reutilizar entre llamadas para
|
|
989
|
+
* evitar nuevas asignaciones.
|
|
990
|
+
*
|
|
991
|
+
* @param {number} handler - Identificador a decodificar y validar.
|
|
992
|
+
* @param {Metadata} out - Objeto que recibirá los metadatos decodificados.
|
|
993
|
+
* @returns {Metadata} La misma referencia proporcionada en `out`.
|
|
994
|
+
* @throws {Error} Si el cookie de la cabecera no coincide con el identificador o
|
|
995
|
+
* si el identificador no identifica una cabecera válida.
|
|
996
|
+
* @private
|
|
997
|
+
*/
|
|
998
|
+
extractMetadata(handler, out) {
|
|
999
|
+
out.generation = handler / ROTATE_32BITS & CLAMP_11BITS;
|
|
1000
|
+
out.headerAddress = handler >>> 0;
|
|
1001
|
+
const cookie = this.controlAdapter.getUint8(out.headerAddress + COOKIE_OFFSET);
|
|
1002
|
+
if (cookie !== this.bakeCookie(out.headerAddress, out.generation)) {
|
|
1003
|
+
throw new Error("Invalid or corrupted handle");
|
|
1004
|
+
}
|
|
1005
|
+
out.dataAddress = this.controlAdapter.getUint32(out.headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
1006
|
+
out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
|
|
1007
|
+
out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
|
|
1008
|
+
out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
|
|
1009
|
+
return out;
|
|
1010
|
+
}
|
|
1011
|
+
/**
|
|
1012
|
+
* [USO INTERNO]
|
|
1013
|
+
* Calcula el cookie de validación de una cabecera.
|
|
1014
|
+
*
|
|
1015
|
+
* El cookie se deriva de la dirección de la cabecera y de los 11 bits de la generación mediante
|
|
1016
|
+
* un hash rápido.
|
|
1017
|
+
* El resultado se reduce a 8 bits.
|
|
1018
|
+
*
|
|
1019
|
+
* El valor cero se reserva como indicador de cabecera inválida; por este motivo,
|
|
1020
|
+
* cuando el cálculo produce cero, el método devuelve `1`.
|
|
1021
|
+
*
|
|
1022
|
+
* El cookie no constituye un mecanismo criptográfico. Su finalidad es
|
|
1023
|
+
* detectar identificadores inválidos, obsoletos o corruptos dentro del modelo de
|
|
1024
|
+
* gestión de memoria del asignador.
|
|
1025
|
+
*
|
|
1026
|
+
* @param {number} addr - Dirección de la cabecera.
|
|
1027
|
+
* @param {number} gen - Generación asociada al identificador. Solo se consideran los 11 bits
|
|
1028
|
+
* menos significativos.
|
|
1029
|
+
* @returns {number} Cookie de 8 bits en el rango [1, 255].
|
|
1030
|
+
* @private
|
|
1031
|
+
*/
|
|
1032
|
+
bakeCookie(addr, gen) {
|
|
1033
|
+
return (addr ^ gen & 2047 * 2654435761) & 255 || 1;
|
|
1034
|
+
}
|
|
1035
|
+
/**
|
|
1036
|
+
* Devuelve la cantidad de regiones almacenadas actualmente en la lista de
|
|
1037
|
+
* reciclaje.
|
|
1038
|
+
*
|
|
1039
|
+
* Cada región corresponde a un bloque liberado que no pudo devolverse
|
|
1040
|
+
* directamente a la parte superior del `dataBus` y, por tanto, permanece disponible para
|
|
1041
|
+
* su reutilización en una asignación futura de capacidad idéntica.
|
|
1042
|
+
*
|
|
1043
|
+
* @returns {number} Número de regiones libres mantenidas en `recycle`.
|
|
1044
|
+
*/
|
|
1045
|
+
recycleCount() {
|
|
1046
|
+
let count = 0;
|
|
1047
|
+
for (const [, page] of this.recycle) {
|
|
1048
|
+
count += page[0];
|
|
1049
|
+
}
|
|
1050
|
+
return count;
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Devuelve el total de bytes pertenecientes a las regiones almacenadas
|
|
1054
|
+
* actualmente en la lista de reciclaje.
|
|
1055
|
+
*
|
|
1056
|
+
* El valor se calcula sumando la capacidad de cada región libre multiplicada
|
|
1057
|
+
* por la cantidad de regiones registradas para dicha capacidad.
|
|
1058
|
+
*
|
|
1059
|
+
* @returns {number} Número de bytes ocupados por regiones reciclables.
|
|
1060
|
+
*/
|
|
1061
|
+
get recycleBytes() {
|
|
1062
|
+
let total = 0;
|
|
1063
|
+
for (const [capacity, page] of this.recycle) {
|
|
1064
|
+
total += page[0] * capacity;
|
|
1065
|
+
}
|
|
1066
|
+
return total;
|
|
1067
|
+
}
|
|
1068
|
+
/**
|
|
1069
|
+
* Devuelve la cantidad de bytes asignados que no pertenecen a las regiones
|
|
1070
|
+
* reciclables actualmente.
|
|
1071
|
+
*
|
|
1072
|
+
* El valor se obtiene restando del avance total del `dataPointer` los bytes
|
|
1073
|
+
* pertenecientes a las regiones libres mantenidas en `recycle`.
|
|
1074
|
+
*
|
|
1075
|
+
* @returns {number} Número de bytes asociados a regiones no reciclables
|
|
1076
|
+
* dentro del área ya utilizada por el `dataBus`.
|
|
1077
|
+
*/
|
|
1078
|
+
get allocatedBytes() {
|
|
1079
|
+
return this.dataPointer - this.recycleBytes;
|
|
1080
|
+
}
|
|
1081
|
+
/**
|
|
1082
|
+
* Devuelve la cantidad de bytes que aún no se han utilizado en la parte superior del `dataBus`.
|
|
1083
|
+
*
|
|
1084
|
+
* Este espacio corresponde a la región comprendida entre `dataPointer` y el final de la
|
|
1085
|
+
* capacidad reservada actualmente para el búster.
|
|
1086
|
+
*
|
|
1087
|
+
* @returns {number} Número de bytes disponibles después de `dataPointer`.
|
|
1088
|
+
*/
|
|
1089
|
+
get unallocatedBytes() {
|
|
1090
|
+
return this.size - this.dataPointer;
|
|
1091
|
+
}
|
|
1092
|
+
/**
|
|
1093
|
+
* Devuelve la razón entre la memoria reciclable y el área de montón utilizada.
|
|
1094
|
+
*
|
|
1095
|
+
* La métrica considera como fragmentación las regiones libres mantenidas en
|
|
1096
|
+
* `recycle` y utiliza `dataPointer` como denominador. Cuando no se ha utilizado
|
|
1097
|
+
* ningún byte por el montón, el resultado es cero.
|
|
1098
|
+
*
|
|
1099
|
+
* El valor no representa la fracción de toda la capacidad del `dataBus`, sino
|
|
1100
|
+
* específicamente la proporción de bytes reciclables dentro del área ya
|
|
1101
|
+
* recorrida por el puntero de tipo bump.
|
|
1102
|
+
*
|
|
1103
|
+
* @returns {number} Razón de fragmentación en el rango [0, 1] bajo condiciones
|
|
1104
|
+
* normales de operación.
|
|
1105
|
+
*/
|
|
1106
|
+
get fragmentationRatio() {
|
|
1107
|
+
if (this.dataPointer === 0) return 0;
|
|
1108
|
+
return this.recycleBytes / this.dataPointer;
|
|
1109
|
+
}
|
|
1110
|
+
};
|
|
1111
|
+
module.exports = { Balloc };
|