balloc 1.2.0 → 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/src/jp/balloc.mjs CHANGED
@@ -254,7 +254,7 @@ export default class Balloc {
254
254
  * @throws {AggregateError} 容量がサポートされている最大制限に達した場合。
255
255
  */
256
256
  realloc(handler) {
257
-
257
+
258
258
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
259
259
  const headerAddress = handler >>> 0;
260
260
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
@@ -299,22 +299,47 @@ export default class Balloc {
299
299
  this.recyclePush(oldBlockSize, dataAddress);
300
300
  }
301
301
 
302
- /**
303
- * メモリブロックを解放します。
302
+ /**
303
+ * ブロックのアドレスとハンドルを維持したまま、使用中の要素を格納できる
304
+ * 最小の2のべき乗の容量まで縮小します。
304
305
  *
305
- * ブロックのヘッダーはクッキーをゼロに設定することで無効化され、
306
- * そのアドレスは後で再利用するために登録されます。ブロックが `dataBus` の
307
- * 正確なトップにある場合を除き、データ領域も再利用システムに戻されます。
308
- * トップにある場合は、`dataPointer` が単に巻き戻され、再利用リストに
309
- * エントリを作成せずに領域が破棄されます。
306
+ * ブロックが dataBus のトップにある場合、dataPointer を後退させます。
307
+ * それ以外の場合、解放された末尾領域を2のべき乗の領域に分割し、
308
+ * 各領域を再利用リストに戻します。
310
309
  *
311
- * @param {number} handler - 解放するブロックのハンドル。
310
+ * @param {number} handler - 縮小するブロックのハンドル。
312
311
  * @returns {void}
313
- * @throws {Error} ハンドルが無効、破損している場合、またはブロックが
314
- * withView() によって借用されている場合。
312
+ * @throws {Error} ハンドルが無効または破損している場合、あるいは
313
+ * withView() によってブロックが借用されている場合。
315
314
  */
315
+ shrink(handler) {
316
+ const meta = this.extractMetadata(handler, this.metadata);
317
+ this.assertNotBorrowed(meta.headerAddress);
318
+
319
+ const newCapacity = Math.max(1, 32 - Math.clz32(Math.max(2, meta.occupied) - 1));
320
+ if (newCapacity >= meta.capacityExponent) return;
321
+
322
+ const oldBlockSize = meta.byteCapacity;
323
+ const newBlockSize = (2 ** newCapacity) * this.wordSize;
324
+ const oldEnd = meta.dataAddress + oldBlockSize;
325
+
326
+ this.controlAdapter.setUint8(meta.headerAddress + CAPACITY_OFFSET, newCapacity);
327
+
328
+ if (oldEnd === this.dataPointer) {
329
+ this.dataPointer = meta.dataAddress + newBlockSize;
330
+ return;
331
+ }
332
+
333
+ let address = meta.dataAddress + newBlockSize;
334
+ for (let exponent = newCapacity; exponent < meta.capacityExponent; exponent++) {
335
+ const segmentSize = (2 ** exponent) * this.wordSize;
336
+ this.recyclePush(segmentSize, address);
337
+ address += segmentSize;
338
+ }
339
+ }
340
+
316
341
  free(handler) {
317
-
342
+
318
343
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
319
344
  const headerAddress = handler >>> 0;
320
345
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
@@ -513,7 +538,6 @@ export default class Balloc {
513
538
  * 要素は、最後尾の占有要素の直後の最初の空き位置に書き込まれます。
514
539
  * ブロックの占有数は、その容量内に空きスペースが存在する場合にのみインクリメントされます。
515
540
  *
516
- * @param {number} handler - ブロックのハンドル。
517
541
  * @param {number} value - 挿入する値。
518
542
  * @returns {boolean} 値が挿入された場合は `true`、ブロックに利用可能な
519
543
  * スペースがない場合は `false`。
@@ -912,27 +936,45 @@ export default class Balloc {
912
936
  * サブビューにも適用されます。
913
937
  *
914
938
  * @param {number} handler - ブロックのハンドル。
915
- * @param {Function} callback - 共有された TypedArray を受け取る関数。
939
+ * @param {...(number|Function)} args - 1つ以上のブロックハンドルと、その後に続くコールバック。
916
940
  * @returns {*} コールバックによって生成された戻り値。
917
- * @throws {TypeError} コールバックが関数ではない場合。
918
- * @throws {Error} ハンドルが無効であるか、すでに借用されている場合。
941
+ * @throws {TypeError} ハンドルが指定されていない場合、またはコールバックが関数ではない場合。
942
+ * @throws {Error} いずれかのハンドルが無効、重複、または借用中の場合。
919
943
  */
920
- withView(handler, callback) {
944
+ withView(...args) {
945
+ if (args.length < 2) throw new TypeError("At least one handler and one callback are required");
946
+
947
+ const callback = args.pop();
921
948
  if (typeof callback !== "function") throw new TypeError("callback must be a function");
922
949
 
923
- const meta = this.extractMetadata(handler, this.metadata);
924
- const flagsAddress = meta.headerAddress + FLAGS_OFFSET;
925
- const flags = this.controlBus[flagsAddress];
950
+ const handlers = args;
951
+ const metadata = handlers.map(handler => this.extractMetadata(handler, {}));
952
+ const headers = metadata.map(meta => meta.headerAddress);
953
+
954
+ if (new Set(headers).size !== headers.length) throw new Error("Duplicate handler");
926
955
 
927
- if (flags & VIEW_LOCK) throw new Error("Block is already borrowed");
956
+ const flags = headers.map(header => this.controlBus[header + FLAGS_OFFSET]);
928
957
 
929
- this.controlBus[flagsAddress] = flags | VIEW_LOCK;
958
+ if (flags.some(flag => flag & VIEW_LOCK)) throw new Error("Block is already borrowed");
959
+
960
+ let acquiredCount = 0;
930
961
 
931
962
  try {
932
- const rawAddress = meta.dataAddress >>> this.wordShift;
933
- return callback(this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied));
963
+ for (const header of headers) {
964
+ this.controlBus[header + FLAGS_OFFSET] |= VIEW_LOCK;
965
+ acquiredCount++;
966
+ }
967
+
968
+ const views = metadata.map(meta => {
969
+ const rawAddress = meta.dataAddress >>> this.wordShift;
970
+ return this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied);
971
+ });
972
+
973
+ return callback(...views);
934
974
  } finally {
935
- this.controlBus[flagsAddress] &= ~VIEW_LOCK;
975
+ for (let i = 0; i < acquiredCount; i++) {
976
+ this.controlBus[headers[i] + FLAGS_OFFSET] &= ~VIEW_LOCK;
977
+ }
936
978
  }
937
979
  }
938
980
 
@@ -997,27 +1039,27 @@ export default class Balloc {
997
1039
 
998
1040
  // ========== ブロック間の操作 (Operations between blocks)=============
999
1041
 
1000
- /**
1001
- * あるブロックから別のブロックへ占有要素をコピーします。
1002
- *
1003
- * コピーは `source` の最初の要素と `destination` の最初のスロットから開始されます。
1004
- * 実際にコピーされる量は、ソース内の占有要素数、宛先の物理的容量、および
1005
- * `slots` で指定された制限によって制限されます。
1006
- *
1007
- * 必要に応じて、コピーされた要素をカバーするように宛先の占有数が引き上げられます。
1008
- * 宛先の容量は変更されません。
1009
- *
1010
- * この操作では `dataBus` に対して `Uint8Array.prototype.copyWithin()` を使用するため、
1011
- * 戻り値はデータバスを表す `Uint8Array` 自体になります。
1012
- *
1013
- * @param {number} source - コピー元ブロックのハンドル。
1014
- * @param {number} destination - コピー先ブロックのハンドル。
1015
- * @param {number} [slots=UNKNOWN] - コピーする最大要素数。
1016
- * `UNKNOWN` は、追加の制限を課さないために使用されるセンチネル値を表します。
1017
- * @returns {Uint8Array} 操作後の `dataBus`。
1018
- * @throws {Error} ハンドルが無効、破損している場合、
1019
- * またはコピー先ブロックが withView() によって借用されている場合。
1020
- */
1042
+ /**
1043
+ * あるブロックから別のブロックへ占有要素をコピーします。
1044
+ *
1045
+ * コピーは `source` の最初の要素と `destination` の最初のスロットから開始されます。
1046
+ * 実際にコピーされる量は、ソース内の占有要素数、宛先の物理的容量、および
1047
+ * `slots` で指定された制限によって制限されます。
1048
+ *
1049
+ * 必要に応じて、コピーされた要素をカバーするように宛先の占有数が引き上げられます。
1050
+ * 宛先の容量は変更されません。
1051
+ *
1052
+ * この操作では `dataBus` に対して `Uint8Array.prototype.copyWithin()` を使用するため、
1053
+ * 戻り値はデータバスを表す `Uint8Array` 自体になります。
1054
+ *
1055
+ * @param {number} source - コピー元ブロックのハンドル。
1056
+ * @param {number} destination - コピー先ブロックのハンドル。
1057
+ * @param {number} [slots=UNKNOWN] - コピーする最大要素数。
1058
+ * `UNKNOWN` は、追加の制限を課さないために使用されるセンチネル値を表します。
1059
+ * @returns {Uint8Array} 操作後の `dataBus`。
1060
+ * @throws {Error} ハンドルが無効、破損している場合、
1061
+ * またはコピー先ブロックが withView() によって借用されている場合。
1062
+ */
1021
1063
  copy(source, destination, slots = UNKNOWN) {
1022
1064
  /** @type {Metadata} */
1023
1065
  const metaA = {};
package/src/pt/balloc.cjs CHANGED
@@ -219,20 +219,38 @@ var Balloc = class {
219
219
  this.recyclePush(oldBlockSize, dataAddress);
220
220
  }
221
221
  /**
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
- */
222
+ * Reduz um bloco à menor capacidade em potência de dois capaz de comportar
223
+ * seus elementos ocupados, preservando seu endereço e handler.
224
+ *
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.
228
+ *
229
+ * @param {number} handler - Handler do bloco a ser reduzido.
230
+ * @returns {void}
231
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou estiver
232
+ * emprestado por withView().
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
+ }
236
254
  free(handler) {
237
255
  const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
238
256
  const headerAddress = handler >>> 0;
@@ -772,24 +790,36 @@ var Balloc = class {
772
790
  * retornada ou utilizada após o término do callback. Essa restrição
773
791
  * também se aplica a subviews derivadas da view original.
774
792
  *
775
- * @param {number} handler - Handler do bloco.
776
- * @param {Function} callback - Função que recebe a TypedArray compartilhada.
793
+ * @param {...number|Function} args - Um ou mais handlers, seguidos pelo callback.
777
794
  * @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.
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.
780
797
  */
781
- withView(handler, callback) {
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();
782
801
  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;
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;
788
809
  try {
789
- const rawAddress = meta.dataAddress >>> this.wordShift;
790
- return callback(this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied));
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);
791
819
  } finally {
792
- this.controlBus[flagsAddress] &= ~VIEW_LOCK;
820
+ for (let i = 0; i < acquiredCount; i++) {
821
+ this.controlBus[headers[i] + FLAGS_OFFSET] &= ~VIEW_LOCK;
822
+ }
793
823
  }
794
824
  }
795
825
  // ======== CAPACIDADE EM SLOTS ==========