balloc 1.2.0 → 1.3.1

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
@@ -90,6 +90,7 @@ const CLAMP_11BITS = 0x7FF >>> 0;
90
90
  * @property {number} generation - ハンドルが属する世代。
91
91
  * @property {number} headerAddress - controlBus内におけるヘッダーのアドレス。
92
92
  * @property {number} occupied - ブロック内の占有要素数。
93
+ * @property {number} borrowed - ブロックが withView() によって借用されているかどうかを示すフラグ。
93
94
  */
94
95
 
95
96
  /**
@@ -254,7 +255,7 @@ export default class Balloc {
254
255
  * @throws {AggregateError} 容量がサポートされている最大制限に達した場合。
255
256
  */
256
257
  realloc(handler) {
257
-
258
+
258
259
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
259
260
  const headerAddress = handler >>> 0;
260
261
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
@@ -299,22 +300,47 @@ export default class Balloc {
299
300
  this.recyclePush(oldBlockSize, dataAddress);
300
301
  }
301
302
 
302
- /**
303
- * メモリブロックを解放します。
303
+ /**
304
+ * ブロックのアドレスとハンドルを維持したまま、使用中の要素を格納できる
305
+ * 最小の2のべき乗の容量まで縮小します。
304
306
  *
305
- * ブロックのヘッダーはクッキーをゼロに設定することで無効化され、
306
- * そのアドレスは後で再利用するために登録されます。ブロックが `dataBus` の
307
- * 正確なトップにある場合を除き、データ領域も再利用システムに戻されます。
308
- * トップにある場合は、`dataPointer` が単に巻き戻され、再利用リストに
309
- * エントリを作成せずに領域が破棄されます。
307
+ * ブロックが dataBus のトップにある場合、dataPointer を後退させます。
308
+ * それ以外の場合、解放された末尾領域を2のべき乗の領域に分割し、
309
+ * 各領域を再利用リストに戻します。
310
310
  *
311
- * @param {number} handler - 解放するブロックのハンドル。
311
+ * @param {number} handler - 縮小するブロックのハンドル。
312
312
  * @returns {void}
313
- * @throws {Error} ハンドルが無効、破損している場合、またはブロックが
314
- * withView() によって借用されている場合。
313
+ * @throws {Error} ハンドルが無効または破損している場合、あるいは
314
+ * withView() によってブロックが借用されている場合。
315
315
  */
316
+ shrink(handler) {
317
+ const meta = this.extractMetadata(handler, this.metadata);
318
+ this.assertNotBorrowed(meta.headerAddress);
319
+
320
+ const newCapacity = Math.max(1, 32 - Math.clz32(Math.max(2, meta.occupied) - 1));
321
+ if (newCapacity >= meta.capacityExponent) return;
322
+
323
+ const oldBlockSize = meta.byteCapacity;
324
+ const newBlockSize = (2 ** newCapacity) * this.wordSize;
325
+ const oldEnd = meta.dataAddress + oldBlockSize;
326
+
327
+ this.controlAdapter.setUint8(meta.headerAddress + CAPACITY_OFFSET, newCapacity);
328
+
329
+ if (oldEnd === this.dataPointer) {
330
+ this.dataPointer = meta.dataAddress + newBlockSize;
331
+ return;
332
+ }
333
+
334
+ let address = meta.dataAddress + newBlockSize;
335
+ for (let exponent = newCapacity; exponent < meta.capacityExponent; exponent++) {
336
+ const segmentSize = (2 ** exponent) * this.wordSize;
337
+ this.recyclePush(segmentSize, address);
338
+ address += segmentSize;
339
+ }
340
+ }
341
+
316
342
  free(handler) {
317
-
343
+
318
344
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
319
345
  const headerAddress = handler >>> 0;
320
346
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
@@ -513,7 +539,6 @@ export default class Balloc {
513
539
  * 要素は、最後尾の占有要素の直後の最初の空き位置に書き込まれます。
514
540
  * ブロックの占有数は、その容量内に空きスペースが存在する場合にのみインクリメントされます。
515
541
  *
516
- * @param {number} handler - ブロックのハンドル。
517
542
  * @param {number} value - 挿入する値。
518
543
  * @returns {boolean} 値が挿入された場合は `true`、ブロックに利用可能な
519
544
  * スペースがない場合は `false`。
@@ -912,27 +937,39 @@ export default class Balloc {
912
937
  * サブビューにも適用されます。
913
938
  *
914
939
  * @param {number} handler - ブロックのハンドル。
915
- * @param {Function} callback - 共有された TypedArray を受け取る関数。
940
+ * @param {...(number|Function)} args - 1つ以上のブロックハンドルと、その後に続くコールバック。
916
941
  * @returns {*} コールバックによって生成された戻り値。
917
- * @throws {TypeError} コールバックが関数ではない場合。
918
- * @throws {Error} ハンドルが無効であるか、すでに借用されている場合。
942
+ * @throws {TypeError} ハンドルが指定されていない場合、またはコールバックが関数ではない場合。
943
+ * @throws {Error} いずれかのハンドルが無効、重複、または借用中の場合。
919
944
  */
920
- withView(handler, callback) {
945
+ withView(...args) {
946
+ if (args.length < 2) throw new TypeError("At least one handler and one callback are required");
947
+ const lastIndex = args.length - 1;
948
+ const callback = args[lastIndex];
921
949
  if (typeof callback !== "function") throw new TypeError("callback must be a function");
922
950
 
923
- const meta = this.extractMetadata(handler, this.metadata);
924
- const flagsAddress = meta.headerAddress + FLAGS_OFFSET;
925
- const flags = this.controlBus[flagsAddress];
926
-
927
- if (flags & VIEW_LOCK) throw new Error("Block is already borrowed");
928
-
929
- this.controlBus[flagsAddress] = flags | VIEW_LOCK;
951
+ const lookup = Object.create(null);
952
+ const views = [];
930
953
 
931
954
  try {
932
- const rawAddress = meta.dataAddress >>> this.wordShift;
933
- return callback(this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied));
955
+ for(let i = 0; i < lastIndex; i++) {
956
+ const metadata = this.extractMetadata(args[i], {});
957
+
958
+
959
+ if (Object.hasOwn(lookup, metadata.headerAddress)) throw new Error("Duplicate handler");
960
+ if (metadata.borrowed) throw new Error("Block is already borrowed");
961
+
962
+ this.controlBus[metadata.headerAddress + FLAGS_OFFSET] |= VIEW_LOCK;
963
+
964
+ const rawAddress = metadata.dataAddress >>> this.wordShift;
965
+ lookup[metadata.headerAddress] = metadata.headerAddress;
966
+ views.push(this.auxiliary.subarray(rawAddress, rawAddress + metadata.occupied))
967
+ }
968
+ return callback(...views);
934
969
  } finally {
935
- this.controlBus[flagsAddress] &= ~VIEW_LOCK;
970
+ for (const key in lookup) {
971
+ this.controlBus[lookup[key] + FLAGS_OFFSET] &= ~VIEW_LOCK;
972
+ }
936
973
  }
937
974
  }
938
975
 
@@ -997,27 +1034,27 @@ export default class Balloc {
997
1034
 
998
1035
  // ========== ブロック間の操作 (Operations between blocks)=============
999
1036
 
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
- */
1037
+ /**
1038
+ * あるブロックから別のブロックへ占有要素をコピーします。
1039
+ *
1040
+ * コピーは `source` の最初の要素と `destination` の最初のスロットから開始されます。
1041
+ * 実際にコピーされる量は、ソース内の占有要素数、宛先の物理的容量、および
1042
+ * `slots` で指定された制限によって制限されます。
1043
+ *
1044
+ * 必要に応じて、コピーされた要素をカバーするように宛先の占有数が引き上げられます。
1045
+ * 宛先の容量は変更されません。
1046
+ *
1047
+ * この操作では `dataBus` に対して `Uint8Array.prototype.copyWithin()` を使用するため、
1048
+ * 戻り値はデータバスを表す `Uint8Array` 自体になります。
1049
+ *
1050
+ * @param {number} source - コピー元ブロックのハンドル。
1051
+ * @param {number} destination - コピー先ブロックのハンドル。
1052
+ * @param {number} [slots=UNKNOWN] - コピーする最大要素数。
1053
+ * `UNKNOWN` は、追加の制限を課さないために使用されるセンチネル値を表します。
1054
+ * @returns {Uint8Array} 操作後の `dataBus`。
1055
+ * @throws {Error} ハンドルが無効、破損している場合、
1056
+ * またはコピー先ブロックが withView() によって借用されている場合。
1057
+ */
1021
1058
  copy(source, destination, slots = UNKNOWN) {
1022
1059
  /** @type {Metadata} */
1023
1060
  const metaA = {};
@@ -1356,6 +1393,7 @@ export default class Balloc {
1356
1393
  out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1357
1394
  out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
1358
1395
  out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
1396
+ out.borrowed = this.controlAdapter.getUint32(out.headerAddress + FLAGS_OFFSET, IS_LITTLE_ENDIAN) & VIEW_LOCK;
1359
1397
 
1360
1398
  return out;
1361
1399
  }
package/src/pt/balloc.cjs CHANGED
@@ -107,7 +107,8 @@ var Balloc = class {
107
107
  dataAddress: 0 >>> 0,
108
108
  capacityExponent: 0 >>> 0,
109
109
  byteCapacity: 0 >>> 0,
110
- occupied: 0 >>> 0
110
+ occupied: 0 >>> 0,
111
+ borrowed: 0 >>> 0
111
112
  };
112
113
  }
113
114
  // ========== ALOCAÇÃO ==========
@@ -219,20 +220,38 @@ var Balloc = class {
219
220
  this.recyclePush(oldBlockSize, dataAddress);
220
221
  }
221
222
  /**
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
- */
223
+ * Reduz um bloco à menor capacidade em potência de dois capaz de comportar
224
+ * seus elementos ocupados, preservando seu endereço e handler.
225
+ *
226
+ * Se o bloco estiver no topo do dataBus, dataPointer será recuado.
227
+ * Caso contrário, a cauda liberada será dividida em regiões de potências
228
+ * de dois, e cada região será devolvida à lista de reciclagem.
229
+ *
230
+ * @param {number} handler - Handler do bloco a ser reduzido.
231
+ * @returns {void}
232
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou estiver
233
+ * emprestado por withView().
234
+ */
235
+ shrink(handler) {
236
+ const meta = this.extractMetadata(handler, this.metadata);
237
+ this.assertNotBorrowed(meta.headerAddress);
238
+ const newCapacity = Math.max(1, 32 - Math.clz32(Math.max(2, meta.occupied) - 1));
239
+ if (newCapacity >= meta.capacityExponent) return;
240
+ const oldBlockSize = meta.byteCapacity;
241
+ const newBlockSize = 2 ** newCapacity * this.wordSize;
242
+ const oldEnd = meta.dataAddress + oldBlockSize;
243
+ this.controlAdapter.setUint8(meta.headerAddress + CAPACITY_OFFSET, newCapacity);
244
+ if (oldEnd === this.dataPointer) {
245
+ this.dataPointer = meta.dataAddress + newBlockSize;
246
+ return;
247
+ }
248
+ let address = meta.dataAddress + newBlockSize;
249
+ for (let exponent = newCapacity; exponent < meta.capacityExponent; exponent++) {
250
+ const segmentSize = 2 ** exponent * this.wordSize;
251
+ this.recyclePush(segmentSize, address);
252
+ address += segmentSize;
253
+ }
254
+ }
236
255
  free(handler) {
237
256
  const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
238
257
  const headerAddress = handler >>> 0;
@@ -772,24 +791,33 @@ var Balloc = class {
772
791
  * retornada ou utilizada após o término do callback. Essa restrição
773
792
  * também se aplica a subviews derivadas da view original.
774
793
  *
775
- * @param {number} handler - Handler do bloco.
776
- * @param {Function} callback - Função que recebe a TypedArray compartilhada.
794
+ * @param {...number|Function} args - Um ou mais handlers, seguidos pelo callback.
777
795
  * @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.
796
+ * @throws {TypeError} Se não houver handler ou se o callback não for uma função.
797
+ * @throws {Error} Se algum handler for inválido, duplicado ou já estiver emprestado.
780
798
  */
781
- withView(handler, callback) {
799
+ withView(...args) {
800
+ if (args.length < 2) throw new TypeError("At least one handler and one callback are required");
801
+ const lastIndex = args.length - 1;
802
+ const callback = args[lastIndex];
782
803
  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;
804
+ const lookup = /* @__PURE__ */ Object.create(null);
805
+ const views = [];
788
806
  try {
789
- const rawAddress = meta.dataAddress >>> this.wordShift;
790
- return callback(this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied));
807
+ for (let i = 0; i < lastIndex; i++) {
808
+ const metadata = this.extractMetadata(args[i], {});
809
+ if (Object.hasOwn(lookup, metadata.headerAddress)) throw new Error("Duplicate handler");
810
+ if (metadata.borrowed) throw new Error("Block is already borrowed");
811
+ this.controlBus[metadata.headerAddress + FLAGS_OFFSET] |= VIEW_LOCK;
812
+ const rawAddress = metadata.dataAddress >>> this.wordShift;
813
+ lookup[metadata.headerAddress] = metadata.headerAddress;
814
+ views.push(this.auxiliary.subarray(rawAddress, rawAddress + metadata.occupied));
815
+ }
816
+ return callback(...views);
791
817
  } finally {
792
- this.controlBus[flagsAddress] &= ~VIEW_LOCK;
818
+ for (const key in lookup) {
819
+ this.controlBus[lookup[key] + FLAGS_OFFSET] &= ~VIEW_LOCK;
820
+ }
793
821
  }
794
822
  }
795
823
  // ======== CAPACIDADE EM SLOTS ==========
@@ -1159,6 +1187,7 @@ var Balloc = class {
1159
1187
  out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1160
1188
  out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
1161
1189
  out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
1190
+ out.borrowed = this.controlAdapter.getUint32(out.headerAddress + FLAGS_OFFSET, IS_LITTLE_ENDIAN) & VIEW_LOCK;
1162
1191
  return out;
1163
1192
  }
1164
1193
  /**