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.mjs CHANGED
@@ -16,7 +16,7 @@ const UNKNOWN = 0xFFFFFFFF >>> 0;
16
16
  *
17
17
  * Bucket identifier syntax:
18
18
  *
19
- * [Size in bits][Data type]
19
+ * [Size in bits][data type]
20
20
  *
21
21
  * Examples:
22
22
  * A 32-bit unsigned integer bucket: 32u
@@ -24,14 +24,14 @@ const UNKNOWN = 0xFFFFFFFF >>> 0;
24
24
  *
25
25
  */
26
26
  const BUCKET_MAPPING = Object.freeze({
27
- "8u": { type: "Uint8", bits: 8 },
28
- "16u": { type: "Uint16", bits: 16 },
29
- "32u": { type: "Uint32", bits: 32 },
30
- "64u": { type: "BigUint64", bits: 64 },
31
- "8i": { type: "Int8", bits: 8 },
32
- "16i": { type: "Int16", bits: 16 },
33
- "32i": { type: "Int32", bits: 32 },
34
- "64i": { type: "BigInt64", bits: 64 },
27
+ "8u": { type: "Uint8", bits: 8 },
28
+ "16u": { type: "Uint16", bits: 16 },
29
+ "32u": { type: "Uint32", bits: 32 },
30
+ "64u": { type: "BigUint64", bits: 64 },
31
+ "8i": { type: "Int8", bits: 8 },
32
+ "16i": { type: "Int16", bits: 16 },
33
+ "32i": { type: "Int32", bits: 32 },
34
+ "64i": { type: "BigInt64", bits: 64 },
35
35
  "16f": { type: "Float16", bits: 16 },
36
36
  "32f": { type: "Float32", bits: 32 },
37
37
  "64f": { type: "Float64", bits: 64 }
@@ -41,7 +41,7 @@ const BUCKET_MAPPING = Object.freeze({
41
41
  * Bucket types supported by the allocator:
42
42
  * - Unsigned integers: '8u', '16u', '32u', '64u'
43
43
  * - Signed integers: '8i', '16i', '32i', '64i'
44
- * - Floating-point: '16f', '32f', '64f'
44
+ * - Floating point: '16f', '32f', '64f'
45
45
  *
46
46
  * @typedef {'8u'|'16u'|'32u'|'64u'|'8i'|'16i'|'32i'|'64i'|'16f'|'32f'|'64f'} BucketType
47
47
  */
@@ -57,27 +57,34 @@ const IS_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
57
57
 
58
58
  /**
59
59
  * Metadata format.
60
- * 0 4 8 9 10
61
- * [32bits address][32bits occupied][8bits capacity][8bits cookie][48bits reserved]
62
- *
63
- * Total: 4 + 4 + 1 + 1 + 6 = 16 bytes
60
+ *
61
+ * [32bits address][32bits occupied][8bits capacity][8bits cookie][8bits flags][40bits reserved]
62
+ *
63
+ *
64
+ * Total: 16 bytes
64
65
  */
65
66
  const HEADER_SIZE = 16 >>> 0;
66
-
67
- const ADDRESS_OFFSET = 0 >>> 0;
67
+ const ADDRESS_OFFSET = 0 >>> 0;
68
68
  const OCCUPIED_OFFSET = 4 >>> 0;
69
69
  const CAPACITY_OFFSET = 8 >>> 0;
70
- const COOKIE_OFFSET = 9 >>> 0;
70
+ const COOKIE_OFFSET = 9 >>> 0;
71
+ const FLAGS_OFFSET = 10 >>> 0;
72
+
73
+ /**
74
+ * Flags:
75
+ * bit 0: VIEW_LOCK
76
+ */
77
+ const VIEW_LOCK = 1 >>> 0;
71
78
 
72
79
 
73
80
  const ROTATE_32BITS = 4294967296;
74
81
  const CLAMP_11BITS = 0x7FF >>> 0;
75
82
 
76
83
  /**
77
- * Structure containing metadata encoded within a handle.
84
+ * Structure containing the metadata encoded in a handle.
78
85
  *
79
86
  * @typedef {Object} Metadata
80
- * @property {number} byteCapacity - The capacity of the memory block in bytes.
87
+ * @property {number} byteCapacity - The byte capacity of the memory block.
81
88
  * @property {number} capacityExponent - The capacity of the memory block expressed as a base-two exponent.
82
89
  * @property {number} dataAddress - Address of the memory block within the dataBus.
83
90
  * @property {number} generation - Generation to which the handle belongs.
@@ -86,9 +93,9 @@ const CLAMP_11BITS = 0x7FF >>> 0;
86
93
  */
87
94
 
88
95
  /**
89
- * Checks if a value is an instance of a TypedArray.
96
+ * Checks if a value is a TypedArray instance.
90
97
  *
91
- * @param {any} val - Value to test.
98
+ * @param {any} val - Value to be tested.
92
99
  * @returns {boolean} `true` if the value is a TypedArray, otherwise `false`.
93
100
  */
94
101
  const isTypedArray = (val) => ArrayBuffer.isView(val) && !(val instanceof DataView);
@@ -105,44 +112,44 @@ export default class Balloc {
105
112
  * - `dataBus`: stores the data of allocated blocks;
106
113
  * - `controlBus`: stores headers and other control metadata.
107
114
  *
108
- * Each block has a fixed-size header (`HEADER_SIZE`) and is externally
109
- * identified by a 43-bit logical handle, composed of an 11-bit generation
110
- * and a 32-bit header address.
115
+ * Each block has a fixed-size header (`HEADER_SIZE`) and is
116
+ * identified externally by a 43-bit logical handle, composed
117
+ * of an 11-bit generation and its 32-bit header address.
111
118
  *
112
- * The capacity of each block is rounded up to the next power of two
113
- * in elements, respecting the configured bucket width.
119
+ * The capacity of each block is rounded up to the next power of
120
+ * two in elements, respecting the width of the configured bucket.
114
121
  *
115
122
  * @param {number} [size=65535] - Initial capacity of the `dataBus`, in bytes.
116
123
  * Must be a safe integer in the range [2, 0x80000000].
117
- * @param {BucketType} [bucketSize="32u"] - Bucket type and size identifier
124
+ * @param {BucketType} [bucketSize="32u"] - Identifier for the bucket type and size
118
125
  * (e.g., '32u' for Uint32, '64f' for Float64, '8i' for Int8).
119
126
  * @param {number} [metadataSize=1024] - Initial capacity of the `controlBus`,
120
127
  * in bytes. Must be a safe integer in the range
121
128
  * [HEADER_SIZE, 0x80000000].
122
129
  *
123
- * @throws {RangeError} If `size` is out of the allowed range.
130
+ * @throws {RangeError} If `size` is outside the allowed range.
124
131
  * @throws {RangeError} If `bucketSize` is not a valid bucket identifier.
125
- * @throws {RangeError} If `metadataSize` is out of the allowed range.
132
+ * @throws {RangeError} If `metadataSize` is outside the allowed range.
126
133
  */
127
- constructor(size = 65535, bucketSize = "32u", metadataSize = 1024) {
134
+ constructor(size = 65535, bucketSize = "32u", metadataSize = 1024) {
128
135
 
129
136
  if (!Number.isSafeInteger(size) || size < 2 || size > 0x80000000) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
130
137
 
131
-
138
+
132
139
  if (!BUCKET_MAPPING[bucketSize]) {
133
140
  throw new RangeError(`bucketSize must be in ([ 8 || 16 || 32 || 64][ u || i ]) || ([ 16 || 32 || 64][ f ]) but I found ${bucketSize}`);
134
141
  }
135
142
 
136
143
  if (!Number.isSafeInteger(metadataSize) || metadataSize < HEADER_SIZE || metadataSize > 0x80000000) throw new RangeError(`Parameter metadataSize must be in range [HEADER_SIZE, 0x80000000] but metadataSize is ${metadataSize}`);
137
-
144
+
138
145
  this.wordType = bucketSize;
139
146
  this.bucketType = BUCKET_MAPPING[bucketSize].type;
140
147
  this.bucketSize = BUCKET_MAPPING[bucketSize].bits >>> 0;
141
148
  this.bucketArray = globalThis[`${this.bucketType}Array`];
142
149
  this.wordSize = this.bucketSize >>> 3;
143
150
  this.wordShift = this.bucketSize >>> 4;
144
- this.size = Math.max(1 << (32 - Math.clz32(size)) >>> 0, this.wordSize);
145
- this.headerSize = 1 << (32 - Math.clz32(metadataSize)) >>> 0;
151
+ this.size = Math.max(1 << (32 - Math.clz32(size - 1)) >>> 0, this.wordSize);
152
+ this.headerSize = 1 << (32 - Math.clz32(metadataSize - 1)) >>> 0;
146
153
  this.dataPointer = 0 >>> 0;
147
154
  this.controlPointer = 0 >>> 0;
148
155
  this.echoPointer = 0 >>> 0;
@@ -165,7 +172,7 @@ export default class Balloc {
165
172
  byteCapacity: 0 >>> 0,
166
173
  occupied: 0 >>> 0,
167
174
  };
168
-
175
+
169
176
  }
170
177
 
171
178
  // ========== ALLOCATION ==========
@@ -174,29 +181,30 @@ export default class Balloc {
174
181
  * Allocates a new memory block.
175
182
  *
176
183
  * The requested capacity is converted to the smallest power of two that
177
- * accommodates `size` elements. The block is preferably obtained from the list
178
- * of recyclable regions with the corresponding capacity; if no compatible
179
- * region exists, the block is reserved at the top of the `dataBus`.
184
+ * can accommodate `size` elements. The block is obtained preferentially from the list
185
+ * of recyclable regions with the corresponding capacity; if a compatible
186
+ * region does not exist, the block is reserved at the top of the `dataBus`.
180
187
  *
181
188
  * Next, a header is obtained from the control space. Previously freed headers
182
- * can be reused via the internal recycling stack; otherwise, the `controlBus`
183
- * is expanded when necessary.
189
+ * can be reused via the internal recycling stack;
190
+ * otherwise, the `controlBus` is expanded when necessary.
184
191
  *
185
192
  * The header receives the address, capacity, initial occupancy (zero), and
186
193
  * a validation cookie. The returned value encodes the allocation generation
187
194
  * and the header address:
188
195
  *
189
- * [11 bits generation][32 bits header address]
196
+ * [11 generation bits][32 header address bits]
190
197
  *
191
198
  * @param {number} [size=16] - Minimum number of elements the block must
192
199
  * accommodate. Must be a safe integer in the range [2, 0x80000000].
193
200
  * @returns {number} Handle identifying the allocated block.
194
- * @throws {RangeError} If `size` is out of the allowed range.
201
+ * @throws {RangeError} If `size` is outside the allowed range.
202
+ * @throws {Error} If it is necessary to expand the `dataBus` while any
203
+ * block is borrowed via withView().
195
204
  */
196
205
  alloc(size = 16) {
197
206
  if (!Number.isSafeInteger(size) || size < 2 || size > 0x80000000) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
198
207
 
199
-
200
208
  const capacity = (32 - Math.clz32(size - 1));
201
209
  const blockSize = (1 << capacity >>> 0) * this.wordSize;
202
210
 
@@ -209,21 +217,21 @@ export default class Balloc {
209
217
  }
210
218
 
211
219
  let headerAddress = 0 >>> 0;
212
-
213
220
  if (this.echoPointer > this.controlPointer) {
214
221
  this.echoPointer -= 4;
215
- headerAddress = this.controlAdapter.getUint32(this.echoPointer, IS_LITTLE_ENDIAN);
222
+ headerAddress = this.controlAdapter.getUint32(this.echoPointer, IS_LITTLE_ENDIAN);
216
223
  } else {
217
224
  if (this.controlPointer + HEADER_SIZE > this.controlAdapter.byteLength) this.headerGrow();
218
225
  headerAddress = this.controlPointer;
219
- this.controlPointer+= HEADER_SIZE;
220
- this.echoPointer+= HEADER_SIZE;
226
+ this.controlPointer += HEADER_SIZE;
227
+ this.echoPointer += HEADER_SIZE;
221
228
  }
222
229
 
223
230
  this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, dataAddress, IS_LITTLE_ENDIAN);
224
231
  this.controlAdapter.setUint32(headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
225
232
  this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, capacity);
226
233
  this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, this.bakeCookie(headerAddress, ++this.generation));
234
+ this.controlBus[headerAddress + FLAGS_OFFSET] = 0;
227
235
 
228
236
  return (this.generation & CLAMP_11BITS) * ROTATE_32BITS + headerAddress;
229
237
  }
@@ -232,37 +240,41 @@ export default class Balloc {
232
240
  * Expands a block's capacity to the next power of two.
233
241
  *
234
242
  * When the block is located at the current top of the `dataBus`, expansion
235
- * occurs in-place: only its capacity and `dataPointer` are updated.
243
+ * occurs in-place: only its capacity and `dataPointer` are
244
+ * updated.
236
245
  *
237
246
  * If another region exists after the block, a new region with double the
238
- * capacity is obtained from the recyclable space or allocated at the top of
239
- * the `dataBus`. Currently occupied elements are then copied to the new region,
247
+ * capacity is obtained from the recyclable space or allocated at the top of the `dataBus`.
248
+ * The currently occupied elements are then copied to the new region,
240
249
  * and the previous region is returned to the recycling list.
241
250
  *
242
- * The handle remains valid because its header is preserved, and only the
243
- * address and capacity recorded within it are updated.
251
+ * The handle remains valid because its header is preserved and only the
252
+ * address and capacity recorded in it are updated.
244
253
  *
245
- * @param {number} handler - Handle of the block to expand.
254
+ * @param {number} handler - Handle of the block to be expanded.
246
255
  * @returns {void}
247
- * @throws {Error} If the handle is invalid or corrupted.
248
- * @throws {AggregateError} If the capacity has reached its maximum
256
+ * @throws {Error} If the handle is invalid, corrupted, or the block
257
+ * is borrowed via withView(). Also occurs if expansion requires
258
+ * dataBus remapping while another block is borrowed.
259
+ * @throws {AggregateError} If the capacity has reached the maximum
249
260
  * supported limit.
250
261
  */
251
262
  realloc(handler) {
252
- const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
253
- let headerAddress = handler >>> 0;
254
263
 
264
+ const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
265
+ const headerAddress = handler >>> 0;
255
266
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
256
267
  const occupied = this.controlAdapter.getUint32(headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
257
268
  const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
258
269
  const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
259
270
 
260
-
261
271
  if (cookie !== this.bakeCookie(headerAddress, generation)) {
262
272
  throw new Error("Invalid or corrupted handle");
263
273
  }
264
274
 
265
- if (capacity >= 31) throw new AggregateError([new Error("Can´t reallocate handler.") ,new RangeError("Capacity has reached its limit.")], "Internal Error.");
275
+ this.assertNotBorrowed(headerAddress);
276
+
277
+ if (capacity >= 31) throw new AggregateError([new Error("Can´t reallocate handler."), new RangeError("Capacity has reached its limit.")], "Internal Error.");
266
278
 
267
279
  const newCapacity = capacity + 1;
268
280
  const newBlockSize = (1 << newCapacity >>> 0) * this.wordSize;
@@ -271,14 +283,11 @@ export default class Balloc {
271
283
  if (dataAddress + oldBlockSize === this.dataPointer) {
272
284
  while (dataAddress + newBlockSize > this.size) this.grow();
273
285
 
274
- this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity, IS_LITTLE_ENDIAN);
286
+ this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
275
287
  this.dataPointer = dataAddress + newBlockSize;
276
-
277
288
  return;
278
289
  }
279
290
 
280
- this.recyclePush(oldBlockSize, dataAddress);
281
-
282
291
  let newAddress = this.recyclePop(newBlockSize);
283
292
 
284
293
  if (newAddress === UNKNOWN) {
@@ -288,56 +297,95 @@ export default class Balloc {
288
297
  this.dataPointer += newBlockSize;
289
298
  }
290
299
 
291
- this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
292
300
  this.dataBus.copyWithin(newAddress, dataAddress, dataAddress + occupied * this.wordSize);
293
301
 
294
302
  this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, newAddress, IS_LITTLE_ENDIAN);
303
+ this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
304
+
305
+ this.recyclePush(oldBlockSize, dataAddress);
295
306
  }
296
307
 
297
308
  /**
298
- * Frees a memory block.
309
+ * Reduces a block to the smallest power-of-two capacity that can contain
310
+ * its occupied elements, while preserving its address and handler.
299
311
  *
300
- * The block's header is invalidated by zeroing its cookie, and its address
301
- * is registered for later reuse. The data region is also returned to the
302
- * recycling system, except when the block is exactly at the top of the
303
- * `dataBus`; in that case, `dataPointer` is simply rolled back, eliminating
304
- * the region without creating an entry in the recycling 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.
305
315
  *
306
- * @param {number} handler - Handle of the block to free.
316
+ * @param {number} handler - Handler of the block to shrink.
307
317
  * @returns {void}
308
- * @throws {Error} If the handle is invalid or corrupted.
318
+ * @throws {Error} If the handler is invalid, corrupted, or borrowed by withView().
309
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
+ */
310
361
  free(handler) {
311
- const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
312
- let headerAddress = handler >>> 0;
313
362
 
363
+ const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
364
+ const headerAddress = handler >>> 0;
314
365
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
315
366
  const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
316
367
  const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
317
368
 
318
-
319
369
  if (cookie !== this.bakeCookie(headerAddress, generation)) {
320
370
  throw new Error("Invalid or corrupted handle");
321
371
  }
322
372
 
323
- const blockSize = (1 << capacity >>> 0) * this.wordSize;
373
+ this.assertNotBorrowed(headerAddress);
324
374
 
375
+ const blockSize = (1 << capacity >>> 0) * this.wordSize;
325
376
  this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
326
377
 
327
378
  if (this.echoPointer + 4 <= this.controlBus.byteLength) {
328
379
  this.controlAdapter.setUint32(this.echoPointer, headerAddress, IS_LITTLE_ENDIAN);
329
380
  this.echoPointer += 4;
330
- }
331
-
381
+ }
332
382
 
333
383
  if (dataAddress + blockSize === this.dataPointer) {
334
384
  this.dataPointer = dataAddress;
335
385
  } else {
336
386
  this.recyclePush(blockSize, dataAddress);
337
387
  }
338
-
339
388
  }
340
-
341
389
  // ========== RECYCLING ==========
342
390
 
343
391
  /**
@@ -345,13 +393,13 @@ export default class Balloc {
345
393
  * Inserts a free region into the recycling list.
346
394
  *
347
395
  * The list is organized by capacity in bytes. For each capacity, the
348
- * stored value is a `Uint32Array` whose zero position contains the number
349
- * of registered addresses, and subsequent positions contain the addresses
350
- * of the free regions:
396
+ * stored value is a `Uint32Array` whose zero position contains the quantity
397
+ * of registered addresses and subsequent positions contain the addresses of
398
+ * the free regions:
351
399
  *
352
400
  * [count, address1, address2, ...]
353
401
  *
354
- * When the page becomes full, its buffer is expanded to double the current
402
+ * When the page becomes full, its buffer is expanded to double its current
355
403
  * capacity.
356
404
  *
357
405
  * @param {number} capacity - Capacity of the free region, in bytes.
@@ -387,7 +435,7 @@ export default class Balloc {
387
435
  *
388
436
  * @param {number} capacity - Desired capacity, in bytes.
389
437
  * @returns {number} Initial address of a recyclable region or `UNKNOWN`
390
- * when no region exists with the requested capacity.
438
+ * when a region with the requested capacity does not exist.
391
439
  * @private
392
440
  */
393
441
  recyclePop(capacity) {
@@ -405,41 +453,50 @@ export default class Balloc {
405
453
  }
406
454
 
407
455
  // ========== GARBAGE COLLECTION ==========
456
+
408
457
  /**
409
458
  * Compacts the `dataBus` using the ReBump algorithm.
410
459
  *
411
460
  * Sequentially traverses the headers registered in the `controlBus` and copies
412
- * still-valid regions to a new `dataBus`, eliminating free spaces between them.
413
- * The address of each surviving block is updated in its respective header.
461
+ * still-valid regions to a new `dataBus`, eliminating free spaces
462
+ * between them. Each surviving block's address is updated in its
463
+ * respective header.
414
464
  *
415
- * The order of blocks in the `controlBus` is preserved. Internal data of each
416
- * block is also fully preserved, including its reserved capacity and current
417
- * occupancy.
465
+ * The order of blocks in the `controlBus` is preserved. The internal data of
466
+ * each block is also fully preserved, including its reserved capacity
467
+ * and current occupancy.
418
468
  *
419
- * At the end of compaction:
469
+ * Upon completion of compaction:
420
470
  * - all recyclable regions are eliminated;
421
471
  * - `dataPointer` points to the first byte after the last live block;
422
- * - `dataBus` represents a contiguous heap for active blocks.
472
+ * - the `dataBus` represents a contiguous heap for active blocks.
423
473
  *
424
- * Control complexity is O(n), where `n` is the number of headers traversed.
425
- * The effective cost of memory movement also depends on the volume of bytes
426
- * belonging to live blocks.
474
+ * Control complexity is O(n), where `n` is the number of traversed
475
+ * headers. The effective memory movement cost also depends on the volume
476
+ * of bytes belonging to live blocks.
427
477
  *
428
478
  * @returns {void}
479
+ * @throws {Error} If any block is borrowed via withView().
429
480
  */
430
481
  gc() {
482
+ this.assertNoActiveViews();
483
+
431
484
  const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
432
485
  this.recycle.clear();
433
486
  this.dataPointer = 0 >>> 0;
434
- for (let i = 0; i < this.controlPointer; i+= HEADER_SIZE) {
487
+
488
+ for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
435
489
  if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
490
+
436
491
  const start = this.controlAdapter.getUint32(i + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
437
492
  const size = (1 << this.controlBus[i + CAPACITY_OFFSET] >>> 0) * this.wordSize;
438
493
  const end = start + size;
494
+
439
495
  newDataBus.set(this.dataBus.subarray(start, end), this.dataPointer);
440
496
  this.controlAdapter.setUint32(i + ADDRESS_OFFSET, this.dataPointer, IS_LITTLE_ENDIAN);
441
497
  this.dataPointer += size;
442
498
  }
499
+
443
500
  this.dataBus = newDataBus;
444
501
  this.dataAdapter = new DataView(this.dataBus.buffer);
445
502
  this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
@@ -448,20 +505,24 @@ export default class Balloc {
448
505
  }
449
506
 
450
507
  // ========== SCALING ==========
508
+
451
509
  /**
452
510
  * [!!! INTERNAL USE, DO NOT USE IN YOUR CODE !!!]
453
511
  * Expands the `dataBus` to double its current capacity.
454
512
  *
455
513
  * The underlying buffer is transferred to a larger `ArrayBuffer`, preserving
456
- * existing data. All views associated with the buffer are recreated to reference
457
- * the new storage.
514
+ * existing data. All views associated with the buffer are recreated
515
+ * to reference the new storage.
458
516
  *
459
517
  * @returns {void}
460
- * @throws {RangeError} If the `dataBus` capacity has exceeded the maximum
461
- * supported limit.
518
+ * @throws {Error} If any block is borrowed via withView().
519
+ * @throws {RangeError} If the `dataBus` capacity has already exceeded the
520
+ * maximum supported limit.
462
521
  * @private
463
522
  */
464
523
  grow() {
524
+ this.assertNoActiveViews();
525
+
465
526
  if (this.size > 0x80000000) throw new RangeError("Data bus capacity exceeded");
466
527
 
467
528
  const newSize = (this.size * 2) >>> 0;
@@ -480,12 +541,12 @@ export default class Balloc {
480
541
  * Expands the `controlBus` to double its current capacity.
481
542
  *
482
543
  * The underlying buffer is transferred to a larger `ArrayBuffer`, preserving
483
- * existing headers. The `controlAdapter` is recreated to reference the new
484
- * storage.
544
+ * existing headers. The `controlAdapter` is recreated to reference
545
+ * the new storage.
485
546
  *
486
547
  * @returns {void}
487
- * @throws {RangeError} If the current `controlBus` capacity has exceeded
488
- * the maximum supported limit.
548
+ * @throws {RangeError} If the current `controlBus` capacity has already
549
+ * exceeded the maximum supported limit.
489
550
  * @private
490
551
  */
491
552
  headerGrow() {
@@ -500,48 +561,49 @@ export default class Balloc {
500
561
  // ========== STACK OPERATIONS ==========
501
562
 
502
563
  /**
503
- * Appends an element to the end of the block's occupied sequence.
564
+ * Appends an element to the end of the sequence occupied by the block.
504
565
  *
505
566
  * The element is written at the first free position after the last occupied
506
- * element. Block occupancy is incremented only when space is available within
507
- * its capacity.
567
+ * element. Block occupancy is incremented only when space is available
568
+ * within its capacity.
508
569
  *
509
- * @param {number} handler - Block handle.
510
- * @param {number} value - Value to insert.
570
+ * @param {number} value - Value to be inserted.
511
571
  * @returns {boolean} `true` if the value was inserted; `false` if the block
512
- * has no available space.
513
- * @throws {Error} If the handle is invalid or corrupted.
572
+ * is already out of available space.
573
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
574
+ *
514
575
  */
515
576
  push(handler, value) {
516
-
517
577
  const meta = this.extractMetadata(handler, this.metadata);
578
+ this.assertNotBorrowed(meta.headerAddress);
518
579
 
519
580
  if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
520
581
 
521
- this.writer(meta.dataAddress + meta.occupied * this.wordSize , value, IS_LITTLE_ENDIAN);
522
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1,IS_LITTLE_ENDIAN);
582
+ this.writer(meta.dataAddress + meta.occupied * this.wordSize, value, IS_LITTLE_ENDIAN);
583
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
523
584
 
524
585
  return true;
525
586
  }
526
587
 
527
588
  /**
528
- * Removes and returns the last occupied element from the block.
589
+ * Removes the last occupied element from the block and returns it.
529
590
  *
530
- * Occupancy is decremented before reading the removed element. Corresponding
591
+ * Occupancy is decremented before reading the removed element. The corresponding
531
592
  * bytes are not cleared and remain in the allocated region, but cease to be
532
593
  * part of the occupied sequence.
533
594
  *
534
595
  * @param {number} handler - Block handle.
535
596
  * @returns {number|undefined} Removed value or `undefined` if the block
536
597
  * is empty.
537
- * @throws {Error} If the handle is invalid or corrupted.
598
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
538
599
  */
539
600
  pop(handler) {
540
601
  const meta = this.extractMetadata(handler, this.metadata);
602
+ this.assertNotBorrowed(meta.headerAddress);
541
603
 
542
604
  if (meta.occupied === 0) return undefined;
543
605
 
544
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1,IS_LITTLE_ENDIAN);
606
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
545
607
  return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
546
608
  }
547
609
 
@@ -566,52 +628,55 @@ export default class Balloc {
566
628
  /**
567
629
  * Inserts an element at the beginning of the occupied sequence.
568
630
  *
569
- * Currently occupied elements are shifted one position forward and `value`
570
- * is written to the first position. The operation requires a free position
571
- * within the block's capacity.
631
+ * Currently occupied elements are shifted forward by one position and
632
+ * `value` is written at the first position. The operation requires a free
633
+ * position within the block's capacity.
572
634
  *
573
- * The operation's cost is proportional to the number of occupied elements,
635
+ * The operation cost is proportional to the number of occupied elements,
574
636
  * as data needs to be shifted.
575
637
  *
576
638
  * @param {number} handler - Block handle.
577
- * @param {number} value - Value to insert.
639
+ * @param {number} value - Value to be inserted.
578
640
  * @returns {boolean} `true` if the value was inserted; `false` if the block
579
641
  * is full.
580
- * @throws {Error} If the handle is invalid or corrupted.
642
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
581
643
  */
582
644
  nudge(handler, value) {
583
645
  const meta = this.extractMetadata(handler, this.metadata);
646
+ this.assertNotBorrowed(meta.headerAddress);
584
647
 
585
648
  if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
586
649
 
587
650
  this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
588
651
  this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
589
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1,IS_LITTLE_ENDIAN);
652
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
590
653
 
591
654
  return true;
592
655
  }
593
656
 
594
657
  /**
595
- * Removes and returns the first occupied element from the block.
658
+ * Removes the first occupied element from the block and returns it.
596
659
  *
597
- * Remaining elements are shifted one position toward the beginning of the
598
- * occupied region. The block's physical capacity remains unchanged.
660
+ * Remaining elements are shifted one position toward the beginning
661
+ * of the occupied region. The physical capacity of the block remains unchanged.
599
662
  *
600
- * The operation's cost is proportional to the number of shifted elements.
663
+ * The operation cost is proportional to the number of shifted elements.
601
664
  *
602
665
  * @param {number} handler - Block handle.
603
666
  * @returns {number|undefined} First removed value or `undefined` if the
604
667
  * block is empty.
605
- * @throws {Error} If the handle is invalid or corrupted.
668
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
606
669
  */
607
670
  pull(handler) {
608
671
  const meta = this.extractMetadata(handler, this.metadata);
672
+ this.assertNotBorrowed(meta.headerAddress);
609
673
 
610
674
  if (meta.occupied === 0) return undefined;
611
675
 
612
676
  const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
613
677
  this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
614
678
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
679
+
615
680
  return result;
616
681
  }
617
682
 
@@ -628,21 +693,21 @@ export default class Balloc {
628
693
 
629
694
  if (meta.occupied === 0) return undefined;
630
695
 
631
- return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
696
+ return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
632
697
  }
633
698
 
634
699
  // ========== RANDOM ACCESS ==========
635
700
 
636
701
  /**
637
- * Checks if a value is present among the block's occupied elements.
702
+ * Checks if a value is present among the occupied elements of the block.
638
703
  *
639
704
  * The search is performed directly on the auxiliary `TypedArray` and considers
640
705
  * only the currently occupied range, not the entire reserved physical capacity.
641
706
  *
642
707
  * @param {number} handler - Block handle.
643
708
  * @param {number} value - Value to search for.
644
- * @returns {boolean} `true` if `value` is present among the occupied elements;
645
- * otherwise, `false`.
709
+ * @returns {boolean} `true` if `value` is present among the occupied
710
+ * elements; otherwise, `false`.
646
711
  * @throws {Error} If the handle is invalid or corrupted.
647
712
  */
648
713
  has(handler, value) {
@@ -655,18 +720,74 @@ export default class Balloc {
655
720
  return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
656
721
  }
657
722
 
658
- /**
659
- * Returns the occupied element at a zero-based index.
723
+ /**
724
+ * Locates the first occurrence of an element in the block's occupied sequence.
725
+ *
726
+ * The search is performed in ascending order of indices, using the `indexOf`
727
+ * operation of the underlying TypedArray. The search exclusively considers
728
+ * occupied elements, ignoring the block's unused capacity.
660
729
  *
661
- * Indices outside the range `[0, occupied)` are not considered an error and
662
- * result in `undefined`.
730
+ * The starting search position can be specified by `fromIndex`,
731
+ * following TypedArray indexing rules.
663
732
  *
664
733
  * @param {number} handler - Block handle.
665
- * @param {number} index - Zero-based index of the element.
666
- * @returns {number|undefined} Value stored at the index or `undefined` if
667
- * the index is outside the occupied region.
734
+ * @param {number|bigint} searchElement - Element to locate.
735
+ * @param {number} [fromIndex=0] - Index from which to start the search.
736
+ * @returns {number} Index of the first occurrence or `-1` if the
737
+ * element is not found or if the block is empty.
668
738
  * @throws {Error} If the handle is invalid or corrupted.
669
739
  */
740
+ indexOf(handler, searchElement, fromIndex = 0) {
741
+ const meta = this.extractMetadata(handler, this.metadata);
742
+
743
+ if (meta.occupied === 0) return -1;
744
+
745
+ const rawAddres = meta.dataAddress >>> this.wordShift;
746
+
747
+ return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).indexOf(searchElement, fromIndex);
748
+ }
749
+
750
+ /**
751
+ * Locates the last occurrence of an element in the block's occupied sequence.
752
+ *
753
+ * The search is performed in descending order of indices, using the `lastIndexOf`
754
+ * operation of the underlying TypedArray. The search exclusively considers
755
+ * occupied elements, ignoring the block's unused capacity.
756
+ *
757
+ * The starting search position can be specified by `fromIndex`,
758
+ * following TypedArray indexing rules. By default, the search starts
759
+ * at the last occupied element.
760
+ *
761
+ * @param {number} handler - Block handle.
762
+ * @param {number|bigint} searchElement - Element to locate.
763
+ * @param {number} [fromIndex=-1] - Index from which to start the search.
764
+ * @returns {number} Index of the last occurrence or `-1` if the
765
+ * element is not found or if the block is empty.
766
+ * @throws {Error} If the handle is invalid or corrupted.
767
+ */
768
+ lastIndexOf(handler, searchElement, fromIndex = -1) {
769
+ const meta = this.extractMetadata(handler, this.metadata);
770
+
771
+ if (meta.occupied === 0) return -1;
772
+
773
+ const rawAddres = meta.dataAddress >>> this.wordShift;
774
+
775
+ return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).lastIndexOf(searchElement, fromIndex);
776
+ }
777
+
778
+
779
+ /**
780
+ * Returns the occupied element at a zero-based index.
781
+ *
782
+ * Indices outside the range `[0, occupied)` are not considered an error and
783
+ * result in `undefined`.
784
+ *
785
+ * @param {number} handler - Block handle.
786
+ * @param {number} index - Zero-based index of the element.
787
+ * @returns {number|undefined} Value stored at the index or `undefined` if
788
+ * the index is outside the occupied region.
789
+ * @throws {Error} If the handle is invalid or corrupted.
790
+ */
670
791
  get(handler, index) {
671
792
 
672
793
  const meta = this.extractMetadata(handler, this.metadata);
@@ -687,10 +808,11 @@ export default class Balloc {
687
808
  * @param {number} value - New value.
688
809
  * @returns {boolean} `true` if the value was written; `false` if the index
689
810
  * is outside the occupied region.
690
- * @throws {Error} If the handle is invalid or corrupted.
811
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
691
812
  */
692
813
  set(handler, index, value) {
693
814
  const meta = this.extractMetadata(handler, this.metadata);
815
+ this.assertNotBorrowed(meta.headerAddress);
694
816
 
695
817
  if (index < 0 || index >= meta.occupied) return false;
696
818
 
@@ -701,24 +823,26 @@ export default class Balloc {
701
823
  // ============= MISCELLANEOUS ===============
702
824
 
703
825
  /**
704
- * Clears block occupancy and fills its entire physical capacity with a single value.
826
+ * Zeroes block occupancy and fills its entire physical capacity with
827
+ * a single value.
705
828
  *
706
- * Filling covers all available slots, not just currently occupied elements.
707
- * After the operation, the block is considered empty regardless of the value
708
- * used for filling.
829
+ * The fill covers all available slots, not just currently
830
+ * occupied elements. After the operation, the block is considered
831
+ * empty regardless of the value used for filling.
709
832
  *
710
833
  * @param {number} handler - Block handle.
711
834
  * @param {number} [value=0] - Value used to fill all slots.
712
835
  * @returns {void}
713
- * @throws {Error} If the handle is invalid or corrupted.
836
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
714
837
  */
715
- clear(handler, value=0) {
838
+ clear(handler, value = 0) {
716
839
  const meta = this.extractMetadata(handler, this.metadata);
840
+ this.assertNotBorrowed(meta.headerAddress);
717
841
 
718
842
  const slots = meta.byteCapacity / this.wordSize;
719
843
  const rawAddress = meta.dataAddress >>> this.wordShift;
720
844
 
721
- this.auxiliary.fill(value, rawAddress, rawAddress + slots);
845
+ this.auxiliary.fill(value, rawAddress, rawAddress + slots);
722
846
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
723
847
  }
724
848
 
@@ -726,26 +850,28 @@ export default class Balloc {
726
850
  /**
727
851
  * Fills a range of block slots with a value.
728
852
  *
729
- * The range uses zero-based indices and follows the convention `[start, end)`,
730
- * meaning `start` is inclusive and `end` is exclusive. When `end` is not provided,
731
- * filling extends to the end of the block's physical capacity.
853
+ * The range uses zero-based indices and follows the convention
854
+ * `[start, end)`, therefore `start` is inclusive and `end` is exclusive.
855
+ * When `end` is not provided, filling extends to the end of the block's
856
+ * physical capacity.
732
857
  *
733
- * Block occupancy becomes `end`, including when the filled range extends beyond
734
- * the previous occupancy.
858
+ * Block occupancy becomes `end`, including when the filled range
859
+ * extends beyond previous occupancy.
735
860
  *
736
861
  * @param {number} handler - Block handle.
737
862
  * @param {number} value - Value used for filling.
738
863
  * @param {number} [start=0] - Initial index, inclusive.
739
- * @param {number|null} [end=null] - Final index, exclusive. When omitted or
740
- * `null`, uses the total block capacity.
864
+ * @param {number|null} [end=null] - Final index, exclusive. When
865
+ * omitted or `null`, uses the block's total capacity.
741
866
  * @returns {void}
742
- * @throws {Error} If the handle is invalid or corrupted.
743
- * @throws {RangeError} If `start` or `end` is out of capacity bounds, or if
744
- * `start > end`.
867
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
868
+ * @throws {RangeError} If `start` or `end` is outside capacity limits,
869
+ * or if `start > end`.
745
870
  */
746
871
  fill(handler, value, start = 0, end = null) {
747
872
  const meta = this.extractMetadata(handler, this.metadata);
748
-
873
+ this.assertNotBorrowed(meta.headerAddress);
874
+
749
875
  const slots = meta.byteCapacity / this.wordSize;
750
876
  const lastIndex = end ?? slots;
751
877
 
@@ -760,7 +886,6 @@ export default class Balloc {
760
886
  }
761
887
 
762
888
  const rawAddress = meta.dataAddress >>> this.wordShift;
763
-
764
889
  this.auxiliary.fill(value, rawAddress + start, rawAddress + lastIndex);
765
890
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, lastIndex, IS_LITTLE_ENDIAN);
766
891
  }
@@ -769,16 +894,17 @@ export default class Balloc {
769
894
  * Fills all physical slots of the block with a value and marks the entire
770
895
  * capacity as occupied.
771
896
  *
772
- * Unlike `clear()`, the operation results in a fully occupied block.
897
+ * Unlike `clear()`, this operation results in a fully occupied block.
773
898
  *
774
899
  * @param {number} handler - Block handle.
775
900
  * @param {number} value - Value used for filling.
776
901
  * @returns {void}
777
- * @throws {Error} If the handle is invalid or corrupted.
902
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
778
903
  */
779
904
  fillAll(handler, value) {
780
905
  const meta = this.extractMetadata(handler, this.metadata);
781
-
906
+ this.assertNotBorrowed(meta.headerAddress);
907
+
782
908
  const rawAddress = meta.dataAddress >>> this.wordShift;
783
909
  const capacityElements = meta.byteCapacity / this.wordSize;
784
910
 
@@ -789,28 +915,27 @@ export default class Balloc {
789
915
  /**
790
916
  * Copies elements from an `Array` or `TypedArray` to the beginning of the block.
791
917
  *
792
- * The copied quantity is limited by the block's capacity. Occupancy is updated
793
- * to the greater value between the previous occupancy and the quantity effectively
794
- * copied; therefore, a call to `put()` does not reduce existing occupancy when
795
- * receiving a smaller sequence.
918
+ * The copied quantity is limited by the block's capacity. Occupancy is
919
+ * updated to the greater value between previous occupancy and the quantity
920
+ * effectively copied; therefore, a call to `put()` does not reduce existing
921
+ * occupancy when receiving a smaller sequence.
796
922
  *
797
- * For `Array`, only the first fitting elements are copied. For `TypedArray`,
798
- * a source subarray is used without intermediate copying.
923
+ * For `Array`, only the first elements that fit are copied.
924
+ * For `TypedArray`, a source subarray is used without intermediate copying.
799
925
  *
800
926
  * @param {number} handler - Block handle.
801
927
  * @param {Array|TypedArray} data - Sequence of values to copy.
802
928
  * @returns {void}
803
- * @throws {Error} If the handle is invalid or corrupted.
929
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
804
930
  * @throws {TypeError} If `data` is neither an `Array` nor a `TypedArray`.
805
931
  */
806
932
  put(handler, data) {
807
933
  const meta = this.extractMetadata(handler, this.metadata);
934
+ this.assertNotBorrowed(meta.headerAddress);
808
935
 
809
936
  const rawAddress = meta.dataAddress >>> this.wordShift;
810
937
  const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
811
938
 
812
- meta.occupied = Math.max(length, meta.occupied);
813
-
814
939
  if (Array.isArray(data)) {
815
940
  this.auxiliary.set(data.slice(0, length), rawAddress);
816
941
  } else if (isTypedArray(data)) {
@@ -818,43 +943,98 @@ export default class Balloc {
818
943
  } else {
819
944
  const actual = data?.constructor?.name ?? (data === null ? 'null' : typeof data);
820
945
  throw new TypeError(`data must be Array or TypedArray, but ${actual} was given.`);
821
- }
822
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
946
+ }
947
+
948
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, Math.max(length, meta.occupied), IS_LITTLE_ENDIAN);
823
949
  }
824
950
 
825
- /**
826
- * Returns a copy of the elements currently occupied by the block.
827
- *
828
- * The result is a `TypedArray` of the same type configured by `bucketSize`.
829
- * Unoccupied physical capacity is not included in the result.
830
- *
831
- * The operation does not directly expose internal storage: the method uses
832
- * `TypedArray.prototype.slice()`, producing a new view with independent storage.
833
- *
834
- * @param {number} handler - Block handle.
835
- * @returns {TypedArray} Copy of the elements occupied by the block. When the
836
- * block is empty, returns an empty `TypedArray` of the configured type.
837
- * @throws {Error} If the handle is invalid or corrupted.
838
- */
951
+ /**
952
+ * Returns a copy of the elements currently occupied by the block.
953
+ *
954
+ * The result is a `TypedArray` of the same type configured by
955
+ * `bucketSize`. Unoccupied physical capacity is not included in the result.
956
+ *
957
+ * The operation does not directly expose internal storage: the method
958
+ * uses `TypedArray.prototype.slice()`, producing a new view with
959
+ * independent storage.
960
+ *
961
+ * @param {number} handler - Block handle.
962
+ * @returns {TypedArray} Copy of elements occupied by the block. When
963
+ * the block is empty, returns an empty `TypedArray` of the configured type.
964
+ * @throws {Error} If the handle is invalid or corrupted.
965
+ */
839
966
  pick(handler) {
840
967
  const meta = this.extractMetadata(handler, this.metadata);
841
968
 
842
969
  const rawAddress = meta.dataAddress >>> this.wordShift;
843
970
 
844
971
  if (meta.occupied === 0) {
845
- return this.auxiliary.slice(rawAddress, rawAddress);
846
- }
972
+ return this.auxiliary.slice(rawAddress, rawAddress);
973
+ }
847
974
 
848
975
  return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
849
976
  }
850
977
 
978
+ /**
979
+ * Executes a callback over a direct view of the block's occupied region.
980
+ *
981
+ * The view shares Balloc's internal storage and performs no copying.
982
+ * The block is protected against incompatible operations during the callback.
983
+ *
984
+ * The callback must be synchronous. The received view must not be stored,
985
+ * returned, or used after the callback terminates. This restriction
986
+ * also applies to subviews derived from the original view.
987
+ *
988
+ * @param {number} handler - Block handle.
989
+ * @param {...(number|Function)} args - One or more block handles followed by the callback.
990
+ * @returns {*} Return value produced by the callback.
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.
993
+ */
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();
998
+ if (typeof callback !== "function") throw new TypeError("callback must be a function");
999
+
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]);
1007
+
1008
+ if (flags.some(flag => flag & VIEW_LOCK)) throw new Error("Block is already borrowed");
1009
+
1010
+ let acquiredCount = 0;
1011
+
1012
+ try {
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);
1024
+ } finally {
1025
+ for (let i = 0; i < acquiredCount; i++) {
1026
+ this.controlBus[headers[i] + FLAGS_OFFSET] &= ~VIEW_LOCK;
1027
+ }
1028
+ }
1029
+ }
1030
+
851
1031
  // ======== CAPACITY IN SLOTS ==========
852
1032
 
853
1033
  /**
854
1034
  * Returns the physical capacity of the block in bytes.
855
1035
  *
856
- * Capacity corresponds to the space reserved for all slots in the block,
857
- * regardless of how many elements are currently occupied.
1036
+ * Capacity corresponds to the space reserved for all slots in the
1037
+ * block, regardless of how many elements are currently occupied.
858
1038
  *
859
1039
  * @param {number} handler - Block handle.
860
1040
  * @returns {number} Physical capacity of the block, in bytes.
@@ -872,16 +1052,16 @@ export default class Balloc {
872
1052
  * @returns {number} Number of occupied elements.
873
1053
  * @throws {Error} If the handle is invalid or corrupted.
874
1054
  */
875
- occupied(handler){
1055
+ occupied(handler) {
876
1056
  const meta = this.extractMetadata(handler, this.metadata);
877
1057
  return meta.occupied;
878
1058
 
879
1059
  }
880
1060
 
881
1061
  /**
882
- * Returns the capacity of the block in number of elements.
1062
+ * Returns the block's capacity in number of elements.
883
1063
  *
884
- * The value corresponds to the total quantity of physically reserved slots,
1064
+ * The value corresponds to the total number of physically reserved slots,
885
1065
  * not the currently occupied quantity.
886
1066
  *
887
1067
  * @param {number} handler - Block handle.
@@ -893,72 +1073,93 @@ export default class Balloc {
893
1073
  return 1 << meta.capacityExponent >>> 0;
894
1074
  }
895
1075
 
896
- // ========== Inter-block Operations =============
897
-
898
1076
  /**
899
- * Copies occupied elements from one block to another.
1077
+ * Checks if the memory block has reached its allocation capacity.
900
1078
  *
901
- * Copying begins at the first element of `source` and the first slot of
902
- * `destiny`. The effectively copied quantity is limited by the number of occupied
903
- * elements in the source, the destination's physical capacity, and the limit
904
- * specified in `slots`.
1079
+ * A block is considered full when the number of occupied elements
1080
+ * equals its total allocated capacity, leaving no positions available
1081
+ * to store new elements.
905
1082
  *
906
- * Destination occupancy is increased, when necessary, to cover the copied
907
- * elements. Destination capacity is not changed.
908
- *
909
- * The operation uses `Uint8Array.prototype.copyWithin()` on the `dataBus`,
910
- * therefore the return value is the `Uint8Array` representing the data bus.
911
- *
912
- * @param {number} source - Source block handle.
913
- * @param {number} destiny - Destination block handle.
914
- * @param {number} [slots=UNKNOWN] - Maximum number of elements to copy.
915
- * `UNKNOWN` represents the sentinel value used not to impose an additional limit.
916
- * @returns {Uint8Array} The `dataBus` after the operation.
917
- * @throws {Error} If `source` or `destiny` is invalid or corrupted.
1083
+ * @param {number} handler - Block handle.
1084
+ * @returns {boolean} `true` if the block is full; otherwise, `false`.
1085
+ * @throws {Error} If the handle is invalid or corrupted.
918
1086
  */
919
- copy(source, destiny, slots = UNKNOWN){
1087
+ isFull(handler) {
1088
+ const meta = this.extractMetadata(handler, this.metadata);
1089
+ return (1 << meta.capacityExponent >>> 0) - meta.occupied === 0;
1090
+ }
1091
+
1092
+ // ========== Operations between blocks=============
1093
+
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
+ */
1117
+ copy(source, destination, slots = UNKNOWN) {
920
1118
  /** @type {Metadata} */
921
1119
  const metaA = {};
922
1120
  /** @type {Metadata} */
923
1121
  const metaB = {};
924
1122
 
925
1123
  this.extractMetadata(source, metaA);
926
- this.extractMetadata(destiny, metaB);
1124
+ this.extractMetadata(destination, metaB);
1125
+ this.assertNotBorrowed(metaB.headerAddress);
927
1126
 
928
1127
  const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
929
1128
  const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
930
1129
  const newOccupied = Math.max(metaB.occupied, slotsToCopy);
931
1130
 
932
1131
  this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
933
-
934
1132
  return this.dataBus.copyWithin(metaB.dataAddress, metaA.dataAddress, metaA.dataAddress + slotsToCopy * this.wordSize);
935
1133
  }
936
1134
 
937
1135
  /**
938
1136
  * Copies a region of elements within the same block.
939
1137
  *
940
- * Indices are zero-based and follow the semantics of `Array.prototype.copyWithin()`:
941
- * `target` identifies the destination position, `start` the source starting
942
- * position, and `length` the maximum number of elements to copy.
1138
+ * Indices are zero-based and follow the semantics of
1139
+ * `Array.prototype.copyWithin()`: `target` identifies the destination position,
1140
+ * `start` the starting source position, and `length` the maximum quantity of
1141
+ * elements to copy.
943
1142
  *
944
- * Negative indices are interpreted from the end of the block's capacity. After
945
- * this normalization, indices are clamped to physical capacity. The copied quantity
946
- * is also limited by effectively occupied elements and available space from `target`.
1143
+ * Negative indices are interpreted from the end of the block's capacity.
1144
+ * After this normalization, indices are clamped to physical capacity.
1145
+ * The copied quantity is also limited by effectively occupied elements
1146
+ * and available space starting from `target`.
947
1147
  *
948
1148
  * The operation supports overlapping regions and can increase block occupancy
949
- * when the target range exceeds current occupancy.
1149
+ * when the destination range exceeds previous occupancy.
950
1150
  *
951
1151
  * @param {number} handler - Block handle.
952
1152
  * @param {number} target - Initial destination index.
953
1153
  * @param {number} start - Initial source index.
954
1154
  * @param {number} length - Maximum number of elements to copy.
955
1155
  * @returns {Uint8Array} The `dataBus` after the operation.
956
- * @throws {Error} If the handle is invalid or corrupted.
1156
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
957
1157
  */
958
1158
  copyWithin(handler, target, start, length) {
959
1159
  const meta = this.extractMetadata(handler, this.metadata);
960
- const slots = Math.floor(meta.byteCapacity / this.wordSize);
1160
+ this.assertNotBorrowed(meta.headerAddress);
961
1161
 
1162
+ const slots = Math.floor(meta.byteCapacity / this.wordSize);
962
1163
  target = Math.trunc(target);
963
1164
  start = Math.trunc(start);
964
1165
  length = Math.trunc(length);
@@ -966,12 +1167,9 @@ export default class Balloc {
966
1167
  if (target < 0) target += slots;
967
1168
  if (start < 0) start += slots;
968
1169
 
969
- // Clamps indices within capacity limits
970
1170
  target = Math.max(0, Math.min(target, slots));
971
1171
  start = Math.max(0, Math.min(start, slots));
972
1172
 
973
- // Limits copying to available space starting from target
974
- // and effectively occupied elements starting from start
975
1173
  const maxRead = Math.max(0, meta.occupied - start);
976
1174
  const maxWrite = slots - target;
977
1175
  length = Math.max(0, Math.min(length, maxRead, maxWrite));
@@ -980,9 +1178,8 @@ export default class Balloc {
980
1178
 
981
1179
  const targetAddress = meta.dataAddress + target * this.wordSize;
982
1180
  const sourceAddress = meta.dataAddress + start * this.wordSize;
983
-
984
- // Updates occupancy if the copy expands the block's occupied top
985
1181
  const newOccupied = Math.max(meta.occupied, target + length);
1182
+
986
1183
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
987
1184
 
988
1185
  return this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + length * this.wordSize);
@@ -992,16 +1189,18 @@ export default class Balloc {
992
1189
  * Appends occupied elements of `source` to the end of `target`.
993
1190
  *
994
1191
  * The copied quantity is limited by the number of occupied elements in the
995
- * source and the remaining free space in the destination's capacity.
1192
+ * source and remaining free space in the destination's capacity.
996
1193
  *
997
1194
  * The operation supports `target` and `source` referencing the same block.
998
- * In that case, the copy is performed on the block's own region and preserves
999
- * `copyWithin()` overlap semantics.
1195
+ * In this case, copying is performed over the block's own region and
1196
+ * preserves `copyWithin()` overlap semantics.
1000
1197
  *
1001
- * @param {number} target - Handle of the block that will receive the elements.
1002
- * @param {number} source - Handle of the block whose elements will be appended.
1198
+ * @param {number} target - Handle of the block that will receive elements.
1199
+ * @param {number} source - Handle of the block whose elements will be
1200
+ * appended.
1003
1201
  * @returns {number} Number of elements effectively appended.
1004
- * @throws {Error} If `target` or `source` is invalid or corrupted.
1202
+ * @throws {Error} If handles are invalid, corrupted,
1203
+ * or the destination block is borrowed via withView().
1005
1204
  */
1006
1205
  append(target, source) {
1007
1206
  const metaTarget = {};
@@ -1009,6 +1208,7 @@ export default class Balloc {
1009
1208
 
1010
1209
  this.extractMetadata(target, metaTarget);
1011
1210
  this.extractMetadata(source, metaSource);
1211
+ this.assertNotBorrowed(metaTarget.headerAddress);
1012
1212
 
1013
1213
  const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
1014
1214
  const count = Math.min(available, metaSource.occupied);
@@ -1018,11 +1218,7 @@ export default class Balloc {
1018
1218
  const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
1019
1219
  const sourceAddress = metaSource.dataAddress;
1020
1220
 
1021
- if (target === source) {
1022
- this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
1023
- } else {
1024
- this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
1025
- }
1221
+ this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
1026
1222
 
1027
1223
  this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
1028
1224
 
@@ -1032,14 +1228,14 @@ export default class Balloc {
1032
1228
  /**
1033
1229
  * Creates an independent copy of a block.
1034
1230
  *
1035
- * The new block has the same physical capacity and occupancy as the original block.
1036
- * All bytes in the reserved region, including currently unoccupied positions,
1037
- * are copied.
1231
+ * The new block has the same physical capacity and occupancy as the
1232
+ * original block. All bytes in the reserved region, including currently
1233
+ * unoccupied positions, are copied.
1038
1234
  *
1039
- * The new block receives a new handle and remains subject to normal allocation
1040
- * and recycling rules.
1235
+ * The new block receives a new handle and remains subject to normal
1236
+ * allocation and recycling rules.
1041
1237
  *
1042
- * @param {number} handler - Handle of the block to clone.
1238
+ * @param {number} handler - Handle of the block to be cloned.
1043
1239
  * @returns {number} Handle of the new block.
1044
1240
  * @throws {Error} If the handle is invalid or corrupted.
1045
1241
  */
@@ -1059,28 +1255,33 @@ export default class Balloc {
1059
1255
  /**
1060
1256
  * Swaps the data regions associated with two blocks.
1061
1257
  *
1062
- * The operation swaps region addresses, capacities, and occupancies between headers.
1063
- * Handles remain unchanged: after the operation, each handle continues identifying
1064
- * its own header, but that header now describes the region previously belonging
1065
- * to the other block.
1258
+ * The operation swaps region addresses, capacities, and occupancies
1259
+ * between headers. Handles remain unchanged:
1260
+ * after the operation, each handle continues identifying its own
1261
+ * header, but that header now describes the region previously
1262
+ * belonging to the other block.
1066
1263
  *
1067
- * No data is copied in the `dataBus`; only the metadata of the two headers
1068
- * is modified.
1264
+ * No data is copied in the `dataBus`; only the metadata of the two
1265
+ * headers is modified.
1069
1266
  *
1070
1267
  * @param {number} source - Handle of the first block.
1071
1268
  * @param {number} target - Handle of the second block.
1072
1269
  * @returns {void}
1073
- * @throws {Error} If `source` or `target` is invalid or corrupted.
1270
+ * @throws {Error} If handles are invalid, corrupted,
1271
+ * or either block is borrowed via withView().
1074
1272
  */
1075
1273
  swap(source, target) {
1076
1274
  /** @type {Metadata} */
1077
1275
  const metaA = {};
1078
1276
  /** @type {Metadata} */
1079
1277
  const metaB = {};
1080
-
1278
+
1081
1279
  this.extractMetadata(source, metaA);
1082
1280
  this.extractMetadata(target, metaB);
1083
1281
 
1282
+ this.assertNotBorrowed(metaA.headerAddress);
1283
+ this.assertNotBorrowed(metaB.headerAddress);
1284
+
1084
1285
  this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
1085
1286
  this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
1086
1287
 
@@ -1089,7 +1290,7 @@ export default class Balloc {
1089
1290
 
1090
1291
  this.controlAdapter.setUint32(metaA.headerAddress + OCCUPIED_OFFSET, metaB.occupied, IS_LITTLE_ENDIAN);
1091
1292
  this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, metaA.occupied, IS_LITTLE_ENDIAN);
1092
- }
1293
+ }
1093
1294
 
1094
1295
 
1095
1296
  // ============= SERIALIZATION ==============
@@ -1097,11 +1298,11 @@ export default class Balloc {
1097
1298
  /**
1098
1299
  * Serializes the content and metadata of a memory block.
1099
1300
  *
1100
- * The method extracts occupied data from the block via `pick()`, groups them
1101
- * along with capacity and word type information into a data envelope, and encodes
1102
- * them using the CBOR format.
1301
+ * The method extracts occupied block data via `pick()`,
1302
+ * groups it alongside capacity and word type information
1303
+ * into a data envelope, and encodes it using the CBOR format.
1103
1304
  *
1104
- * @param {number} handler - Handle of the block to serialize.
1305
+ * @param {number} handler - Handle of the block to be serialized.
1105
1306
  * @returns {Uint8Array} A buffer containing the serialized block data.
1106
1307
  * @throws {Error} If the handle is invalid or corrupted.
1107
1308
  */
@@ -1134,13 +1335,13 @@ export default class Balloc {
1134
1335
  * Restores a memory block from serialized data.
1135
1336
  *
1136
1337
  * Decodes the CBOR envelope, validates whether the word type of the serialized
1137
- * data is compatible with the current allocator instance, and allocates a new
1138
- * block with the necessary capacity to accommodate the content. Then, the original
1139
- * data and occupancy are restored in the new block.
1338
+ * data is compatible with the current allocator instance, and allocates
1339
+ * a new block with the capacity required to accommodate the content.
1340
+ * Then, original data and occupancy are restored in the new block.
1140
1341
  *
1141
1342
  * @param {Uint8Array|ArrayBuffer} serialized - Buffer containing serialized data.
1142
1343
  * @returns {number} Handle of the newly recreated block.
1143
- * @throws {Error} If the decoded data's word type differs from the one configured in the allocator.
1344
+ * @throws {Error} If the decoded data's word type differs from the allocator's configuration.
1144
1345
  */
1145
1346
  load(serialized) {
1146
1347
  if (!(serialized instanceof ArrayBuffer) && !(serialized instanceof Uint8Array)) {
@@ -1195,22 +1396,56 @@ export default class Balloc {
1195
1396
 
1196
1397
  // ============= UTILITIES ==============
1197
1398
 
1399
+ /**
1400
+ * Prevents modification operations on a borrowed block.
1401
+ *
1402
+ * Checks the VIEW_LOCK flag in the header associated with the provided address.
1403
+ *
1404
+ * @param {number} headerAddress - Address of the header in controlBus.
1405
+ * @returns {void}
1406
+ * @throws {Error} If the block is borrowed via withView().
1407
+ * @private
1408
+ */
1409
+ assertNotBorrowed(headerAddress) {
1410
+ if (this.controlBus[headerAddress + FLAGS_OFFSET] & VIEW_LOCK) {
1411
+ throw new Error("Block is borrowed");
1412
+ }
1413
+ }
1414
+
1415
+ /**
1416
+ * Prevents operations that replace or remap the dataBus
1417
+ * while any segment is borrowed.
1418
+ *
1419
+ * @returns {void}
1420
+ * @throws {Error} If any block is borrowed via withView().
1421
+ * @private
1422
+ */
1423
+ assertNoActiveViews() {
1424
+ for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
1425
+ if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
1426
+ if (this.controlBus[i + FLAGS_OFFSET] & VIEW_LOCK) {
1427
+ throw new Error("Cannot remap memory while a block is borrowed");
1428
+ }
1429
+ }
1430
+ }
1431
+
1198
1432
  /**
1199
1433
  * [INTERNAL USE]
1200
- * Decodes the metadata associated with a handle.
1434
+ * Decodes metadata associated with a handle.
1201
1435
  *
1202
1436
  * The handle is split into generation and header address. The cookie stored
1203
1437
  * in the header is then recalculated to validate the combination; only after
1204
- * this validation is metadata read.
1438
+ * this validation are metadata read.
1205
1439
  *
1206
- * Decoded fields are written to the `out` object, which is returned by the function
1207
- * itself. The object can be reused across calls to avoid new allocations.
1440
+ * Decoded fields are written to the `out` object, which is returned
1441
+ * by the function itself. The object can be reused between calls to avoid
1442
+ * new allocations.
1208
1443
  *
1209
- * @param {number} handler - Handle to decode and validate.
1210
- * @param {Metadata} out - Object that will receive the decoded metadata.
1444
+ * @param {number} handler - Handle to be decoded and validated.
1445
+ * @param {Metadata} out - Object that will receive decoded metadata.
1211
1446
  * @returns {Metadata} The same reference provided in `out`.
1212
- * @throws {Error} If the header cookie does not match the handle or if the
1213
- * handle does not identify a valid header.
1447
+ * @throws {Error} If the header cookie does not match the handle or
1448
+ * if the handle does not identify a valid header.
1214
1449
  * @private
1215
1450
  */
1216
1451
  extractMetadata(handler, out) {
@@ -1225,7 +1460,7 @@ export default class Balloc {
1225
1460
  }
1226
1461
 
1227
1462
  out.dataAddress = this.controlAdapter.getUint32(out.headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
1228
- out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1463
+ out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1229
1464
  out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
1230
1465
  out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
1231
1466
 
@@ -1234,20 +1469,22 @@ export default class Balloc {
1234
1469
 
1235
1470
  /**
1236
1471
  * [INTERNAL USE]
1237
- * Calculates the validation cookie of a header.
1472
+ * Calculates a header's validation cookie.
1238
1473
  *
1239
- * The cookie is derived from the header address and the 11-bit generation via
1240
- * fast hash. The result is reduced to 8 bits.
1474
+ * The cookie is derived from the header address and the 11 generation bits via
1475
+ * fast hash.
1476
+ * The result is reduced to 8 bits.
1241
1477
  *
1242
- * The value zero is reserved as an invalid header indicator; therefore, when
1243
- * the calculation yields zero, the method returns `1`.
1478
+ * The value zero is reserved as an invalid header indicator; therefore,
1479
+ * when the calculation produces zero, the method returns `1`.
1244
1480
  *
1245
- * The cookie is not a cryptographic mechanism. Its purpose is to detect invalid,
1246
- * stale, or corrupted handles within the allocator's memory management model.
1481
+ * The cookie does not constitute a cryptographic mechanism. Its purpose is
1482
+ * to detect invalid, stale, or corrupted handles within the allocator's
1483
+ * memory management model.
1247
1484
  *
1248
1485
  * @param {number} addr - Header address.
1249
- * @param {number} gen - Generation associated with the handle. Only the 11 least
1250
- * significant bits are considered.
1486
+ * @param {number} gen - Generation associated with the handle. Only the 11
1487
+ * least significant bits are considered.
1251
1488
  * @returns {number} 8-bit cookie in the range [1, 255].
1252
1489
  * @private
1253
1490
  */
@@ -1258,11 +1495,11 @@ export default class Balloc {
1258
1495
  /**
1259
1496
  * Returns the number of regions currently stored in the recycling list.
1260
1497
  *
1261
- * Each region corresponds to a freed block that could not be returned directly
1262
- * to the top of the `dataBus` and therefore remains available for reuse by a
1263
- * future allocation of identical capacity.
1498
+ * Each region corresponds to a freed block that could not be returned
1499
+ * directly to the top of the `dataBus` and, therefore, remains available for
1500
+ * reuse by a future allocation of identical capacity.
1264
1501
  *
1265
- * @returns {number} Number of free regions maintained in `recycle`.
1502
+ * @returns {number} Number of free regions kept in `recycle`.
1266
1503
  */
1267
1504
  recycleCount() {
1268
1505
  let count = 0;
@@ -1275,9 +1512,10 @@ export default class Balloc {
1275
1512
  }
1276
1513
 
1277
1514
  /**
1278
- * Returns the total bytes belonging to regions currently stored in the recycling list.
1515
+ * Returns the total bytes belonging to regions currently stored in the
1516
+ * recycling list.
1279
1517
  *
1280
- * The value is calculated by summing the capacity of each free region multiplied
1518
+ * The value is calculated by summing each free region's capacity multiplied
1281
1519
  * by the number of regions registered for that capacity.
1282
1520
  *
1283
1521
  * @returns {number} Number of bytes occupied by recyclable regions.
@@ -1293,25 +1531,26 @@ export default class Balloc {
1293
1531
  }
1294
1532
 
1295
1533
  /**
1296
- * Returns the amount of allocated bytes that do not belong to currently recyclable regions.
1534
+ * Returns the quantity of allocated bytes that do not belong to currently
1535
+ * recyclable regions.
1297
1536
  *
1298
- * The value is obtained by subtracting the bytes belonging to free regions maintained
1299
- * in `recycle` from the total advance of `dataPointer`.
1537
+ * The value is obtained by subtracting the bytes belonging to free regions
1538
+ * kept in `recycle` from the total advance of `dataPointer`.
1300
1539
  *
1301
- * @returns {number} Number of bytes associated with non-recyclable regions within
1302
- * the area already used by the `dataBus`.
1540
+ * @returns {number} Number of bytes associated with non-recyclable regions
1541
+ * within the area already used by `dataBus`.
1303
1542
  */
1304
1543
  get allocatedBytes() {
1305
1544
  return this.dataPointer - this.recycleBytes;
1306
1545
  }
1307
1546
 
1308
1547
  /**
1309
- * Returns the amount of bytes not yet used at the top of the `dataBus`.
1548
+ * Returns the quantity of bytes not yet used at the top of the `dataBus`.
1310
1549
  *
1311
1550
  * This space corresponds to the region between `dataPointer` and the end of the
1312
1551
  * capacity currently reserved for the buffer.
1313
1552
  *
1314
- * @returns {number} Number of available bytes after `dataPointer`.
1553
+ * @returns {number} Number of bytes available after `dataPointer`.
1315
1554
  */
1316
1555
  get unallocatedBytes() {
1317
1556
  return this.size - this.dataPointer;
@@ -1320,13 +1559,13 @@ export default class Balloc {
1320
1559
  /**
1321
1560
  * Returns the ratio between recyclable memory and the used heap area.
1322
1561
  *
1323
- * The metric considers free regions maintained in `recycle` as fragmentation
1324
- * and uses `dataPointer` as the denominator. When no bytes have been used by the heap,
1325
- * the result is zero.
1562
+ * The metric considers free regions kept in `recycle` as fragmentation
1563
+ * and uses `dataPointer` as the denominator. When no bytes have been used
1564
+ * by the heap, the result is zero.
1326
1565
  *
1327
- * The value does not represent the fraction of the entire `dataBus` capacity,
1328
- * but specifically the proportion of recyclable bytes within the area already
1329
- * traversed by the bump pointer.
1566
+ * The value does not represent the fraction of the entire `dataBus` capacity, but
1567
+ * specifically the proportion of recyclable bytes within the area already traversed
1568
+ * by the bump pointer.
1330
1569
  *
1331
1570
  * @returns {number} Fragmentation ratio in the range [0, 1] under normal
1332
1571
  * operating conditions.