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.cjs
CHANGED
|
@@ -43,6 +43,8 @@ var ADDRESS_OFFSET = 0 >>> 0;
|
|
|
43
43
|
var OCCUPIED_OFFSET = 4 >>> 0;
|
|
44
44
|
var CAPACITY_OFFSET = 8 >>> 0;
|
|
45
45
|
var COOKIE_OFFSET = 9 >>> 0;
|
|
46
|
+
var FLAGS_OFFSET = 10 >>> 0;
|
|
47
|
+
var VIEW_LOCK = 1 >>> 0;
|
|
46
48
|
var ROTATE_32BITS = 4294967296;
|
|
47
49
|
var CLAMP_11BITS = 2047 >>> 0;
|
|
48
50
|
var isTypedArray = (val) => ArrayBuffer.isView(val) && !(val instanceof DataView);
|
|
@@ -85,8 +87,8 @@ var Balloc = class {
|
|
|
85
87
|
this.bucketArray = globalThis[`${this.bucketType}Array`];
|
|
86
88
|
this.wordSize = this.bucketSize >>> 3;
|
|
87
89
|
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.size = Math.max(1 << 32 - Math.clz32(size - 1) >>> 0, this.wordSize);
|
|
91
|
+
this.headerSize = 1 << 32 - Math.clz32(metadataSize - 1) >>> 0;
|
|
90
92
|
this.dataPointer = 0 >>> 0;
|
|
91
93
|
this.controlPointer = 0 >>> 0;
|
|
92
94
|
this.echoPointer = 0 >>> 0;
|
|
@@ -131,6 +133,8 @@ var Balloc = class {
|
|
|
131
133
|
* comportar. Deve ser um inteiro seguro no intervalo [2, 0x80000000].
|
|
132
134
|
* @returns {number} Handler que identifica o bloco alocado.
|
|
133
135
|
* @throws {RangeError} Se `size` estiver fora do intervalo permitido.
|
|
136
|
+
* @throws {Error} Se for necessário expandir o `dataBus` enquanto houver
|
|
137
|
+
* algum bloco emprestado por withView().
|
|
134
138
|
*/
|
|
135
139
|
alloc(size = 16) {
|
|
136
140
|
if (!Number.isSafeInteger(size) || size < 2 || size > 2147483648) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
|
|
@@ -156,6 +160,7 @@ var Balloc = class {
|
|
|
156
160
|
this.controlAdapter.setUint32(headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
|
|
157
161
|
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, capacity);
|
|
158
162
|
this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, this.bakeCookie(headerAddress, ++this.generation));
|
|
163
|
+
this.controlBus[headerAddress + FLAGS_OFFSET] = 0;
|
|
159
164
|
return (this.generation & CLAMP_11BITS) * ROTATE_32BITS + headerAddress;
|
|
160
165
|
}
|
|
161
166
|
/**
|
|
@@ -175,13 +180,15 @@ var Balloc = class {
|
|
|
175
180
|
*
|
|
176
181
|
* @param {number} handler - Handler do bloco a ser expandido.
|
|
177
182
|
* @returns {void}
|
|
178
|
-
* @throws {Error} Se o handler for inválido ou
|
|
183
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco
|
|
184
|
+
* estiver emprestado por withView(). Também ocorre se a expansão exigir
|
|
185
|
+
* remapeamento do dataBus enquanto houver outro bloco emprestado.
|
|
179
186
|
* @throws {AggregateError} Se a capacidade já tiver atingido o limite
|
|
180
187
|
* máximo suportado.
|
|
181
188
|
*/
|
|
182
189
|
realloc(handler) {
|
|
183
190
|
const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
|
|
184
|
-
|
|
191
|
+
const headerAddress = handler >>> 0;
|
|
185
192
|
const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
186
193
|
const occupied = this.controlAdapter.getUint32(headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
|
|
187
194
|
const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
|
|
@@ -189,50 +196,71 @@ var Balloc = class {
|
|
|
189
196
|
if (cookie !== this.bakeCookie(headerAddress, generation)) {
|
|
190
197
|
throw new Error("Invalid or corrupted handle");
|
|
191
198
|
}
|
|
199
|
+
this.assertNotBorrowed(headerAddress);
|
|
192
200
|
if (capacity >= 31) throw new AggregateError([new Error("Can\xB4t reallocate handler."), new RangeError("Capacity has reached its limit.")], "Internal Error.");
|
|
193
201
|
const newCapacity = capacity + 1;
|
|
194
202
|
const newBlockSize = (1 << newCapacity >>> 0) * this.wordSize;
|
|
195
203
|
const oldBlockSize = (1 << capacity >>> 0) * this.wordSize;
|
|
196
204
|
if (dataAddress + oldBlockSize === this.dataPointer) {
|
|
197
205
|
while (dataAddress + newBlockSize > this.size) this.grow();
|
|
198
|
-
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity
|
|
206
|
+
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
|
|
199
207
|
this.dataPointer = dataAddress + newBlockSize;
|
|
200
208
|
return;
|
|
201
209
|
}
|
|
202
|
-
this.recyclePush(oldBlockSize, dataAddress);
|
|
203
210
|
let newAddress = this.recyclePop(newBlockSize);
|
|
204
211
|
if (newAddress === UNKNOWN) {
|
|
205
212
|
while (this.dataPointer + newBlockSize > this.size) this.grow();
|
|
206
213
|
newAddress = this.dataPointer;
|
|
207
214
|
this.dataPointer += newBlockSize;
|
|
208
215
|
}
|
|
209
|
-
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
|
|
210
216
|
this.dataBus.copyWithin(newAddress, dataAddress, dataAddress + occupied * this.wordSize);
|
|
211
217
|
this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, newAddress, IS_LITTLE_ENDIAN);
|
|
218
|
+
this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
|
|
219
|
+
this.recyclePush(oldBlockSize, dataAddress);
|
|
212
220
|
}
|
|
213
221
|
/**
|
|
214
|
-
*
|
|
222
|
+
* Reduz um bloco à menor capacidade em potência de dois capaz de comportar
|
|
223
|
+
* seus elementos ocupados, preservando seu endereço e handler.
|
|
215
224
|
*
|
|
216
|
-
*
|
|
217
|
-
*
|
|
218
|
-
*
|
|
219
|
-
* exatamente no topo do `dataBus`; nesse caso, o `dataPointer` é simplesmente
|
|
220
|
-
* retrocedido, eliminando a região sem criar uma entrada na lista de
|
|
221
|
-
* reciclagem.
|
|
225
|
+
* Se o bloco estiver no topo do dataBus, dataPointer será recuado.
|
|
226
|
+
* Caso contrário, a cauda liberada será dividida em regiões de potências
|
|
227
|
+
* de dois, e cada região será devolvida à lista de reciclagem.
|
|
222
228
|
*
|
|
223
|
-
* @param {number} handler - Handler do bloco a ser
|
|
229
|
+
* @param {number} handler - Handler do bloco a ser reduzido.
|
|
224
230
|
* @returns {void}
|
|
225
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
231
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou estiver
|
|
232
|
+
* emprestado por withView().
|
|
226
233
|
*/
|
|
234
|
+
shrink(handler) {
|
|
235
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
236
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
237
|
+
const newCapacity = Math.max(1, 32 - Math.clz32(Math.max(2, meta.occupied) - 1));
|
|
238
|
+
if (newCapacity >= meta.capacityExponent) return;
|
|
239
|
+
const oldBlockSize = meta.byteCapacity;
|
|
240
|
+
const newBlockSize = 2 ** newCapacity * this.wordSize;
|
|
241
|
+
const oldEnd = meta.dataAddress + oldBlockSize;
|
|
242
|
+
this.controlAdapter.setUint8(meta.headerAddress + CAPACITY_OFFSET, newCapacity);
|
|
243
|
+
if (oldEnd === this.dataPointer) {
|
|
244
|
+
this.dataPointer = meta.dataAddress + newBlockSize;
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
let address = meta.dataAddress + newBlockSize;
|
|
248
|
+
for (let exponent = newCapacity; exponent < meta.capacityExponent; exponent++) {
|
|
249
|
+
const segmentSize = 2 ** exponent * this.wordSize;
|
|
250
|
+
this.recyclePush(segmentSize, address);
|
|
251
|
+
address += segmentSize;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
227
254
|
free(handler) {
|
|
228
255
|
const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
|
|
229
|
-
|
|
256
|
+
const headerAddress = handler >>> 0;
|
|
230
257
|
const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
|
|
231
258
|
const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
|
|
232
259
|
const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
|
|
233
260
|
if (cookie !== this.bakeCookie(headerAddress, generation)) {
|
|
234
261
|
throw new Error("Invalid or corrupted handle");
|
|
235
262
|
}
|
|
263
|
+
this.assertNotBorrowed(headerAddress);
|
|
236
264
|
const blockSize = (1 << capacity >>> 0) * this.wordSize;
|
|
237
265
|
this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
|
|
238
266
|
if (this.echoPointer + 4 <= this.controlBus.byteLength) {
|
|
@@ -326,8 +354,10 @@ var Balloc = class {
|
|
|
326
354
|
* do volume de bytes pertencente aos blocos vivos.
|
|
327
355
|
*
|
|
328
356
|
* @returns {void}
|
|
357
|
+
* @throws {Error} Se houver algum bloco emprestado por withView().
|
|
329
358
|
*/
|
|
330
359
|
gc() {
|
|
360
|
+
this.assertNoActiveViews();
|
|
331
361
|
const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
|
|
332
362
|
this.recycle.clear();
|
|
333
363
|
this.dataPointer = 0 >>> 0;
|
|
@@ -356,11 +386,13 @@ var Balloc = class {
|
|
|
356
386
|
* para referenciar o novo armazenamento.
|
|
357
387
|
*
|
|
358
388
|
* @returns {void}
|
|
389
|
+
* @throws {Error} Se houver algum bloco emprestado por withView().
|
|
359
390
|
* @throws {RangeError} Se a capacidade do `dataBus` já tiver excedido o
|
|
360
391
|
* limite máximo suportado.
|
|
361
392
|
* @private
|
|
362
393
|
*/
|
|
363
394
|
grow() {
|
|
395
|
+
this.assertNoActiveViews();
|
|
364
396
|
if (this.size > 2147483648) throw new RangeError("Data bus capacity exceeded");
|
|
365
397
|
const newSize = this.size * 2 >>> 0;
|
|
366
398
|
const newBuffer = this.dataBus.buffer.transfer(newSize);
|
|
@@ -403,10 +435,12 @@ var Balloc = class {
|
|
|
403
435
|
* @param {number} value - Valor a ser inserido.
|
|
404
436
|
* @returns {boolean} `true` se o valor foi inserido; `false` se o bloco
|
|
405
437
|
* já estiver sem espaço disponível.
|
|
406
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
438
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
439
|
+
*
|
|
407
440
|
*/
|
|
408
441
|
push(handler, value) {
|
|
409
442
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
443
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
410
444
|
if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
|
|
411
445
|
this.writer(meta.dataAddress + meta.occupied * this.wordSize, value, IS_LITTLE_ENDIAN);
|
|
412
446
|
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
|
|
@@ -422,10 +456,11 @@ var Balloc = class {
|
|
|
422
456
|
* @param {number} handler - Handler do bloco.
|
|
423
457
|
* @returns {number|undefined} Valor removido ou `undefined` se o bloco
|
|
424
458
|
* estiver vazio.
|
|
425
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
459
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
426
460
|
*/
|
|
427
461
|
pop(handler) {
|
|
428
462
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
463
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
429
464
|
if (meta.occupied === 0) return void 0;
|
|
430
465
|
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
|
|
431
466
|
return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
|
|
@@ -458,10 +493,11 @@ var Balloc = class {
|
|
|
458
493
|
* @param {number} value - Valor a ser inserido.
|
|
459
494
|
* @returns {boolean} `true` se o valor foi inserido; `false` se o bloco
|
|
460
495
|
* estiver cheio.
|
|
461
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
496
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
462
497
|
*/
|
|
463
498
|
nudge(handler, value) {
|
|
464
499
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
500
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
465
501
|
if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
|
|
466
502
|
this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
|
|
467
503
|
this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
|
|
@@ -479,10 +515,11 @@ var Balloc = class {
|
|
|
479
515
|
* @param {number} handler - Handler do bloco.
|
|
480
516
|
* @returns {number|undefined} Primeiro valor removido ou `undefined` se o
|
|
481
517
|
* bloco estiver vazio.
|
|
482
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
518
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
483
519
|
*/
|
|
484
520
|
pull(handler) {
|
|
485
521
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
522
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
486
523
|
if (meta.occupied === 0) return void 0;
|
|
487
524
|
const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
|
|
488
525
|
this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
|
|
@@ -522,6 +559,53 @@ var Balloc = class {
|
|
|
522
559
|
const rawAddres = meta.dataAddress >>> this.wordShift;
|
|
523
560
|
return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
|
|
524
561
|
}
|
|
562
|
+
/**
|
|
563
|
+
* Localiza a primeira ocorrência de um elemento na sequência ocupada do bloco.
|
|
564
|
+
*
|
|
565
|
+
* A busca é realizada em ordem crescente de índices, utilizando a operação
|
|
566
|
+
* `indexOf` do TypedArray subjacente. A pesquisa considera exclusivamente
|
|
567
|
+
* os elementos ocupados, ignorando a capacidade não utilizada do bloco.
|
|
568
|
+
*
|
|
569
|
+
* A posição inicial da busca pode ser especificada por `fromIndex`,
|
|
570
|
+
* seguindo as regras de indexação de TypedArray.
|
|
571
|
+
*
|
|
572
|
+
* @param {number} handler - Handler do bloco.
|
|
573
|
+
* @param {number|bigint} searchElement - Elemento a ser localizado.
|
|
574
|
+
* @param {number} [fromIndex=0] - Índice a partir do qual a busca será iniciada.
|
|
575
|
+
* @returns {number} Índice da primeira ocorrência ou `-1` se o
|
|
576
|
+
* elemento não for encontrado ou se o bloco estiver vazio.
|
|
577
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
578
|
+
*/
|
|
579
|
+
indexOf(handler, searchElement, fromIndex = 0) {
|
|
580
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
581
|
+
if (meta.occupied === 0) return -1;
|
|
582
|
+
const rawAddres = meta.dataAddress >>> this.wordShift;
|
|
583
|
+
return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).indexOf(searchElement, fromIndex);
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Localiza a última ocorrência de um elemento na sequência ocupada do bloco.
|
|
587
|
+
*
|
|
588
|
+
* A busca é realizada em ordem decrescente de índices, utilizando a operação
|
|
589
|
+
* `lastIndexOf` do TypedArray subjacente. A pesquisa considera exclusivamente
|
|
590
|
+
* os elementos ocupados, ignorando a capacidade não utilizada do bloco.
|
|
591
|
+
*
|
|
592
|
+
* A posição inicial da busca pode ser especificada por `fromIndex`,
|
|
593
|
+
* seguindo as regras de indexação de TypedArray. Por padrão, a busca começa
|
|
594
|
+
* no último elemento ocupado.
|
|
595
|
+
*
|
|
596
|
+
* @param {number} handler - Handler do bloco.
|
|
597
|
+
* @param {number|bigint} searchElement - Elemento a ser localizado.
|
|
598
|
+
* @param {number} [fromIndex=-1] - Índice a partir do qual a busca será iniciada.
|
|
599
|
+
* @returns {number} Índice da última ocorrência ou `-1` se o
|
|
600
|
+
* elemento não for encontrado ou se o bloco estiver vazio.
|
|
601
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
602
|
+
*/
|
|
603
|
+
lastIndexOf(handler, searchElement, fromIndex = -1) {
|
|
604
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
605
|
+
if (meta.occupied === 0) return -1;
|
|
606
|
+
const rawAddres = meta.dataAddress >>> this.wordShift;
|
|
607
|
+
return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).lastIndexOf(searchElement, fromIndex);
|
|
608
|
+
}
|
|
525
609
|
/**
|
|
526
610
|
* Retorna o elemento ocupado em um índice baseado em zero.
|
|
527
611
|
*
|
|
@@ -550,10 +634,11 @@ var Balloc = class {
|
|
|
550
634
|
* @param {number} value - Novo valor.
|
|
551
635
|
* @returns {boolean} `true` se o valor foi gravado; `false` se o índice
|
|
552
636
|
* estiver fora da região ocupada.
|
|
553
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
637
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
554
638
|
*/
|
|
555
639
|
set(handler, index, value) {
|
|
556
640
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
641
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
557
642
|
if (index < 0 || index >= meta.occupied) return false;
|
|
558
643
|
this.writer(meta.dataAddress + index * this.wordSize, value, IS_LITTLE_ENDIAN);
|
|
559
644
|
return true;
|
|
@@ -570,10 +655,11 @@ var Balloc = class {
|
|
|
570
655
|
* @param {number} handler - Handler do bloco.
|
|
571
656
|
* @param {number} [value=0] - Valor utilizado para preencher todos os slots.
|
|
572
657
|
* @returns {void}
|
|
573
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
658
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
574
659
|
*/
|
|
575
660
|
clear(handler, value = 0) {
|
|
576
661
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
662
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
577
663
|
const slots = meta.byteCapacity / this.wordSize;
|
|
578
664
|
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
579
665
|
this.auxiliary.fill(value, rawAddress, rawAddress + slots);
|
|
@@ -596,12 +682,13 @@ var Balloc = class {
|
|
|
596
682
|
* @param {number|null} [end=null] - Índice final, exclusivo. Quando
|
|
597
683
|
* omitido ou `null`, utiliza a capacidade total do bloco.
|
|
598
684
|
* @returns {void}
|
|
599
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
685
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
600
686
|
* @throws {RangeError} Se `start` ou `end` estiver fora dos limites da
|
|
601
687
|
* capacidade, ou se `start > end`.
|
|
602
688
|
*/
|
|
603
689
|
fill(handler, value, start = 0, end = null) {
|
|
604
690
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
691
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
605
692
|
const slots = meta.byteCapacity / this.wordSize;
|
|
606
693
|
const lastIndex = end ?? slots;
|
|
607
694
|
if (start > lastIndex) {
|
|
@@ -627,10 +714,11 @@ var Balloc = class {
|
|
|
627
714
|
* @param {number} handler - Handler do bloco.
|
|
628
715
|
* @param {number} value - Valor utilizado no preenchimento.
|
|
629
716
|
* @returns {void}
|
|
630
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
717
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
631
718
|
*/
|
|
632
719
|
fillAll(handler, value) {
|
|
633
720
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
721
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
634
722
|
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
635
723
|
const capacityElements = meta.byteCapacity / this.wordSize;
|
|
636
724
|
this.auxiliary.fill(value, rawAddress, rawAddress + capacityElements);
|
|
@@ -651,14 +739,14 @@ var Balloc = class {
|
|
|
651
739
|
* @param {number} handler - Handler do bloco.
|
|
652
740
|
* @param {Array|TypedArray} data - Sequência de valores a copiar.
|
|
653
741
|
* @returns {void}
|
|
654
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
742
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
655
743
|
* @throws {TypeError} Se `data` não for uma `Array` nem uma `TypedArray`.
|
|
656
744
|
*/
|
|
657
745
|
put(handler, data) {
|
|
658
746
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
747
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
659
748
|
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
660
749
|
const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
|
|
661
|
-
meta.occupied = Math.max(length, meta.occupied);
|
|
662
750
|
if (Array.isArray(data)) {
|
|
663
751
|
this.auxiliary.set(data.slice(0, length), rawAddress);
|
|
664
752
|
} else if (isTypedArray(data)) {
|
|
@@ -667,7 +755,7 @@ var Balloc = class {
|
|
|
667
755
|
const actual = data?.constructor?.name ?? (data === null ? "null" : typeof data);
|
|
668
756
|
throw new TypeError(`data must be Array or TypedArray, but ${actual} was given.`);
|
|
669
757
|
}
|
|
670
|
-
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
|
|
758
|
+
this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, Math.max(length, meta.occupied), IS_LITTLE_ENDIAN);
|
|
671
759
|
}
|
|
672
760
|
/**
|
|
673
761
|
* Retorna uma cópia dos elementos atualmente ocupados pelo bloco.
|
|
@@ -692,6 +780,48 @@ var Balloc = class {
|
|
|
692
780
|
}
|
|
693
781
|
return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
|
|
694
782
|
}
|
|
783
|
+
/**
|
|
784
|
+
* Executa um callback sobre uma view direta da região ocupada pelo bloco.
|
|
785
|
+
*
|
|
786
|
+
* A view compartilha o armazenamento interno do Balloc e não realiza cópia.
|
|
787
|
+
* O bloco fica protegido contra operações incompatíveis durante o callback.
|
|
788
|
+
*
|
|
789
|
+
* O callback deve ser síncrono. A view recebida não deve ser armazenada,
|
|
790
|
+
* retornada ou utilizada após o término do callback. Essa restrição
|
|
791
|
+
* também se aplica a subviews derivadas da view original.
|
|
792
|
+
*
|
|
793
|
+
* @param {...number|Function} args - Um ou mais handlers, seguidos pelo callback.
|
|
794
|
+
* @returns {*} Retorno produzido pelo callback.
|
|
795
|
+
* @throws {TypeError} Se não houver handler ou se o callback não for uma função.
|
|
796
|
+
* @throws {Error} Se algum handler for inválido, duplicado ou já estiver emprestado.
|
|
797
|
+
*/
|
|
798
|
+
withView(...args) {
|
|
799
|
+
if (args.length < 2) throw new TypeError("At least one handler and one callback are required");
|
|
800
|
+
const callback = args.pop();
|
|
801
|
+
if (typeof callback !== "function") throw new TypeError("callback must be a function");
|
|
802
|
+
const handlers = args;
|
|
803
|
+
const metadata = handlers.map((handler) => this.extractMetadata(handler, {}));
|
|
804
|
+
const headers = metadata.map((meta) => meta.headerAddress);
|
|
805
|
+
if (new Set(headers).size !== headers.length) throw new Error("Duplicate handler");
|
|
806
|
+
const flags = headers.map((header) => this.controlBus[header + FLAGS_OFFSET]);
|
|
807
|
+
if (flags.some((flag) => flag & VIEW_LOCK)) throw new Error("Block is already borrowed");
|
|
808
|
+
let acquiredCount = 0;
|
|
809
|
+
try {
|
|
810
|
+
for (const header of headers) {
|
|
811
|
+
this.controlBus[header + FLAGS_OFFSET] |= VIEW_LOCK;
|
|
812
|
+
acquiredCount++;
|
|
813
|
+
}
|
|
814
|
+
const views = metadata.map((meta) => {
|
|
815
|
+
const rawAddress = meta.dataAddress >>> this.wordShift;
|
|
816
|
+
return this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied);
|
|
817
|
+
});
|
|
818
|
+
return callback(...views);
|
|
819
|
+
} finally {
|
|
820
|
+
for (let i = 0; i < acquiredCount; i++) {
|
|
821
|
+
this.controlBus[headers[i] + FLAGS_OFFSET] &= ~VIEW_LOCK;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
}
|
|
695
825
|
// ======== CAPACIDADE EM SLOTS ==========
|
|
696
826
|
/**
|
|
697
827
|
* Retorna a capacidade física do bloco em bytes.
|
|
@@ -733,35 +863,52 @@ var Balloc = class {
|
|
|
733
863
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
734
864
|
return 1 << meta.capacityExponent >>> 0;
|
|
735
865
|
}
|
|
736
|
-
// ==========Operações entre blocos=============
|
|
737
866
|
/**
|
|
738
|
-
*
|
|
739
|
-
*
|
|
740
|
-
* A cópia começa no primeiro elemento de `source` e no primeiro slot de
|
|
741
|
-
* `destiny`. A quantidade efetivamente copiada é limitada pelo número de
|
|
742
|
-
* elementos ocupados na origem, pela capacidade física do destino e pelo
|
|
743
|
-
* limite especificado em `slots`.
|
|
867
|
+
* Verifica se o bloco de memória atingiu sua capacidade de alocação.
|
|
744
868
|
*
|
|
745
|
-
*
|
|
746
|
-
*
|
|
869
|
+
* Um bloco é considerado cheio quando a quantidade de elementos ocupados
|
|
870
|
+
* é igual à sua capacidade total alocada, não restando posições disponíveis
|
|
871
|
+
* para armazenar novos elementos.
|
|
747
872
|
*
|
|
748
|
-
*
|
|
749
|
-
*
|
|
750
|
-
*
|
|
751
|
-
*
|
|
752
|
-
* @param {number} source - Handler do bloco de origem.
|
|
753
|
-
* @param {number} destiny - Handler do bloco de destino.
|
|
754
|
-
* @param {number} [slots=UNKNOWN] - Número máximo de elementos a copiar.
|
|
755
|
-
* `UNKNOWN` representa o valor sentinela utilizado para não impor um
|
|
756
|
-
* limite adicional.
|
|
757
|
-
* @returns {Uint8Array} O `dataBus` após a operação.
|
|
758
|
-
* @throws {Error} Se `source` ou `destiny` for inválido ou estiver corrompido.
|
|
873
|
+
* @param {number} handler - Handler do bloco.
|
|
874
|
+
* @returns {boolean} `true` se o bloco estiver cheio; caso contrário, `false`.
|
|
875
|
+
* @throws {Error} Se o handler for inválido ou estiver corrompido.
|
|
759
876
|
*/
|
|
760
|
-
|
|
877
|
+
isFull(handler) {
|
|
878
|
+
const meta = this.extractMetadata(handler, this.metadata);
|
|
879
|
+
return (1 << meta.capacityExponent >>> 0) - meta.occupied === 0;
|
|
880
|
+
}
|
|
881
|
+
// ==========Operações entre blocos=============
|
|
882
|
+
/**
|
|
883
|
+
* Copia elementos ocupados de um bloco para outro.
|
|
884
|
+
*
|
|
885
|
+
* A cópia começa no primeiro elemento de `source` e no primeiro slot de
|
|
886
|
+
* `destination`. A quantidade efetivamente copiada é limitada pelo número de
|
|
887
|
+
* elementos ocupados na origem, pela capacidade física do destino e pelo
|
|
888
|
+
* limite especificado em `slots`.
|
|
889
|
+
*
|
|
890
|
+
* A ocupação do destino é elevada, quando necessário, para abranger os
|
|
891
|
+
* elementos copiados. A capacidade do destino não é alterada.
|
|
892
|
+
*
|
|
893
|
+
* A operação utiliza `Uint8Array.prototype.copyWithin()` sobre o `dataBus`,
|
|
894
|
+
* portanto o retorno é o próprio `Uint8Array` que representa o barramento
|
|
895
|
+
* de dados.
|
|
896
|
+
*
|
|
897
|
+
* @param {number} source - Handler do bloco de origem.
|
|
898
|
+
* @param {number} destination - Handler do bloco de destino.
|
|
899
|
+
* @param {number} [slots=UNKNOWN] - Número máximo de elementos a copiar.
|
|
900
|
+
* `UNKNOWN` representa o valor sentinela utilizado para não impor um
|
|
901
|
+
* limite adicional.
|
|
902
|
+
* @returns {Uint8Array} O `dataBus` após a operação.
|
|
903
|
+
* @throws {Error} Se os handlers forem inválidos, estiverem corrompidos
|
|
904
|
+
* ou o bloco de destino estiver emprestado por withView().
|
|
905
|
+
*/
|
|
906
|
+
copy(source, destination, slots = UNKNOWN) {
|
|
761
907
|
const metaA = {};
|
|
762
908
|
const metaB = {};
|
|
763
909
|
this.extractMetadata(source, metaA);
|
|
764
|
-
this.extractMetadata(
|
|
910
|
+
this.extractMetadata(destination, metaB);
|
|
911
|
+
this.assertNotBorrowed(metaB.headerAddress);
|
|
765
912
|
const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
|
|
766
913
|
const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
|
|
767
914
|
const newOccupied = Math.max(metaB.occupied, slotsToCopy);
|
|
@@ -789,10 +936,11 @@ var Balloc = class {
|
|
|
789
936
|
* @param {number} start - Índice inicial da origem.
|
|
790
937
|
* @param {number} length - Número máximo de elementos a copiar.
|
|
791
938
|
* @returns {Uint8Array} O `dataBus` após a operação.
|
|
792
|
-
* @throws {Error} Se o handler for inválido ou estiver
|
|
939
|
+
* @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
|
|
793
940
|
*/
|
|
794
941
|
copyWithin(handler, target, start, length) {
|
|
795
942
|
const meta = this.extractMetadata(handler, this.metadata);
|
|
943
|
+
this.assertNotBorrowed(meta.headerAddress);
|
|
796
944
|
const slots = Math.floor(meta.byteCapacity / this.wordSize);
|
|
797
945
|
target = Math.trunc(target);
|
|
798
946
|
start = Math.trunc(start);
|
|
@@ -825,23 +973,21 @@ var Balloc = class {
|
|
|
825
973
|
* @param {number} source - Handler do bloco cujos elementos serão
|
|
826
974
|
* acrescentados.
|
|
827
975
|
* @returns {number} Número de elementos efetivamente acrescentados.
|
|
828
|
-
* @throws {Error} Se
|
|
976
|
+
* @throws {Error} Se os handlers forem inválidos, estiverem corrompidos
|
|
977
|
+
* ou o bloco de destino estiver emprestado por withView().
|
|
829
978
|
*/
|
|
830
979
|
append(target, source) {
|
|
831
980
|
const metaTarget = {};
|
|
832
981
|
const metaSource = {};
|
|
833
982
|
this.extractMetadata(target, metaTarget);
|
|
834
983
|
this.extractMetadata(source, metaSource);
|
|
984
|
+
this.assertNotBorrowed(metaTarget.headerAddress);
|
|
835
985
|
const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
|
|
836
986
|
const count = Math.min(available, metaSource.occupied);
|
|
837
987
|
if (count === 0) return 0;
|
|
838
988
|
const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
|
|
839
989
|
const sourceAddress = metaSource.dataAddress;
|
|
840
|
-
|
|
841
|
-
this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
|
|
842
|
-
} else {
|
|
843
|
-
this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
|
|
844
|
-
}
|
|
990
|
+
this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
|
|
845
991
|
this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
|
|
846
992
|
return count;
|
|
847
993
|
}
|
|
@@ -883,13 +1029,16 @@ var Balloc = class {
|
|
|
883
1029
|
* @param {number} source - Handler do primeiro bloco.
|
|
884
1030
|
* @param {number} target - Handler do segundo bloco.
|
|
885
1031
|
* @returns {void}
|
|
886
|
-
* @throws {Error} Se
|
|
1032
|
+
* @throws {Error} Se os handlers forem inválidos, estiverem corrompidos
|
|
1033
|
+
* ou qualquer um dos blocos estiver emprestado por withView().
|
|
887
1034
|
*/
|
|
888
1035
|
swap(source, target) {
|
|
889
1036
|
const metaA = {};
|
|
890
1037
|
const metaB = {};
|
|
891
1038
|
this.extractMetadata(source, metaA);
|
|
892
1039
|
this.extractMetadata(target, metaB);
|
|
1040
|
+
this.assertNotBorrowed(metaA.headerAddress);
|
|
1041
|
+
this.assertNotBorrowed(metaB.headerAddress);
|
|
893
1042
|
this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
|
|
894
1043
|
this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
|
|
895
1044
|
this.controlAdapter.setUint8(metaA.headerAddress + CAPACITY_OFFSET, metaB.capacityExponent);
|
|
@@ -979,6 +1128,37 @@ var Balloc = class {
|
|
|
979
1128
|
return handler;
|
|
980
1129
|
}
|
|
981
1130
|
// ============= UTILITÁRIOS ==============
|
|
1131
|
+
/**
|
|
1132
|
+
* Impede operações de modificação sobre um bloco emprestado.
|
|
1133
|
+
*
|
|
1134
|
+
* Verifica a flag VIEW_LOCK no header associado ao endereço informado.
|
|
1135
|
+
*
|
|
1136
|
+
* @param {number} headerAddress - Endereço do header no controlBus.
|
|
1137
|
+
* @returns {void}
|
|
1138
|
+
* @throws {Error} Se o bloco estiver emprestado por withView().
|
|
1139
|
+
* @private
|
|
1140
|
+
*/
|
|
1141
|
+
assertNotBorrowed(headerAddress) {
|
|
1142
|
+
if (this.controlBus[headerAddress + FLAGS_OFFSET] & VIEW_LOCK) {
|
|
1143
|
+
throw new Error("Block is borrowed");
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
/**
|
|
1147
|
+
* Impede operações que substituem ou remanejam o dataBus
|
|
1148
|
+
* enquanto existir algum segmento emprestado.
|
|
1149
|
+
*
|
|
1150
|
+
* @returns {void}
|
|
1151
|
+
* @throws {Error} Se existir algum bloco emprestado por withView().
|
|
1152
|
+
* @private
|
|
1153
|
+
*/
|
|
1154
|
+
assertNoActiveViews() {
|
|
1155
|
+
for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
|
|
1156
|
+
if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
|
|
1157
|
+
if (this.controlBus[i + FLAGS_OFFSET] & VIEW_LOCK) {
|
|
1158
|
+
throw new Error("Cannot remap memory while a block is borrowed");
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
982
1162
|
/**
|
|
983
1163
|
* [USO INTERNO]
|
|
984
1164
|
* Decodifica os metadados associados a um handler.
|