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/en/balloc.mjs CHANGED
@@ -90,6 +90,7 @@ const CLAMP_11BITS = 0x7FF >>> 0;
90
90
  * @property {number} generation - Generation to which the handle belongs.
91
91
  * @property {number} headerAddress - Address of the header within the controlBus.
92
92
  * @property {number} occupied - Number of occupied elements in the block.
93
+ * @property {number} borrowed - Flag indicating whether the block has been borrowed by withView().
93
94
  */
94
95
 
95
96
  /**
@@ -260,7 +261,7 @@ export default class Balloc {
260
261
  * supported limit.
261
262
  */
262
263
  realloc(handler) {
263
-
264
+
264
265
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
265
266
  const headerAddress = handler >>> 0;
266
267
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
@@ -305,23 +306,61 @@ export default class Balloc {
305
306
  this.recyclePush(oldBlockSize, dataAddress);
306
307
  }
307
308
 
308
- /**
309
- * Frees a memory block.
309
+ /**
310
+ * Reduces a block to the smallest power-of-two capacity that can contain
311
+ * its occupied elements, while preserving its address and handler.
310
312
  *
311
- * The block's header is invalidated by zeroing its cookie, and its
312
- * address is registered for later reuse. The data region
313
- * is also returned to the recycling system, except when the block is
314
- * exactly at the top of the `dataBus`; in that case, the `dataPointer` is simply
315
- * rolled back, eliminating the region without creating an entry in the recycling
316
- * list.
313
+ * If the block is at the top of the dataBus, dataPointer is moved backward.
314
+ * Otherwise, the released tail is split into power-of-two regions and each
315
+ * region is returned to the recycling list.
317
316
  *
318
- * @param {number} handler - Handle of the block to be freed.
317
+ * @param {number} handler - Handler of the block to shrink.
319
318
  * @returns {void}
320
- * @throws {Error} If the handle is invalid, corrupted, or the block
321
- * is borrowed via withView().
319
+ * @throws {Error} If the handler is invalid, corrupted, or borrowed by withView().
322
320
  */
321
+ shrink(handler) {
322
+ const meta = this.extractMetadata(handler, this.metadata);
323
+ this.assertNotBorrowed(meta.headerAddress);
324
+
325
+ const newCapacity = Math.max(1, 32 - Math.clz32(Math.max(2, meta.occupied) - 1));
326
+ if (newCapacity >= meta.capacityExponent) return;
327
+
328
+ const oldBlockSize = meta.byteCapacity;
329
+ const newBlockSize = (2 ** newCapacity) * this.wordSize;
330
+ const oldEnd = meta.dataAddress + oldBlockSize;
331
+
332
+ this.controlAdapter.setUint8(meta.headerAddress + CAPACITY_OFFSET, newCapacity);
333
+
334
+ if (oldEnd === this.dataPointer) {
335
+ this.dataPointer = meta.dataAddress + newBlockSize;
336
+ return;
337
+ }
338
+
339
+ let address = meta.dataAddress + newBlockSize;
340
+ for (let exponent = newCapacity; exponent < meta.capacityExponent; exponent++) {
341
+ const segmentSize = (2 ** exponent) * this.wordSize;
342
+ this.recyclePush(segmentSize, address);
343
+ address += segmentSize;
344
+ }
345
+ }
346
+
347
+ /**
348
+ * Frees a memory block.
349
+ *
350
+ * The block's header is invalidated by zeroing its cookie, and its
351
+ * address is registered for later reuse. The data region
352
+ * is also returned to the recycling system, except when the block is
353
+ * exactly at the top of the `dataBus`; in that case, the `dataPointer` is simply
354
+ * rolled back, eliminating the region without creating an entry in the recycling
355
+ * list.
356
+ *
357
+ * @param {number} handler - Handle of the block to be freed.
358
+ * @returns {void}
359
+ * @throws {Error} If the handle is invalid, corrupted, or the block
360
+ * is borrowed via withView().
361
+ */
323
362
  free(handler) {
324
-
363
+
325
364
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
326
365
  const headerAddress = handler >>> 0;
327
366
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
@@ -529,7 +568,6 @@ export default class Balloc {
529
568
  * element. Block occupancy is incremented only when space is available
530
569
  * within its capacity.
531
570
  *
532
- * @param {number} handler - Block handle.
533
571
  * @param {number} value - Value to be inserted.
534
572
  * @returns {boolean} `true` if the value was inserted; `false` if the block
535
573
  * is already out of available space.
@@ -949,27 +987,39 @@ export default class Balloc {
949
987
  * also applies to subviews derived from the original view.
950
988
  *
951
989
  * @param {number} handler - Block handle.
952
- * @param {Function} callback - Function receiving the shared TypedArray.
990
+ * @param {...(number|Function)} args - One or more block handles followed by the callback.
953
991
  * @returns {*} Return value produced by the callback.
954
- * @throws {TypeError} If callback is not a function.
955
- * @throws {Error} If the handle is invalid or already borrowed.
992
+ * @throws {TypeError} If no handle is provided or the callback is not a function.
993
+ * @throws {Error} If a handle is invalid, duplicated, or already borrowed.
956
994
  */
957
- withView(handler, callback) {
995
+ withView(...args) {
996
+ if (args.length < 2) throw new TypeError("At least one handler and one callback are required");
997
+ const lastIndex = args.length - 1;
998
+ const callback = args[lastIndex];
958
999
  if (typeof callback !== "function") throw new TypeError("callback must be a function");
959
1000
 
960
- const meta = this.extractMetadata(handler, this.metadata);
961
- const flagsAddress = meta.headerAddress + FLAGS_OFFSET;
962
- const flags = this.controlBus[flagsAddress];
963
-
964
- if (flags & VIEW_LOCK) throw new Error("Block is already borrowed");
965
-
966
- this.controlBus[flagsAddress] = flags | VIEW_LOCK;
1001
+ const lookup = Object.create(null);
1002
+ const views = [];
967
1003
 
968
1004
  try {
969
- const rawAddress = meta.dataAddress >>> this.wordShift;
970
- return callback(this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied));
1005
+ for(let i = 0; i < lastIndex; i++) {
1006
+ const metadata = this.extractMetadata(args[i], {});
1007
+
1008
+
1009
+ if (Object.hasOwn(lookup, metadata.headerAddress)) throw new Error("Duplicate handler");
1010
+ if (metadata.borrowed) throw new Error("Block is already borrowed");
1011
+
1012
+ this.controlBus[metadata.headerAddress + FLAGS_OFFSET] |= VIEW_LOCK;
1013
+
1014
+ const rawAddress = metadata.dataAddress >>> this.wordShift;
1015
+ lookup[metadata.headerAddress] = metadata.headerAddress;
1016
+ views.push(this.auxiliary.subarray(rawAddress, rawAddress + metadata.occupied))
1017
+ }
1018
+ return callback(...views);
971
1019
  } finally {
972
- this.controlBus[flagsAddress] &= ~VIEW_LOCK;
1020
+ for (const key in lookup) {
1021
+ this.controlBus[lookup[key] + FLAGS_OFFSET] &= ~VIEW_LOCK;
1022
+ }
973
1023
  }
974
1024
  }
975
1025
 
@@ -1036,29 +1086,29 @@ export default class Balloc {
1036
1086
 
1037
1087
  // ========== Operations between blocks=============
1038
1088
 
1039
- /**
1040
- * Copies occupied elements from one block to another.
1041
- *
1042
- * Copying starts at the first element of `source` and the first slot of
1043
- * `destination`. The quantity effectively copied is limited by the number of
1044
- * occupied elements in the source, the physical capacity of the destination, and the
1045
- * limit specified in `slots`.
1046
- *
1047
- * Destination occupancy is increased, when necessary, to cover the
1048
- * copied elements. Destination capacity is unchanged.
1049
- *
1050
- * The operation uses `Uint8Array.prototype.copyWithin()` on the `dataBus`,
1051
- * therefore the return value is the `Uint8Array` representing the data bus.
1052
- *
1053
- * @param {number} source - Source block handle.
1054
- * @param {number} destination - Destination block handle.
1055
- * @param {number} [slots=UNKNOWN] - Maximum number of elements to copy.
1056
- * `UNKNOWN` represents the sentinel value used not to impose an
1057
- * additional limit.
1058
- * @returns {Uint8Array} The `dataBus` after the operation.
1059
- * @throws {Error} If handles are invalid, corrupted,
1060
- * or the destination block is borrowed via withView().
1061
- */
1089
+ /**
1090
+ * Copies occupied elements from one block to another.
1091
+ *
1092
+ * Copying starts at the first element of `source` and the first slot of
1093
+ * `destination`. The quantity effectively copied is limited by the number of
1094
+ * occupied elements in the source, the physical capacity of the destination, and the
1095
+ * limit specified in `slots`.
1096
+ *
1097
+ * Destination occupancy is increased, when necessary, to cover the
1098
+ * copied elements. Destination capacity is unchanged.
1099
+ *
1100
+ * The operation uses `Uint8Array.prototype.copyWithin()` on the `dataBus`,
1101
+ * therefore the return value is the `Uint8Array` representing the data bus.
1102
+ *
1103
+ * @param {number} source - Source block handle.
1104
+ * @param {number} destination - Destination block handle.
1105
+ * @param {number} [slots=UNKNOWN] - Maximum number of elements to copy.
1106
+ * `UNKNOWN` represents the sentinel value used not to impose an
1107
+ * additional limit.
1108
+ * @returns {Uint8Array} The `dataBus` after the operation.
1109
+ * @throws {Error} If handles are invalid, corrupted,
1110
+ * or the destination block is borrowed via withView().
1111
+ */
1062
1112
  copy(source, destination, slots = UNKNOWN) {
1063
1113
  /** @type {Metadata} */
1064
1114
  const metaA = {};
@@ -1408,6 +1458,7 @@ export default class Balloc {
1408
1458
  out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1409
1459
  out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
1410
1460
  out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
1461
+ out.borrowed = this.controlAdapter.getUint32(out.headerAddress + FLAGS_OFFSET, IS_LITTLE_ENDIAN) & VIEW_LOCK;
1411
1462
 
1412
1463
  return out;
1413
1464
  }
package/src/es/balloc.cjs CHANGED
@@ -218,20 +218,38 @@ var Balloc = class {
218
218
  this.recyclePush(oldBlockSize, dataAddress);
219
219
  }
220
220
  /**
221
- * Libera un bloque de memoria.
222
- *
223
- * La cabecera del bloque se invalida poniendo su cookie a cero y su
224
- * dirección se registra para su posterior reutilización. La región de datos
225
- * también se devuelve al sistema de reciclaje, excepto cuando el bloque está
226
- * exactamente en la cima del `dataBus`; en ese caso, el puntero `dataPointer` simplemente
227
- * retrocede, eliminando la región sin crear una entrada en la lista de
228
- * reciclaje.
229
- *
230
- * @param {number} handler - Descriptor del bloque a liberar.
231
- * @returns {void}
232
- * @throws {Error} Si el descriptor no es válido, está corrupto o el bloque
233
- * está prestado mediante `withView()`.
234
- */
221
+ * Reduce un bloque a la menor capacidad potencia de dos que pueda contener
222
+ * sus elementos ocupados, preservando su dirección y su handler.
223
+ *
224
+ * Si el bloque está en la parte superior de dataBus, dataPointer retrocede.
225
+ * De lo contrario, la cola liberada se divide en regiones de potencias
226
+ * de dos y cada región se devuelve a la lista de reciclaje.
227
+ *
228
+ * @param {number} handler - Handler del bloque que se va a reducir.
229
+ * @returns {void}
230
+ * @throws {Error} Si el handler no es válido, está dañado o está prestado
231
+ * mediante withView().
232
+ */
233
+ shrink(handler) {
234
+ const meta = this.extractMetadata(handler, this.metadata);
235
+ this.assertNotBorrowed(meta.headerAddress);
236
+ const newCapacity = Math.max(1, 32 - Math.clz32(Math.max(2, meta.occupied) - 1));
237
+ if (newCapacity >= meta.capacityExponent) return;
238
+ const oldBlockSize = meta.byteCapacity;
239
+ const newBlockSize = 2 ** newCapacity * this.wordSize;
240
+ const oldEnd = meta.dataAddress + oldBlockSize;
241
+ this.controlAdapter.setUint8(meta.headerAddress + CAPACITY_OFFSET, newCapacity);
242
+ if (oldEnd === this.dataPointer) {
243
+ this.dataPointer = meta.dataAddress + newBlockSize;
244
+ return;
245
+ }
246
+ let address = meta.dataAddress + newBlockSize;
247
+ for (let exponent = newCapacity; exponent < meta.capacityExponent; exponent++) {
248
+ const segmentSize = 2 ** exponent * this.wordSize;
249
+ this.recyclePush(segmentSize, address);
250
+ address += segmentSize;
251
+ }
252
+ }
235
253
  free(handler) {
236
254
  const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
237
255
  const headerAddress = handler >>> 0;
@@ -412,7 +430,6 @@ var Balloc = class {
412
430
  * ocupado. La ocupación del bloque se incrementa únicamente cuando hay espacio
413
431
  * disponible dentro de su capacidad.
414
432
  *
415
- * @param {number} handler - Descriptor del bloque.
416
433
  * @param {number} value - Valor que se va a insertar.
417
434
  * @returns {boolean} `true` si el valor fue insertado; `false` si el bloque
418
435
  * ya no dispone de espacio libre.
@@ -771,23 +788,33 @@ var Balloc = class {
771
788
  * también se aplica a las subvistas derivadas de la vista original.
772
789
  *
773
790
  * @param {number} handler - Descriptor del bloque.
774
- * @param {Function} callback - Función que recibe el TypedArray compartido.
791
+ * @param {...(number|Function)} args - Uno o más descriptores de bloque, seguidos de la retrollamada.
775
792
  * @returns {*} Valor devuelto por la retrollamada.
776
- * @throws {TypeError} Si la retrollamada no es una función.
777
- * @throws {Error} Si el descriptor no es válido o ya está prestado.
793
+ * @throws {TypeError} Si no se proporciona ningún descriptor o la retrollamada no es una función.
794
+ * @throws {Error} Si algún descriptor no es válido, está duplicado o ya está prestado.
778
795
  */
779
- withView(handler, callback) {
796
+ withView(...args) {
797
+ if (args.length < 2) throw new TypeError("At least one handler and one callback are required");
798
+ const lastIndex = args.length - 1;
799
+ const callback = args[lastIndex];
780
800
  if (typeof callback !== "function") throw new TypeError("callback must be a function");
781
- const meta = this.extractMetadata(handler, this.metadata);
782
- const flagsAddress = meta.headerAddress + FLAGS_OFFSET;
783
- const flags = this.controlBus[flagsAddress];
784
- if (flags & VIEW_LOCK) throw new Error("Block is already borrowed");
785
- this.controlBus[flagsAddress] = flags | VIEW_LOCK;
801
+ const lookup = /* @__PURE__ */ Object.create(null);
802
+ const views = [];
786
803
  try {
787
- const rawAddress = meta.dataAddress >>> this.wordShift;
788
- return callback(this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied));
804
+ for (let i = 0; i < lastIndex; i++) {
805
+ const metadata = this.extractMetadata(args[i], {});
806
+ if (Object.hasOwn(lookup, metadata.headerAddress)) throw new Error("Duplicate handler");
807
+ if (metadata.borrowed) throw new Error("Block is already borrowed");
808
+ this.controlBus[metadata.headerAddress + FLAGS_OFFSET] |= VIEW_LOCK;
809
+ const rawAddress = metadata.dataAddress >>> this.wordShift;
810
+ lookup[metadata.headerAddress] = metadata.headerAddress;
811
+ views.push(this.auxiliary.subarray(rawAddress, rawAddress + metadata.occupied));
812
+ }
813
+ return callback(...views);
789
814
  } finally {
790
- this.controlBus[flagsAddress] &= ~VIEW_LOCK;
815
+ for (const key in lookup) {
816
+ this.controlBus[lookup[key] + FLAGS_OFFSET] &= ~VIEW_LOCK;
817
+ }
791
818
  }
792
819
  }
793
820
  // ======== CAPACIDAD EN RANURAS (CAPACITY IN SLOTS) ==========
@@ -1155,6 +1182,7 @@ var Balloc = class {
1155
1182
  out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1156
1183
  out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
1157
1184
  out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
1185
+ out.borrowed = this.controlAdapter.getUint32(out.headerAddress + FLAGS_OFFSET, IS_LITTLE_ENDIAN) & VIEW_LOCK;
1158
1186
  return out;
1159
1187
  }
1160
1188
  /**