balloc 1.0.1 → 1.3.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.
- package/CHANGELOG.md +29 -0
- package/README.MD +22 -14
- package/README.ar.md +7 -3
- package/README.en.md +7 -3
- package/README.es.md +7 -3
- package/README.jp.md +7 -3
- package/README.pt.md +6 -6
- package/README.zh.md +7 -3
- package/docs/API /342/200/224 balloc.ar.md" +113 -25
- package/docs/API /342/200/224 balloc.en.md" +153 -15
- package/docs/API /342/200/224 balloc.es.md" +100 -11
- package/docs/API /342/200/224 balloc.jp.md" +137 -16
- package/docs/API /342/200/224 balloc.pt.md" +150 -25
- package/docs/API /342/200/224 balloc.zh.md" +108 -8
- package/package.json +22 -8
- package/src/ar/balloc.cjs +502 -306
- package/src/ar/balloc.js +1 -1
- package/src/ar/balloc.mjs +617 -392
- package/src/en/balloc.cjs +428 -218
- package/src/en/balloc.js +1 -1
- package/src/en/balloc.mjs +542 -303
- package/src/es/balloc.cjs +409 -230
- package/src/es/balloc.js +1 -1
- package/src/es/balloc.mjs +540 -333
- package/src/jp/balloc.cjs +437 -274
- package/src/jp/balloc.js +1 -1
- package/src/jp/balloc.mjs +551 -359
- package/src/pt/balloc.cjs +238 -58
- package/src/pt/balloc.js +1 -1
- package/src/pt/balloc.mjs +353 -144
- package/src/zh/balloc.cjs +358 -194
- package/src/zh/balloc.js +1 -1
- package/src/zh/balloc.mjs +475 -283
- package/types/ar/balloc.d.mts +388 -277
- package/types/en/balloc.d.mts +329 -204
- package/types/es/balloc.d.mts +302 -208
- package/types/jp/balloc.d.mts +330 -252
- package/types/pt/balloc.d.mts +138 -43
- package/types/zh/balloc.d.mts +262 -183
- package/img/pix.png +0 -0
package/src/pt/balloc.mjs
CHANGED
|
@@ -24,14 +24,14 @@ const UNKNOWN = 0xFFFFFFFF >>> 0;
|
|
|
24
24
|
*
|
|
25
25
|
*/
|
|
26
26
|
const BUCKET_MAPPING = Object.freeze({
|
|
27
|
-
"8u":
|
|
28
|
-
"16u": { type: "Uint16",
|
|
29
|
-
"32u": { type: "Uint32",
|
|
30
|
-
"64u": { type: "BigUint64",
|
|
31
|
-
"8i":
|
|
32
|
-
"16i": { type: "Int16",
|
|
33
|
-
"32i": { type: "Int32",
|
|
34
|
-
"64i": { type: "BigInt64",
|
|
27
|
+
"8u": { type: "Uint8", bits: 8 },
|
|
28
|
+
"16u": { type: "Uint16", bits: 16 },
|
|
29
|
+
"32u": { type: "Uint32", bits: 32 },
|
|
30
|
+
"64u": { type: "BigUint64", bits: 64 },
|
|
31
|
+
"8i": { type: "Int8", bits: 8 },
|
|
32
|
+
"16i": { type: "Int16", bits: 16 },
|
|
33
|
+
"32i": { type: "Int32", bits: 32 },
|
|
34
|
+
"64i": { type: "BigInt64", bits: 64 },
|
|
35
35
|
"16f": { type: "Float16", bits: 16 },
|
|
36
36
|
"32f": { type: "Float32", bits: 32 },
|
|
37
37
|
"64f": { type: "Float64", bits: 64 }
|
|
@@ -57,17 +57,24 @@ const IS_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
|
|
|
57
57
|
|
|
58
58
|
/**
|
|
59
59
|
* Formato dos metadados.
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
60
|
+
*
|
|
61
|
+
* [32bits address][32bits occupied][8bits capacity][8bits cookie][8bits flags][40bits reserved]
|
|
62
|
+
*
|
|
63
|
+
*
|
|
64
|
+
* Total: 16 bytes
|
|
64
65
|
*/
|
|
65
66
|
const HEADER_SIZE = 16 >>> 0;
|
|
66
|
-
|
|
67
|
-
const ADDRESS_OFFSET = 0 >>> 0;
|
|
67
|
+
const ADDRESS_OFFSET = 0 >>> 0;
|
|
68
68
|
const OCCUPIED_OFFSET = 4 >>> 0;
|
|
69
69
|
const CAPACITY_OFFSET = 8 >>> 0;
|
|
70
|
-
const COOKIE_OFFSET
|
|
70
|
+
const COOKIE_OFFSET = 9 >>> 0;
|
|
71
|
+
const FLAGS_OFFSET = 10 >>> 0;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Flags:
|
|
75
|
+
* bit 0: VIEW_LOCK
|
|
76
|
+
*/
|
|
77
|
+
const VIEW_LOCK = 1 >>> 0;
|
|
71
78
|
|
|
72
79
|
|
|
73
80
|
const ROTATE_32BITS = 4294967296;
|
|
@@ -124,25 +131,25 @@ export default class Balloc {
|
|
|
124
131
|
* @throws {RangeError} Se `bucketSize` não for um identificador de bucket válido.
|
|
125
132
|
* @throws {RangeError} Se `metadataSize` estiver fora do intervalo permitido.
|
|
126
133
|
*/
|
|
127
|
-
|
|
134
|
+
constructor(size = 65535, bucketSize = "32u", metadataSize = 1024) {
|
|
128
135
|
|
|
129
136
|
if (!Number.isSafeInteger(size) || size < 2 || size > 0x80000000) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
|
|
130
137
|
|
|
131
|
-
|
|
138
|
+
|
|
132
139
|
if (!BUCKET_MAPPING[bucketSize]) {
|
|
133
140
|
throw new RangeError(`bucketSize must be in ([ 8 || 16 || 32 || 64][ u || i ]) || ([ 16 || 32 || 64][ f ]) but I found ${bucketSize}`);
|
|
134
141
|
}
|
|
135
142
|
|
|
136
143
|
if (!Number.isSafeInteger(metadataSize) || metadataSize < HEADER_SIZE || metadataSize > 0x80000000) throw new RangeError(`Parameter metadataSize must be in range [HEADER_SIZE, 0x80000000] but metadataSize is ${metadataSize}`);
|
|
137
|
-
|
|
144
|
+
|
|
138
145
|
this.wordType = bucketSize;
|
|
139
146
|
this.bucketType = BUCKET_MAPPING[bucketSize].type;
|
|
140
147
|
this.bucketSize = BUCKET_MAPPING[bucketSize].bits >>> 0;
|
|
141
148
|
this.bucketArray = globalThis[`${this.bucketType}Array`];
|
|
142
149
|
this.wordSize = this.bucketSize >>> 3;
|
|
143
150
|
this.wordShift = this.bucketSize >>> 4;
|
|
144
|
-
this.size = Math.max(1 << (32 - Math.clz32(size)) >>> 0, this.wordSize);
|
|
145
|
-
this.headerSize = 1 << (32 - Math.clz32(metadataSize)) >>> 0;
|
|
151
|
+
this.size = Math.max(1 << (32 - Math.clz32(size - 1)) >>> 0, this.wordSize);
|
|
152
|
+
this.headerSize = 1 << (32 - Math.clz32(metadataSize - 1)) >>> 0;
|
|
146
153
|
this.dataPointer = 0 >>> 0;
|
|
147
154
|
this.controlPointer = 0 >>> 0;
|
|
148
155
|
this.echoPointer = 0 >>> 0;
|
|
@@ -165,7 +172,7 @@ export default class Balloc {
|
|
|
165
172
|
byteCapacity: 0 >>> 0,
|
|
166
173
|
occupied: 0 >>> 0,
|
|
167
174
|
};
|
|
168
|
-
|
|
175
|
+
|
|
169
176
|
}
|
|
170
177
|
|
|
171
178
|
// ========== ALOCAÇÃO ==========
|
|
@@ -192,11 +199,12 @@ export default class Balloc {
|
|
|
192
199
|
* comportar. Deve ser um inteiro seguro no intervalo [2, 0x80000000].
|
|
193
200
|
* @returns {number} Handler que identifica o bloco alocado.
|
|
194
201
|
* @throws {RangeError} Se `size` estiver fora do intervalo permitido.
|
|
202
|
+
* @throws {Error} Se for necessário expandir o `dataBus` enquanto houver
|
|
203
|
+
* algum bloco emprestado por withView().
|
|
195
204
|
*/
|
|
196
205
|
alloc(size = 16) {
|
|
197
206
|
if (!Number.isSafeInteger(size) || size < 2 || size > 0x80000000) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
|
|
198
207
|
|
|
199
|
-
|
|
200
208
|
const capacity = (32 - Math.clz32(size - 1));
|
|
201
209
|
const blockSize = (1 << capacity >>> 0) * this.wordSize;
|
|
202
210
|
|
|
@@ -209,21 +217,21 @@ export default class Balloc {
|
|
|
209
217
|
}
|
|
210
218
|
|
|
211
219
|
let headerAddress = 0 >>> 0;
|
|
212
|
-
|
|
213
220
|
if (this.echoPointer > this.controlPointer) {
|
|
214
221
|
this.echoPointer -= 4;
|
|
215
|
-
headerAddress = this.controlAdapter.getUint32(this.echoPointer, IS_LITTLE_ENDIAN);
|
|
222
|
+
headerAddress = this.controlAdapter.getUint32(this.echoPointer, IS_LITTLE_ENDIAN);
|
|
216
223
|
} else {
|
|
217
224
|
if (this.controlPointer + HEADER_SIZE > this.controlAdapter.byteLength) this.headerGrow();
|
|
218
225
|
headerAddress = this.controlPointer;
|
|
219
|
-
this.controlPointer+= HEADER_SIZE;
|
|
220
|
-
this.echoPointer+= HEADER_SIZE;
|
|
226
|
+
this.controlPointer += HEADER_SIZE;
|
|
227
|
+
this.echoPointer += HEADER_SIZE;
|
|
221
228
|
}
|
|
222
229
|
|
|
223
230
|
this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, dataAddress, IS_LITTLE_ENDIAN);
|
|
224
231
|
this.controlAdapter.setUint32(headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
|
|
225
232
|
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, capacity);
|
|
226
233
|
this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, this.bakeCookie(headerAddress, ++this.generation));
|
|
234
|
+
this.controlBus[headerAddress + FLAGS_OFFSET] = 0;
|
|
227
235
|
|
|
228
236
|
return (this.generation & CLAMP_11BITS) * ROTATE_32BITS + headerAddress;
|
|
229
237
|
}
|
|
@@ -245,25 +253,28 @@ export default class Balloc {
|
|
|
245
253
|
*
|
|
246
254
|
* @param {number} handler - Handler do bloco a ser expandido.
|
|
247
255
|
* @returns {void}
|
|
248
|
-
* @throws {Error} Se o handler for inválido ou
|
|
256
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco
|
|
257
|
+
* estiver emprestado por withView(). Também ocorre se a expansão exigir
|
|
258
|
+
* remapeamento do dataBus enquanto houver outro bloco emprestado.
|
|
249
259
|
* @throws {AggregateError} Se a capacidade já tiver atingido o limite
|
|
250
260
|
* máximo suportado.
|
|
251
261
|
*/
|
|
252
262
|
realloc(handler) {
|
|
253
|
-
const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
|
|
254
|
-
let headerAddress = handler >>> 0;
|
|
255
263
|
|
|
264
|
+
const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
|
|
265
|
+
const headerAddress = handler >>> 0;
|
|
256
266
|
const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
257
267
|
const occupied = this.controlAdapter.getUint32(headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
|
|
258
268
|
const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
|
|
259
269
|
const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
|
|
260
270
|
|
|
261
|
-
|
|
262
271
|
if (cookie !== this.bakeCookie(headerAddress, generation)) {
|
|
263
272
|
throw new Error("Invalid or corrupted handle");
|
|
264
273
|
}
|
|
265
274
|
|
|
266
|
-
|
|
275
|
+
this.assertNotBorrowed(headerAddress);
|
|
276
|
+
|
|
277
|
+
if (capacity >= 31) throw new AggregateError([new Error("Can´t reallocate handler."), new RangeError("Capacity has reached its limit.")], "Internal Error.");
|
|
267
278
|
|
|
268
279
|
const newCapacity = capacity + 1;
|
|
269
280
|
const newBlockSize = (1 << newCapacity >>> 0) * this.wordSize;
|
|
@@ -272,14 +283,11 @@ export default class Balloc {
|
|
|
272
283
|
if (dataAddress + oldBlockSize === this.dataPointer) {
|
|
273
284
|
while (dataAddress + newBlockSize > this.size) this.grow();
|
|
274
285
|
|
|
275
|
-
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity
|
|
286
|
+
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
|
|
276
287
|
this.dataPointer = dataAddress + newBlockSize;
|
|
277
|
-
|
|
278
288
|
return;
|
|
279
289
|
}
|
|
280
290
|
|
|
281
|
-
this.recyclePush(oldBlockSize, dataAddress);
|
|
282
|
-
|
|
283
291
|
let newAddress = this.recyclePop(newBlockSize);
|
|
284
292
|
|
|
285
293
|
if (newAddress === UNKNOWN) {
|
|
@@ -289,57 +297,81 @@ export default class Balloc {
|
|
|
289
297
|
this.dataPointer += newBlockSize;
|
|
290
298
|
}
|
|
291
299
|
|
|
292
|
-
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
|
|
293
300
|
this.dataBus.copyWithin(newAddress, dataAddress, dataAddress + occupied * this.wordSize);
|
|
294
301
|
|
|
295
302
|
this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, newAddress, IS_LITTLE_ENDIAN);
|
|
303
|
+
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
|
|
304
|
+
|
|
305
|
+
this.recyclePush(oldBlockSize, dataAddress);
|
|
296
306
|
}
|
|
297
307
|
|
|
298
308
|
/**
|
|
299
|
-
*
|
|
309
|
+
* Reduz um bloco à menor capacidade em potência de dois capaz de comportar
|
|
310
|
+
* seus elementos ocupados, preservando seu endereço e handler.
|
|
300
311
|
*
|
|
301
|
-
*
|
|
302
|
-
*
|
|
303
|
-
*
|
|
304
|
-
* exatamente no topo do `dataBus`; nesse caso, o `dataPointer` é simplesmente
|
|
305
|
-
* retrocedido, eliminando a região sem criar uma entrada na lista de
|
|
306
|
-
* reciclagem.
|
|
312
|
+
* Se o bloco estiver no topo do dataBus, dataPointer será recuado.
|
|
313
|
+
* Caso contrário, a cauda liberada será dividida em regiões de potências
|
|
314
|
+
* de dois, e cada região será devolvida à lista de reciclagem.
|
|
307
315
|
*
|
|
308
|
-
* @param {number} handler - Handler do bloco a ser
|
|
316
|
+
* @param {number} handler - Handler do bloco a ser reduzido.
|
|
309
317
|
* @returns {void}
|
|
310
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
318
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou estiver
|
|
319
|
+
* emprestado por withView().
|
|
311
320
|
*/
|
|
321
|
+
shrink(handler) {
|
|
322
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
323
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
324
|
+
|
|
325
|
+
const newCapacity = Math.max(1, 32 - Math.clz32(Math.max(2, meta.occupied) - 1));
|
|
326
|
+
if (newCapacity >= meta.capacityExponent) return;
|
|
327
|
+
|
|
328
|
+
const oldBlockSize = meta.byteCapacity;
|
|
329
|
+
const newBlockSize = (2 ** newCapacity) * this.wordSize;
|
|
330
|
+
const oldEnd = meta.dataAddress + oldBlockSize;
|
|
331
|
+
|
|
332
|
+
this.controlAdapter.setUint8(meta.headerAddress + CAPACITY_OFFSET, newCapacity);
|
|
333
|
+
|
|
334
|
+
if (oldEnd === this.dataPointer) {
|
|
335
|
+
this.dataPointer = meta.dataAddress + newBlockSize;
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
let address = meta.dataAddress + newBlockSize;
|
|
340
|
+
for (let exponent = newCapacity; exponent < meta.capacityExponent; exponent++) {
|
|
341
|
+
const segmentSize = (2 ** exponent) * this.wordSize;
|
|
342
|
+
this.recyclePush(segmentSize, address);
|
|
343
|
+
address += segmentSize;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
312
347
|
free(handler) {
|
|
313
|
-
const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
|
|
314
|
-
let headerAddress = handler >>> 0;
|
|
315
348
|
|
|
349
|
+
const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
|
|
350
|
+
const headerAddress = handler >>> 0;
|
|
316
351
|
const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
317
352
|
const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
|
|
318
353
|
const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
|
|
319
354
|
|
|
320
|
-
|
|
321
355
|
if (cookie !== this.bakeCookie(headerAddress, generation)) {
|
|
322
356
|
throw new Error("Invalid or corrupted handle");
|
|
323
357
|
}
|
|
324
358
|
|
|
325
|
-
|
|
359
|
+
this.assertNotBorrowed(headerAddress);
|
|
326
360
|
|
|
361
|
+
const blockSize = (1 << capacity >>> 0) * this.wordSize;
|
|
327
362
|
this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
|
|
328
363
|
|
|
329
364
|
if (this.echoPointer + 4 <= this.controlBus.byteLength) {
|
|
330
365
|
this.controlAdapter.setUint32(this.echoPointer, headerAddress, IS_LITTLE_ENDIAN);
|
|
331
366
|
this.echoPointer += 4;
|
|
332
|
-
}
|
|
333
|
-
|
|
367
|
+
}
|
|
334
368
|
|
|
335
369
|
if (dataAddress + blockSize === this.dataPointer) {
|
|
336
370
|
this.dataPointer = dataAddress;
|
|
337
371
|
} else {
|
|
338
372
|
this.recyclePush(blockSize, dataAddress);
|
|
339
373
|
}
|
|
340
|
-
|
|
341
374
|
}
|
|
342
|
-
|
|
343
375
|
// ========== RECICLAGEM ==========
|
|
344
376
|
|
|
345
377
|
/**
|
|
@@ -407,6 +439,7 @@ export default class Balloc {
|
|
|
407
439
|
}
|
|
408
440
|
|
|
409
441
|
// ========== COLETA DE LIXO ==========
|
|
442
|
+
|
|
410
443
|
/**
|
|
411
444
|
* Compacta o `dataBus` por meio do algoritmo ReBump.
|
|
412
445
|
*
|
|
@@ -430,20 +463,27 @@ export default class Balloc {
|
|
|
430
463
|
* do volume de bytes pertencente aos blocos vivos.
|
|
431
464
|
*
|
|
432
465
|
* @returns {void}
|
|
466
|
+
* @throws {Error} Se houver algum bloco emprestado por withView().
|
|
433
467
|
*/
|
|
434
468
|
gc() {
|
|
469
|
+
this.assertNoActiveViews();
|
|
470
|
+
|
|
435
471
|
const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
|
|
436
472
|
this.recycle.clear();
|
|
437
473
|
this.dataPointer = 0 >>> 0;
|
|
438
|
-
|
|
474
|
+
|
|
475
|
+
for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
|
|
439
476
|
if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
|
|
477
|
+
|
|
440
478
|
const start = this.controlAdapter.getUint32(i + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
441
479
|
const size = (1 << this.controlBus[i + CAPACITY_OFFSET] >>> 0) * this.wordSize;
|
|
442
480
|
const end = start + size;
|
|
481
|
+
|
|
443
482
|
newDataBus.set(this.dataBus.subarray(start, end), this.dataPointer);
|
|
444
483
|
this.controlAdapter.setUint32(i + ADDRESS_OFFSET, this.dataPointer, IS_LITTLE_ENDIAN);
|
|
445
484
|
this.dataPointer += size;
|
|
446
485
|
}
|
|
486
|
+
|
|
447
487
|
this.dataBus = newDataBus;
|
|
448
488
|
this.dataAdapter = new DataView(this.dataBus.buffer);
|
|
449
489
|
this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
|
|
@@ -452,6 +492,7 @@ export default class Balloc {
|
|
|
452
492
|
}
|
|
453
493
|
|
|
454
494
|
// ========== ESCALONAGEM ==========
|
|
495
|
+
|
|
455
496
|
/**
|
|
456
497
|
* [!!! USO INTERNO, NÃO USE NO SEU CÓDIGO !!!]
|
|
457
498
|
* Expande o `dataBus` para o dobro de sua capacidade atual.
|
|
@@ -461,11 +502,14 @@ export default class Balloc {
|
|
|
461
502
|
* para referenciar o novo armazenamento.
|
|
462
503
|
*
|
|
463
504
|
* @returns {void}
|
|
505
|
+
* @throws {Error} Se houver algum bloco emprestado por withView().
|
|
464
506
|
* @throws {RangeError} Se a capacidade do `dataBus` já tiver excedido o
|
|
465
507
|
* limite máximo suportado.
|
|
466
508
|
* @private
|
|
467
509
|
*/
|
|
468
510
|
grow() {
|
|
511
|
+
this.assertNoActiveViews();
|
|
512
|
+
|
|
469
513
|
if (this.size > 0x80000000) throw new RangeError("Data bus capacity exceeded");
|
|
470
514
|
|
|
471
515
|
const newSize = (this.size * 2) >>> 0;
|
|
@@ -514,16 +558,17 @@ export default class Balloc {
|
|
|
514
558
|
* @param {number} value - Valor a ser inserido.
|
|
515
559
|
* @returns {boolean} `true` se o valor foi inserido; `false` se o bloco
|
|
516
560
|
* já estiver sem espaço disponível.
|
|
517
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
561
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
562
|
+
*
|
|
518
563
|
*/
|
|
519
564
|
push(handler, value) {
|
|
520
|
-
|
|
521
565
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
566
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
522
567
|
|
|
523
568
|
if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
|
|
524
569
|
|
|
525
|
-
this.writer(meta.dataAddress + meta.occupied * this.wordSize
|
|
526
|
-
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1,IS_LITTLE_ENDIAN);
|
|
570
|
+
this.writer(meta.dataAddress + meta.occupied * this.wordSize, value, IS_LITTLE_ENDIAN);
|
|
571
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
|
|
527
572
|
|
|
528
573
|
return true;
|
|
529
574
|
}
|
|
@@ -538,14 +583,15 @@ export default class Balloc {
|
|
|
538
583
|
* @param {number} handler - Handler do bloco.
|
|
539
584
|
* @returns {number|undefined} Valor removido ou `undefined` se o bloco
|
|
540
585
|
* estiver vazio.
|
|
541
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
586
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
542
587
|
*/
|
|
543
588
|
pop(handler) {
|
|
544
589
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
590
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
545
591
|
|
|
546
592
|
if (meta.occupied === 0) return undefined;
|
|
547
593
|
|
|
548
|
-
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1,IS_LITTLE_ENDIAN);
|
|
594
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
|
|
549
595
|
return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
|
|
550
596
|
}
|
|
551
597
|
|
|
@@ -581,16 +627,17 @@ export default class Balloc {
|
|
|
581
627
|
* @param {number} value - Valor a ser inserido.
|
|
582
628
|
* @returns {boolean} `true` se o valor foi inserido; `false` se o bloco
|
|
583
629
|
* estiver cheio.
|
|
584
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
630
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
585
631
|
*/
|
|
586
632
|
nudge(handler, value) {
|
|
587
633
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
634
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
588
635
|
|
|
589
636
|
if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
|
|
590
637
|
|
|
591
638
|
this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
|
|
592
639
|
this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
|
|
593
|
-
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1,IS_LITTLE_ENDIAN);
|
|
640
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
|
|
594
641
|
|
|
595
642
|
return true;
|
|
596
643
|
}
|
|
@@ -606,16 +653,18 @@ export default class Balloc {
|
|
|
606
653
|
* @param {number} handler - Handler do bloco.
|
|
607
654
|
* @returns {number|undefined} Primeiro valor removido ou `undefined` se o
|
|
608
655
|
* bloco estiver vazio.
|
|
609
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
656
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
610
657
|
*/
|
|
611
658
|
pull(handler) {
|
|
612
659
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
660
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
613
661
|
|
|
614
662
|
if (meta.occupied === 0) return undefined;
|
|
615
663
|
|
|
616
664
|
const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
|
|
617
665
|
this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
|
|
618
666
|
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
|
|
667
|
+
|
|
619
668
|
return result;
|
|
620
669
|
}
|
|
621
670
|
|
|
@@ -632,7 +681,7 @@ export default class Balloc {
|
|
|
632
681
|
|
|
633
682
|
if (meta.occupied === 0) return undefined;
|
|
634
683
|
|
|
635
|
-
return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
|
|
684
|
+
return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
|
|
636
685
|
}
|
|
637
686
|
|
|
638
687
|
// ========== ACESSO ALEATÓRIO ==========
|
|
@@ -660,18 +709,74 @@ export default class Balloc {
|
|
|
660
709
|
return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
|
|
661
710
|
}
|
|
662
711
|
|
|
663
|
-
|
|
664
|
-
*
|
|
712
|
+
/**
|
|
713
|
+
* Localiza a primeira ocorrência de um elemento na sequência ocupada do bloco.
|
|
714
|
+
*
|
|
715
|
+
* A busca é realizada em ordem crescente de índices, utilizando a operação
|
|
716
|
+
* `indexOf` do TypedArray subjacente. A pesquisa considera exclusivamente
|
|
717
|
+
* os elementos ocupados, ignorando a capacidade não utilizada do bloco.
|
|
718
|
+
*
|
|
719
|
+
* A posição inicial da busca pode ser especificada por `fromIndex`,
|
|
720
|
+
* seguindo as regras de indexação de TypedArray.
|
|
721
|
+
*
|
|
722
|
+
* @param {number} handler - Handler do bloco.
|
|
723
|
+
* @param {number|bigint} searchElement - Elemento a ser localizado.
|
|
724
|
+
* @param {number} [fromIndex=0] - Índice a partir do qual a busca será iniciada.
|
|
725
|
+
* @returns {number} Índice da primeira ocorrência ou `-1` se o
|
|
726
|
+
* elemento não for encontrado ou se o bloco estiver vazio.
|
|
727
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
728
|
+
*/
|
|
729
|
+
indexOf(handler, searchElement, fromIndex = 0) {
|
|
730
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
731
|
+
|
|
732
|
+
if (meta.occupied === 0) return -1;
|
|
733
|
+
|
|
734
|
+
const rawAddres = meta.dataAddress >>> this.wordShift;
|
|
735
|
+
|
|
736
|
+
return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).indexOf(searchElement, fromIndex);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* Localiza a última ocorrência de um elemento na sequência ocupada do bloco.
|
|
741
|
+
*
|
|
742
|
+
* A busca é realizada em ordem decrescente de índices, utilizando a operação
|
|
743
|
+
* `lastIndexOf` do TypedArray subjacente. A pesquisa considera exclusivamente
|
|
744
|
+
* os elementos ocupados, ignorando a capacidade não utilizada do bloco.
|
|
665
745
|
*
|
|
666
|
-
*
|
|
667
|
-
*
|
|
746
|
+
* A posição inicial da busca pode ser especificada por `fromIndex`,
|
|
747
|
+
* seguindo as regras de indexação de TypedArray. Por padrão, a busca começa
|
|
748
|
+
* no último elemento ocupado.
|
|
668
749
|
*
|
|
669
750
|
* @param {number} handler - Handler do bloco.
|
|
670
|
-
* @param {number}
|
|
671
|
-
* @
|
|
672
|
-
*
|
|
751
|
+
* @param {number|bigint} searchElement - Elemento a ser localizado.
|
|
752
|
+
* @param {number} [fromIndex=-1] - Índice a partir do qual a busca será iniciada.
|
|
753
|
+
* @returns {number} Índice da última ocorrência ou `-1` se o
|
|
754
|
+
* elemento não for encontrado ou se o bloco estiver vazio.
|
|
673
755
|
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
674
756
|
*/
|
|
757
|
+
lastIndexOf(handler, searchElement, fromIndex = -1) {
|
|
758
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
759
|
+
|
|
760
|
+
if (meta.occupied === 0) return -1;
|
|
761
|
+
|
|
762
|
+
const rawAddres = meta.dataAddress >>> this.wordShift;
|
|
763
|
+
|
|
764
|
+
return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).lastIndexOf(searchElement, fromIndex);
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
/**
|
|
769
|
+
* Retorna o elemento ocupado em um índice baseado em zero.
|
|
770
|
+
*
|
|
771
|
+
* Índices fora do intervalo `[0, occupied)` não são considerados erro e
|
|
772
|
+
* resultam em `undefined`.
|
|
773
|
+
*
|
|
774
|
+
* @param {number} handler - Handler do bloco.
|
|
775
|
+
* @param {number} index - Índice baseado em zero do elemento.
|
|
776
|
+
* @returns {number|undefined} Valor armazenado no índice ou `undefined` se
|
|
777
|
+
* o índice estiver fora da região ocupada.
|
|
778
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
779
|
+
*/
|
|
675
780
|
get(handler, index) {
|
|
676
781
|
|
|
677
782
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
@@ -692,10 +797,11 @@ export default class Balloc {
|
|
|
692
797
|
* @param {number} value - Novo valor.
|
|
693
798
|
* @returns {boolean} `true` se o valor foi gravado; `false` se o índice
|
|
694
799
|
* estiver fora da região ocupada.
|
|
695
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
800
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
696
801
|
*/
|
|
697
802
|
set(handler, index, value) {
|
|
698
803
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
804
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
699
805
|
|
|
700
806
|
if (index < 0 || index >= meta.occupied) return false;
|
|
701
807
|
|
|
@@ -716,15 +822,16 @@ export default class Balloc {
|
|
|
716
822
|
* @param {number} handler - Handler do bloco.
|
|
717
823
|
* @param {number} [value=0] - Valor utilizado para preencher todos os slots.
|
|
718
824
|
* @returns {void}
|
|
719
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
825
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
720
826
|
*/
|
|
721
|
-
clear(handler, value=0) {
|
|
827
|
+
clear(handler, value = 0) {
|
|
722
828
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
829
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
723
830
|
|
|
724
831
|
const slots = meta.byteCapacity / this.wordSize;
|
|
725
832
|
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
726
833
|
|
|
727
|
-
this.auxiliary.fill(value, rawAddress, rawAddress + slots);
|
|
834
|
+
this.auxiliary.fill(value, rawAddress, rawAddress + slots);
|
|
728
835
|
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
|
|
729
836
|
}
|
|
730
837
|
|
|
@@ -746,13 +853,14 @@ export default class Balloc {
|
|
|
746
853
|
* @param {number|null} [end=null] - Índice final, exclusivo. Quando
|
|
747
854
|
* omitido ou `null`, utiliza a capacidade total do bloco.
|
|
748
855
|
* @returns {void}
|
|
749
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
856
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
750
857
|
* @throws {RangeError} Se `start` ou `end` estiver fora dos limites da
|
|
751
858
|
* capacidade, ou se `start > end`.
|
|
752
859
|
*/
|
|
753
860
|
fill(handler, value, start = 0, end = null) {
|
|
754
861
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
755
|
-
|
|
862
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
863
|
+
|
|
756
864
|
const slots = meta.byteCapacity / this.wordSize;
|
|
757
865
|
const lastIndex = end ?? slots;
|
|
758
866
|
|
|
@@ -767,7 +875,6 @@ export default class Balloc {
|
|
|
767
875
|
}
|
|
768
876
|
|
|
769
877
|
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
770
|
-
|
|
771
878
|
this.auxiliary.fill(value, rawAddress + start, rawAddress + lastIndex);
|
|
772
879
|
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, lastIndex, IS_LITTLE_ENDIAN);
|
|
773
880
|
}
|
|
@@ -782,11 +889,12 @@ export default class Balloc {
|
|
|
782
889
|
* @param {number} handler - Handler do bloco.
|
|
783
890
|
* @param {number} value - Valor utilizado no preenchimento.
|
|
784
891
|
* @returns {void}
|
|
785
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
892
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
786
893
|
*/
|
|
787
894
|
fillAll(handler, value) {
|
|
788
895
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
789
|
-
|
|
896
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
897
|
+
|
|
790
898
|
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
791
899
|
const capacityElements = meta.byteCapacity / this.wordSize;
|
|
792
900
|
|
|
@@ -809,17 +917,16 @@ export default class Balloc {
|
|
|
809
917
|
* @param {number} handler - Handler do bloco.
|
|
810
918
|
* @param {Array|TypedArray} data - Sequência de valores a copiar.
|
|
811
919
|
* @returns {void}
|
|
812
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
920
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
813
921
|
* @throws {TypeError} Se `data` não for uma `Array` nem uma `TypedArray`.
|
|
814
922
|
*/
|
|
815
923
|
put(handler, data) {
|
|
816
924
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
925
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
817
926
|
|
|
818
927
|
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
819
928
|
const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
|
|
820
929
|
|
|
821
|
-
meta.occupied = Math.max(length, meta.occupied);
|
|
822
|
-
|
|
823
930
|
if (Array.isArray(data)) {
|
|
824
931
|
this.auxiliary.set(data.slice(0, length), rawAddress);
|
|
825
932
|
} else if (isTypedArray(data)) {
|
|
@@ -827,37 +934,90 @@ export default class Balloc {
|
|
|
827
934
|
} else {
|
|
828
935
|
const actual = data?.constructor?.name ?? (data === null ? 'null' : typeof data);
|
|
829
936
|
throw new TypeError(`data must be Array or TypedArray, but ${actual} was given.`);
|
|
830
|
-
}
|
|
831
|
-
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, Math.max(length, meta.occupied), IS_LITTLE_ENDIAN);
|
|
832
940
|
}
|
|
833
941
|
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
942
|
+
/**
|
|
943
|
+
* Retorna uma cópia dos elementos atualmente ocupados pelo bloco.
|
|
944
|
+
*
|
|
945
|
+
* O resultado é uma `TypedArray` do mesmo tipo configurado por
|
|
946
|
+
* `bucketSize`. A capacidade física não ocupada não é incluída no resultado.
|
|
947
|
+
*
|
|
948
|
+
* A operação não expõe diretamente o armazenamento interno: o método
|
|
949
|
+
* utiliza `TypedArray.prototype.slice()`, produzindo uma nova view com
|
|
950
|
+
* armazenamento independente.
|
|
951
|
+
*
|
|
952
|
+
* @param {number} handler - Handler do bloco.
|
|
953
|
+
* @returns {TypedArray} Cópia dos elementos ocupados pelo bloco. Quando
|
|
954
|
+
* o bloco está vazio, retorna uma `TypedArray` vazia do tipo configurado.
|
|
955
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
956
|
+
*/
|
|
849
957
|
pick(handler) {
|
|
850
958
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
851
959
|
|
|
852
960
|
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
853
961
|
|
|
854
962
|
if (meta.occupied === 0) {
|
|
855
|
-
return this.auxiliary.slice(rawAddress, rawAddress);
|
|
856
|
-
}
|
|
963
|
+
return this.auxiliary.slice(rawAddress, rawAddress);
|
|
964
|
+
}
|
|
857
965
|
|
|
858
966
|
return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
|
|
859
967
|
}
|
|
860
968
|
|
|
969
|
+
/**
|
|
970
|
+
* Executa um callback sobre uma view direta da região ocupada pelo bloco.
|
|
971
|
+
*
|
|
972
|
+
* A view compartilha o armazenamento interno do Balloc e não realiza cópia.
|
|
973
|
+
* O bloco fica protegido contra operações incompatíveis durante o callback.
|
|
974
|
+
*
|
|
975
|
+
* O callback deve ser síncrono. A view recebida não deve ser armazenada,
|
|
976
|
+
* retornada ou utilizada após o término do callback. Essa restrição
|
|
977
|
+
* também se aplica a subviews derivadas da view original.
|
|
978
|
+
*
|
|
979
|
+
* @param {...number|Function} args - Um ou mais handlers, seguidos pelo callback.
|
|
980
|
+
* @returns {*} Retorno produzido pelo callback.
|
|
981
|
+
* @throws {TypeError} Se não houver handler ou se o callback não for uma função.
|
|
982
|
+
* @throws {Error} Se algum handler for inválido, duplicado ou já estiver emprestado.
|
|
983
|
+
*/
|
|
984
|
+
withView(...args) {
|
|
985
|
+
if (args.length < 2) throw new TypeError("At least one handler and one callback are required");
|
|
986
|
+
|
|
987
|
+
const callback = args.pop();
|
|
988
|
+
if (typeof callback !== "function") throw new TypeError("callback must be a function");
|
|
989
|
+
|
|
990
|
+
const handlers = args;
|
|
991
|
+
const metadata = handlers.map(handler => this.extractMetadata(handler, {}));
|
|
992
|
+
const headers = metadata.map(meta => meta.headerAddress);
|
|
993
|
+
|
|
994
|
+
if (new Set(headers).size !== headers.length) throw new Error("Duplicate handler");
|
|
995
|
+
|
|
996
|
+
const flags = headers.map(header => this.controlBus[header + FLAGS_OFFSET]);
|
|
997
|
+
|
|
998
|
+
if (flags.some(flag => flag & VIEW_LOCK)) throw new Error("Block is already borrowed");
|
|
999
|
+
|
|
1000
|
+
let acquiredCount = 0;
|
|
1001
|
+
|
|
1002
|
+
try {
|
|
1003
|
+
for (const header of headers) {
|
|
1004
|
+
this.controlBus[header + FLAGS_OFFSET] |= VIEW_LOCK;
|
|
1005
|
+
acquiredCount++;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
const views = metadata.map(meta => {
|
|
1009
|
+
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
1010
|
+
return this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied);
|
|
1011
|
+
});
|
|
1012
|
+
|
|
1013
|
+
return callback(...views);
|
|
1014
|
+
} finally {
|
|
1015
|
+
for (let i = 0; i < acquiredCount; i++) {
|
|
1016
|
+
this.controlBus[headers[i] + FLAGS_OFFSET] &= ~VIEW_LOCK;
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
|
|
861
1021
|
// ======== CAPACIDADE EM SLOTS ==========
|
|
862
1022
|
|
|
863
1023
|
/**
|
|
@@ -883,7 +1043,7 @@ export default class Balloc {
|
|
|
883
1043
|
* @returns {number} Número de elementos ocupados.
|
|
884
1044
|
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
885
1045
|
*/
|
|
886
|
-
occupied(handler){
|
|
1046
|
+
occupied(handler) {
|
|
887
1047
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
888
1048
|
return meta.occupied;
|
|
889
1049
|
|
|
@@ -904,46 +1064,63 @@ export default class Balloc {
|
|
|
904
1064
|
return 1 << meta.capacityExponent >>> 0;
|
|
905
1065
|
}
|
|
906
1066
|
|
|
907
|
-
// ==========Operações entre blocos=============
|
|
908
|
-
|
|
909
1067
|
/**
|
|
910
|
-
*
|
|
911
|
-
*
|
|
912
|
-
* A cópia começa no primeiro elemento de `source` e no primeiro slot de
|
|
913
|
-
* `destiny`. A quantidade efetivamente copiada é limitada pelo número de
|
|
914
|
-
* elementos ocupados na origem, pela capacidade física do destino e pelo
|
|
915
|
-
* limite especificado em `slots`.
|
|
916
|
-
*
|
|
917
|
-
* A ocupação do destino é elevada, quando necessário, para abranger os
|
|
918
|
-
* elementos copiados. A capacidade do destino não é alterada.
|
|
1068
|
+
* Verifica se o bloco de memória atingiu sua capacidade de alocação.
|
|
919
1069
|
*
|
|
920
|
-
*
|
|
921
|
-
*
|
|
922
|
-
*
|
|
1070
|
+
* Um bloco é considerado cheio quando a quantidade de elementos ocupados
|
|
1071
|
+
* é igual à sua capacidade total alocada, não restando posições disponíveis
|
|
1072
|
+
* para armazenar novos elementos.
|
|
923
1073
|
*
|
|
924
|
-
* @param {number}
|
|
925
|
-
* @
|
|
926
|
-
* @
|
|
927
|
-
* `UNKNOWN` representa o valor sentinela utilizado para não impor um
|
|
928
|
-
* limite adicional.
|
|
929
|
-
* @returns {Uint8Array} O `dataBus` após a operação.
|
|
930
|
-
* @throws {Error} Se `source` ou `destiny` for inválido ou estiver corrompido.
|
|
1074
|
+
* @param {number} handler - Handler do bloco.
|
|
1075
|
+
* @returns {boolean} `true` se o bloco estiver cheio; caso contrário, `false`.
|
|
1076
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
931
1077
|
*/
|
|
932
|
-
|
|
1078
|
+
isFull(handler) {
|
|
1079
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
1080
|
+
return (1 << meta.capacityExponent >>> 0) - meta.occupied === 0;
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
// ==========Operações entre blocos=============
|
|
1084
|
+
|
|
1085
|
+
/**
|
|
1086
|
+
* Copia elementos ocupados de um bloco para outro.
|
|
1087
|
+
*
|
|
1088
|
+
* A cópia começa no primeiro elemento de `source` e no primeiro slot de
|
|
1089
|
+
* `destination`. A quantidade efetivamente copiada é limitada pelo número de
|
|
1090
|
+
* elementos ocupados na origem, pela capacidade física do destino e pelo
|
|
1091
|
+
* limite especificado em `slots`.
|
|
1092
|
+
*
|
|
1093
|
+
* A ocupação do destino é elevada, quando necessário, para abranger os
|
|
1094
|
+
* elementos copiados. A capacidade do destino não é alterada.
|
|
1095
|
+
*
|
|
1096
|
+
* A operação utiliza `Uint8Array.prototype.copyWithin()` sobre o `dataBus`,
|
|
1097
|
+
* portanto o retorno é o próprio `Uint8Array` que representa o barramento
|
|
1098
|
+
* de dados.
|
|
1099
|
+
*
|
|
1100
|
+
* @param {number} source - Handler do bloco de origem.
|
|
1101
|
+
* @param {number} destination - Handler do bloco de destino.
|
|
1102
|
+
* @param {number} [slots=UNKNOWN] - Número máximo de elementos a copiar.
|
|
1103
|
+
* `UNKNOWN` representa o valor sentinela utilizado para não impor um
|
|
1104
|
+
* limite adicional.
|
|
1105
|
+
* @returns {Uint8Array} O `dataBus` após a operação.
|
|
1106
|
+
* @throws {Error} Se os handlers forem inválidos, estiverem corrompidos
|
|
1107
|
+
* ou o bloco de destino estiver emprestado por withView().
|
|
1108
|
+
*/
|
|
1109
|
+
copy(source, destination, slots = UNKNOWN) {
|
|
933
1110
|
/** @type {Metadata} */
|
|
934
1111
|
const metaA = {};
|
|
935
1112
|
/** @type {Metadata} */
|
|
936
1113
|
const metaB = {};
|
|
937
1114
|
|
|
938
1115
|
this.extractMetadata(source, metaA);
|
|
939
|
-
this.extractMetadata(
|
|
1116
|
+
this.extractMetadata(destination, metaB);
|
|
1117
|
+
this.assertNotBorrowed(metaB.headerAddress);
|
|
940
1118
|
|
|
941
1119
|
const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
|
|
942
1120
|
const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
|
|
943
1121
|
const newOccupied = Math.max(metaB.occupied, slotsToCopy);
|
|
944
1122
|
|
|
945
1123
|
this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
|
|
946
|
-
|
|
947
1124
|
return this.dataBus.copyWithin(metaB.dataAddress, metaA.dataAddress, metaA.dataAddress + slotsToCopy * this.wordSize);
|
|
948
1125
|
}
|
|
949
1126
|
|
|
@@ -968,12 +1145,13 @@ export default class Balloc {
|
|
|
968
1145
|
* @param {number} start - Índice inicial da origem.
|
|
969
1146
|
* @param {number} length - Número máximo de elementos a copiar.
|
|
970
1147
|
* @returns {Uint8Array} O `dataBus` após a operação.
|
|
971
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
1148
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
972
1149
|
*/
|
|
973
1150
|
copyWithin(handler, target, start, length) {
|
|
974
1151
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
975
|
-
|
|
1152
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
976
1153
|
|
|
1154
|
+
const slots = Math.floor(meta.byteCapacity / this.wordSize);
|
|
977
1155
|
target = Math.trunc(target);
|
|
978
1156
|
start = Math.trunc(start);
|
|
979
1157
|
length = Math.trunc(length);
|
|
@@ -981,12 +1159,9 @@ export default class Balloc {
|
|
|
981
1159
|
if (target < 0) target += slots;
|
|
982
1160
|
if (start < 0) start += slots;
|
|
983
1161
|
|
|
984
|
-
// Clampa índices dentro dos limites da capacidade
|
|
985
1162
|
target = Math.max(0, Math.min(target, slots));
|
|
986
1163
|
start = Math.max(0, Math.min(start, slots));
|
|
987
1164
|
|
|
988
|
-
// Limita a cópia à capacidade disponível a partir do target
|
|
989
|
-
// e aos elementos efetivamente ocupados a partir de start
|
|
990
1165
|
const maxRead = Math.max(0, meta.occupied - start);
|
|
991
1166
|
const maxWrite = slots - target;
|
|
992
1167
|
length = Math.max(0, Math.min(length, maxRead, maxWrite));
|
|
@@ -995,9 +1170,8 @@ export default class Balloc {
|
|
|
995
1170
|
|
|
996
1171
|
const targetAddress = meta.dataAddress + target * this.wordSize;
|
|
997
1172
|
const sourceAddress = meta.dataAddress + start * this.wordSize;
|
|
998
|
-
|
|
999
|
-
// Atualiza a ocupação caso a cópia expanda o topo ocupado do bloco
|
|
1000
1173
|
const newOccupied = Math.max(meta.occupied, target + length);
|
|
1174
|
+
|
|
1001
1175
|
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
|
|
1002
1176
|
|
|
1003
1177
|
return this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + length * this.wordSize);
|
|
@@ -1017,7 +1191,8 @@ export default class Balloc {
|
|
|
1017
1191
|
* @param {number} source - Handler do bloco cujos elementos serão
|
|
1018
1192
|
* acrescentados.
|
|
1019
1193
|
* @returns {number} Número de elementos efetivamente acrescentados.
|
|
1020
|
-
* @throws {Error} Se
|
|
1194
|
+
* @throws {Error} Se os handlers forem inválidos, estiverem corrompidos
|
|
1195
|
+
* ou o bloco de destino estiver emprestado por withView().
|
|
1021
1196
|
*/
|
|
1022
1197
|
append(target, source) {
|
|
1023
1198
|
const metaTarget = {};
|
|
@@ -1025,6 +1200,7 @@ export default class Balloc {
|
|
|
1025
1200
|
|
|
1026
1201
|
this.extractMetadata(target, metaTarget);
|
|
1027
1202
|
this.extractMetadata(source, metaSource);
|
|
1203
|
+
this.assertNotBorrowed(metaTarget.headerAddress);
|
|
1028
1204
|
|
|
1029
1205
|
const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
|
|
1030
1206
|
const count = Math.min(available, metaSource.occupied);
|
|
@@ -1034,11 +1210,7 @@ export default class Balloc {
|
|
|
1034
1210
|
const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
|
|
1035
1211
|
const sourceAddress = metaSource.dataAddress;
|
|
1036
1212
|
|
|
1037
|
-
|
|
1038
|
-
this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
|
|
1039
|
-
} else {
|
|
1040
|
-
this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
|
|
1041
|
-
}
|
|
1213
|
+
this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
|
|
1042
1214
|
|
|
1043
1215
|
this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
|
|
1044
1216
|
|
|
@@ -1087,17 +1259,21 @@ export default class Balloc {
|
|
|
1087
1259
|
* @param {number} source - Handler do primeiro bloco.
|
|
1088
1260
|
* @param {number} target - Handler do segundo bloco.
|
|
1089
1261
|
* @returns {void}
|
|
1090
|
-
* @throws {Error} Se
|
|
1262
|
+
* @throws {Error} Se os handlers forem inválidos, estiverem corrompidos
|
|
1263
|
+
* ou qualquer um dos blocos estiver emprestado por withView().
|
|
1091
1264
|
*/
|
|
1092
1265
|
swap(source, target) {
|
|
1093
1266
|
/** @type {Metadata} */
|
|
1094
1267
|
const metaA = {};
|
|
1095
1268
|
/** @type {Metadata} */
|
|
1096
1269
|
const metaB = {};
|
|
1097
|
-
|
|
1270
|
+
|
|
1098
1271
|
this.extractMetadata(source, metaA);
|
|
1099
1272
|
this.extractMetadata(target, metaB);
|
|
1100
1273
|
|
|
1274
|
+
this.assertNotBorrowed(metaA.headerAddress);
|
|
1275
|
+
this.assertNotBorrowed(metaB.headerAddress);
|
|
1276
|
+
|
|
1101
1277
|
this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
|
|
1102
1278
|
this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
|
|
1103
1279
|
|
|
@@ -1106,7 +1282,7 @@ export default class Balloc {
|
|
|
1106
1282
|
|
|
1107
1283
|
this.controlAdapter.setUint32(metaA.headerAddress + OCCUPIED_OFFSET, metaB.occupied, IS_LITTLE_ENDIAN);
|
|
1108
1284
|
this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, metaA.occupied, IS_LITTLE_ENDIAN);
|
|
1109
|
-
}
|
|
1285
|
+
}
|
|
1110
1286
|
|
|
1111
1287
|
|
|
1112
1288
|
// ============= SERIALIZAÇÃO ==============
|
|
@@ -1212,6 +1388,39 @@ export default class Balloc {
|
|
|
1212
1388
|
|
|
1213
1389
|
// ============= UTILITÁRIOS ==============
|
|
1214
1390
|
|
|
1391
|
+
/**
|
|
1392
|
+
* Impede operações de modificação sobre um bloco emprestado.
|
|
1393
|
+
*
|
|
1394
|
+
* Verifica a flag VIEW_LOCK no header associado ao endereço informado.
|
|
1395
|
+
*
|
|
1396
|
+
* @param {number} headerAddress - Endereço do header no controlBus.
|
|
1397
|
+
* @returns {void}
|
|
1398
|
+
* @throws {Error} Se o bloco estiver emprestado por withView().
|
|
1399
|
+
* @private
|
|
1400
|
+
*/
|
|
1401
|
+
assertNotBorrowed(headerAddress) {
|
|
1402
|
+
if (this.controlBus[headerAddress + FLAGS_OFFSET] & VIEW_LOCK) {
|
|
1403
|
+
throw new Error("Block is borrowed");
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
/**
|
|
1408
|
+
* Impede operações que substituem ou remanejam o dataBus
|
|
1409
|
+
* enquanto existir algum segmento emprestado.
|
|
1410
|
+
*
|
|
1411
|
+
* @returns {void}
|
|
1412
|
+
* @throws {Error} Se existir algum bloco emprestado por withView().
|
|
1413
|
+
* @private
|
|
1414
|
+
*/
|
|
1415
|
+
assertNoActiveViews() {
|
|
1416
|
+
for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
|
|
1417
|
+
if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
|
|
1418
|
+
if (this.controlBus[i + FLAGS_OFFSET] & VIEW_LOCK) {
|
|
1419
|
+
throw new Error("Cannot remap memory while a block is borrowed");
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1215
1424
|
/**
|
|
1216
1425
|
* [USO INTERNO]
|
|
1217
1426
|
* Decodifica os metadados associados a um handler.
|
|
@@ -1243,7 +1452,7 @@ export default class Balloc {
|
|
|
1243
1452
|
}
|
|
1244
1453
|
|
|
1245
1454
|
out.dataAddress = this.controlAdapter.getUint32(out.headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
1246
|
-
out.capacityExponent
|
|
1455
|
+
out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
|
|
1247
1456
|
out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
|
|
1248
1457
|
out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
|
|
1249
1458
|
|