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/en/balloc.mjs CHANGED
@@ -260,7 +260,7 @@ export default class Balloc {
260
260
  * supported limit.
261
261
  */
262
262
  realloc(handler) {
263
-
263
+
264
264
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
265
265
  const headerAddress = handler >>> 0;
266
266
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
@@ -305,23 +305,61 @@ export default class Balloc {
305
305
  this.recyclePush(oldBlockSize, dataAddress);
306
306
  }
307
307
 
308
- /**
309
- * Frees a memory block.
308
+ /**
309
+ * Reduces a block to the smallest power-of-two capacity that can contain
310
+ * its occupied elements, while preserving its address and handler.
310
311
  *
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.
312
+ * If the block is at the top of the dataBus, dataPointer is moved backward.
313
+ * Otherwise, the released tail is split into power-of-two regions and each
314
+ * region is returned to the recycling list.
317
315
  *
318
- * @param {number} handler - Handle of the block to be freed.
316
+ * @param {number} handler - Handler of the block to shrink.
319
317
  * @returns {void}
320
- * @throws {Error} If the handle is invalid, corrupted, or the block
321
- * is borrowed via withView().
318
+ * @throws {Error} If the handler is invalid, corrupted, or borrowed by withView().
322
319
  */
320
+ shrink(handler) {
321
+ const meta = this.extractMetadata(handler, this.metadata);
322
+ this.assertNotBorrowed(meta.headerAddress);
323
+
324
+ const newCapacity = Math.max(1, 32 - Math.clz32(Math.max(2, meta.occupied) - 1));
325
+ if (newCapacity >= meta.capacityExponent) return;
326
+
327
+ const oldBlockSize = meta.byteCapacity;
328
+ const newBlockSize = (2 ** newCapacity) * this.wordSize;
329
+ const oldEnd = meta.dataAddress + oldBlockSize;
330
+
331
+ this.controlAdapter.setUint8(meta.headerAddress + CAPACITY_OFFSET, newCapacity);
332
+
333
+ if (oldEnd === this.dataPointer) {
334
+ this.dataPointer = meta.dataAddress + newBlockSize;
335
+ return;
336
+ }
337
+
338
+ let address = meta.dataAddress + newBlockSize;
339
+ for (let exponent = newCapacity; exponent < meta.capacityExponent; exponent++) {
340
+ const segmentSize = (2 ** exponent) * this.wordSize;
341
+ this.recyclePush(segmentSize, address);
342
+ address += segmentSize;
343
+ }
344
+ }
345
+
346
+ /**
347
+ * Frees a memory block.
348
+ *
349
+ * The block's header is invalidated by zeroing its cookie, and its
350
+ * address is registered for later reuse. The data region
351
+ * is also returned to the recycling system, except when the block is
352
+ * exactly at the top of the `dataBus`; in that case, the `dataPointer` is simply
353
+ * rolled back, eliminating the region without creating an entry in the recycling
354
+ * list.
355
+ *
356
+ * @param {number} handler - Handle of the block to be freed.
357
+ * @returns {void}
358
+ * @throws {Error} If the handle is invalid, corrupted, or the block
359
+ * is borrowed via withView().
360
+ */
323
361
  free(handler) {
324
-
362
+
325
363
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
326
364
  const headerAddress = handler >>> 0;
327
365
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
@@ -529,7 +567,6 @@ export default class Balloc {
529
567
  * element. Block occupancy is incremented only when space is available
530
568
  * within its capacity.
531
569
  *
532
- * @param {number} handler - Block handle.
533
570
  * @param {number} value - Value to be inserted.
534
571
  * @returns {boolean} `true` if the value was inserted; `false` if the block
535
572
  * is already out of available space.
@@ -949,27 +986,45 @@ export default class Balloc {
949
986
  * also applies to subviews derived from the original view.
950
987
  *
951
988
  * @param {number} handler - Block handle.
952
- * @param {Function} callback - Function receiving the shared TypedArray.
989
+ * @param {...(number|Function)} args - One or more block handles followed by the callback.
953
990
  * @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.
991
+ * @throws {TypeError} If no handle is provided or the callback is not a function.
992
+ * @throws {Error} If a handle is invalid, duplicated, or already borrowed.
956
993
  */
957
- withView(handler, callback) {
994
+ withView(...args) {
995
+ if (args.length < 2) throw new TypeError("At least one handler and one callback are required");
996
+
997
+ const callback = args.pop();
958
998
  if (typeof callback !== "function") throw new TypeError("callback must be a function");
959
999
 
960
- const meta = this.extractMetadata(handler, this.metadata);
961
- const flagsAddress = meta.headerAddress + FLAGS_OFFSET;
962
- const flags = this.controlBus[flagsAddress];
1000
+ const handlers = args;
1001
+ const metadata = handlers.map(handler => this.extractMetadata(handler, {}));
1002
+ const headers = metadata.map(meta => meta.headerAddress);
1003
+
1004
+ if (new Set(headers).size !== headers.length) throw new Error("Duplicate handler");
1005
+
1006
+ const flags = headers.map(header => this.controlBus[header + FLAGS_OFFSET]);
963
1007
 
964
- if (flags & VIEW_LOCK) throw new Error("Block is already borrowed");
1008
+ if (flags.some(flag => flag & VIEW_LOCK)) throw new Error("Block is already borrowed");
965
1009
 
966
- this.controlBus[flagsAddress] = flags | VIEW_LOCK;
1010
+ let acquiredCount = 0;
967
1011
 
968
1012
  try {
969
- const rawAddress = meta.dataAddress >>> this.wordShift;
970
- return callback(this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied));
1013
+ for (const header of headers) {
1014
+ this.controlBus[header + FLAGS_OFFSET] |= VIEW_LOCK;
1015
+ acquiredCount++;
1016
+ }
1017
+
1018
+ const views = metadata.map(meta => {
1019
+ const rawAddress = meta.dataAddress >>> this.wordShift;
1020
+ return this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied);
1021
+ });
1022
+
1023
+ return callback(...views);
971
1024
  } finally {
972
- this.controlBus[flagsAddress] &= ~VIEW_LOCK;
1025
+ for (let i = 0; i < acquiredCount; i++) {
1026
+ this.controlBus[headers[i] + FLAGS_OFFSET] &= ~VIEW_LOCK;
1027
+ }
973
1028
  }
974
1029
  }
975
1030
 
@@ -1036,29 +1091,29 @@ export default class Balloc {
1036
1091
 
1037
1092
  // ========== Operations between blocks=============
1038
1093
 
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
- */
1094
+ /**
1095
+ * Copies occupied elements from one block to another.
1096
+ *
1097
+ * Copying starts at the first element of `source` and the first slot of
1098
+ * `destination`. The quantity effectively copied is limited by the number of
1099
+ * occupied elements in the source, the physical capacity of the destination, and the
1100
+ * limit specified in `slots`.
1101
+ *
1102
+ * Destination occupancy is increased, when necessary, to cover the
1103
+ * copied elements. Destination capacity is unchanged.
1104
+ *
1105
+ * The operation uses `Uint8Array.prototype.copyWithin()` on the `dataBus`,
1106
+ * therefore the return value is the `Uint8Array` representing the data bus.
1107
+ *
1108
+ * @param {number} source - Source block handle.
1109
+ * @param {number} destination - Destination block handle.
1110
+ * @param {number} [slots=UNKNOWN] - Maximum number of elements to copy.
1111
+ * `UNKNOWN` represents the sentinel value used not to impose an
1112
+ * additional limit.
1113
+ * @returns {Uint8Array} The `dataBus` after the operation.
1114
+ * @throws {Error} If handles are invalid, corrupted,
1115
+ * or the destination block is borrowed via withView().
1116
+ */
1062
1117
  copy(source, destination, slots = UNKNOWN) {
1063
1118
  /** @type {Metadata} */
1064
1119
  const metaA = {};
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,36 @@ 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 callback = args.pop();
780
799
  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;
800
+ const handlers = args;
801
+ const metadata = handlers.map((handler) => this.extractMetadata(handler, {}));
802
+ const headers = metadata.map((meta) => meta.headerAddress);
803
+ if (new Set(headers).size !== headers.length) throw new Error("Duplicate handler");
804
+ const flags = headers.map((header) => this.controlBus[header + FLAGS_OFFSET]);
805
+ if (flags.some((flag) => flag & VIEW_LOCK)) throw new Error("Block is already borrowed");
806
+ let acquiredCount = 0;
786
807
  try {
787
- const rawAddress = meta.dataAddress >>> this.wordShift;
788
- return callback(this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied));
808
+ for (const header of headers) {
809
+ this.controlBus[header + FLAGS_OFFSET] |= VIEW_LOCK;
810
+ acquiredCount++;
811
+ }
812
+ const views = metadata.map((meta) => {
813
+ const rawAddress = meta.dataAddress >>> this.wordShift;
814
+ return this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied);
815
+ });
816
+ return callback(...views);
789
817
  } finally {
790
- this.controlBus[flagsAddress] &= ~VIEW_LOCK;
818
+ for (let i = 0; i < acquiredCount; i++) {
819
+ this.controlBus[headers[i] + FLAGS_OFFSET] &= ~VIEW_LOCK;
820
+ }
791
821
  }
792
822
  }
793
823
  // ======== CAPACIDAD EN RANURAS (CAPACITY IN SLOTS) ==========