balloc 1.0.1 → 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.cjs CHANGED
@@ -43,6 +43,8 @@ var ADDRESS_OFFSET = 0 >>> 0;
43
43
  var OCCUPIED_OFFSET = 4 >>> 0;
44
44
  var CAPACITY_OFFSET = 8 >>> 0;
45
45
  var COOKIE_OFFSET = 9 >>> 0;
46
+ var FLAGS_OFFSET = 10 >>> 0;
47
+ var VIEW_LOCK = 1 >>> 0;
46
48
  var ROTATE_32BITS = 4294967296;
47
49
  var CLAMP_11BITS = 2047 >>> 0;
48
50
  var isTypedArray = (val) => ArrayBuffer.isView(val) && !(val instanceof DataView);
@@ -54,24 +56,24 @@ var Balloc = class {
54
56
  * - `dataBus`: stores the data of allocated blocks;
55
57
  * - `controlBus`: stores headers and other control metadata.
56
58
  *
57
- * Each block has a fixed-size header (`HEADER_SIZE`) and is externally
58
- * identified by a 43-bit logical handle, composed of an 11-bit generation
59
- * and a 32-bit header address.
59
+ * Each block has a fixed-size header (`HEADER_SIZE`) and is
60
+ * identified externally by a 43-bit logical handle, composed
61
+ * of an 11-bit generation and its 32-bit header address.
60
62
  *
61
- * The capacity of each block is rounded up to the next power of two
62
- * in elements, respecting the configured bucket width.
63
+ * The capacity of each block is rounded up to the next power of
64
+ * two in elements, respecting the width of the configured bucket.
63
65
  *
64
66
  * @param {number} [size=65535] - Initial capacity of the `dataBus`, in bytes.
65
67
  * Must be a safe integer in the range [2, 0x80000000].
66
- * @param {BucketType} [bucketSize="32u"] - Bucket type and size identifier
68
+ * @param {BucketType} [bucketSize="32u"] - Identifier for the bucket type and size
67
69
  * (e.g., '32u' for Uint32, '64f' for Float64, '8i' for Int8).
68
70
  * @param {number} [metadataSize=1024] - Initial capacity of the `controlBus`,
69
71
  * in bytes. Must be a safe integer in the range
70
72
  * [HEADER_SIZE, 0x80000000].
71
73
  *
72
- * @throws {RangeError} If `size` is out of the allowed range.
74
+ * @throws {RangeError} If `size` is outside the allowed range.
73
75
  * @throws {RangeError} If `bucketSize` is not a valid bucket identifier.
74
- * @throws {RangeError} If `metadataSize` is out of the allowed range.
76
+ * @throws {RangeError} If `metadataSize` is outside the allowed range.
75
77
  */
76
78
  constructor(size = 65535, bucketSize = "32u", metadataSize = 1024) {
77
79
  if (!Number.isSafeInteger(size) || size < 2 || size > 2147483648) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
@@ -85,8 +87,8 @@ var Balloc = class {
85
87
  this.bucketArray = globalThis[`${this.bucketType}Array`];
86
88
  this.wordSize = this.bucketSize >>> 3;
87
89
  this.wordShift = this.bucketSize >>> 4;
88
- this.size = Math.max(1 << 32 - Math.clz32(size) >>> 0, this.wordSize);
89
- this.headerSize = 1 << 32 - Math.clz32(metadataSize) >>> 0;
90
+ this.size = Math.max(1 << 32 - Math.clz32(size - 1) >>> 0, this.wordSize);
91
+ this.headerSize = 1 << 32 - Math.clz32(metadataSize - 1) >>> 0;
90
92
  this.dataPointer = 0 >>> 0;
91
93
  this.controlPointer = 0 >>> 0;
92
94
  this.echoPointer = 0 >>> 0;
@@ -113,24 +115,26 @@ var Balloc = class {
113
115
  * Allocates a new memory block.
114
116
  *
115
117
  * The requested capacity is converted to the smallest power of two that
116
- * accommodates `size` elements. The block is preferably obtained from the list
117
- * of recyclable regions with the corresponding capacity; if no compatible
118
- * region exists, the block is reserved at the top of the `dataBus`.
118
+ * can accommodate `size` elements. The block is obtained preferentially from the list
119
+ * of recyclable regions with the corresponding capacity; if a compatible
120
+ * region does not exist, the block is reserved at the top of the `dataBus`.
119
121
  *
120
122
  * Next, a header is obtained from the control space. Previously freed headers
121
- * can be reused via the internal recycling stack; otherwise, the `controlBus`
122
- * is expanded when necessary.
123
+ * can be reused via the internal recycling stack;
124
+ * otherwise, the `controlBus` is expanded when necessary.
123
125
  *
124
126
  * The header receives the address, capacity, initial occupancy (zero), and
125
127
  * a validation cookie. The returned value encodes the allocation generation
126
128
  * and the header address:
127
129
  *
128
- * [11 bits generation][32 bits header address]
130
+ * [11 generation bits][32 header address bits]
129
131
  *
130
132
  * @param {number} [size=16] - Minimum number of elements the block must
131
133
  * accommodate. Must be a safe integer in the range [2, 0x80000000].
132
134
  * @returns {number} Handle identifying the allocated block.
133
- * @throws {RangeError} If `size` is out of the allowed range.
135
+ * @throws {RangeError} If `size` is outside the allowed range.
136
+ * @throws {Error} If it is necessary to expand the `dataBus` while any
137
+ * block is borrowed via withView().
134
138
  */
135
139
  alloc(size = 16) {
136
140
  if (!Number.isSafeInteger(size) || size < 2 || size > 2147483648) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
@@ -156,31 +160,35 @@ var Balloc = class {
156
160
  this.controlAdapter.setUint32(headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
157
161
  this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, capacity);
158
162
  this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, this.bakeCookie(headerAddress, ++this.generation));
163
+ this.controlBus[headerAddress + FLAGS_OFFSET] = 0;
159
164
  return (this.generation & CLAMP_11BITS) * ROTATE_32BITS + headerAddress;
160
165
  }
161
166
  /**
162
167
  * Expands a block's capacity to the next power of two.
163
168
  *
164
169
  * When the block is located at the current top of the `dataBus`, expansion
165
- * occurs in-place: only its capacity and `dataPointer` are updated.
170
+ * occurs in-place: only its capacity and `dataPointer` are
171
+ * updated.
166
172
  *
167
173
  * If another region exists after the block, a new region with double the
168
- * capacity is obtained from the recyclable space or allocated at the top of
169
- * the `dataBus`. Currently occupied elements are then copied to the new region,
174
+ * capacity is obtained from the recyclable space or allocated at the top of the `dataBus`.
175
+ * The currently occupied elements are then copied to the new region,
170
176
  * and the previous region is returned to the recycling list.
171
177
  *
172
- * The handle remains valid because its header is preserved, and only the
173
- * address and capacity recorded within it are updated.
178
+ * The handle remains valid because its header is preserved and only the
179
+ * address and capacity recorded in it are updated.
174
180
  *
175
- * @param {number} handler - Handle of the block to expand.
181
+ * @param {number} handler - Handle of the block to be expanded.
176
182
  * @returns {void}
177
- * @throws {Error} If the handle is invalid or corrupted.
178
- * @throws {AggregateError} If the capacity has reached its maximum
183
+ * @throws {Error} If the handle is invalid, corrupted, or the block
184
+ * is borrowed via withView(). Also occurs if expansion requires
185
+ * dataBus remapping while another block is borrowed.
186
+ * @throws {AggregateError} If the capacity has reached the maximum
179
187
  * supported limit.
180
188
  */
181
189
  realloc(handler) {
182
190
  const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
183
- let headerAddress = handler >>> 0;
191
+ const headerAddress = handler >>> 0;
184
192
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
185
193
  const occupied = this.controlAdapter.getUint32(headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
186
194
  const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
@@ -188,49 +196,85 @@ var Balloc = class {
188
196
  if (cookie !== this.bakeCookie(headerAddress, generation)) {
189
197
  throw new Error("Invalid or corrupted handle");
190
198
  }
199
+ this.assertNotBorrowed(headerAddress);
191
200
  if (capacity >= 31) throw new AggregateError([new Error("Can\xB4t reallocate handler."), new RangeError("Capacity has reached its limit.")], "Internal Error.");
192
201
  const newCapacity = capacity + 1;
193
202
  const newBlockSize = (1 << newCapacity >>> 0) * this.wordSize;
194
203
  const oldBlockSize = (1 << capacity >>> 0) * this.wordSize;
195
204
  if (dataAddress + oldBlockSize === this.dataPointer) {
196
205
  while (dataAddress + newBlockSize > this.size) this.grow();
197
- this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity, IS_LITTLE_ENDIAN);
206
+ this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
198
207
  this.dataPointer = dataAddress + newBlockSize;
199
208
  return;
200
209
  }
201
- this.recyclePush(oldBlockSize, dataAddress);
202
210
  let newAddress = this.recyclePop(newBlockSize);
203
211
  if (newAddress === UNKNOWN) {
204
212
  while (this.dataPointer + newBlockSize > this.size) this.grow();
205
213
  newAddress = this.dataPointer;
206
214
  this.dataPointer += newBlockSize;
207
215
  }
208
- this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
209
216
  this.dataBus.copyWithin(newAddress, dataAddress, dataAddress + occupied * this.wordSize);
210
217
  this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, newAddress, IS_LITTLE_ENDIAN);
218
+ this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
219
+ this.recyclePush(oldBlockSize, dataAddress);
211
220
  }
212
221
  /**
213
- * Frees a memory block.
222
+ * Reduces a block to the smallest power-of-two capacity that can contain
223
+ * its occupied elements, while preserving its address and handler.
214
224
  *
215
- * The block's header is invalidated by zeroing its cookie, and its address
216
- * is registered for later reuse. The data region is also returned to the
217
- * recycling system, except when the block is exactly at the top of the
218
- * `dataBus`; in that case, `dataPointer` is simply rolled back, eliminating
219
- * the region without creating an entry in the recycling list.
225
+ * If the block is at the top of the dataBus, dataPointer is moved backward.
226
+ * Otherwise, the released tail is split into power-of-two regions and each
227
+ * region is returned to the recycling list.
220
228
  *
221
- * @param {number} handler - Handle of the block to free.
229
+ * @param {number} handler - Handler of the block to shrink.
222
230
  * @returns {void}
223
- * @throws {Error} If the handle is invalid or corrupted.
231
+ * @throws {Error} If the handler is invalid, corrupted, or borrowed by withView().
224
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
+ }
253
+ /**
254
+ * Frees a memory block.
255
+ *
256
+ * The block's header is invalidated by zeroing its cookie, and its
257
+ * address is registered for later reuse. The data region
258
+ * is also returned to the recycling system, except when the block is
259
+ * exactly at the top of the `dataBus`; in that case, the `dataPointer` is simply
260
+ * rolled back, eliminating the region without creating an entry in the recycling
261
+ * list.
262
+ *
263
+ * @param {number} handler - Handle of the block to be freed.
264
+ * @returns {void}
265
+ * @throws {Error} If the handle is invalid, corrupted, or the block
266
+ * is borrowed via withView().
267
+ */
225
268
  free(handler) {
226
269
  const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
227
- let headerAddress = handler >>> 0;
270
+ const headerAddress = handler >>> 0;
228
271
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
229
272
  const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
230
273
  const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
231
274
  if (cookie !== this.bakeCookie(headerAddress, generation)) {
232
275
  throw new Error("Invalid or corrupted handle");
233
276
  }
277
+ this.assertNotBorrowed(headerAddress);
234
278
  const blockSize = (1 << capacity >>> 0) * this.wordSize;
235
279
  this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
236
280
  if (this.echoPointer + 4 <= this.controlBus.byteLength) {
@@ -249,13 +293,13 @@ var Balloc = class {
249
293
  * Inserts a free region into the recycling list.
250
294
  *
251
295
  * The list is organized by capacity in bytes. For each capacity, the
252
- * stored value is a `Uint32Array` whose zero position contains the number
253
- * of registered addresses, and subsequent positions contain the addresses
254
- * of the free regions:
296
+ * stored value is a `Uint32Array` whose zero position contains the quantity
297
+ * of registered addresses and subsequent positions contain the addresses of
298
+ * the free regions:
255
299
  *
256
300
  * [count, address1, address2, ...]
257
301
  *
258
- * When the page becomes full, its buffer is expanded to double the current
302
+ * When the page becomes full, its buffer is expanded to double its current
259
303
  * capacity.
260
304
  *
261
305
  * @param {number} capacity - Capacity of the free region, in bytes.
@@ -288,7 +332,7 @@ var Balloc = class {
288
332
  *
289
333
  * @param {number} capacity - Desired capacity, in bytes.
290
334
  * @returns {number} Initial address of a recyclable region or `UNKNOWN`
291
- * when no region exists with the requested capacity.
335
+ * when a region with the requested capacity does not exist.
292
336
  * @private
293
337
  */
294
338
  recyclePop(capacity) {
@@ -305,25 +349,28 @@ var Balloc = class {
305
349
  * Compacts the `dataBus` using the ReBump algorithm.
306
350
  *
307
351
  * Sequentially traverses the headers registered in the `controlBus` and copies
308
- * still-valid regions to a new `dataBus`, eliminating free spaces between them.
309
- * The address of each surviving block is updated in its respective header.
352
+ * still-valid regions to a new `dataBus`, eliminating free spaces
353
+ * between them. Each surviving block's address is updated in its
354
+ * respective header.
310
355
  *
311
- * The order of blocks in the `controlBus` is preserved. Internal data of each
312
- * block is also fully preserved, including its reserved capacity and current
313
- * occupancy.
356
+ * The order of blocks in the `controlBus` is preserved. The internal data of
357
+ * each block is also fully preserved, including its reserved capacity
358
+ * and current occupancy.
314
359
  *
315
- * At the end of compaction:
360
+ * Upon completion of compaction:
316
361
  * - all recyclable regions are eliminated;
317
362
  * - `dataPointer` points to the first byte after the last live block;
318
- * - `dataBus` represents a contiguous heap for active blocks.
363
+ * - the `dataBus` represents a contiguous heap for active blocks.
319
364
  *
320
- * Control complexity is O(n), where `n` is the number of headers traversed.
321
- * The effective cost of memory movement also depends on the volume of bytes
322
- * belonging to live blocks.
365
+ * Control complexity is O(n), where `n` is the number of traversed
366
+ * headers. The effective memory movement cost also depends on the volume
367
+ * of bytes belonging to live blocks.
323
368
  *
324
369
  * @returns {void}
370
+ * @throws {Error} If any block is borrowed via withView().
325
371
  */
326
372
  gc() {
373
+ this.assertNoActiveViews();
327
374
  const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
328
375
  this.recycle.clear();
329
376
  this.dataPointer = 0 >>> 0;
@@ -348,15 +395,17 @@ var Balloc = class {
348
395
  * Expands the `dataBus` to double its current capacity.
349
396
  *
350
397
  * The underlying buffer is transferred to a larger `ArrayBuffer`, preserving
351
- * existing data. All views associated with the buffer are recreated to reference
352
- * the new storage.
398
+ * existing data. All views associated with the buffer are recreated
399
+ * to reference the new storage.
353
400
  *
354
401
  * @returns {void}
355
- * @throws {RangeError} If the `dataBus` capacity has exceeded the maximum
356
- * supported limit.
402
+ * @throws {Error} If any block is borrowed via withView().
403
+ * @throws {RangeError} If the `dataBus` capacity has already exceeded the
404
+ * maximum supported limit.
357
405
  * @private
358
406
  */
359
407
  grow() {
408
+ this.assertNoActiveViews();
360
409
  if (this.size > 2147483648) throw new RangeError("Data bus capacity exceeded");
361
410
  const newSize = this.size * 2 >>> 0;
362
411
  const newBuffer = this.dataBus.buffer.transfer(newSize);
@@ -372,12 +421,12 @@ var Balloc = class {
372
421
  * Expands the `controlBus` to double its current capacity.
373
422
  *
374
423
  * The underlying buffer is transferred to a larger `ArrayBuffer`, preserving
375
- * existing headers. The `controlAdapter` is recreated to reference the new
376
- * storage.
424
+ * existing headers. The `controlAdapter` is recreated to reference
425
+ * the new storage.
377
426
  *
378
427
  * @returns {void}
379
- * @throws {RangeError} If the current `controlBus` capacity has exceeded
380
- * the maximum supported limit.
428
+ * @throws {RangeError} If the current `controlBus` capacity has already
429
+ * exceeded the maximum supported limit.
381
430
  * @private
382
431
  */
383
432
  headerGrow() {
@@ -389,39 +438,41 @@ var Balloc = class {
389
438
  }
390
439
  // ========== STACK OPERATIONS ==========
391
440
  /**
392
- * Appends an element to the end of the block's occupied sequence.
441
+ * Appends an element to the end of the sequence occupied by the block.
393
442
  *
394
443
  * The element is written at the first free position after the last occupied
395
- * element. Block occupancy is incremented only when space is available within
396
- * its capacity.
444
+ * element. Block occupancy is incremented only when space is available
445
+ * within its capacity.
397
446
  *
398
- * @param {number} handler - Block handle.
399
- * @param {number} value - Value to insert.
447
+ * @param {number} value - Value to be inserted.
400
448
  * @returns {boolean} `true` if the value was inserted; `false` if the block
401
- * has no available space.
402
- * @throws {Error} If the handle is invalid or corrupted.
449
+ * is already out of available space.
450
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
451
+ *
403
452
  */
404
453
  push(handler, value) {
405
454
  const meta = this.extractMetadata(handler, this.metadata);
455
+ this.assertNotBorrowed(meta.headerAddress);
406
456
  if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
407
457
  this.writer(meta.dataAddress + meta.occupied * this.wordSize, value, IS_LITTLE_ENDIAN);
408
458
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
409
459
  return true;
410
460
  }
411
461
  /**
412
- * Removes and returns the last occupied element from the block.
462
+ * Removes the last occupied element from the block and returns it.
413
463
  *
414
- * Occupancy is decremented before reading the removed element. Corresponding
464
+ * Occupancy is decremented before reading the removed element. The corresponding
415
465
  * bytes are not cleared and remain in the allocated region, but cease to be
416
466
  * part of the occupied sequence.
417
467
  *
418
468
  * @param {number} handler - Block handle.
419
469
  * @returns {number|undefined} Removed value or `undefined` if the block
420
470
  * is empty.
421
- * @throws {Error} If the handle is invalid or corrupted.
471
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
422
472
  */
423
473
  pop(handler) {
424
474
  const meta = this.extractMetadata(handler, this.metadata);
475
+ this.assertNotBorrowed(meta.headerAddress);
425
476
  if (meta.occupied === 0) return void 0;
426
477
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
427
478
  return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
@@ -443,21 +494,22 @@ var Balloc = class {
443
494
  /**
444
495
  * Inserts an element at the beginning of the occupied sequence.
445
496
  *
446
- * Currently occupied elements are shifted one position forward and `value`
447
- * is written to the first position. The operation requires a free position
448
- * within the block's capacity.
497
+ * Currently occupied elements are shifted forward by one position and
498
+ * `value` is written at the first position. The operation requires a free
499
+ * position within the block's capacity.
449
500
  *
450
- * The operation's cost is proportional to the number of occupied elements,
501
+ * The operation cost is proportional to the number of occupied elements,
451
502
  * as data needs to be shifted.
452
503
  *
453
504
  * @param {number} handler - Block handle.
454
- * @param {number} value - Value to insert.
505
+ * @param {number} value - Value to be inserted.
455
506
  * @returns {boolean} `true` if the value was inserted; `false` if the block
456
507
  * is full.
457
- * @throws {Error} If the handle is invalid or corrupted.
508
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
458
509
  */
459
510
  nudge(handler, value) {
460
511
  const meta = this.extractMetadata(handler, this.metadata);
512
+ this.assertNotBorrowed(meta.headerAddress);
461
513
  if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
462
514
  this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
463
515
  this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
@@ -465,20 +517,21 @@ var Balloc = class {
465
517
  return true;
466
518
  }
467
519
  /**
468
- * Removes and returns the first occupied element from the block.
520
+ * Removes the first occupied element from the block and returns it.
469
521
  *
470
- * Remaining elements are shifted one position toward the beginning of the
471
- * occupied region. The block's physical capacity remains unchanged.
522
+ * Remaining elements are shifted one position toward the beginning
523
+ * of the occupied region. The physical capacity of the block remains unchanged.
472
524
  *
473
- * The operation's cost is proportional to the number of shifted elements.
525
+ * The operation cost is proportional to the number of shifted elements.
474
526
  *
475
527
  * @param {number} handler - Block handle.
476
528
  * @returns {number|undefined} First removed value or `undefined` if the
477
529
  * block is empty.
478
- * @throws {Error} If the handle is invalid or corrupted.
530
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
479
531
  */
480
532
  pull(handler) {
481
533
  const meta = this.extractMetadata(handler, this.metadata);
534
+ this.assertNotBorrowed(meta.headerAddress);
482
535
  if (meta.occupied === 0) return void 0;
483
536
  const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
484
537
  this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
@@ -500,15 +553,15 @@ var Balloc = class {
500
553
  }
501
554
  // ========== RANDOM ACCESS ==========
502
555
  /**
503
- * Checks if a value is present among the block's occupied elements.
556
+ * Checks if a value is present among the occupied elements of the block.
504
557
  *
505
558
  * The search is performed directly on the auxiliary `TypedArray` and considers
506
559
  * only the currently occupied range, not the entire reserved physical capacity.
507
560
  *
508
561
  * @param {number} handler - Block handle.
509
562
  * @param {number} value - Value to search for.
510
- * @returns {boolean} `true` if `value` is present among the occupied elements;
511
- * otherwise, `false`.
563
+ * @returns {boolean} `true` if `value` is present among the occupied
564
+ * elements; otherwise, `false`.
512
565
  * @throws {Error} If the handle is invalid or corrupted.
513
566
  */
514
567
  has(handler, value) {
@@ -517,6 +570,53 @@ var Balloc = class {
517
570
  const rawAddres = meta.dataAddress >>> this.wordShift;
518
571
  return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
519
572
  }
573
+ /**
574
+ * Locates the first occurrence of an element in the block's occupied sequence.
575
+ *
576
+ * The search is performed in ascending order of indices, using the `indexOf`
577
+ * operation of the underlying TypedArray. The search exclusively considers
578
+ * occupied elements, ignoring the block's unused capacity.
579
+ *
580
+ * The starting search position can be specified by `fromIndex`,
581
+ * following TypedArray indexing rules.
582
+ *
583
+ * @param {number} handler - Block handle.
584
+ * @param {number|bigint} searchElement - Element to locate.
585
+ * @param {number} [fromIndex=0] - Index from which to start the search.
586
+ * @returns {number} Index of the first occurrence or `-1` if the
587
+ * element is not found or if the block is empty.
588
+ * @throws {Error} If the handle is invalid or corrupted.
589
+ */
590
+ indexOf(handler, searchElement, fromIndex = 0) {
591
+ const meta = this.extractMetadata(handler, this.metadata);
592
+ if (meta.occupied === 0) return -1;
593
+ const rawAddres = meta.dataAddress >>> this.wordShift;
594
+ return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).indexOf(searchElement, fromIndex);
595
+ }
596
+ /**
597
+ * Locates the last occurrence of an element in the block's occupied sequence.
598
+ *
599
+ * The search is performed in descending order of indices, using the `lastIndexOf`
600
+ * operation of the underlying TypedArray. The search exclusively considers
601
+ * occupied elements, ignoring the block's unused capacity.
602
+ *
603
+ * The starting search position can be specified by `fromIndex`,
604
+ * following TypedArray indexing rules. By default, the search starts
605
+ * at the last occupied element.
606
+ *
607
+ * @param {number} handler - Block handle.
608
+ * @param {number|bigint} searchElement - Element to locate.
609
+ * @param {number} [fromIndex=-1] - Index from which to start the search.
610
+ * @returns {number} Index of the last occurrence or `-1` if the
611
+ * element is not found or if the block is empty.
612
+ * @throws {Error} If the handle is invalid or corrupted.
613
+ */
614
+ lastIndexOf(handler, searchElement, fromIndex = -1) {
615
+ const meta = this.extractMetadata(handler, this.metadata);
616
+ if (meta.occupied === 0) return -1;
617
+ const rawAddres = meta.dataAddress >>> this.wordShift;
618
+ return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).lastIndexOf(searchElement, fromIndex);
619
+ }
520
620
  /**
521
621
  * Returns the occupied element at a zero-based index.
522
622
  *
@@ -545,29 +645,32 @@ var Balloc = class {
545
645
  * @param {number} value - New value.
546
646
  * @returns {boolean} `true` if the value was written; `false` if the index
547
647
  * is outside the occupied region.
548
- * @throws {Error} If the handle is invalid or corrupted.
648
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
549
649
  */
550
650
  set(handler, index, value) {
551
651
  const meta = this.extractMetadata(handler, this.metadata);
652
+ this.assertNotBorrowed(meta.headerAddress);
552
653
  if (index < 0 || index >= meta.occupied) return false;
553
654
  this.writer(meta.dataAddress + index * this.wordSize, value, IS_LITTLE_ENDIAN);
554
655
  return true;
555
656
  }
556
657
  // ============= MISCELLANEOUS ===============
557
658
  /**
558
- * Clears block occupancy and fills its entire physical capacity with a single value.
659
+ * Zeroes block occupancy and fills its entire physical capacity with
660
+ * a single value.
559
661
  *
560
- * Filling covers all available slots, not just currently occupied elements.
561
- * After the operation, the block is considered empty regardless of the value
562
- * used for filling.
662
+ * The fill covers all available slots, not just currently
663
+ * occupied elements. After the operation, the block is considered
664
+ * empty regardless of the value used for filling.
563
665
  *
564
666
  * @param {number} handler - Block handle.
565
667
  * @param {number} [value=0] - Value used to fill all slots.
566
668
  * @returns {void}
567
- * @throws {Error} If the handle is invalid or corrupted.
669
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
568
670
  */
569
671
  clear(handler, value = 0) {
570
672
  const meta = this.extractMetadata(handler, this.metadata);
673
+ this.assertNotBorrowed(meta.headerAddress);
571
674
  const slots = meta.byteCapacity / this.wordSize;
572
675
  const rawAddress = meta.dataAddress >>> this.wordShift;
573
676
  this.auxiliary.fill(value, rawAddress, rawAddress + slots);
@@ -576,25 +679,27 @@ var Balloc = class {
576
679
  /**
577
680
  * Fills a range of block slots with a value.
578
681
  *
579
- * The range uses zero-based indices and follows the convention `[start, end)`,
580
- * meaning `start` is inclusive and `end` is exclusive. When `end` is not provided,
581
- * filling extends to the end of the block's physical capacity.
682
+ * The range uses zero-based indices and follows the convention
683
+ * `[start, end)`, therefore `start` is inclusive and `end` is exclusive.
684
+ * When `end` is not provided, filling extends to the end of the block's
685
+ * physical capacity.
582
686
  *
583
- * Block occupancy becomes `end`, including when the filled range extends beyond
584
- * the previous occupancy.
687
+ * Block occupancy becomes `end`, including when the filled range
688
+ * extends beyond previous occupancy.
585
689
  *
586
690
  * @param {number} handler - Block handle.
587
691
  * @param {number} value - Value used for filling.
588
692
  * @param {number} [start=0] - Initial index, inclusive.
589
- * @param {number|null} [end=null] - Final index, exclusive. When omitted or
590
- * `null`, uses the total block capacity.
693
+ * @param {number|null} [end=null] - Final index, exclusive. When
694
+ * omitted or `null`, uses the block's total capacity.
591
695
  * @returns {void}
592
- * @throws {Error} If the handle is invalid or corrupted.
593
- * @throws {RangeError} If `start` or `end` is out of capacity bounds, or if
594
- * `start > end`.
696
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
697
+ * @throws {RangeError} If `start` or `end` is outside capacity limits,
698
+ * or if `start > end`.
595
699
  */
596
700
  fill(handler, value, start = 0, end = null) {
597
701
  const meta = this.extractMetadata(handler, this.metadata);
702
+ this.assertNotBorrowed(meta.headerAddress);
598
703
  const slots = meta.byteCapacity / this.wordSize;
599
704
  const lastIndex = end ?? slots;
600
705
  if (start > lastIndex) {
@@ -614,15 +719,16 @@ var Balloc = class {
614
719
  * Fills all physical slots of the block with a value and marks the entire
615
720
  * capacity as occupied.
616
721
  *
617
- * Unlike `clear()`, the operation results in a fully occupied block.
722
+ * Unlike `clear()`, this operation results in a fully occupied block.
618
723
  *
619
724
  * @param {number} handler - Block handle.
620
725
  * @param {number} value - Value used for filling.
621
726
  * @returns {void}
622
- * @throws {Error} If the handle is invalid or corrupted.
727
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
623
728
  */
624
729
  fillAll(handler, value) {
625
730
  const meta = this.extractMetadata(handler, this.metadata);
731
+ this.assertNotBorrowed(meta.headerAddress);
626
732
  const rawAddress = meta.dataAddress >>> this.wordShift;
627
733
  const capacityElements = meta.byteCapacity / this.wordSize;
628
734
  this.auxiliary.fill(value, rawAddress, rawAddress + capacityElements);
@@ -631,25 +737,25 @@ var Balloc = class {
631
737
  /**
632
738
  * Copies elements from an `Array` or `TypedArray` to the beginning of the block.
633
739
  *
634
- * The copied quantity is limited by the block's capacity. Occupancy is updated
635
- * to the greater value between the previous occupancy and the quantity effectively
636
- * copied; therefore, a call to `put()` does not reduce existing occupancy when
637
- * receiving a smaller sequence.
740
+ * The copied quantity is limited by the block's capacity. Occupancy is
741
+ * updated to the greater value between previous occupancy and the quantity
742
+ * effectively copied; therefore, a call to `put()` does not reduce existing
743
+ * occupancy when receiving a smaller sequence.
638
744
  *
639
- * For `Array`, only the first fitting elements are copied. For `TypedArray`,
640
- * a source subarray is used without intermediate copying.
745
+ * For `Array`, only the first elements that fit are copied.
746
+ * For `TypedArray`, a source subarray is used without intermediate copying.
641
747
  *
642
748
  * @param {number} handler - Block handle.
643
749
  * @param {Array|TypedArray} data - Sequence of values to copy.
644
750
  * @returns {void}
645
- * @throws {Error} If the handle is invalid or corrupted.
751
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
646
752
  * @throws {TypeError} If `data` is neither an `Array` nor a `TypedArray`.
647
753
  */
648
754
  put(handler, data) {
649
755
  const meta = this.extractMetadata(handler, this.metadata);
756
+ this.assertNotBorrowed(meta.headerAddress);
650
757
  const rawAddress = meta.dataAddress >>> this.wordShift;
651
758
  const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
652
- meta.occupied = Math.max(length, meta.occupied);
653
759
  if (Array.isArray(data)) {
654
760
  this.auxiliary.set(data.slice(0, length), rawAddress);
655
761
  } else if (isTypedArray(data)) {
@@ -658,20 +764,21 @@ var Balloc = class {
658
764
  const actual = data?.constructor?.name ?? (data === null ? "null" : typeof data);
659
765
  throw new TypeError(`data must be Array or TypedArray, but ${actual} was given.`);
660
766
  }
661
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
767
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, Math.max(length, meta.occupied), IS_LITTLE_ENDIAN);
662
768
  }
663
769
  /**
664
770
  * Returns a copy of the elements currently occupied by the block.
665
771
  *
666
- * The result is a `TypedArray` of the same type configured by `bucketSize`.
667
- * Unoccupied physical capacity is not included in the result.
772
+ * The result is a `TypedArray` of the same type configured by
773
+ * `bucketSize`. Unoccupied physical capacity is not included in the result.
668
774
  *
669
- * The operation does not directly expose internal storage: the method uses
670
- * `TypedArray.prototype.slice()`, producing a new view with independent storage.
775
+ * The operation does not directly expose internal storage: the method
776
+ * uses `TypedArray.prototype.slice()`, producing a new view with
777
+ * independent storage.
671
778
  *
672
779
  * @param {number} handler - Block handle.
673
- * @returns {TypedArray} Copy of the elements occupied by the block. When the
674
- * block is empty, returns an empty `TypedArray` of the configured type.
780
+ * @returns {TypedArray} Copy of elements occupied by the block. When
781
+ * the block is empty, returns an empty `TypedArray` of the configured type.
675
782
  * @throws {Error} If the handle is invalid or corrupted.
676
783
  */
677
784
  pick(handler) {
@@ -682,12 +789,55 @@ var Balloc = class {
682
789
  }
683
790
  return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
684
791
  }
792
+ /**
793
+ * Executes a callback over a direct view of the block's occupied region.
794
+ *
795
+ * The view shares Balloc's internal storage and performs no copying.
796
+ * The block is protected against incompatible operations during the callback.
797
+ *
798
+ * The callback must be synchronous. The received view must not be stored,
799
+ * returned, or used after the callback terminates. This restriction
800
+ * also applies to subviews derived from the original view.
801
+ *
802
+ * @param {number} handler - Block handle.
803
+ * @param {...(number|Function)} args - One or more block handles followed by the callback.
804
+ * @returns {*} Return value produced by the callback.
805
+ * @throws {TypeError} If no handle is provided or the callback is not a function.
806
+ * @throws {Error} If a handle is invalid, duplicated, or already borrowed.
807
+ */
808
+ withView(...args) {
809
+ if (args.length < 2) throw new TypeError("At least one handler and one callback are required");
810
+ const callback = args.pop();
811
+ if (typeof callback !== "function") throw new TypeError("callback must be a function");
812
+ const handlers = args;
813
+ const metadata = handlers.map((handler) => this.extractMetadata(handler, {}));
814
+ const headers = metadata.map((meta) => meta.headerAddress);
815
+ if (new Set(headers).size !== headers.length) throw new Error("Duplicate handler");
816
+ const flags = headers.map((header) => this.controlBus[header + FLAGS_OFFSET]);
817
+ if (flags.some((flag) => flag & VIEW_LOCK)) throw new Error("Block is already borrowed");
818
+ let acquiredCount = 0;
819
+ try {
820
+ for (const header of headers) {
821
+ this.controlBus[header + FLAGS_OFFSET] |= VIEW_LOCK;
822
+ acquiredCount++;
823
+ }
824
+ const views = metadata.map((meta) => {
825
+ const rawAddress = meta.dataAddress >>> this.wordShift;
826
+ return this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied);
827
+ });
828
+ return callback(...views);
829
+ } finally {
830
+ for (let i = 0; i < acquiredCount; i++) {
831
+ this.controlBus[headers[i] + FLAGS_OFFSET] &= ~VIEW_LOCK;
832
+ }
833
+ }
834
+ }
685
835
  // ======== CAPACITY IN SLOTS ==========
686
836
  /**
687
837
  * Returns the physical capacity of the block in bytes.
688
838
  *
689
- * Capacity corresponds to the space reserved for all slots in the block,
690
- * regardless of how many elements are currently occupied.
839
+ * Capacity corresponds to the space reserved for all slots in the
840
+ * block, regardless of how many elements are currently occupied.
691
841
  *
692
842
  * @param {number} handler - Block handle.
693
843
  * @returns {number} Physical capacity of the block, in bytes.
@@ -709,9 +859,9 @@ var Balloc = class {
709
859
  return meta.occupied;
710
860
  }
711
861
  /**
712
- * Returns the capacity of the block in number of elements.
862
+ * Returns the block's capacity in number of elements.
713
863
  *
714
- * The value corresponds to the total quantity of physically reserved slots,
864
+ * The value corresponds to the total number of physically reserved slots,
715
865
  * not the currently occupied quantity.
716
866
  *
717
867
  * @param {number} handler - Block handle.
@@ -722,33 +872,51 @@ var Balloc = class {
722
872
  const meta = this.extractMetadata(handler, this.metadata);
723
873
  return 1 << meta.capacityExponent >>> 0;
724
874
  }
725
- // ========== Inter-block Operations =============
726
875
  /**
727
- * Copies occupied elements from one block to another.
876
+ * Checks if the memory block has reached its allocation capacity.
728
877
  *
729
- * Copying begins at the first element of `source` and the first slot of
730
- * `destiny`. The effectively copied quantity is limited by the number of occupied
731
- * elements in the source, the destination's physical capacity, and the limit
732
- * specified in `slots`.
878
+ * A block is considered full when the number of occupied elements
879
+ * equals its total allocated capacity, leaving no positions available
880
+ * to store new elements.
733
881
  *
734
- * Destination occupancy is increased, when necessary, to cover the copied
735
- * elements. Destination capacity is not changed.
736
- *
737
- * The operation uses `Uint8Array.prototype.copyWithin()` on the `dataBus`,
738
- * therefore the return value is the `Uint8Array` representing the data bus.
739
- *
740
- * @param {number} source - Source block handle.
741
- * @param {number} destiny - Destination block handle.
742
- * @param {number} [slots=UNKNOWN] - Maximum number of elements to copy.
743
- * `UNKNOWN` represents the sentinel value used not to impose an additional limit.
744
- * @returns {Uint8Array} The `dataBus` after the operation.
745
- * @throws {Error} If `source` or `destiny` is invalid or corrupted.
882
+ * @param {number} handler - Block handle.
883
+ * @returns {boolean} `true` if the block is full; otherwise, `false`.
884
+ * @throws {Error} If the handle is invalid or corrupted.
746
885
  */
747
- copy(source, destiny, slots = UNKNOWN) {
886
+ isFull(handler) {
887
+ const meta = this.extractMetadata(handler, this.metadata);
888
+ return (1 << meta.capacityExponent >>> 0) - meta.occupied === 0;
889
+ }
890
+ // ========== Operations between blocks=============
891
+ /**
892
+ * Copies occupied elements from one block to another.
893
+ *
894
+ * Copying starts at the first element of `source` and the first slot of
895
+ * `destination`. The quantity effectively copied is limited by the number of
896
+ * occupied elements in the source, the physical capacity of the destination, and the
897
+ * limit specified in `slots`.
898
+ *
899
+ * Destination occupancy is increased, when necessary, to cover the
900
+ * copied elements. Destination capacity is unchanged.
901
+ *
902
+ * The operation uses `Uint8Array.prototype.copyWithin()` on the `dataBus`,
903
+ * therefore the return value is the `Uint8Array` representing the data bus.
904
+ *
905
+ * @param {number} source - Source block handle.
906
+ * @param {number} destination - Destination block handle.
907
+ * @param {number} [slots=UNKNOWN] - Maximum number of elements to copy.
908
+ * `UNKNOWN` represents the sentinel value used not to impose an
909
+ * additional limit.
910
+ * @returns {Uint8Array} The `dataBus` after the operation.
911
+ * @throws {Error} If handles are invalid, corrupted,
912
+ * or the destination block is borrowed via withView().
913
+ */
914
+ copy(source, destination, slots = UNKNOWN) {
748
915
  const metaA = {};
749
916
  const metaB = {};
750
917
  this.extractMetadata(source, metaA);
751
- this.extractMetadata(destiny, metaB);
918
+ this.extractMetadata(destination, metaB);
919
+ this.assertNotBorrowed(metaB.headerAddress);
752
920
  const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
753
921
  const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
754
922
  const newOccupied = Math.max(metaB.occupied, slotsToCopy);
@@ -758,26 +926,29 @@ var Balloc = class {
758
926
  /**
759
927
  * Copies a region of elements within the same block.
760
928
  *
761
- * Indices are zero-based and follow the semantics of `Array.prototype.copyWithin()`:
762
- * `target` identifies the destination position, `start` the source starting
763
- * position, and `length` the maximum number of elements to copy.
929
+ * Indices are zero-based and follow the semantics of
930
+ * `Array.prototype.copyWithin()`: `target` identifies the destination position,
931
+ * `start` the starting source position, and `length` the maximum quantity of
932
+ * elements to copy.
764
933
  *
765
- * Negative indices are interpreted from the end of the block's capacity. After
766
- * this normalization, indices are clamped to physical capacity. The copied quantity
767
- * is also limited by effectively occupied elements and available space from `target`.
934
+ * Negative indices are interpreted from the end of the block's capacity.
935
+ * After this normalization, indices are clamped to physical capacity.
936
+ * The copied quantity is also limited by effectively occupied elements
937
+ * and available space starting from `target`.
768
938
  *
769
939
  * The operation supports overlapping regions and can increase block occupancy
770
- * when the target range exceeds current occupancy.
940
+ * when the destination range exceeds previous occupancy.
771
941
  *
772
942
  * @param {number} handler - Block handle.
773
943
  * @param {number} target - Initial destination index.
774
944
  * @param {number} start - Initial source index.
775
945
  * @param {number} length - Maximum number of elements to copy.
776
946
  * @returns {Uint8Array} The `dataBus` after the operation.
777
- * @throws {Error} If the handle is invalid or corrupted.
947
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
778
948
  */
779
949
  copyWithin(handler, target, start, length) {
780
950
  const meta = this.extractMetadata(handler, this.metadata);
951
+ this.assertNotBorrowed(meta.headerAddress);
781
952
  const slots = Math.floor(meta.byteCapacity / this.wordSize);
782
953
  target = Math.trunc(target);
783
954
  start = Math.trunc(start);
@@ -800,46 +971,45 @@ var Balloc = class {
800
971
  * Appends occupied elements of `source` to the end of `target`.
801
972
  *
802
973
  * The copied quantity is limited by the number of occupied elements in the
803
- * source and the remaining free space in the destination's capacity.
974
+ * source and remaining free space in the destination's capacity.
804
975
  *
805
976
  * The operation supports `target` and `source` referencing the same block.
806
- * In that case, the copy is performed on the block's own region and preserves
807
- * `copyWithin()` overlap semantics.
977
+ * In this case, copying is performed over the block's own region and
978
+ * preserves `copyWithin()` overlap semantics.
808
979
  *
809
- * @param {number} target - Handle of the block that will receive the elements.
810
- * @param {number} source - Handle of the block whose elements will be appended.
980
+ * @param {number} target - Handle of the block that will receive elements.
981
+ * @param {number} source - Handle of the block whose elements will be
982
+ * appended.
811
983
  * @returns {number} Number of elements effectively appended.
812
- * @throws {Error} If `target` or `source` is invalid or corrupted.
984
+ * @throws {Error} If handles are invalid, corrupted,
985
+ * or the destination block is borrowed via withView().
813
986
  */
814
987
  append(target, source) {
815
988
  const metaTarget = {};
816
989
  const metaSource = {};
817
990
  this.extractMetadata(target, metaTarget);
818
991
  this.extractMetadata(source, metaSource);
992
+ this.assertNotBorrowed(metaTarget.headerAddress);
819
993
  const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
820
994
  const count = Math.min(available, metaSource.occupied);
821
995
  if (count === 0) return 0;
822
996
  const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
823
997
  const sourceAddress = metaSource.dataAddress;
824
- if (target === source) {
825
- this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
826
- } else {
827
- this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
828
- }
998
+ this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
829
999
  this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
830
1000
  return count;
831
1001
  }
832
1002
  /**
833
1003
  * Creates an independent copy of a block.
834
1004
  *
835
- * The new block has the same physical capacity and occupancy as the original block.
836
- * All bytes in the reserved region, including currently unoccupied positions,
837
- * are copied.
1005
+ * The new block has the same physical capacity and occupancy as the
1006
+ * original block. All bytes in the reserved region, including currently
1007
+ * unoccupied positions, are copied.
838
1008
  *
839
- * The new block receives a new handle and remains subject to normal allocation
840
- * and recycling rules.
1009
+ * The new block receives a new handle and remains subject to normal
1010
+ * allocation and recycling rules.
841
1011
  *
842
- * @param {number} handler - Handle of the block to clone.
1012
+ * @param {number} handler - Handle of the block to be cloned.
843
1013
  * @returns {number} Handle of the new block.
844
1014
  * @throws {Error} If the handle is invalid or corrupted.
845
1015
  */
@@ -855,24 +1025,28 @@ var Balloc = class {
855
1025
  /**
856
1026
  * Swaps the data regions associated with two blocks.
857
1027
  *
858
- * The operation swaps region addresses, capacities, and occupancies between headers.
859
- * Handles remain unchanged: after the operation, each handle continues identifying
860
- * its own header, but that header now describes the region previously belonging
861
- * to the other block.
1028
+ * The operation swaps region addresses, capacities, and occupancies
1029
+ * between headers. Handles remain unchanged:
1030
+ * after the operation, each handle continues identifying its own
1031
+ * header, but that header now describes the region previously
1032
+ * belonging to the other block.
862
1033
  *
863
- * No data is copied in the `dataBus`; only the metadata of the two headers
864
- * is modified.
1034
+ * No data is copied in the `dataBus`; only the metadata of the two
1035
+ * headers is modified.
865
1036
  *
866
1037
  * @param {number} source - Handle of the first block.
867
1038
  * @param {number} target - Handle of the second block.
868
1039
  * @returns {void}
869
- * @throws {Error} If `source` or `target` is invalid or corrupted.
1040
+ * @throws {Error} If handles are invalid, corrupted,
1041
+ * or either block is borrowed via withView().
870
1042
  */
871
1043
  swap(source, target) {
872
1044
  const metaA = {};
873
1045
  const metaB = {};
874
1046
  this.extractMetadata(source, metaA);
875
1047
  this.extractMetadata(target, metaB);
1048
+ this.assertNotBorrowed(metaA.headerAddress);
1049
+ this.assertNotBorrowed(metaB.headerAddress);
876
1050
  this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
877
1051
  this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
878
1052
  this.controlAdapter.setUint8(metaA.headerAddress + CAPACITY_OFFSET, metaB.capacityExponent);
@@ -884,11 +1058,11 @@ var Balloc = class {
884
1058
  /**
885
1059
  * Serializes the content and metadata of a memory block.
886
1060
  *
887
- * The method extracts occupied data from the block via `pick()`, groups them
888
- * along with capacity and word type information into a data envelope, and encodes
889
- * them using the CBOR format.
1061
+ * The method extracts occupied block data via `pick()`,
1062
+ * groups it alongside capacity and word type information
1063
+ * into a data envelope, and encodes it using the CBOR format.
890
1064
  *
891
- * @param {number} handler - Handle of the block to serialize.
1065
+ * @param {number} handler - Handle of the block to be serialized.
892
1066
  * @returns {Uint8Array} A buffer containing the serialized block data.
893
1067
  * @throws {Error} If the handle is invalid or corrupted.
894
1068
  */
@@ -916,13 +1090,13 @@ var Balloc = class {
916
1090
  * Restores a memory block from serialized data.
917
1091
  *
918
1092
  * Decodes the CBOR envelope, validates whether the word type of the serialized
919
- * data is compatible with the current allocator instance, and allocates a new
920
- * block with the necessary capacity to accommodate the content. Then, the original
921
- * data and occupancy are restored in the new block.
1093
+ * data is compatible with the current allocator instance, and allocates
1094
+ * a new block with the capacity required to accommodate the content.
1095
+ * Then, original data and occupancy are restored in the new block.
922
1096
  *
923
1097
  * @param {Uint8Array|ArrayBuffer} serialized - Buffer containing serialized data.
924
1098
  * @returns {number} Handle of the newly recreated block.
925
- * @throws {Error} If the decoded data's word type differs from the one configured in the allocator.
1099
+ * @throws {Error} If the decoded data's word type differs from the allocator's configuration.
926
1100
  */
927
1101
  load(serialized) {
928
1102
  if (!(serialized instanceof ArrayBuffer) && !(serialized instanceof Uint8Array)) {
@@ -962,22 +1136,54 @@ var Balloc = class {
962
1136
  return handler;
963
1137
  }
964
1138
  // ============= UTILITIES ==============
1139
+ /**
1140
+ * Prevents modification operations on a borrowed block.
1141
+ *
1142
+ * Checks the VIEW_LOCK flag in the header associated with the provided address.
1143
+ *
1144
+ * @param {number} headerAddress - Address of the header in controlBus.
1145
+ * @returns {void}
1146
+ * @throws {Error} If the block is borrowed via withView().
1147
+ * @private
1148
+ */
1149
+ assertNotBorrowed(headerAddress) {
1150
+ if (this.controlBus[headerAddress + FLAGS_OFFSET] & VIEW_LOCK) {
1151
+ throw new Error("Block is borrowed");
1152
+ }
1153
+ }
1154
+ /**
1155
+ * Prevents operations that replace or remap the dataBus
1156
+ * while any segment is borrowed.
1157
+ *
1158
+ * @returns {void}
1159
+ * @throws {Error} If any block is borrowed via withView().
1160
+ * @private
1161
+ */
1162
+ assertNoActiveViews() {
1163
+ for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
1164
+ if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
1165
+ if (this.controlBus[i + FLAGS_OFFSET] & VIEW_LOCK) {
1166
+ throw new Error("Cannot remap memory while a block is borrowed");
1167
+ }
1168
+ }
1169
+ }
965
1170
  /**
966
1171
  * [INTERNAL USE]
967
- * Decodes the metadata associated with a handle.
1172
+ * Decodes metadata associated with a handle.
968
1173
  *
969
1174
  * The handle is split into generation and header address. The cookie stored
970
1175
  * in the header is then recalculated to validate the combination; only after
971
- * this validation is metadata read.
1176
+ * this validation are metadata read.
972
1177
  *
973
- * Decoded fields are written to the `out` object, which is returned by the function
974
- * itself. The object can be reused across calls to avoid new allocations.
1178
+ * Decoded fields are written to the `out` object, which is returned
1179
+ * by the function itself. The object can be reused between calls to avoid
1180
+ * new allocations.
975
1181
  *
976
- * @param {number} handler - Handle to decode and validate.
977
- * @param {Metadata} out - Object that will receive the decoded metadata.
1182
+ * @param {number} handler - Handle to be decoded and validated.
1183
+ * @param {Metadata} out - Object that will receive decoded metadata.
978
1184
  * @returns {Metadata} The same reference provided in `out`.
979
- * @throws {Error} If the header cookie does not match the handle or if the
980
- * handle does not identify a valid header.
1185
+ * @throws {Error} If the header cookie does not match the handle or
1186
+ * if the handle does not identify a valid header.
981
1187
  * @private
982
1188
  */
983
1189
  extractMetadata(handler, out) {
@@ -995,20 +1201,22 @@ var Balloc = class {
995
1201
  }
996
1202
  /**
997
1203
  * [INTERNAL USE]
998
- * Calculates the validation cookie of a header.
1204
+ * Calculates a header's validation cookie.
999
1205
  *
1000
- * The cookie is derived from the header address and the 11-bit generation via
1001
- * fast hash. The result is reduced to 8 bits.
1206
+ * The cookie is derived from the header address and the 11 generation bits via
1207
+ * fast hash.
1208
+ * The result is reduced to 8 bits.
1002
1209
  *
1003
- * The value zero is reserved as an invalid header indicator; therefore, when
1004
- * the calculation yields zero, the method returns `1`.
1210
+ * The value zero is reserved as an invalid header indicator; therefore,
1211
+ * when the calculation produces zero, the method returns `1`.
1005
1212
  *
1006
- * The cookie is not a cryptographic mechanism. Its purpose is to detect invalid,
1007
- * stale, or corrupted handles within the allocator's memory management model.
1213
+ * The cookie does not constitute a cryptographic mechanism. Its purpose is
1214
+ * to detect invalid, stale, or corrupted handles within the allocator's
1215
+ * memory management model.
1008
1216
  *
1009
1217
  * @param {number} addr - Header address.
1010
- * @param {number} gen - Generation associated with the handle. Only the 11 least
1011
- * significant bits are considered.
1218
+ * @param {number} gen - Generation associated with the handle. Only the 11
1219
+ * least significant bits are considered.
1012
1220
  * @returns {number} 8-bit cookie in the range [1, 255].
1013
1221
  * @private
1014
1222
  */
@@ -1018,11 +1226,11 @@ var Balloc = class {
1018
1226
  /**
1019
1227
  * Returns the number of regions currently stored in the recycling list.
1020
1228
  *
1021
- * Each region corresponds to a freed block that could not be returned directly
1022
- * to the top of the `dataBus` and therefore remains available for reuse by a
1023
- * future allocation of identical capacity.
1229
+ * Each region corresponds to a freed block that could not be returned
1230
+ * directly to the top of the `dataBus` and, therefore, remains available for
1231
+ * reuse by a future allocation of identical capacity.
1024
1232
  *
1025
- * @returns {number} Number of free regions maintained in `recycle`.
1233
+ * @returns {number} Number of free regions kept in `recycle`.
1026
1234
  */
1027
1235
  recycleCount() {
1028
1236
  let count = 0;
@@ -1032,9 +1240,10 @@ var Balloc = class {
1032
1240
  return count;
1033
1241
  }
1034
1242
  /**
1035
- * Returns the total bytes belonging to regions currently stored in the recycling list.
1243
+ * Returns the total bytes belonging to regions currently stored in the
1244
+ * recycling list.
1036
1245
  *
1037
- * The value is calculated by summing the capacity of each free region multiplied
1246
+ * The value is calculated by summing each free region's capacity multiplied
1038
1247
  * by the number of regions registered for that capacity.
1039
1248
  *
1040
1249
  * @returns {number} Number of bytes occupied by recyclable regions.
@@ -1047,24 +1256,25 @@ var Balloc = class {
1047
1256
  return total;
1048
1257
  }
1049
1258
  /**
1050
- * Returns the amount of allocated bytes that do not belong to currently recyclable regions.
1259
+ * Returns the quantity of allocated bytes that do not belong to currently
1260
+ * recyclable regions.
1051
1261
  *
1052
- * The value is obtained by subtracting the bytes belonging to free regions maintained
1053
- * in `recycle` from the total advance of `dataPointer`.
1262
+ * The value is obtained by subtracting the bytes belonging to free regions
1263
+ * kept in `recycle` from the total advance of `dataPointer`.
1054
1264
  *
1055
- * @returns {number} Number of bytes associated with non-recyclable regions within
1056
- * the area already used by the `dataBus`.
1265
+ * @returns {number} Number of bytes associated with non-recyclable regions
1266
+ * within the area already used by `dataBus`.
1057
1267
  */
1058
1268
  get allocatedBytes() {
1059
1269
  return this.dataPointer - this.recycleBytes;
1060
1270
  }
1061
1271
  /**
1062
- * Returns the amount of bytes not yet used at the top of the `dataBus`.
1272
+ * Returns the quantity of bytes not yet used at the top of the `dataBus`.
1063
1273
  *
1064
1274
  * This space corresponds to the region between `dataPointer` and the end of the
1065
1275
  * capacity currently reserved for the buffer.
1066
1276
  *
1067
- * @returns {number} Number of available bytes after `dataPointer`.
1277
+ * @returns {number} Number of bytes available after `dataPointer`.
1068
1278
  */
1069
1279
  get unallocatedBytes() {
1070
1280
  return this.size - this.dataPointer;
@@ -1072,13 +1282,13 @@ var Balloc = class {
1072
1282
  /**
1073
1283
  * Returns the ratio between recyclable memory and the used heap area.
1074
1284
  *
1075
- * The metric considers free regions maintained in `recycle` as fragmentation
1076
- * and uses `dataPointer` as the denominator. When no bytes have been used by the heap,
1077
- * the result is zero.
1285
+ * The metric considers free regions kept in `recycle` as fragmentation
1286
+ * and uses `dataPointer` as the denominator. When no bytes have been used
1287
+ * by the heap, the result is zero.
1078
1288
  *
1079
- * The value does not represent the fraction of the entire `dataBus` capacity,
1080
- * but specifically the proportion of recyclable bytes within the area already
1081
- * traversed by the bump pointer.
1289
+ * The value does not represent the fraction of the entire `dataBus` capacity, but
1290
+ * specifically the proportion of recyclable bytes within the area already traversed
1291
+ * by the bump pointer.
1082
1292
  *
1083
1293
  * @returns {number} Fragmentation ratio in the range [0, 1] under normal
1084
1294
  * operating conditions.