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/zh/balloc.mjs CHANGED
@@ -90,6 +90,7 @@ const CLAMP_11BITS = 0x7FF >>> 0;
90
90
  * @property {number} generation - 句柄所属的代数(generation)。
91
91
  * @property {number} headerAddress - controlBus 内的标头地址。
92
92
  * @property {number} occupied - 块中已占用的元素数量。
93
+ * @property {number} borrowed - 指示该内存块是否已被 withView() 借用的标志。
93
94
  */
94
95
 
95
96
  /**
@@ -248,7 +249,7 @@ export default class Balloc {
248
249
  * @throws {AggregateError} 如果容量已达到支持的最大限制。
249
250
  */
250
251
  realloc(handler) {
251
-
252
+
252
253
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
253
254
  const headerAddress = handler >>> 0;
254
255
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
@@ -293,19 +294,46 @@ export default class Balloc {
293
294
  this.recyclePush(oldBlockSize, dataAddress);
294
295
  }
295
296
 
296
- /**
297
- * 释放内存块。
297
+ /**
298
+ * 将内存块缩小到能够容纳其已占用元素的最小 2 的幂次容量,
299
+ * 同时保留其地址和句柄。
298
300
  *
299
- * 通过将块标头的 cookie 清零使其失效,并记录其地址以便后续复用。
300
- * 数据区域也会被交还给回收系统,除非该块刚好位于 `dataBus` 的顶部;
301
- * 在这种情况下,`dataPointer` 会直接回滚,从而消除该区域而无需在回收列表中创建条目。
301
+ * 如果该块位于 dataBus 的顶部,则向后回退 dataPointer。
302
+ * 否则,将释放的尾部区域拆分为若干个容量为 2 的幂次的区域,
303
+ * 并将每个区域归还到回收列表。
302
304
  *
303
- * @param {number} handler - 要释放的块的句柄。
305
+ * @param {number} handler - 要缩小的内存块的句柄。
304
306
  * @returns {void}
305
- * @throws {Error} 如果句柄无效、已损坏,或者块正通过 withView() 被借用。
307
+ * @throws {Error} 如果句柄无效、已损坏,或该块正通过 withView() 被借用。
306
308
  */
309
+ shrink(handler) {
310
+ const meta = this.extractMetadata(handler, this.metadata);
311
+ this.assertNotBorrowed(meta.headerAddress);
312
+
313
+ const newCapacity = Math.max(1, 32 - Math.clz32(Math.max(2, meta.occupied) - 1));
314
+ if (newCapacity >= meta.capacityExponent) return;
315
+
316
+ const oldBlockSize = meta.byteCapacity;
317
+ const newBlockSize = (2 ** newCapacity) * this.wordSize;
318
+ const oldEnd = meta.dataAddress + oldBlockSize;
319
+
320
+ this.controlAdapter.setUint8(meta.headerAddress + CAPACITY_OFFSET, newCapacity);
321
+
322
+ if (oldEnd === this.dataPointer) {
323
+ this.dataPointer = meta.dataAddress + newBlockSize;
324
+ return;
325
+ }
326
+
327
+ let address = meta.dataAddress + newBlockSize;
328
+ for (let exponent = newCapacity; exponent < meta.capacityExponent; exponent++) {
329
+ const segmentSize = (2 ** exponent) * this.wordSize;
330
+ this.recyclePush(segmentSize, address);
331
+ address += segmentSize;
332
+ }
333
+ }
334
+
307
335
  free(handler) {
308
-
336
+
309
337
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
310
338
  const headerAddress = handler >>> 0;
311
339
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
@@ -499,7 +527,6 @@ export default class Balloc {
499
527
  * 该元素被写入最后一个占用元素之后的第一个空闲位置。
500
528
  * 只有在容量范围内有可用空间时,块的占用数才会递增。
501
529
  *
502
- * @param {number} handler - 块句柄。
503
530
  * @param {number} value - 要插入的值。
504
531
  * @returns {boolean} 如果值已成功插入则为 `true`;如果块已无可用空间则为 `false`。
505
532
  * @throws {Error} 如果句柄无效、已损坏,或者块正通过 withView() 被借用。
@@ -884,27 +911,39 @@ export default class Balloc {
884
911
  * 此限制同样适用于从原始视图派生的子视图(subviews)。
885
912
  *
886
913
  * @param {number} handler - 块句柄。
887
- * @param {Function} callback - 接收共享 TypedArray 的函数。
914
+ * @param {...(number|Function)} args - 一个或多个块句柄,最后一个参数为回调函数。
888
915
  * @returns {*} 回调函数产生 返回值。
889
- * @throws {TypeError} 如果回调不是函数。
890
- * @throws {Error} 如果句柄无效或已被借用。
916
+ * @throws {TypeError} 如果未提供句柄或回调不是函数。
917
+ * @throws {Error} 如果任一句柄无效、重复或已被借用。
891
918
  */
892
- withView(handler, callback) {
919
+ withView(...args) {
920
+ if (args.length < 2) throw new TypeError("At least one handler and one callback are required");
921
+ const lastIndex = args.length - 1;
922
+ const callback = args[lastIndex];
893
923
  if (typeof callback !== "function") throw new TypeError("callback must be a function");
894
924
 
895
- const meta = this.extractMetadata(handler, this.metadata);
896
- const flagsAddress = meta.headerAddress + FLAGS_OFFSET;
897
- const flags = this.controlBus[flagsAddress];
898
-
899
- if (flags & VIEW_LOCK) throw new Error("Block is already borrowed");
900
-
901
- this.controlBus[flagsAddress] = flags | VIEW_LOCK;
925
+ const lookup = Object.create(null);
926
+ const views = [];
902
927
 
903
928
  try {
904
- const rawAddress = meta.dataAddress >>> this.wordShift;
905
- return callback(this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied));
929
+ for(let i = 0; i < lastIndex; i++) {
930
+ const metadata = this.extractMetadata(args[i], {});
931
+
932
+
933
+ if (Object.hasOwn(lookup, metadata.headerAddress)) throw new Error("Duplicate handler");
934
+ if (metadata.borrowed) throw new Error("Block is already borrowed");
935
+
936
+ this.controlBus[metadata.headerAddress + FLAGS_OFFSET] |= VIEW_LOCK;
937
+
938
+ const rawAddress = metadata.dataAddress >>> this.wordShift;
939
+ lookup[metadata.headerAddress] = metadata.headerAddress;
940
+ views.push(this.auxiliary.subarray(rawAddress, rawAddress + metadata.occupied))
941
+ }
942
+ return callback(...views);
906
943
  } finally {
907
- this.controlBus[flagsAddress] &= ~VIEW_LOCK;
944
+ for (const key in lookup) {
945
+ this.controlBus[lookup[key] + FLAGS_OFFSET] &= ~VIEW_LOCK;
946
+ }
908
947
  }
909
948
  }
910
949
 
@@ -967,24 +1006,24 @@ export default class Balloc {
967
1006
 
968
1007
  // ========== 块间操作 (Operations between blocks)=============
969
1008
 
970
- /**
971
- * 将占用元素从一个块复制到另一个块。
972
- *
973
- * 复制从 `source` 的第一个元素和 `destination` 的第一个槽位开始。
974
- * 实际复制的数量受源中占用元素数量、目标物理容量以及 `slots` 中指定限制的约束。
975
- *
976
- * 必要时会提高目标的占用数,以涵盖复制的元素。目标的容量保持不变。
977
- *
978
- * 该操作在 `dataBus` 上使用 `Uint8Array.prototype.copyWithin()`,
979
- * 因此返回值为代表数据总线的 `Uint8Array` 本身。
980
- *
981
- * @param {number} source - 源块句柄。
982
- * @param {number} destination - 目标块句柄。
983
- * @param {number} [slots=UNKNOWN] - 要复制的最大元素数。
984
- * `UNKNOWN` 代表哨兵值,用于不施加额外的限制。
985
- * @returns {Uint8Array} 操作后的 `dataBus`。
986
- * @throws {Error} 如果句柄无效、已损坏,或者目标块正通过 withView() 被借用。
987
- */
1009
+ /**
1010
+ * 将占用元素从一个块复制到另一个块。
1011
+ *
1012
+ * 复制从 `source` 的第一个元素和 `destination` 的第一个槽位开始。
1013
+ * 实际复制的数量受源中占用元素数量、目标物理容量以及 `slots` 中指定限制的约束。
1014
+ *
1015
+ * 必要时会提高目标的占用数,以涵盖复制的元素。目标的容量保持不变。
1016
+ *
1017
+ * 该操作在 `dataBus` 上使用 `Uint8Array.prototype.copyWithin()`,
1018
+ * 因此返回值为代表数据总线的 `Uint8Array` 本身。
1019
+ *
1020
+ * @param {number} source - 源块句柄。
1021
+ * @param {number} destination - 目标块句柄。
1022
+ * @param {number} [slots=UNKNOWN] - 要复制的最大元素数。
1023
+ * `UNKNOWN` 代表哨兵值,用于不施加额外的限制。
1024
+ * @returns {Uint8Array} 操作后的 `dataBus`。
1025
+ * @throws {Error} 如果句柄无效、已损坏,或者目标块正通过 withView() 被借用。
1026
+ */
988
1027
  copy(source, destination, slots = UNKNOWN) {
989
1028
  /** @type {Metadata} */
990
1029
  const metaA = {};
@@ -1310,6 +1349,7 @@ export default class Balloc {
1310
1349
  out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1311
1350
  out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
1312
1351
  out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
1352
+ out.borrowed = this.controlAdapter.getUint32(out.headerAddress + FLAGS_OFFSET, IS_LITTLE_ENDIAN) & VIEW_LOCK;
1313
1353
 
1314
1354
  return out;
1315
1355
  }
@@ -24,6 +24,10 @@ export type Metadata = {
24
24
  * - عدد العناصر المشغولة في الكتلة.
25
25
  */
26
26
  occupied: number;
27
+ /**
28
+ * - علامة تشير إلى ما إذا كانت الكتلة قد أُعيرت بواسطة withView().
29
+ */
30
+ borrowed: number;
27
31
  };
28
32
  /**
29
33
  * مخصص الذاكرة المتقاطع ذو الحافتين مع مكدس صدى وإدارة النفايات ReBump.
@@ -126,19 +130,19 @@ export default class Balloc {
126
130
  */
127
131
  realloc(handler: number): void;
128
132
  /**
129
- * يحرر كتلة ذاكرة.
130
- *
131
- * يتم إبطال ترويسة الكتلة عن طريق تصفير ملف تعريف الارتباط الخاص بها وتسجيل
132
- * عنوانها لإعادة استخدامها لاحقاً. كما يتم إرجاع منطقة البيانات
133
- * إلى نظام إعادة التدوير، إلا إذا كانت الكتلة في قمة `dataBus` تماماً؛
134
- * في هذه الحالة، يتم التراجع عن `dataPointer` ببساطة، مما يلغي المنطقة دون إنشاء إدخال في قائمة إعادة التدوير.
135
- *
136
- * @param {number} handler - مقبض الكتلة المراد تحريرها.
137
- * @returns {void}
138
- * @throws {Error} إذا كان المقبض غير صالح، أو تالفاً، أو إذا كانت الكتلة
139
- * معارة بواسطة withView().
140
- */
141
- free(handler: number): void;
133
+ * يقلّص الكتلة إلى أصغر سعة تمثل قوة للعدد اثنين وتكفي لاحتواء
134
+ * العناصر المشغولة فيها، مع الحفاظ على عنوانها ومعرّفها (handler).
135
+ *
136
+ * إذا كانت الكتلة في أعلى dataBus، يُرجع dataPointer إلى الخلف.
137
+ * وإلا، يُقسّم الجزء الطرفي المُحرر إلى مناطق ذات أحجام تمثل قوى للعدد
138
+ * اثنين، ثم تُعاد كل منطقة إلى قائمة إعادة التدوير.
139
+ *
140
+ * @param {number} handler - معرّف الكتلة المراد تقليصها.
141
+ * @returns {void}
142
+ * @throws {Error} إذا كان المعرّف غير صالح أو تالفاً أو مستعاراً عبر withView().
143
+ */
144
+ shrink(handler: number): void;
145
+ free(handler: any): void;
142
146
  /**
143
147
  * [استخدام داخلي]
144
148
  * يدخل منطقة حرة في قائمة إعادة التدوير.
@@ -228,14 +232,13 @@ export default class Balloc {
228
232
  * مشغول. يتم زيادة إشغال الكتلة فقط عندما تكون هناك مساحة
229
233
  * متاحة ضمن سعتها.
230
234
  *
231
- * @param {number} handler - مقبض الكتلة.
232
235
  * @param {number} value - القيمة المراد إدراجها.
233
236
  * @returns {boolean} `true` إذا تم إدراج القيمة؛ `false` إذا كانت الكتلة
234
237
  * بلا مساحة متاحة.
235
238
  * @throws {Error} إذا كان المقبض غير صالح، أو تالفاً، أو كانت الكتلة معارة بواسطة withView().
236
239
  *
237
240
  */
238
- push(handler: number, value: number): boolean;
241
+ push(handler: any, value: number): boolean;
239
242
  /**
240
243
  * يزيل آخر عنصر مشغول من الكتلة ويرجعه.
241
244
  *
@@ -469,12 +472,12 @@ export default class Balloc {
469
472
  * على العروض الفرعية (Subviews) المشتقة من العرض الأصلي.
470
473
  *
471
474
  * @param {number} handler - مقبض الكتلة.
472
- * @param {Function} callback - الدالة التي تتلقى TypedArray المشترك.
475
+ * @param {...(number|Function)} args - مقبض كتلة واحد أو أكثر، تليها دالة رد الاتصال.
473
476
  * @returns {*} القيمة المُرجعة بواسطة دالة رد الاتصال.
474
- * @throws {TypeError} إذا لم تكن دالة رد الاتصال دالة.
475
- * @throws {Error} إذا كان المقبض غير صالح أو معاراً مسبقاً.
477
+ * @throws {TypeError} إذا لم يتم توفير أي مقبض أو لم تكن دالة رد الاتصال دالة.
478
+ * @throws {Error} إذا كان أي مقبض غير صالح أو مكرراً أو معاراً مسبقاً.
476
479
  */
477
- withView(handler: number, callback: Function): any;
480
+ withView(...args: (number | Function)[]): any;
478
481
  /**
479
482
  * يرجع السعة الفيزيائية للكتلة بالبايت.
480
483
  *
@@ -24,6 +24,10 @@ export type Metadata = {
24
24
  * - Number of occupied elements in the block.
25
25
  */
26
26
  occupied: number;
27
+ /**
28
+ * - Flag indicating whether the block has been borrowed by withView().
29
+ */
30
+ borrowed: number;
27
31
  };
28
32
  /**
29
33
  * Echo Stack Dual Bus Bump Allocator with ReBump GC.
@@ -128,6 +132,19 @@ export default class Balloc {
128
132
  * supported limit.
129
133
  */
130
134
  realloc(handler: number): void;
135
+ /**
136
+ * Reduces a block to the smallest power-of-two capacity that can contain
137
+ * its occupied elements, while preserving its address and handler.
138
+ *
139
+ * If the block is at the top of the dataBus, dataPointer is moved backward.
140
+ * Otherwise, the released tail is split into power-of-two regions and each
141
+ * region is returned to the recycling list.
142
+ *
143
+ * @param {number} handler - Handler of the block to shrink.
144
+ * @returns {void}
145
+ * @throws {Error} If the handler is invalid, corrupted, or borrowed by withView().
146
+ */
147
+ shrink(handler: number): void;
131
148
  /**
132
149
  * Frees a memory block.
133
150
  *
@@ -239,14 +256,13 @@ export default class Balloc {
239
256
  * element. Block occupancy is incremented only when space is available
240
257
  * within its capacity.
241
258
  *
242
- * @param {number} handler - Block handle.
243
259
  * @param {number} value - Value to be inserted.
244
260
  * @returns {boolean} `true` if the value was inserted; `false` if the block
245
261
  * is already out of available space.
246
262
  * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
247
263
  *
248
264
  */
249
- push(handler: number, value: number): boolean;
265
+ push(handler: any, value: number): boolean;
250
266
  /**
251
267
  * Removes the last occupied element from the block and returns it.
252
268
  *
@@ -479,12 +495,12 @@ export default class Balloc {
479
495
  * also applies to subviews derived from the original view.
480
496
  *
481
497
  * @param {number} handler - Block handle.
482
- * @param {Function} callback - Function receiving the shared TypedArray.
498
+ * @param {...(number|Function)} args - One or more block handles followed by the callback.
483
499
  * @returns {*} Return value produced by the callback.
484
- * @throws {TypeError} If callback is not a function.
485
- * @throws {Error} If the handle is invalid or already borrowed.
500
+ * @throws {TypeError} If no handle is provided or the callback is not a function.
501
+ * @throws {Error} If a handle is invalid, duplicated, or already borrowed.
486
502
  */
487
- withView(handler: number, callback: Function): any;
503
+ withView(...args: (number | Function)[]): any;
488
504
  /**
489
505
  * Returns the physical capacity of the block in bytes.
490
506
  *
@@ -24,6 +24,10 @@ export type Metadata = {
24
24
  * - Número de elementos ocupados en el bloque.
25
25
  */
26
26
  occupied: number;
27
+ /**
28
+ * - Indicador de si el bloque ha sido prestado por withView().
29
+ */
30
+ borrowed: number;
27
31
  };
28
32
  /**
29
33
  * Asignador tipo Bump de doble bus con pila de eco y recolección de basura ReBump.
@@ -128,21 +132,20 @@ export default class Balloc {
128
132
  */
129
133
  realloc(handler: number): void;
130
134
  /**
131
- * Libera un bloque de memoria.
132
- *
133
- * La cabecera del bloque se invalida poniendo su cookie a cero y su
134
- * dirección se registra para su posterior reutilización. La región de datos
135
- * también se devuelve al sistema de reciclaje, excepto cuando el bloque está
136
- * exactamente en la cima del `dataBus`; en ese caso, el puntero `dataPointer` simplemente
137
- * retrocede, eliminando la región sin crear una entrada en la lista de
138
- * reciclaje.
139
- *
140
- * @param {number} handler - Descriptor del bloque a liberar.
141
- * @returns {void}
142
- * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque
143
- * está prestado mediante `withView()`.
144
- */
145
- free(handler: number): void;
135
+ * Reduce un bloque a la menor capacidad potencia de dos que pueda contener
136
+ * sus elementos ocupados, preservando su dirección y su handler.
137
+ *
138
+ * Si el bloque está en la parte superior de dataBus, dataPointer retrocede.
139
+ * De lo contrario, la cola liberada se divide en regiones de potencias
140
+ * de dos y cada región se devuelve a la lista de reciclaje.
141
+ *
142
+ * @param {number} handler - Handler del bloque que se va a reducir.
143
+ * @returns {void}
144
+ * @throws {Error} Si el handler no es válido, está dañado o está prestado
145
+ * mediante withView().
146
+ */
147
+ shrink(handler: number): void;
148
+ free(handler: any): void;
146
149
  /**
147
150
  * [USO INTERNO]
148
151
  * Inserta una región libre en la lista de reciclaje.
@@ -239,14 +242,13 @@ export default class Balloc {
239
242
  * ocupado. La ocupación del bloque se incrementa únicamente cuando hay espacio
240
243
  * disponible dentro de su capacidad.
241
244
  *
242
- * @param {number} handler - Descriptor del bloque.
243
245
  * @param {number} value - Valor que se va a insertar.
244
246
  * @returns {boolean} `true` si el valor fue insertado; `false` si el bloque
245
247
  * ya no dispone de espacio libre.
246
248
  * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque está prestado mediante `withView()`.
247
249
  *
248
250
  */
249
- push(handler: number, value: number): boolean;
251
+ push(handler: any, value: number): boolean;
250
252
  /**
251
253
  * Elimina el último elemento ocupado del bloque y lo devuelve.
252
254
  *
@@ -481,12 +483,12 @@ export default class Balloc {
481
483
  * también se aplica a las subvistas derivadas de la vista original.
482
484
  *
483
485
  * @param {number} handler - Descriptor del bloque.
484
- * @param {Function} callback - Función que recibe el TypedArray compartido.
486
+ * @param {...(number|Function)} args - Uno o más descriptores de bloque, seguidos de la retrollamada.
485
487
  * @returns {*} Valor devuelto por la retrollamada.
486
- * @throws {TypeError} Si la retrollamada no es una función.
487
- * @throws {Error} Si el descriptor no es válido o ya está prestado.
488
+ * @throws {TypeError} Si no se proporciona ningún descriptor o la retrollamada no es una función.
489
+ * @throws {Error} Si algún descriptor no es válido, está duplicado o ya está prestado.
488
490
  */
489
- withView(handler: number, callback: Function): any;
491
+ withView(...args: (number | Function)[]): any;
490
492
  /**
491
493
  * Devuelve la capacidad física del bloque en bytes.
492
494
  *
@@ -24,6 +24,10 @@ export type Metadata = {
24
24
  * - ブロック内の占有要素数。
25
25
  */
26
26
  occupied: number;
27
+ /**
28
+ * - ブロックが withView() によって借用されているかどうかを示すフラグ。
29
+ */
30
+ borrowed: number;
27
31
  };
28
32
  /**
29
33
  * ReBump GCを備えたEcho Stackデュアルバス・バンプアロケータ。
@@ -123,20 +127,20 @@ export default class Balloc {
123
127
  */
124
128
  realloc(handler: number): void;
125
129
  /**
126
- * メモリブロックを解放します。
127
- *
128
- * ブロックのヘッダーはクッキーをゼロに設定することで無効化され、
129
- * そのアドレスは後で再利用するために登録されます。ブロックが `dataBus` の
130
- * 正確なトップにある場合を除き、データ領域も再利用システムに戻されます。
131
- * トップにある場合は、`dataPointer` が単に巻き戻され、再利用リストに
132
- * エントリを作成せずに領域が破棄されます。
133
- *
134
- * @param {number} handler - 解放するブロックのハンドル。
135
- * @returns {void}
136
- * @throws {Error} ハンドルが無効、破損している場合、またはブロックが
137
- * withView() によって借用されている場合。
138
- */
139
- free(handler: number): void;
130
+ * ブロックのアドレスとハンドルを維持したまま、使用中の要素を格納できる
131
+ * 最小の2のべき乗の容量まで縮小します。
132
+ *
133
+ * ブロックが dataBus のトップにある場合、dataPointer を後退させます。
134
+ * それ以外の場合、解放された末尾領域を2のべき乗の領域に分割し、
135
+ * 各領域を再利用リストに戻します。
136
+ *
137
+ * @param {number} handler - 縮小するブロックのハンドル。
138
+ * @returns {void}
139
+ * @throws {Error} ハンドルが無効または破損している場合、あるいは
140
+ * withView() によってブロックが借用されている場合。
141
+ */
142
+ shrink(handler: number): void;
143
+ free(handler: any): void;
140
144
  /**
141
145
  * [内部利用]
142
146
  * 空き領域を再利用リストに挿入します。
@@ -223,14 +227,13 @@ export default class Balloc {
223
227
  * 要素は、最後尾の占有要素の直後の最初の空き位置に書き込まれます。
224
228
  * ブロックの占有数は、その容量内に空きスペースが存在する場合にのみインクリメントされます。
225
229
  *
226
- * @param {number} handler - ブロックのハンドル。
227
230
  * @param {number} value - 挿入する値。
228
231
  * @returns {boolean} 値が挿入された場合は `true`、ブロックに利用可能な
229
232
  * スペースがない場合は `false`。
230
233
  * @throws {Error} ハンドルが無効、破損している場合、またはブロックが withView() によって借用されている場合。
231
234
  *
232
235
  */
233
- push(handler: number, value: number): boolean;
236
+ push(handler: any, value: number): boolean;
234
237
  /**
235
238
  * ブロックから最後尾の占有要素を削除し、それを返します。
236
239
  *
@@ -442,12 +445,12 @@ export default class Balloc {
442
445
  * サブビューにも適用されます。
443
446
  *
444
447
  * @param {number} handler - ブロックのハンドル。
445
- * @param {Function} callback - 共有された TypedArray を受け取る関数。
448
+ * @param {...(number|Function)} args - 1つ以上のブロックハンドルと、その後に続くコールバック。
446
449
  * @returns {*} コールバックによって生成された戻り値。
447
- * @throws {TypeError} コールバックが関数ではない場合。
448
- * @throws {Error} ハンドルが無効であるか、すでに借用されている場合。
450
+ * @throws {TypeError} ハンドルが指定されていない場合、またはコールバックが関数ではない場合。
451
+ * @throws {Error} いずれかのハンドルが無効、重複、または借用中の場合。
449
452
  */
450
- withView(handler: number, callback: Function): any;
453
+ withView(...args: (number | Function)[]): any;
451
454
  /**
452
455
  * ブロックの物理的容量をバイト単位で返します。
453
456
  *
@@ -24,6 +24,10 @@ export type Metadata = {
24
24
  * - Número de elementos ocupados no bloco.
25
25
  */
26
26
  occupied: number;
27
+ /**
28
+ * - Flag indicando se o foi o bloco foi emprestado por withView().
29
+ */
30
+ borrowed: number;
27
31
  };
28
32
  /**
29
33
  * Echo Stack Dual Bus Bump Allocator with ReBump GC.
@@ -129,21 +133,20 @@ export default class Balloc {
129
133
  */
130
134
  realloc(handler: number): void;
131
135
  /**
132
- * Libera um bloco de memória.
133
- *
134
- * O header do bloco é invalidado pelo zeramento de seu cookie e seu
135
- * endereço é registrado para posterior reutilização. A região de dados
136
- * também é devolvida ao sistema de reciclagem, exceto quando o bloco está
137
- * exatamente no topo do `dataBus`; nesse caso, o `dataPointer` é simplesmente
138
- * retrocedido, eliminando a região sem criar uma entrada na lista de
139
- * reciclagem.
140
- *
141
- * @param {number} handler - Handler do bloco a ser liberado.
142
- * @returns {void}
143
- * @throws {Error} Se o handler for inválido, estiver corrompido ou o bloco
144
- * estiver emprestado por withView().
145
- */
146
- free(handler: number): void;
136
+ * Reduz um bloco à menor capacidade em potência de dois capaz de comportar
137
+ * seus elementos ocupados, preservando seu endereço e handler.
138
+ *
139
+ * Se o bloco estiver no topo do dataBus, dataPointer será recuado.
140
+ * Caso contrário, a cauda liberada será dividida em regiões de potências
141
+ * de dois, e cada região será devolvida à lista de reciclagem.
142
+ *
143
+ * @param {number} handler - Handler do bloco a ser reduzido.
144
+ * @returns {void}
145
+ * @throws {Error} Se o handler for inválido, estiver corrompido ou estiver
146
+ * emprestado por withView().
147
+ */
148
+ shrink(handler: number): void;
149
+ free(handler: any): void;
147
150
  /**
148
151
  * [USO INTERNO]
149
152
  * Insere uma região livre na lista de reciclagem.
@@ -482,13 +485,12 @@ export default class Balloc {
482
485
  * retornada ou utilizada após o término do callback. Essa restrição
483
486
  * também se aplica a subviews derivadas da view original.
484
487
  *
485
- * @param {number} handler - Handler do bloco.
486
- * @param {Function} callback - Função que recebe a TypedArray compartilhada.
488
+ * @param {...number|Function} args - Um ou mais handlers, seguidos pelo callback.
487
489
  * @returns {*} Retorno produzido pelo callback.
488
- * @throws {TypeError} Se callback não for uma função.
489
- * @throws {Error} Se o handler for inválido ou já estiver emprestado.
490
+ * @throws {TypeError} Se não houver handler ou se o callback não for uma função.
491
+ * @throws {Error} Se algum handler for inválido, duplicado ou já estiver emprestado.
490
492
  */
491
- withView(handler: number, callback: Function): any;
493
+ withView(...args: (number | Function)[]): any;
492
494
  /**
493
495
  * Retorna a capacidade física do bloco em bytes.
494
496
  *
@@ -24,6 +24,10 @@ export type Metadata = {
24
24
  * - 块中已占用的元素数量。
25
25
  */
26
26
  occupied: number;
27
+ /**
28
+ * - 指示该内存块是否已被 withView() 借用的标志。
29
+ */
30
+ borrowed: number;
27
31
  };
28
32
  /**
29
33
  * 带有 ReBump GC 的 Echo 栈双总线指针碰撞分配器(Dual Bus Bump Allocator)。
@@ -117,17 +121,19 @@ export default class Balloc {
117
121
  */
118
122
  realloc(handler: number): void;
119
123
  /**
120
- * 释放内存块。
121
- *
122
- * 通过将块标头的 cookie 清零使其失效,并记录其地址以便后续复用。
123
- * 数据区域也会被交还给回收系统,除非该块刚好位于 `dataBus` 的顶部;
124
- * 在这种情况下,`dataPointer` 会直接回滚,从而消除该区域而无需在回收列表中创建条目。
125
- *
126
- * @param {number} handler - 要释放的块的句柄。
127
- * @returns {void}
128
- * @throws {Error} 如果句柄无效、已损坏,或者块正通过 withView() 被借用。
129
- */
130
- free(handler: number): void;
124
+ * 将内存块缩小到能够容纳其已占用元素的最小 2 的幂次容量,
125
+ * 同时保留其地址和句柄。
126
+ *
127
+ * 如果该块位于 dataBus 的顶部,则向后回退 dataPointer。
128
+ * 否则,将释放的尾部区域拆分为若干个容量为 2 的幂次的区域,
129
+ * 并将每个区域归还到回收列表。
130
+ *
131
+ * @param {number} handler - 要缩小的内存块的句柄。
132
+ * @returns {void}
133
+ * @throws {Error} 如果句柄无效、已损坏,或该块正通过 withView() 被借用。
134
+ */
135
+ shrink(handler: number): void;
136
+ free(handler: any): void;
131
137
  /**
132
138
  * [内部使用]
133
139
  * 将空闲区域插入回收列表。
@@ -209,13 +215,12 @@ export default class Balloc {
209
215
  * 该元素被写入最后一个占用元素之后的第一个空闲位置。
210
216
  * 只有在容量范围内有可用空间时,块的占用数才会递增。
211
217
  *
212
- * @param {number} handler - 块句柄。
213
218
  * @param {number} value - 要插入的值。
214
219
  * @returns {boolean} 如果值已成功插入则为 `true`;如果块已无可用空间则为 `false`。
215
220
  * @throws {Error} 如果句柄无效、已损坏,或者块正通过 withView() 被借用。
216
221
  *
217
222
  */
218
- push(handler: number, value: number): boolean;
223
+ push(handler: any, value: number): boolean;
219
224
  /**
220
225
  * 移除块中最后一个占用的元素并将其返回。
221
226
  *
@@ -414,12 +419,12 @@ export default class Balloc {
414
419
  * 此限制同样适用于从原始视图派生的子视图(subviews)。
415
420
  *
416
421
  * @param {number} handler - 块句柄。
417
- * @param {Function} callback - 接收共享 TypedArray 的函数。
422
+ * @param {...(number|Function)} args - 一个或多个块句柄,最后一个参数为回调函数。
418
423
  * @returns {*} 回调函数产生 返回值。
419
- * @throws {TypeError} 如果回调不是函数。
420
- * @throws {Error} 如果句柄无效或已被借用。
424
+ * @throws {TypeError} 如果未提供句柄或回调不是函数。
425
+ * @throws {Error} 如果任一句柄无效、重复或已被借用。
421
426
  */
422
- withView(handler: number, callback: Function): any;
427
+ withView(...args: (number | Function)[]): any;
423
428
  /**
424
429
  * 返回块的物理容量(以字节为单位)。
425
430
  *
package/change.log.md DELETED
@@ -1,7 +0,0 @@
1
- # version 1.2
2
- - Fix duplicate memory allocation in constructor - https://github.com/AugustoVasques75/balloc/issues/4
3
- - Add `indexOf()` method - https://github.com/AugustoVasques75/balloc/issues/1
4
- - Add `lastIndexOf()` method
5
- - Add method isFull() - https://github.com/AugustoVasques75/balloc/issues/2
6
- - Typo correction
7
- - Add `withView()` method to address the Direct Mutable Access to Allocation Storage issue: https://github.com/AugustoVasques75/balloc/issues/3