balloc 1.0.0 → 1.2.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/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": { 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 },
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
- * 0 4 8 9 10
61
- * [32bits address][32bits occupied][8bits capacity][8bits cookie][48bits reserved]
62
- *
63
- * Total: 4 + 4 + 1 + 1 + 6 = 16 bytes
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 = 9 >>> 0;
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
- constructor(size = 65535, bucketSize = "32u", metadataSize = 1024) {
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 estiver corrompido.
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) {
263
+
253
264
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
254
- let headerAddress = handler >>> 0;
255
-
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
- if (capacity >= 31) throw new AggregateError([new Error("Can´t reallocate handler.") ,new RangeError("Capacity has reached its limit.")], "Internal Error.");
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, IS_LITTLE_ENDIAN);
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,13 +297,15 @@ 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
  * Libera um bloco de memória.
300
310
  *
301
311
  * O header do bloco é invalidado pelo zeramento de seu cookie e seu
@@ -307,39 +317,37 @@ export default class Balloc {
307
317
  *
308
318
  * @param {number} handler - Handler do bloco a ser liberado.
309
319
  * @returns {void}
310
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
320
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco
321
+ * estiver emprestado por withView().
311
322
  */
312
323
  free(handler) {
324
+
313
325
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
314
- let headerAddress = handler >>> 0;
315
-
326
+ const headerAddress = handler >>> 0;
316
327
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
317
328
  const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
318
329
  const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
319
330
 
320
-
321
331
  if (cookie !== this.bakeCookie(headerAddress, generation)) {
322
332
  throw new Error("Invalid or corrupted handle");
323
333
  }
324
334
 
325
- const blockSize = (1 << capacity >>> 0) * this.wordSize;
335
+ this.assertNotBorrowed(headerAddress);
326
336
 
337
+ const blockSize = (1 << capacity >>> 0) * this.wordSize;
327
338
  this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
328
339
 
329
340
  if (this.echoPointer + 4 <= this.controlBus.byteLength) {
330
341
  this.controlAdapter.setUint32(this.echoPointer, headerAddress, IS_LITTLE_ENDIAN);
331
342
  this.echoPointer += 4;
332
- }
333
-
343
+ }
334
344
 
335
345
  if (dataAddress + blockSize === this.dataPointer) {
336
346
  this.dataPointer = dataAddress;
337
347
  } else {
338
348
  this.recyclePush(blockSize, dataAddress);
339
349
  }
340
-
341
350
  }
342
-
343
351
  // ========== RECICLAGEM ==========
344
352
 
345
353
  /**
@@ -407,6 +415,7 @@ export default class Balloc {
407
415
  }
408
416
 
409
417
  // ========== COLETA DE LIXO ==========
418
+
410
419
  /**
411
420
  * Compacta o `dataBus` por meio do algoritmo ReBump.
412
421
  *
@@ -430,20 +439,27 @@ export default class Balloc {
430
439
  * do volume de bytes pertencente aos blocos vivos.
431
440
  *
432
441
  * @returns {void}
442
+ * @throws {Error} Se houver algum bloco emprestado por withView().
433
443
  */
