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.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 estiver corrompido.
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
- let headerAddress = handler >>> 0;
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,53 @@ 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, IS_LITTLE_ENDIAN);
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
- * Libera um bloco de memória.
215
- *
216
- * O header do bloco é invalidado pelo zeramento de seu cookie e seu
217
- * endereço é registrado para posterior reutilização. A região de dados
218
- * também é devolvida ao sistema de reciclagem, exceto quando o bloco está
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.
222
- *
223
- * @param {number} handler - Handler do bloco a ser liberado.
224
- * @returns {void}
225
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
226
- */
222
+ * Libera um bloco de memória.
223
+ *
224
+ * O header do bloco é invalidado pelo zeramento de seu cookie e seu
225
+ * endereço é registrado para posterior reutilização. A região de dados
226
+ * também é devolvida ao sistema de reciclagem, exceto quando o bloco está
227
+ * exatamente no topo do `dataBus`; nesse caso, o `dataPointer` é simplesmente
228
+ * retrocedido, eliminando a região sem criar uma entrada na lista de
229
+ * reciclagem.
230
+ *
231
+ * @param {number} handler - Handler do bloco a ser liberado.
232
+ * @returns {void}
233
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco
234
+ * estiver emprestado por withView().
235
+ */
227
236
  free(handler) {
228
237
  const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
229
- let headerAddress = handler >>> 0;
238
+ const headerAddress = handler >>> 0;
230
239
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
231
240
  const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
232
241
  const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
233
242
  if (cookie !== this.bakeCookie(headerAddress, generation)) {
234
243
  throw new Error("Invalid or corrupted handle");
235
244
  }
245
+ this.assertNotBorrowed(headerAddress);
236
246
  const blockSize = (1 << capacity >>> 0) * this.wordSize;
237
247
  this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
238
248
  if (this.echoPointer + 4 <= this.controlBus.byteLength) {
@@ -326,8 +336,10 @@ var Balloc = class {
326
336
  * do volume de bytes pertencente aos blocos vivos.
327
337
  *
328
338
  * @returns {void}
339
+ * @throws {Error} Se houver algum bloco emprestado por withView().
329
340
  */
330
341
  gc() {
342
+ this.assertNoActiveViews();
331
343
  const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
332
344
  this.recycle.clear();
333
345
  this.dataPointer = 0 >>> 0;
@@ -356,11 +368,13 @@ var Balloc = class {
356
368
  * para referenciar o novo armazenamento.
357
369
  *
358
370
  * @returns {void}
371
+ * @throws {Error} Se houver algum bloco emprestado por withView().
359
372
  * @throws {RangeError} Se a capacidade do `dataBus` já tiver excedido o
360
373
  * limite máximo suportado.
361
374
  * @private
362
375
  */
363
376
  grow() {
377
+ this.assertNoActiveViews();
364
378
  if (this.size > 2147483648) throw new RangeError("Data bus capacity exceeded");
365
379
  const newSize = this.size * 2 >>> 0;
366
380
  const newBuffer = this.dataBus.buffer.transfer(newSize);
@@ -403,10 +417,12 @@ var Balloc = class {
403
417
  * @param {number} value - Valor a ser inserido.
404
418
  * @returns {boolean} `true` se o valor foi inserido; `false` se o bloco
405
419
  * já estiver sem espaço disponível.
406
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
420
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
421
+ *
407
422
  */
408
423
  push(handler, value) {
409
424
  const meta = this.extractMetadata(handler, this.metadata);
425
+ this.assertNotBorrowed(meta.headerAddress);
410
426
  if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
411
427
  this.writer(meta.dataAddress + meta.occupied * this.wordSize, value, IS_LITTLE_ENDIAN);
412
428
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
@@ -422,10 +438,11 @@ var Balloc = class {
422
438
  * @param {number} handler - Handler do bloco.
423
439
  * @returns {number|undefined} Valor removido ou `undefined` se o bloco
424
440
  * estiver vazio.
425
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
441
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
426
442
  */
427
443
  pop(handler) {
428
444
  const meta = this.extractMetadata(handler, this.metadata);
445
+ this.assertNotBorrowed(meta.headerAddress);
429
446
  if (meta.occupied === 0) return void 0;
430
447
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
431
448
  return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
@@ -458,10 +475,11 @@ var Balloc = class {
458
475
  * @param {number} value - Valor a ser inserido.
459
476
  * @returns {boolean} `true` se o valor foi inserido; `false` se o bloco
460
477
  * estiver cheio.
461
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
478
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
462
479
  */
463
480
  nudge(handler, value) {
464
481
  const meta = this.extractMetadata(handler, this.metadata);
482
+ this.assertNotBorrowed(meta.headerAddress);
465
483
  if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
466
484
  this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
467
485
  this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
@@ -479,10 +497,11 @@ var Balloc = class {
479
497
  * @param {number} handler - Handler do bloco.
480
498
  * @returns {number|undefined} Primeiro valor removido ou `undefined` se o
481
499
  * bloco estiver vazio.
482
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
500
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
483
501
  */
484
502
  pull(handler) {
485
503
  const meta = this.extractMetadata(handler, this.metadata);
504
+ this.assertNotBorrowed(meta.headerAddress);
486
505
  if (meta.occupied === 0) return void 0;
487
506
  const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
488
507
  this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
@@ -522,6 +541,53 @@ var Balloc = class {
522
541
  const rawAddres = meta.dataAddress >>> this.wordShift;
523
542
  return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
524
543
  }
544
+ /**
545
+ * Localiza a primeira ocorrência de um elemento na sequência ocupada do bloco.
546
+ *
547
+ * A busca é realizada em ordem crescente de índices, utilizando a operação
548
+ * `indexOf` do TypedArray subjacente. A pesquisa considera exclusivamente
549
+ * os elementos ocupados, ignorando a capacidade não utilizada do bloco.
550
+ *
551
+ * A posição inicial da busca pode ser especificada por `fromIndex`,
552
+ * seguindo as regras de indexação de TypedArray.
553
+ *
554
+ * @param {number} handler - Handler do bloco.
555
+ * @param {number|bigint} searchElement - Elemento a ser localizado.
556
+ * @param {number} [fromIndex=0] - Índice a partir do qual a busca será iniciada.
557
+ * @returns {number} Índice da primeira ocorrência ou `-1` se o
558
+ * elemento não for encontrado ou se o bloco estiver vazio.
559
+ * @throws {Error} Se o handler for inválido ou estiver corrompido.
560
+ */
561
+ indexOf(handler, searchElement, fromIndex = 0) {
562
+ const meta = this.extractMetadata(handler, this.metadata);
563
+ if (meta.occupied === 0) return -1;
564
+ const rawAddres = meta.dataAddress >>> this.wordShift;
565
+ return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).indexOf(searchElement, fromIndex);
566
+ }
567
+ /**
568
+ * Localiza a última ocorrência de um elemento na sequência ocupada do bloco.
569
+ *
570
+ * A busca é realizada em ordem decrescente de índices, utilizando a operação
571
+ * `lastIndexOf` do TypedArray subjacente. A pesquisa considera exclusivamente
572
+ * os elementos ocupados, ignorando a capacidade não utilizada do bloco.
573
+ *
574
+ * A posição inicial da busca pode ser especificada por `fromIndex`,
575
+ * seguindo as regras de indexação de TypedArray. Por padrão, a busca começa
576
+ * no último elemento ocupado.
577
+ *
578
+ * @param {number} handler - Handler do bloco.
579
+ * @param {number|bigint} searchElement - Elemento a ser localizado.
580
+ * @param {number} [fromIndex=-1] - Índice a partir do qual a busca será iniciada.
581
+ * @returns {number} Índice da última ocorrência ou `-1` se o
582
+ * elemento não for encontrado ou se o bloco estiver vazio.
583
+ * @throws {Error} Se o handler for inválido ou estiver corrompido.
584
+ */
585
+ lastIndexOf(handler, searchElement, fromIndex = -1) {
586
+ const meta = this.extractMetadata(handler, this.metadata);
587
+ if (meta.occupied === 0) return -1;
588
+ const rawAddres = meta.dataAddress >>> this.wordShift;
589
+ return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).lastIndexOf(searchElement, fromIndex);
590
+ }
525
591
  /**
526
592
  * Retorna o elemento ocupado em um índice baseado em zero.
527
593
  *
@@ -550,10 +616,11 @@ var Balloc = class {
550
616
  * @param {number} value - Novo valor.
551
617
  * @returns {boolean} `true` se o valor foi gravado; `false` se o índice
552
618
  * estiver fora da região ocupada.
553
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
619
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
554
620
  */
555
621
  set(handler, index, value) {
556
622
  const meta = this.extractMetadata(handler, this.metadata);
623
+ this.assertNotBorrowed(meta.headerAddress);
557
624
  if (index < 0 || index >= meta.occupied) return false;
558
625
  this.writer(meta.dataAddress + index * this.wordSize, value, IS_LITTLE_ENDIAN);
559
626
  return true;
@@ -570,10 +637,11 @@ var Balloc = class {
570
637
  * @param {number} handler - Handler do bloco.
571
638
  * @param {number} [value=0] - Valor utilizado para preencher todos os slots.
572
639
  * @returns {void}
573
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
640
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
574
641
  */
575
642
  clear(handler, value = 0) {
576
643
  const meta = this.extractMetadata(handler, this.metadata);
644
+ this.assertNotBorrowed(meta.headerAddress);
577
645
  const slots = meta.byteCapacity / this.wordSize;
578
646
  const rawAddress = meta.dataAddress >>> this.wordShift;
579
647
  this.auxiliary.fill(value, rawAddress, rawAddress + slots);
@@ -596,12 +664,13 @@ var Balloc = class {
596
664
  * @param {number|null} [end=null] - Índice final, exclusivo. Quando
597
665
  * omitido ou `null`, utiliza a capacidade total do bloco.
598
666
  * @returns {void}
599
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
667
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
600
668
  * @throws {RangeError} Se `start` ou `end` estiver fora dos limites da
601
669
  * capacidade, ou se `start > end`.
602
670
  */
603
671
  fill(handler, value, start = 0, end = null) {
604
672
  const meta = this.extractMetadata(handler, this.metadata);
673
+ this.assertNotBorrowed(meta.headerAddress);
605
674
  const slots = meta.byteCapacity / this.wordSize;
606
675
  const lastIndex = end ?? slots;
607
676
  if (start > lastIndex) {
@@ -627,10 +696,11 @@ var Balloc = class {
627
696
  * @param {number} handler - Handler do bloco.
628
697
  * @param {number} value - Valor utilizado no preenchimento.
629
698
  * @returns {void}
630
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
699
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
631
700
  */
632
701
  fillAll(handler, value) {
633
702
  const meta = this.extractMetadata(handler, this.metadata);
703
+ this.assertNotBorrowed(meta.headerAddress);
634
704
  const rawAddress = meta.dataAddress >>> this.wordShift;
635
705
  const capacityElements = meta.byteCapacity / this.wordSize;
636
706
  this.auxiliary.fill(value, rawAddress, rawAddress + capacityElements);
@@ -651,14 +721,14 @@ var Balloc = class {
651
721
  * @param {number} handler - Handler do bloco.
652
722
  * @param {Array|TypedArray} data - Sequência de valores a copiar.
653
723
  * @returns {void}
654
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
724
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
655
725
  * @throws {TypeError} Se `data` não for uma `Array` nem uma `TypedArray`.
656
726
  */
657
727
  put(handler, data) {
658
728
  const meta = this.extractMetadata(handler, this.metadata);
729
+ this.assertNotBorrowed(meta.headerAddress);
659
730
  const rawAddress = meta.dataAddress >>> this.wordShift;
660
731
  const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
661
- meta.occupied = Math.max(length, meta.occupied);
662
732
  if (Array.isArray(data)) {
663
733
  this.auxiliary.set(data.slice(0, length), rawAddress);
664
734
  } else if (isTypedArray(data)) {
@@ -667,7 +737,7 @@ var Balloc = class {
667
737
  const actual = data?.constructor?.name ?? (data === null ? "null" : typeof data);
668
738
  throw new TypeError(`data must be Array or TypedArray, but ${actual} was given.`);
669
739
  }
670
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
740
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, Math.max(length, meta.occupied), IS_LITTLE_ENDIAN);
671
741
  }
672
742
  /**
673
743
  * Retorna uma cópia dos elementos atualmente ocupados pelo bloco.
@@ -692,6 +762,36 @@ var Balloc = class {
692
762
  }
693
763
  return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
694
764
  }
765
+ /**
766
+ * Executa um callback sobre uma view direta da região ocupada pelo bloco.
767
+ *
768
+ * A view compartilha o armazenamento interno do Balloc e não realiza cópia.
769
+ * O bloco fica protegido contra operações incompatíveis durante o callback.
770
+ *
771
+ * O callback deve ser síncrono. A view recebida não deve ser armazenada,
772
+ * retornada ou utilizada após o término do callback. Essa restrição
773
+ * também se aplica a subviews derivadas da view original.
774
+ *
775
+ * @param {number} handler - Handler do bloco.
776
+ * @param {Function} callback - Função que recebe a TypedArray compartilhada.
777
+ * @returns {*} Retorno produzido pelo callback.
778
+ * @throws {TypeError} Se callback não for uma função.
779
+ * @throws {Error} Se o handler for inválido ou já estiver emprestado.
780
+ */
781
+ withView(handler, callback) {
782
+ if (typeof callback !== "function") throw new TypeError("callback must be a function");
783
+ const meta = this.extractMetadata(handler, this.metadata);
784
+ const flagsAddress = meta.headerAddress + FLAGS_OFFSET;
785
+ const flags = this.controlBus[flagsAddress];
786
+ if (flags & VIEW_LOCK) throw new Error("Block is already borrowed");
787
+ this.controlBus[flagsAddress] = flags | VIEW_LOCK;
788
+ try {
789
+ const rawAddress = meta.dataAddress >>> this.wordShift;
790
+ return callback(this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied));
791
+ } finally {
792
+ this.controlBus[flagsAddress] &= ~VIEW_LOCK;
793
+ }
794
+ }
695
795
  // ======== CAPACIDADE EM SLOTS ==========
696
796
  /**
697
797
  * Retorna a capacidade física do bloco em bytes.
@@ -733,35 +833,52 @@ var Balloc = class {
733
833
  const meta = this.extractMetadata(handler, this.metadata);
734
834
  return 1 << meta.capacityExponent >>> 0;
735
835
  }
736
- // ==========Operações entre blocos=============
737
836
  /**
738
- * Copia elementos ocupados de um bloco para outro.
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`.
744
- *
745
- * A ocupação do destino é elevada, quando necessário, para abranger os
746
- * elementos copiados. A capacidade do destino não é alterada.
837
+ * Verifica se o bloco de memória atingiu sua capacidade de alocação.
747
838
  *
748
- * A operação utiliza `Uint8Array.prototype.copyWithin()` sobre o `dataBus`,
749
- * portanto o retorno é o próprio `Uint8Array` que representa o barramento
750
- * de dados.
839
+ * Um bloco é considerado cheio quando a quantidade de elementos ocupados
840
+ * é igual à sua capacidade total alocada, não restando posições disponíveis
841
+ * para armazenar novos elementos.
751
842
  *
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.
843
+ * @param {number} handler - Handler do bloco.
844
+ * @returns {boolean} `true` se o bloco estiver cheio; caso contrário, `false`.
845
+ * @throws {Error} Se o handler for inválido ou estiver corrompido.
759
846
  */
760
- copy(source, destiny, slots = UNKNOWN) {
847
+ isFull(handler) {
848
+ const meta = this.extractMetadata(handler, this.metadata);
849
+ return (1 << meta.capacityExponent >>> 0) - meta.occupied === 0;
850
+ }
851
+ // ==========Operações entre blocos=============
852
+ /**
853
+ * Copia elementos ocupados de um bloco para outro.
854
+ *
855
+ * A cópia começa no primeiro elemento de `source` e no primeiro slot de
856
+ * `destination`. A quantidade efetivamente copiada é limitada pelo número de
857
+ * elementos ocupados na origem, pela capacidade física do destino e pelo
858
+ * limite especificado em `slots`.
859
+ *
860
+ * A ocupação do destino é elevada, quando necessário, para abranger os
861
+ * elementos copiados. A capacidade do destino não é alterada.
862
+ *
863
+ * A operação utiliza `Uint8Array.prototype.copyWithin()` sobre o `dataBus`,
864
+ * portanto o retorno é o próprio `Uint8Array` que representa o barramento
865
+ * de dados.
866
+ *
867
+ * @param {number} source - Handler do bloco de origem.
868
+ * @param {number} destination - Handler do bloco de destino.
869
+ * @param {number} [slots=UNKNOWN] - Número máximo de elementos a copiar.
870
+ * `UNKNOWN` representa o valor sentinela utilizado para não impor um
871
+ * limite adicional.
872
+ * @returns {Uint8Array} O `dataBus` após a operação.
873
+ * @throws {Error} Se os handlers forem inválidos, estiverem corrompidos
874
+ * ou o bloco de destino estiver emprestado por withView().
875
+ */
876
+ copy(source, destination, slots = UNKNOWN) {
761
877
  const metaA = {};
762
878
  const metaB = {};
763
879
  this.extractMetadata(source, metaA);
764
- this.extractMetadata(destiny, metaB);
880
+ this.extractMetadata(destination, metaB);
881
+ this.assertNotBorrowed(metaB.headerAddress);
765
882
  const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
766
883
  const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
767
884
  const newOccupied = Math.max(metaB.occupied, slotsToCopy);
@@ -789,10 +906,11 @@ var Balloc = class {
789
906
  * @param {number} start - Índice inicial da origem.
790
907
  * @param {number} length - Número máximo de elementos a copiar.
791
908
  * @returns {Uint8Array} O `dataBus` após a operação.
792
- * @throws {Error} Se o handler for inválido ou estiver corrompido.
909
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco estiver emprestado por withView().
793
910
  */
794
911
  copyWithin(handler, target, start, length) {
795
912
  const meta = this.extractMetadata(handler, this.metadata);
913
+ this.assertNotBorrowed(meta.headerAddress);
796
914
  const slots = Math.floor(meta.byteCapacity / this.wordSize);
797
915
  target = Math.trunc(target);
798
916
  start = Math.trunc(start);
@@ -825,23 +943,21 @@ var Balloc = class {
825
943
  * @param {number} source - Handler do bloco cujos elementos serão
826
944
  * acrescentados.
827
945
  * @returns {number} Número de elementos efetivamente acrescentados.
828
- * @throws {Error} Se `target` ou `source` for inválido ou estiver corrompido.
946
+ * @throws {Error} Se os handlers forem inválidos, estiverem corrompidos
947
+ * ou o bloco de destino estiver emprestado por withView().
829
948
  */
830
949
  append(target, source) {
831
950
  const metaTarget = {};
832
951
  const metaSource = {};
833
952
  this.extractMetadata(target, metaTarget);
834
953
  this.extractMetadata(source, metaSource);
954
+ this.assertNotBorrowed(metaTarget.headerAddress);
835
955
  const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
836
956
  const count = Math.min(available, metaSource.occupied);
837
957
  if (count === 0) return 0;
838
958
  const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
839
959
  const sourceAddress = metaSource.dataAddress;
840
- if (target === source) {
841
- this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
842
- } else {
843
- this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
844
- }
960
+ this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
845
961
  this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
846
962
  return count;
847
963
  }
@@ -883,13 +999,16 @@ var Balloc = class {
883
999
  * @param {number} source - Handler do primeiro bloco.
884
1000
  * @param {number} target - Handler do segundo bloco.
885
1001
  * @returns {void}
886
- * @throws {Error} Se `source` ou `target` for inválido ou estiver corrompido.
1002
+ * @throws {Error} Se os handlers forem inválidos, estiverem corrompidos
1003
+ * ou qualquer um dos blocos estiver emprestado por withView().
887
1004
  */
888
1005
  swap(source, target) {
889
1006
  const metaA = {};
890
1007
  const metaB = {};
891
1008
  this.extractMetadata(source, metaA);
892
1009
  this.extractMetadata(target, metaB);
1010
+ this.assertNotBorrowed(metaA.headerAddress);
1011
+ this.assertNotBorrowed(metaB.headerAddress);
893
1012
  this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
894
1013
  this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
895
1014
  this.controlAdapter.setUint8(metaA.headerAddress + CAPACITY_OFFSET, metaB.capacityExponent);
@@ -979,6 +1098,37 @@ var Balloc = class {
979
1098
  return handler;
980
1099
  }
981
1100
  // ============= UTILITÁRIOS ==============
1101
+ /**
1102
+ * Impede operações de modificação sobre um bloco emprestado.
1103
+ *
1104
+ * Verifica a flag VIEW_LOCK no header associado ao endereço informado.
1105
+ *
1106
+ * @param {number} headerAddress - Endereço do header no controlBus.
1107
+ * @returns {void}
1108
+ * @throws {Error} Se o bloco estiver emprestado por withView().
1109
+ * @private
1110
+ */
1111
+ assertNotBorrowed(headerAddress) {
1112
+ if (this.controlBus[headerAddress + FLAGS_OFFSET] & VIEW_LOCK) {
1113
+ throw new Error("Block is borrowed");
1114
+ }
1115
+ }
1116
+ /**
1117
+ * Impede operações que substituem ou remanejam o dataBus
1118
+ * enquanto existir algum segmento emprestado.
1119
+ *
1120
+ * @returns {void}
1121
+ * @throws {Error} Se existir algum bloco emprestado por withView().
1122
+ * @private
1123
+ */
1124
+ assertNoActiveViews() {
1125
+ for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
1126
+ if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
1127
+ if (this.controlBus[i + FLAGS_OFFSET] & VIEW_LOCK) {
1128
+ throw new Error("Cannot remap memory while a block is borrowed");
1129
+ }
1130
+ }
1131
+ }
982
1132
  /**
983
1133
  * [USO INTERNO]
984
1134
  * Decodifica os metadados associados a um handler.