434
444
  gc() {
445
+ this.assertNoActiveViews();
446
+
435
447
  const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
436
448
  this.recycle.clear();
437
449
  this.dataPointer = 0 >>> 0;
438
- for (let i = 0; i < this.controlPointer; i+= HEADER_SIZE) {
450
+
451
+ for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
439
452
  if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
453
+
440
454
  const start = this.controlAdapter.getUint32(i + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
441
455
  const size = (1 << this.controlBus[i + CAPACITY_OFFSET] >>> 0) * this.wordSize;
442
456
  const end = start + size;
457
+
443
458
  newDataBus.set(this.dataBus.subarray(start, end), this.dataPointer);
444
459
  this.controlAdapter.setUint32(i + ADDRESS_OFFSET, this.dataPointer, IS_LITTLE_ENDIAN);
445
460
  this.dataPointer += size;
446
461
  }
462
+
447
463
  this.dataBus = newDataBus;
448
464
  this.dataAdapter = new DataView(this.dataBus.buffer);
449
465
  this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
@@ -452,6 +468,7 @@ export default class Balloc {
452
468
  }
453
469
 
454
470
  // ========== ESCALONAGEM ==========
471
+
455
472
  /**
456
473
  * [!!! USO INTERNO, NÃO USE NO SEU CÓDIGO !!!]
457
474
  * Expande o `dataBus` para o dobro de sua capacidade atual.
@@ -461,11 +478,14 @@ export default class Balloc {
461
478
  * para referenciar o novo armazenamento.
462
479
  *
463
480
  * @returns {void}
481
+ * @throws {Error} Se houver algum bloco emprestado por withView().
464
482
  * @throws {RangeError} Se a capacidade do `dataBus` já tiver excedido o
465
483
  * limite máximo suportado.
466
484
  * @private
467
485
  */
468
486
  grow() {
487
+ this.assertNoActiveViews();
488
+
469
489
  if (this.size > 0x80000000) throw new RangeError("Data bus capacity exceeded");
470
490
 
471
491
  const newSize = (this.size * 2) >>> 0;
@@ -514,16 +534,17 @@ export default class Balloc {
514
534
  * @param {number} value - Valor a ser inserido.
515
535
  * @returns {boolean} `true` se o valor foi inserido; `false` se o bloco
516
536
  * já estiver sem espaço disponível.
517
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
537
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
538
+ *
518
539
  */
519
540
  push(handler, value) {
520
-
521
541
  const meta = this.extractMetadata(handler, this.metadata);
542
+ this.assertNotBorrowed(meta.headerAddress);
522
543
 
523
544
  if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
524
545
 
525
- this.writer(meta.dataAddress + meta.occupied * this.wordSize , value, IS_LITTLE_ENDIAN);
526
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1,IS_LITTLE_ENDIAN);
546
+ this.writer(meta.dataAddress + meta.occupied * this.wordSize, value, IS_LITTLE_ENDIAN);
547
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
527
548
 
528
549
  return true;
529
550
  }
@@ -538,14 +559,15 @@ export default class Balloc {
538
559
  * @param {number} handler - Handler do bloco.
539
560
  * @returns {number|undefined} Valor removido ou `undefined` se o bloco
540
561
  * estiver vazio.
541
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
562
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
542
563
  */
543
564
  pop(handler) {
544
565
  const meta = this.extractMetadata(handler, this.metadata);
566
+ this.assertNotBorrowed(meta.headerAddress);
545
567
 
546
568
  if (meta.occupied === 0) return undefined;
547
569
 
548
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1,IS_LITTLE_ENDIAN);
570
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
549
571
  return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
550
572
  }
551
573
 
@@ -581,16 +603,17 @@ export default class Balloc {
581
603
  * @param {number} value - Valor a ser inserido.
582
604
  * @returns {boolean} `true` se o valor foi inserido; `false` se o bloco
583
605
  * estiver cheio.
584
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
606
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
585
607
  */
586
608
  nudge(handler, value) {
587
609
  const meta = this.extractMetadata(handler, this.metadata);
610
+ this.assertNotBorrowed(meta.headerAddress);
588
611
 
589
612
  if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
590
613
 
591
614
  this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
592
615
  this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
593
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1,IS_LITTLE_ENDIAN);
616
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
594
617
 
595
618
  return true;
596
619
  }
@@ -606,16 +629,18 @@ export default class Balloc {
606
629
  * @param {number} handler - Handler do bloco.
607
630
  * @returns {number|undefined} Primeiro valor removido ou `undefined` se o
608
631
  * bloco estiver vazio.
609
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
632
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
610
633
  */
611
634
  pull(handler) {
612
635
  const meta = this.extractMetadata(handler, this.metadata);
636
+ this.assertNotBorrowed(meta.headerAddress);
613
637
 
614
638
  if (meta.occupied === 0) return undefined;
615
639
 
616
640
  const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
617
641
  this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
618
642
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
643
+
619
644
  return result;
620
645
  }
621
646
 
@@ -632,7 +657,7 @@ export default class Balloc {
632
657
 
633
658
  if (meta.occupied === 0) return undefined;
634
659
 
635
- return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
660
+ return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
636
661
  }
637
662
 
638
663
  // ========== ACESSO ALEATÓRIO ==========
@@ -660,18 +685,74 @@ export default class Balloc {
660
685
  return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
661
686
  }
662
687
 
663
- /**
664
- * Retorna o elemento ocupado em um índice baseado em zero.
688
+ /**
689
+ * Localiza a primeira ocorrência de um elemento na sequência ocupada do bloco.
690
+ *
691
+ * A busca é realizada em ordem crescente de índices, utilizando a operação
692
+ * `indexOf` do TypedArray subjacente. A pesquisa considera exclusivamente
693
+ * os elementos ocupados, ignorando a capacidade não utilizada do bloco.
665
694
  *
666
- * Índices fora do intervalo `[0, occupied)` não são considerados erro e
667
- * resultam em `undefined`.
695
+ * A posição inicial da busca pode ser especificada por `fromIndex`,
696
+ * seguindo as regras de indexação de TypedArray.
668
697
  *
669
698
  * @param {number} handler - Handler do bloco.
670
- * @param {number} index - Índice baseado em zero do elemento.
671
- * @returns {number|undefined} Valor armazenado no índice ou `undefined` se
672
- * o índice estiver fora da região ocupada.
699
+ * @param {number|bigint} searchElement - Elemento a ser localizado.
700
+ * @param {number} [fromIndex=0] - Índice a partir do qual a busca será iniciada.
701
+ * @returns {number} Índice da primeira ocorrência ou `-1` se o
702
+ * elemento não for encontrado ou se o bloco estiver vazio.
673
703
  * @throws {Error} Se o handler for inválido ou estiver corrompido.
674
704
  */
705
+ indexOf(handler, searchElement, fromIndex = 0) {
706
+ const meta = this.extractMetadata(handler, this.metadata);
707
+
708
+ if (meta.occupied === 0) return -1;
709
+
710
+ const rawAddres = meta.dataAddress >>> this.wordShift;
711
+
712
+ return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).indexOf(searchElement, fromIndex);
713
+ }
714
+
715
+ /**
716
+ * Localiza a última ocorrência de um elemento na sequência ocupada do bloco.
717
+ *
718
+ * A busca é realizada em ordem decrescente de índices, utilizando a operação
719
+ * `lastIndexOf` do TypedArray subjacente. A pesquisa considera exclusivamente
720
+ * os elementos ocupados, ignorando a capacidade não utilizada do bloco.
721
+ *
722
+ * A posição inicial da busca pode ser especificada por `fromIndex`,
723
+ * seguindo as regras de indexação de TypedArray. Por padrão, a busca começa
724
+ * no último elemento ocupado.
725
+ *
726
+ * @param {number} handler - Handler do bloco.
727
+ * @param {number|bigint} searchElement - Elemento a ser localizado.
728
+ * @param {number} [fromIndex=-1] - Índice a partir do qual a busca será iniciada.
729
+ * @returns {number} Índice da última ocorrência ou `-1` se o
730
+ * elemento não for encontrado ou se o bloco estiver vazio.
731
+ * @throws {Error} Se o handler for inválido ou estiver corrompido.
732
+ */
733
+ lastIndexOf(handler, searchElement, fromIndex = -1) {
734
+ const meta = this.extractMetadata(handler, this.metadata);
735
+
736
+ if (meta.occupied === 0) return -1;
737
+
738
+ const rawAddres = meta.dataAddress >>> this.wordShift;
739
+
740
+ return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).lastIndexOf(searchElement, fromIndex);
741
+ }
742
+
743
+
744
+ /**
745
+ * Retorna o elemento ocupado em um índice baseado em zero.
746
+ *
747
+ * Índices fora do intervalo `[0, occupied)` não são considerados erro e
748
+ * resultam em `undefined`.
749
+ *
750
+ * @param {number} handler - Handler do bloco.
751
+ * @param {number} index - Índice baseado em zero do elemento.
752
+ * @returns {number|undefined} Valor armazenado no índice ou `undefined` se
753
+ * o índice estiver fora da região ocupada.
754
+ * @throws {Error} Se o handler for inválido ou estiver corrompido.
755
+ */
675
756
  get(handler, index) {
676
757
 
677
758
  const meta = this.extractMetadata(handler, this.metadata);
@@ -692,10 +773,11 @@ export default class Balloc {
692
773
  * @param {number} value - Novo valor.
693
774
  * @returns {boolean} `true` se o valor foi gravado; `false` se o índice
694
775
  * estiver fora da região ocupada.
695
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
776
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
696
777
  */
697
778
  set(handler, index, value) {
698
779
  const meta = this.extractMetadata(handler, this.metadata);
780
+ this.assertNotBorrowed(meta.headerAddress);
699
781
 
700
782
  if (index < 0 || index >= meta.occupied) return false;
701
783
 
@@ -716,15 +798,16 @@ export default class Balloc {
716
798
  * @param {number} handler - Handler do bloco.
717
799
  * @param {number} [value=0] - Valor utilizado para preencher todos os slots.
718
800
  * @returns {void}
719
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
801
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
720
802
  */
721
- clear(handler, value=0) {
803
+ clear(handler, value = 0) {
722
804
  const meta = this.extractMetadata(handler, this.metadata);
805
+ this.assertNotBorrowed(meta.headerAddress);
723
806
 
724
807
  const slots = meta.byteCapacity / this.wordSize;
725
808
  const rawAddress = meta.dataAddress >>> this.wordShift;
726
809
 
727
- this.auxiliary.fill(value, rawAddress, rawAddress + slots);
810
+ this.auxiliary.fill(value, rawAddress, rawAddress + slots);
728
811
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
729
812
  }
730
813
 
@@ -746,13 +829,14 @@ export default class Balloc {
746
829
  * @param {number|null} [end=null] - Índice final, exclusivo. Quando
747
830
  * omitido ou `null`, utiliza a capacidade total do bloco.
748
831
  * @returns {void}
749
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
832
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
750
833
  * @throws {RangeError} Se `start` ou `end` estiver fora dos limites da
751
834
  * capacidade, ou se `start > end`.
752
835
  */
753
836
  fill(handler, value, start = 0, end = null) {
754
837
  const meta = this.extractMetadata(handler, this.metadata);
755
-
838
+ this.assertNotBorrowed(meta.headerAddress);
839
+
756
840
  const slots = meta.byteCapacity / this.wordSize;
757
841
  const lastIndex = end ?? slots;
758
842
 
@@ -767,7 +851,6 @@ export default class Balloc {
767
851
  }
768
852
 
769
853
  const rawAddress = meta.dataAddress >>> this.wordShift;
770
-
771
854
  this.auxiliary.fill(value, rawAddress + start, rawAddress + lastIndex);
772
855
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, lastIndex, IS_LITTLE_ENDIAN);
773
856
  }
@@ -782,11 +865,12 @@ export default class Balloc {
782
865
  * @param {number} handler - Handler do bloco.
783
866
  * @param {number} value - Valor utilizado no preenchimento.
784
867
  * @returns {void}
785
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
868
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
786
869
  */
787
870
  fillAll(handler, value) {
788
871
  const meta = this.extractMetadata(handler, this.metadata);
789
-
872
+ this.assertNotBorrowed(meta.headerAddress);
873
+
790
874
  const rawAddress = meta.dataAddress >>> this.wordShift;
791
875
  const capacityElements = meta.byteCapacity / this.wordSize;
792
876
 
@@ -809,17 +893,16 @@ export default class Balloc {
809
893
  * @param {number} handler - Handler do bloco.
810
894
  * @param {Array|TypedArray} data - Sequência de valores a copiar.
811
895
  * @returns {void}
812
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
896
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
813
897
  * @throws {TypeError} Se `data` não for uma `Array` nem uma `TypedArray`.
814
898
  */
815
899
  put(handler, data) {
816
900
  const meta = this.extractMetadata(handler, this.metadata);
901
+ this.assertNotBorrowed(meta.headerAddress);
817
902
 
818
903
  const rawAddress = meta.dataAddress >>> this.wordShift;
819
904
  const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
820
905
 
821
- meta.occupied = Math.max(length, meta.occupied);
822
-
823
906
  if (Array.isArray(data)) {
824
907
  this.auxiliary.set(data.slice(0, length), rawAddress);
825
908
  } else if (isTypedArray(data)) {
@@ -827,35 +910,71 @@ export default class Balloc {
827
910
  } else {
828
911
  const actual = data?.constructor?.name ?? (data === null ? 'null' : typeof data);
829
912
  throw new TypeError(`data must be Array or TypedArray, but ${actual} was given.`);
830
- }
831
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
913
+ }
914
+
915
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, Math.max(length, meta.occupied), IS_LITTLE_ENDIAN);
832
916
  }
833
917
 
834
- /**
835
- * Retorna uma cópia dos elementos atualmente ocupados pelo bloco.
918
+ /**
919
+ * Retorna uma cópia dos elementos atualmente ocupados pelo bloco.
920
+ *
921
+ * O resultado é uma `TypedArray` do mesmo tipo configurado por
922
+ * `bucketSize`. A capacidade física não ocupada não é incluída no resultado.
923
+ *
924
+ * A operação não expõe diretamente o armazenamento interno: o método
925
+ * utiliza `TypedArray.prototype.slice()`, produzindo uma nova view com
926
+ * armazenamento independente.
927
+ *
928
+ * @param {number} handler - Handler do bloco.
929
+ * @returns {TypedArray} Cópia dos elementos ocupados pelo bloco. Quando
930
+ * o bloco está vazio, retorna uma `TypedArray` vazia do tipo configurado.
931
+ * @throws {Error} Se o handler for inválido ou estiver corrompido.
932
+ */
933
+ pick(handler) {
934
+ const meta = this.extractMetadata(handler, this.metadata);
935
+
936
+ const rawAddress = meta.dataAddress >>> this.wordShift;
937
+
938
+ if (meta.occupied === 0) {
939
+ return this.auxiliary.slice(rawAddress, rawAddress);
940
+ }
941
+
942
+ return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
943
+ }
944
+
945
+ /**
946
+ * Executa um callback sobre uma view direta da região ocupada pelo bloco.
836
947
  *
837
- * O resultado é uma `TypedArray` do mesmo tipo configurado por
838
- * `bucketSize`. A capacidade física não ocupada não é incluída no resultado.
948
+ * A view compartilha o armazenamento interno do Balloc e não realiza cópia.
949
+ * O bloco fica protegido contra operações incompatíveis durante o callback.
839
950
  *
840
- * A operação não expõe diretamente o armazenamento interno: o método
841
- * utiliza `TypedArray.prototype.slice()`, produzindo uma nova view com
842
- * armazenamento independente.
951
+ * O callback deve ser síncrono. A view recebida não deve ser armazenada,
952
+ * retornada ou utilizada após o término do callback. Essa restrição
953
+ * também se aplica a subviews derivadas da view original.
843
954
  *
844
955
  * @param {number} handler - Handler do bloco.
845
- * @returns {TypedArray} Cópia dos elementos ocupados pelo bloco. Quando
846
- * o bloco está vazio, retorna uma `TypedArray` vazia do tipo configurado.
847
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
956
+ * @param {Function} callback - Função que recebe a TypedArray compartilhada.
957
+ * @returns {*} Retorno produzido pelo callback.
958
+ * @throws {TypeError} Se callback não for uma função.
959
+ * @throws {Error} Se o handler for inválido ou já estiver emprestado.
848
960
  */
849
- pick(handler) {
961
+ withView(handler, callback) {
962
+ if (typeof callback !== "function") throw new TypeError("callback must be a function");
963
+
850
964
  const meta = this.extractMetadata(handler, this.metadata);
965
+ const flagsAddress = meta.headerAddress + FLAGS_OFFSET;
966
+ const flags = this.controlBus[flagsAddress];
851
967
 
852
- const rawAddress = meta.dataAddress >>> this.wordShift;
968
+ if (flags & VIEW_LOCK) throw new Error("Block is already borrowed");
853
969
 
854
- if (meta.occupied === 0) {
855
- return this.auxiliary.slice(rawAddress, rawAddress);
856
- }
970
+ this.controlBus[flagsAddress] = flags | VIEW_LOCK;
857
971
 
858
- return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
972
+ try {
973
+ const rawAddress = meta.dataAddress >>> this.wordShift;
974
+ return callback(this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied));
975
+ } finally {
976
+ this.controlBus[flagsAddress] &= ~VIEW_LOCK;
977
+ }
859
978
  }
860
979
 
861
980
  // ======== CAPACIDADE EM SLOTS ==========
@@ -883,7 +1002,7 @@ export default class Balloc {
883
1002
  * @returns {number} Número de elementos ocupados.
884
1003
  * @throws {Error} Se o handler for inválido ou estiver corrompido.
885
1004
  */
886
- occupied(handler){
1005
+ occupied(handler) {
887
1006
  const meta = this.extractMetadata(handler, this.metadata);
888
1007
  return meta.occupied;
889
1008
 
@@ -904,13 +1023,29 @@ export default class Balloc {
904
1023
  return 1 << meta.capacityExponent >>> 0;
905
1024
  }
906
1025
 
1026
+ /**
1027
+ * Verifica se o bloco de memória atingiu sua capacidade de alocação.
1028
+ *
1029
+ * Um bloco é considerado cheio quando a quantidade de elementos ocupados
1030
+ * é igual à sua capacidade total alocada, não restando posições disponíveis
1031
+ * para armazenar novos elementos.
1032
+ *
1033
+ * @param {number} handler - Handler do bloco.
1034
+ * @returns {boolean} `true` se o bloco estiver cheio; caso contrário, `false`.
1035
+ * @throws {Error} Se o handler for inválido ou estiver corrompido.
1036
+ */
1037
+ isFull(handler) {
1038
+ const meta = this.extractMetadata(handler, this.metadata);
1039
+ return (1 << meta.capacityExponent >>> 0) - meta.occupied === 0;
1040
+ }
1041
+
907
1042
  // ==========Operações entre blocos=============
908
1043
 
909
- /**
1044
+ /**
910
1045
  * Copia elementos ocupados de um bloco para outro.
911
1046
  *
912
1047
  * 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
1048
+ * `destination`. A quantidade efetivamente copiada é limitada pelo número de
914
1049
  * elementos ocupados na origem, pela capacidade física do destino e pelo
915
1050
  * limite especificado em `slots`.
916
1051
  *
@@ -922,28 +1057,29 @@ export default class Balloc {
922
1057
  * de dados.
923
1058
  *
924
1059
  * @param {number} source - Handler do bloco de origem.
925
- * @param {number} destiny - Handler do bloco de destino.
1060
+ * @param {number} destination - Handler do bloco de destino.
926
1061
  * @param {number} [slots=UNKNOWN] - Número máximo de elementos a copiar.
927
1062
  * `UNKNOWN` representa o valor sentinela utilizado para não impor um
928
1063
  * limite adicional.
929
1064
  * @returns {Uint8Array} O `dataBus` após a operação.
930
- * @throws {Error} Se `source` ou `destiny` for inválido ou estiver corrompido.
1065
+ * @throws {Error} Se os handlers forem inválidos, estiverem corrompidos
1066
+ * ou o bloco de destino estiver emprestado por withView().
931
1067
  */
932
- copy(source, destiny, slots = UNKNOWN){
1068
+ copy(source, destination, slots = UNKNOWN) {
933
1069
  /** @type {Metadata} */
934
1070
  const metaA = {};
935
1071
  /** @type {Metadata} */
936
1072
  const metaB = {};
937
1073
 
938
1074
  this.extractMetadata(source, metaA);
939
- this.extractMetadata(destiny, metaB);
1075
+ this.extractMetadata(destination, metaB);
1076
+ this.assertNotBorrowed(metaB.headerAddress);
940
1077
 
941
1078
  const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
942
1079
  const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
943
1080
  const newOccupied = Math.max(metaB.occupied, slotsToCopy);
944
1081
 
945
1082
  this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
946
-
947
1083
  return this.dataBus.copyWithin(metaB.dataAddress, metaA.dataAddress, metaA.dataAddress + slotsToCopy * this.wordSize);
948
1084
  }
949
1085
 
@@ -968,12 +1104,13 @@ export default class Balloc {
968
1104
  * @param {number} start - Índice inicial da origem.
969
1105
  * @param {number} length - Número máximo de elementos a copiar.
970
1106
  * @returns {Uint8Array} O `dataBus` após a operação.
971
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
1107
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
972
1108
  */
973
1109
  copyWithin(handler, target, start, length) {
974
1110
  const meta = this.extractMetadata(handler, this.metadata);
975
- const slots = Math.floor(meta.byteCapacity / this.wordSize);
1111
+ this.assertNotBorrowed(meta.headerAddress);
976
1112
 
1113
+ const slots = Math.floor(meta.byteCapacity / this.wordSize);
977
1114
  target = Math.trunc(target);
978
1115
  start = Math.trunc(start);
979
1116
  length = Math.trunc(length);
@@ -981,12 +1118,9 @@ export default class Balloc {
981
1118
  if (target < 0) target += slots;
982
1119
  if (start < 0) start += slots;
983
1120
 
984
- // Clampa índices dentro dos limites da capacidade
985
1121
  target = Math.max(0, Math.min(target, slots));
986
1122
  start = Math.max(0, Math.min(start, slots));
987
1123
 
988
- // Limita a cópia à capacidade disponível a partir do target
989
- // e aos elementos efetivamente ocupados a partir de start
990
1124
  const maxRead = Math.max(0, meta.occupied - start);
991
1125
  const maxWrite = slots - target;
992
1126
  length = Math.max(0, Math.min(length, maxRead, maxWrite));
@@ -995,9 +1129,8 @@ export default class Balloc {
995
1129
 
996
1130
  const targetAddress = meta.dataAddress + target * this.wordSize;
997
1131
  const sourceAddress = meta.dataAddress + start * this.wordSize;
998
-
999
- // Atualiza a ocupação caso a cópia expanda o topo ocupado do bloco
1000
1132
  const newOccupied = Math.max(meta.occupied, target + length);
1133
+
1001
1134
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
1002
1135
 
1003
1136
  return this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + length * this.wordSize);
@@ -1017,7 +1150,8 @@ export default class Balloc {
1017
1150
  * @param {number} source - Handler do bloco cujos elementos serão
1018
1151
  * acrescentados.
1019
1152
  * @returns {number} Número de elementos efetivamente acrescentados.
1020
- * @throws {Error} Se `target` ou `source` for inválido ou estiver corrompido.
1153
+ * @throws {Error} Se os handlers forem inválidos, estiverem corrompidos
1154
+ * ou o bloco de destino estiver emprestado por withView().
1021
1155
  */
1022
1156
  append(target, source) {
1023
1157
  const metaTarget = {};
@@ -1025,6 +1159,7 @@ export default class Balloc {
1025
1159
 
1026
1160
  this.extractMetadata(target, metaTarget);
1027
1161
  this.extractMetadata(source, metaSource);
1162
+ this.assertNotBorrowed(metaTarget.headerAddress);
1028
1163
 
1029
1164
  const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
1030
1165
  const count = Math.min(available, metaSource.occupied);
@@ -1034,11 +1169,7 @@ export default class Balloc {
1034
1169
  const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
1035
1170
  const sourceAddress = metaSource.dataAddress;
1036
1171
 
1037
- if (target === source) {
1038
- this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
1039
- } else {
1040
- this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
1041
- }
1172
+ this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
1042
1173
 
1043
1174
  this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
1044
1175
 
@@ -1087,17 +1218,21 @@ export default class Balloc {
1087
1218
  * @param {number} source - Handler do primeiro bloco.
1088
1219
  * @param {number} target - Handler do segundo bloco.
1089
1220
  * @returns {void}
1090
- * @throws {Error} Se `source` ou `target` for inválido ou estiver corrompido.
1221
+ * @throws {Error} Se os handlers forem inválidos, estiverem corrompidos
1222
+ * ou qualquer um dos blocos estiver emprestado por withView().
1091
1223
  */
1092
1224
  swap(source, target) {
1093
1225
  /** @type {Metadata} */
1094
1226
  const metaA = {};
1095
1227
  /** @type {Metadata} */
1096
1228
  const metaB = {};
1097
-
1229
+
1098
1230
  this.extractMetadata(source, metaA);
1099
1231
  this.extractMetadata(target, metaB);
1100
1232
 
1233
+ this.assertNotBorrowed(metaA.headerAddress);
1234
+ this.assertNotBorrowed(metaB.headerAddress);
1235
+
1101
1236
  this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
1102
1237
  this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
1103
1238
 
@@ -1106,7 +1241,7 @@ export default class Balloc {
1106
1241
 
1107
1242
  this.controlAdapter.setUint32(metaA.headerAddress + OCCUPIED_OFFSET, metaB.occupied, IS_LITTLE_ENDIAN);
1108
1243
  this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, metaA.occupied, IS_LITTLE_ENDIAN);
1109
- }
1244
+ }
1110
1245
 
1111
1246
 
1112
1247
  // ============= SERIALIZAÇÃO ==============
@@ -1212,6 +1347,39 @@ export default class Balloc {
1212
1347
 
1213
1348
  // ============= UTILITÁRIOS ==============
1214
1349
 
1350
+ /**
1351
+ * Impede operações de modificação sobre um bloco emprestado.
1352
+ *
1353
+ * Verifica a flag VIEW_LOCK no header associado ao endereço informado.
1354
+ *
1355
+ * @param {number} headerAddress - Endereço do header no controlBus.
1356
+ * @returns {void}
1357
+ * @throws {Error} Se o bloco estiver emprestado por withView().
1358
+ * @private
1359
+ */
1360
+ assertNotBorrowed(headerAddress) {
1361
+ if (this.controlBus[headerAddress + FLAGS_OFFSET] & VIEW_LOCK) {
1362
+ throw new Error("Block is borrowed");
1363
+ }
1364
+ }
1365
+
1366
+ /**
1367
+ * Impede operações que substituem ou remanejam o dataBus
1368
+ * enquanto existir algum segmento emprestado.
1369
+ *
1370
+ * @returns {void}
1371
+ * @throws {Error} Se existir algum bloco emprestado por withView().
1372
+ * @private
1373
+ */
1374
+ assertNoActiveViews() {
1375
+ for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
1376
+ if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
1377
+ if (this.controlBus[i + FLAGS_OFFSET] & VIEW_LOCK) {
1378
+ throw new Error("Cannot remap memory while a block is borrowed");
1379
+ }
1380
+ }
1381
+ }
1382
+
1215
1383
  /**
1216
1384
  * [USO INTERNO]
1217
1385
  * Decodifica os metadados associados a um handler.
@@ -1243,7 +1411,7 @@ export default class Balloc {
1243
1411
  }
1244
1412
 
1245
1413
  out.dataAddress = this.controlAdapter.getUint32(out.headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
1246
- out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1414
+ out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1247
1415
  out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
1248
1416
  out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
1249
1417