balloc 1.0.1 → 1.2.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) {
263
+
252
264
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
253
- let headerAddress = handler >>> 0;
254
-
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,57 @@ 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
309
  * Frees a memory block.
299
310
  *
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.
311
+ * The block's header is invalidated by zeroing its cookie, and its
312
+ * address is registered for later reuse. The data region
313
+ * is also returned to the recycling system, except when the block is
314
+ * exactly at the top of the `dataBus`; in that case, the `dataPointer` is simply
315
+ * rolled back, eliminating the region without creating an entry in the recycling
316
+ * list.
305
317
  *
306
- * @param {number} handler - Handle of the block to free.
318
+ * @param {number} handler - Handle of the block to be freed.
307
319
  * @returns {void}
308
- * @throws {Error} If the handle is invalid or corrupted.
320
+ * @throws {Error} If the handle is invalid, corrupted, or the block
321
+ * is borrowed via withView().
309
322
  */
310
323
  free(handler) {
324
+
311
325
  const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
312
- let headerAddress = handler >>> 0;
313
-
326
+ const headerAddress = handler >>> 0;
314
327
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
315
328
  const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
316
329
  const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
317
330
 
318
-
319
331
  if (cookie !== this.bakeCookie(headerAddress, generation)) {
320
332
  throw new Error("Invalid or corrupted handle");
321
333
  }
322
334
 
323
- const blockSize = (1 << capacity >>> 0) * this.wordSize;
335
+ this.assertNotBorrowed(headerAddress);
324
336
 
337
+ const blockSize = (1 << capacity >>> 0) * this.wordSize;
325
338
  this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
326
339
 
327
340
  if (this.echoPointer + 4 <= this.controlBus.byteLength) {
328
341
  this.controlAdapter.setUint32(this.echoPointer, headerAddress, IS_LITTLE_ENDIAN);
329
342
  this.echoPointer += 4;
330
- }
331
-
343
+ }
332
344
 
333
345
  if (dataAddress + blockSize === this.dataPointer) {
334
346
  this.dataPointer = dataAddress;
335
347
  } else {
336
348
  this.recyclePush(blockSize, dataAddress);
337
349
  }
338
-
339
350
  }
340
-
341
351
  // ========== RECYCLING ==========
342
352
 
343
353
  /**
@@ -345,13 +355,13 @@ export default class Balloc {
345
355
  * Inserts a free region into the recycling list.
346
356
  *
347
357
  * 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:
358
+ * stored value is a `Uint32Array` whose zero position contains the quantity
359
+ * of registered addresses and subsequent positions contain the addresses of
360
+ * the free regions:
351
361
  *
352
362
  * [count, address1, address2, ...]
353
363
  *
354
- * When the page becomes full, its buffer is expanded to double the current
364
+ * When the page becomes full, its buffer is expanded to double its current
355
365
  * capacity.
356
366
  *
357
367
  * @param {number} capacity - Capacity of the free region, in bytes.
@@ -387,7 +397,7 @@ export default class Balloc {
387
397
  *
388
398
  * @param {number} capacity - Desired capacity, in bytes.
389
399
  * @returns {number} Initial address of a recyclable region or `UNKNOWN`
390
- * when no region exists with the requested capacity.
400
+ * when a region with the requested capacity does not exist.
391
401
  * @private
392
402
  */
393
403
  recyclePop(capacity) {
@@ -405,41 +415,50 @@ export default class Balloc {
405
415
  }
406
416
 
407
417
  // ========== GARBAGE COLLECTION ==========
418
+
408
419
  /**
409
420
  * Compacts the `dataBus` using the ReBump algorithm.
410
421
  *
411
422
  * 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.
423
+ * still-valid regions to a new `dataBus`, eliminating free spaces
424
+ * between them. Each surviving block's address is updated in its
425
+ * respective header.
414
426
  *
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.
427
+ * The order of blocks in the `controlBus` is preserved. The internal data of
428
+ * each block is also fully preserved, including its reserved capacity
429
+ * and current occupancy.
418
430
  *
419
- * At the end of compaction:
431
+ * Upon completion of compaction:
420
432
  * - all recyclable regions are eliminated;
421
433
  * - `dataPointer` points to the first byte after the last live block;
422
- * - `dataBus` represents a contiguous heap for active blocks.
434
+ * - the `dataBus` represents a contiguous heap for active blocks.
423
435
  *
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.
436
+ * Control complexity is O(n), where `n` is the number of traversed
437
+ * headers. The effective memory movement cost also depends on the volume
438
+ * of bytes belonging to live blocks.
427
439
  *
428
440
  * @returns {void}
441
+ * @throws {Error} If any block is borrowed via withView().
429
442
  */
430
443
  gc() {
444
+ this.assertNoActiveViews();
445
+
431
446
  const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
432
447
  this.recycle.clear();
433
448
  this.dataPointer = 0 >>> 0;
434
- for (let i = 0; i < this.controlPointer; i+= HEADER_SIZE) {
449
+
450
+ for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
435
451
  if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
452
+
436
453
  const start = this.controlAdapter.getUint32(i + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
437
454
  const size = (1 << this.controlBus[i + CAPACITY_OFFSET] >>> 0) * this.wordSize;
438
455
  const end = start + size;
456
+
439
457
  newDataBus.set(this.dataBus.subarray(start, end), this.dataPointer);
440
458
  this.controlAdapter.setUint32(i + ADDRESS_OFFSET, this.dataPointer, IS_LITTLE_ENDIAN);
441
459
  this.dataPointer += size;
442
460
  }
461
+
443
462
  this.dataBus = newDataBus;
444
463
  this.dataAdapter = new DataView(this.dataBus.buffer);
445
464
  this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
@@ -448,20 +467,24 @@ export default class Balloc {
448
467
  }
449
468
 
450
469
  // ========== SCALING ==========
470
+
451
471
  /**
452
472
  * [!!! INTERNAL USE, DO NOT USE IN YOUR CODE !!!]
453
473
  * Expands the `dataBus` to double its current capacity.
454
474
  *
455
475
  * 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.
476
+ * existing data. All views associated with the buffer are recreated
477
+ * to reference the new storage.
458
478
  *
459
479
  * @returns {void}
460
- * @throws {RangeError} If the `dataBus` capacity has exceeded the maximum
461
- * supported limit.
480
+ * @throws {Error} If any block is borrowed via withView().
481
+ * @throws {RangeError} If the `dataBus` capacity has already exceeded the
482
+ * maximum supported limit.
462
483
  * @private
463
484
  */
464
485
  grow() {
486
+ this.assertNoActiveViews();
487
+
465
488
  if (this.size > 0x80000000) throw new RangeError("Data bus capacity exceeded");
466
489
 
467
490
  const newSize = (this.size * 2) >>> 0;
@@ -480,12 +503,12 @@ export default class Balloc {
480
503
  * Expands the `controlBus` to double its current capacity.
481
504
  *
482
505
  * The underlying buffer is transferred to a larger `ArrayBuffer`, preserving
483
- * existing headers. The `controlAdapter` is recreated to reference the new
484
- * storage.
506
+ * existing headers. The `controlAdapter` is recreated to reference
507
+ * the new storage.
485
508
  *
486
509
  * @returns {void}
487
- * @throws {RangeError} If the current `controlBus` capacity has exceeded
488
- * the maximum supported limit.
510
+ * @throws {RangeError} If the current `controlBus` capacity has already
511
+ * exceeded the maximum supported limit.
489
512
  * @private
490
513
  */
491
514
  headerGrow() {
@@ -500,48 +523,50 @@ export default class Balloc {
500
523
  // ========== STACK OPERATIONS ==========
501
524
 
502
525
  /**
503
- * Appends an element to the end of the block's occupied sequence.
526
+ * Appends an element to the end of the sequence occupied by the block.
504
527
  *
505
528
  * 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.
529
+ * element. Block occupancy is incremented only when space is available
530
+ * within its capacity.
508
531
  *
509
532
  * @param {number} handler - Block handle.
510
- * @param {number} value - Value to insert.
533
+ * @param {number} value - Value to be inserted.
511
534
  * @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.
535
+ * is already out of available space.
536
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
537
+ *
514
538
  */
515
539
  push(handler, value) {
516
-
517
540
  const meta = this.extractMetadata(handler, this.metadata);
541
+ this.assertNotBorrowed(meta.headerAddress);
518
542
 
519
543
  if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
520
544
 
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);
545
+ this.writer(meta.dataAddress + meta.occupied * this.wordSize, value, IS_LITTLE_ENDIAN);
546
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
523
547
 
524
548
  return true;
525
549
  }
526
550
 
527
551
  /**
528
- * Removes and returns the last occupied element from the block.
552
+ * Removes the last occupied element from the block and returns it.
529
553
  *
530
- * Occupancy is decremented before reading the removed element. Corresponding
554
+ * Occupancy is decremented before reading the removed element. The corresponding
531
555
  * bytes are not cleared and remain in the allocated region, but cease to be
532
556
  * part of the occupied sequence.
533
557
  *
534
558
  * @param {number} handler - Block handle.
535
559
  * @returns {number|undefined} Removed value or `undefined` if the block
536
560
  * is empty.
537
- * @throws {Error} If the handle is invalid or corrupted.
561
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
538
562
  */
539
563
  pop(handler) {
540
564
  const meta = this.extractMetadata(handler, this.metadata);
565
+ this.assertNotBorrowed(meta.headerAddress);
541
566
 
542
567
  if (meta.occupied === 0) return undefined;
543
568
 
544
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1,IS_LITTLE_ENDIAN);
569
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
545
570
  return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
546
571
  }
547
572
 
@@ -566,52 +591,55 @@ export default class Balloc {
566
591
  /**
567
592
  * Inserts an element at the beginning of the occupied sequence.
568
593
  *
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.
594
+ * Currently occupied elements are shifted forward by one position and
595
+ * `value` is written at the first position. The operation requires a free
596
+ * position within the block's capacity.
572
597
  *
573
- * The operation's cost is proportional to the number of occupied elements,
598
+ * The operation cost is proportional to the number of occupied elements,
574
599
  * as data needs to be shifted.
575
600
  *
576
601
  * @param {number} handler - Block handle.
577
- * @param {number} value - Value to insert.
602
+ * @param {number} value - Value to be inserted.
578
603
  * @returns {boolean} `true` if the value was inserted; `false` if the block
579
604
  * is full.
580
- * @throws {Error} If the handle is invalid or corrupted.
605
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
581
606
  */
582
607
  nudge(handler, value) {
583
608
  const meta = this.extractMetadata(handler, this.metadata);
609
+ this.assertNotBorrowed(meta.headerAddress);
584
610
 
585
611
  if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
586
612
 
587
613
  this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
588
614
  this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
589
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1,IS_LITTLE_ENDIAN);
615
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
590
616
 
591
617
  return true;
592
618
  }
593
619
 
594
620
  /**
595
- * Removes and returns the first occupied element from the block.
621
+ * Removes the first occupied element from the block and returns it.
596
622
  *
597
- * Remaining elements are shifted one position toward the beginning of the
598
- * occupied region. The block's physical capacity remains unchanged.
623
+ * Remaining elements are shifted one position toward the beginning
624
+ * of the occupied region. The physical capacity of the block remains unchanged.
599
625
  *
600
- * The operation's cost is proportional to the number of shifted elements.
626
+ * The operation cost is proportional to the number of shifted elements.
601
627
  *
602
628
  * @param {number} handler - Block handle.
603
629
  * @returns {number|undefined} First removed value or `undefined` if the
604
630
  * block is empty.
605
- * @throws {Error} If the handle is invalid or corrupted.
631
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
606
632
  */
607
633
  pull(handler) {
608
634
  const meta = this.extractMetadata(handler, this.metadata);
635
+ this.assertNotBorrowed(meta.headerAddress);
609
636
 
610
637
  if (meta.occupied === 0) return undefined;
611
638
 
612
639
  const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
613
640
  this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
614
641
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
642
+
615
643
  return result;
616
644
  }
617
645
 
@@ -628,21 +656,21 @@ export default class Balloc {
628
656
 
629
657
  if (meta.occupied === 0) return undefined;
630
658
 
631
- return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
659
+ return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
632
660
  }
633
661
 
634
662
  // ========== RANDOM ACCESS ==========
635
663
 
636
664
  /**
637
- * Checks if a value is present among the block's occupied elements.
665
+ * Checks if a value is present among the occupied elements of the block.
638
666
  *
639
667
  * The search is performed directly on the auxiliary `TypedArray` and considers
640
668
  * only the currently occupied range, not the entire reserved physical capacity.
641
669
  *
642
670
  * @param {number} handler - Block handle.
643
671
  * @param {number} value - Value to search for.
644
- * @returns {boolean} `true` if `value` is present among the occupied elements;
645
- * otherwise, `false`.
672
+ * @returns {boolean} `true` if `value` is present among the occupied
673
+ * elements; otherwise, `false`.
646
674
  * @throws {Error} If the handle is invalid or corrupted.
647
675
  */
648
676
  has(handler, value) {
@@ -655,18 +683,74 @@ export default class Balloc {
655
683
  return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
656
684
  }
657
685
 
658
- /**
659
- * Returns the occupied element at a zero-based index.
686
+ /**
687
+ * Locates the first occurrence of an element in the block's occupied sequence.
688
+ *
689
+ * The search is performed in ascending order of indices, using the `indexOf`
690
+ * operation of the underlying TypedArray. The search exclusively considers
691
+ * occupied elements, ignoring the block's unused capacity.
660
692
  *
661
- * Indices outside the range `[0, occupied)` are not considered an error and
662
- * result in `undefined`.
693
+ * The starting search position can be specified by `fromIndex`,
694
+ * following TypedArray indexing rules.
663
695
  *
664
696
  * @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.
697
+ * @param {number|bigint} searchElement - Element to locate.
698
+ * @param {number} [fromIndex=0] - Index from which to start the search.
699
+ * @returns {number} Index of the first occurrence or `-1` if the
700
+ * element is not found or if the block is empty.
701
+ * @throws {Error} If the handle is invalid or corrupted.
702
+ */
703
+ indexOf(handler, searchElement, fromIndex = 0) {
704
+ const meta = this.extractMetadata(handler, this.metadata);
705
+
706
+ if (meta.occupied === 0) return -1;
707
+
708
+ const rawAddres = meta.dataAddress >>> this.wordShift;
709
+
710
+ return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).indexOf(searchElement, fromIndex);
711
+ }
712
+
713
+ /**
714
+ * Locates the last occurrence of an element in the block's occupied sequence.
715
+ *
716
+ * The search is performed in descending order of indices, using the `lastIndexOf`
717
+ * operation of the underlying TypedArray. The search exclusively considers
718
+ * occupied elements, ignoring the block's unused capacity.
719
+ *
720
+ * The starting search position can be specified by `fromIndex`,
721
+ * following TypedArray indexing rules. By default, the search starts
722
+ * at the last occupied element.
723
+ *
724
+ * @param {number} handler - Block handle.
725
+ * @param {number|bigint} searchElement - Element to locate.
726
+ * @param {number} [fromIndex=-1] - Index from which to start the search.
727
+ * @returns {number} Index of the last occurrence or `-1` if the
728
+ * element is not found or if the block is empty.
668
729
  * @throws {Error} If the handle is invalid or corrupted.
669
730
  */
731
+ lastIndexOf(handler, searchElement, fromIndex = -1) {
732
+ const meta = this.extractMetadata(handler, this.metadata);
733
+
734
+ if (meta.occupied === 0) return -1;
735
+
736
+ const rawAddres = meta.dataAddress >>> this.wordShift;
737
+
738
+ return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).lastIndexOf(searchElement, fromIndex);
739
+ }
740
+
741
+
742
+ /**
743
+ * Returns the occupied element at a zero-based index.
744
+ *
745
+ * Indices outside the range `[0, occupied)` are not considered an error and
746
+ * result in `undefined`.
747
+ *
748
+ * @param {number} handler - Block handle.
749
+ * @param {number} index - Zero-based index of the element.
750
+ * @returns {number|undefined} Value stored at the index or `undefined` if
751
+ * the index is outside the occupied region.
752
+ * @throws {Error} If the handle is invalid or corrupted.
753
+ */
670
754
  get(handler, index) {
671
755
 
672
756
  const meta = this.extractMetadata(handler, this.metadata);
@@ -687,10 +771,11 @@ export default class Balloc {
687
771
  * @param {number} value - New value.
688
772
  * @returns {boolean} `true` if the value was written; `false` if the index
689
773
  * is outside the occupied region.
690
- * @throws {Error} If the handle is invalid or corrupted.
774
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
691
775
  */
692
776
  set(handler, index, value) {
693
777
  const meta = this.extractMetadata(handler, this.metadata);
778
+ this.assertNotBorrowed(meta.headerAddress);
694
779
 
695
780
  if (index < 0 || index >= meta.occupied) return false;
696
781
 
@@ -701,24 +786,26 @@ export default class Balloc {
701
786
  // ============= MISCELLANEOUS ===============
702
787
 
703
788
  /**
704
- * Clears block occupancy and fills its entire physical capacity with a single value.
789
+ * Zeroes block occupancy and fills its entire physical capacity with
790
+ * a single value.
705
791
  *
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.
792
+ * The fill covers all available slots, not just currently
793
+ * occupied elements. After the operation, the block is considered
794
+ * empty regardless of the value used for filling.
709
795
  *
710
796
  * @param {number} handler - Block handle.
711
797
  * @param {number} [value=0] - Value used to fill all slots.
712
798
  * @returns {void}
713
- * @throws {Error} If the handle is invalid or corrupted.
799
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
714
800
  */
715
- clear(handler, value=0) {
801
+ clear(handler, value = 0) {
716
802
  const meta = this.extractMetadata(handler, this.metadata);
803
+ this.assertNotBorrowed(meta.headerAddress);
717
804
 
718
805
  const slots = meta.byteCapacity / this.wordSize;
719
806
  const rawAddress = meta.dataAddress >>> this.wordShift;
720
807
 
721
- this.auxiliary.fill(value, rawAddress, rawAddress + slots);
808
+ this.auxiliary.fill(value, rawAddress, rawAddress + slots);
722
809
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
723
810
  }
724
811
 
@@ -726,26 +813,28 @@ export default class Balloc {
726
813
  /**
727
814
  * Fills a range of block slots with a value.
728
815
  *
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.
816
+ * The range uses zero-based indices and follows the convention
817
+ * `[start, end)`, therefore `start` is inclusive and `end` is exclusive.
818
+ * When `end` is not provided, filling extends to the end of the block's
819
+ * physical capacity.
732
820
  *
733
- * Block occupancy becomes `end`, including when the filled range extends beyond
734
- * the previous occupancy.
821
+ * Block occupancy becomes `end`, including when the filled range
822
+ * extends beyond previous occupancy.
735
823
  *
736
824
  * @param {number} handler - Block handle.
737
825
  * @param {number} value - Value used for filling.
738
826
  * @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.
827
+ * @param {number|null} [end=null] - Final index, exclusive. When
828
+ * omitted or `null`, uses the block's total capacity.
741
829
  * @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`.
830
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
831
+ * @throws {RangeError} If `start` or `end` is outside capacity limits,
832
+ * or if `start > end`.
745
833
  */
746
834
  fill(handler, value, start = 0, end = null) {
747
835
  const meta = this.extractMetadata(handler, this.metadata);
748
-
836
+ this.assertNotBorrowed(meta.headerAddress);
837
+
749
838
  const slots = meta.byteCapacity / this.wordSize;
750
839
  const lastIndex = end ?? slots;
751
840
 
@@ -760,7 +849,6 @@ export default class Balloc {
760
849
  }
761
850
 
762
851
  const rawAddress = meta.dataAddress >>> this.wordShift;
763
-
764
852
  this.auxiliary.fill(value, rawAddress + start, rawAddress + lastIndex);
765
853
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, lastIndex, IS_LITTLE_ENDIAN);
766
854
  }
@@ -769,16 +857,17 @@ export default class Balloc {
769
857
  * Fills all physical slots of the block with a value and marks the entire
770
858
  * capacity as occupied.
771
859
  *
772
- * Unlike `clear()`, the operation results in a fully occupied block.
860
+ * Unlike `clear()`, this operation results in a fully occupied block.
773
861
  *
774
862
  * @param {number} handler - Block handle.
775
863
  * @param {number} value - Value used for filling.
776
864
  * @returns {void}
777
- * @throws {Error} If the handle is invalid or corrupted.
865
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
778
866
  */
779
867
  fillAll(handler, value) {
780
868
  const meta = this.extractMetadata(handler, this.metadata);
781
-
869
+ this.assertNotBorrowed(meta.headerAddress);
870
+
782
871
  const rawAddress = meta.dataAddress >>> this.wordShift;
783
872
  const capacityElements = meta.byteCapacity / this.wordSize;
784
873
 
@@ -789,28 +878,27 @@ export default class Balloc {
789
878
  /**
790
879
  * Copies elements from an `Array` or `TypedArray` to the beginning of the block.
791
880
  *
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.
881
+ * The copied quantity is limited by the block's capacity. Occupancy is
882
+ * updated to the greater value between previous occupancy and the quantity
883
+ * effectively copied; therefore, a call to `put()` does not reduce existing
884
+ * occupancy when receiving a smaller sequence.
796
885
  *
797
- * For `Array`, only the first fitting elements are copied. For `TypedArray`,
798
- * a source subarray is used without intermediate copying.
886
+ * For `Array`, only the first elements that fit are copied.
887
+ * For `TypedArray`, a source subarray is used without intermediate copying.
799
888
  *
800
889
  * @param {number} handler - Block handle.
801
890
  * @param {Array|TypedArray} data - Sequence of values to copy.
802
891
  * @returns {void}
803
- * @throws {Error} If the handle is invalid or corrupted.
892
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
804
893
  * @throws {TypeError} If `data` is neither an `Array` nor a `TypedArray`.
805
894
  */
806
895
  put(handler, data) {
807
896
  const meta = this.extractMetadata(handler, this.metadata);
897
+ this.assertNotBorrowed(meta.headerAddress);
808
898
 
809
899
  const rawAddress = meta.dataAddress >>> this.wordShift;
810
900
  const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
811
901
 
812
- meta.occupied = Math.max(length, meta.occupied);
813
-
814
902
  if (Array.isArray(data)) {
815
903
  this.auxiliary.set(data.slice(0, length), rawAddress);
816
904
  } else if (isTypedArray(data)) {
@@ -818,34 +906,71 @@ export default class Balloc {
818
906
  } else {
819
907
  const actual = data?.constructor?.name ?? (data === null ? 'null' : typeof data);
820
908
  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);
909
+ }
910
+
911
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, Math.max(length, meta.occupied), IS_LITTLE_ENDIAN);
823
912
  }
824
913
 
825
- /**
826
- * Returns a copy of the elements currently occupied by the block.
914
+ /**
915
+ * Returns a copy of the elements currently occupied by the block.
916
+ *
917
+ * The result is a `TypedArray` of the same type configured by
918
+ * `bucketSize`. Unoccupied physical capacity is not included in the result.
919
+ *
920
+ * The operation does not directly expose internal storage: the method
921
+ * uses `TypedArray.prototype.slice()`, producing a new view with
922
+ * independent storage.
923
+ *
924
+ * @param {number} handler - Block handle.
925
+ * @returns {TypedArray} Copy of elements occupied by the block. When
926
+ * the block is empty, returns an empty `TypedArray` of the configured type.
927
+ * @throws {Error} If the handle is invalid or corrupted.
928
+ */
929
+ pick(handler) {
930
+ const meta = this.extractMetadata(handler, this.metadata);
931
+
932
+ const rawAddress = meta.dataAddress >>> this.wordShift;
933
+
934
+ if (meta.occupied === 0) {
935
+ return this.auxiliary.slice(rawAddress, rawAddress);
936
+ }
937
+
938
+ return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
939
+ }
940
+
941
+ /**
942
+ * Executes a callback over a direct view of the block's occupied region.
827
943
  *
828
- * The result is a `TypedArray` of the same type configured by `bucketSize`.
829
- * Unoccupied physical capacity is not included in the result.
944
+ * The view shares Balloc's internal storage and performs no copying.
945
+ * The block is protected against incompatible operations during the callback.
830
946
  *
831
- * The operation does not directly expose internal storage: the method uses
832
- * `TypedArray.prototype.slice()`, producing a new view with independent storage.
947
+ * The callback must be synchronous. The received view must not be stored,
948
+ * returned, or used after the callback terminates. This restriction
949
+ * also applies to subviews derived from the original view.
833
950
  *
834
951
  * @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.
952
+ * @param {Function} callback - Function receiving the shared TypedArray.
953
+ * @returns {*} Return value produced by the callback.
954
+ * @throws {TypeError} If callback is not a function.
955
+ * @throws {Error} If the handle is invalid or already borrowed.
838
956
  */
839
- pick(handler) {
957
+ withView(handler, callback) {
958
+ if (typeof callback !== "function") throw new TypeError("callback must be a function");
959
+
840
960
  const meta = this.extractMetadata(handler, this.metadata);
961
+ const flagsAddress = meta.headerAddress + FLAGS_OFFSET;
962
+ const flags = this.controlBus[flagsAddress];
841
963
 
842
- const rawAddress = meta.dataAddress >>> this.wordShift;
964
+ if (flags & VIEW_LOCK) throw new Error("Block is already borrowed");
843
965
 
844
- if (meta.occupied === 0) {
845
- return this.auxiliary.slice(rawAddress, rawAddress);
846
- }
966
+ this.controlBus[flagsAddress] = flags | VIEW_LOCK;
847
967
 
848
- return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
968
+ try {
969
+ const rawAddress = meta.dataAddress >>> this.wordShift;
970
+ return callback(this.auxiliary.subarray(rawAddress, rawAddress + meta.occupied));
971
+ } finally {
972
+ this.controlBus[flagsAddress] &= ~VIEW_LOCK;
973
+ }
849
974
  }
850
975
 
851
976
  // ======== CAPACITY IN SLOTS ==========
@@ -853,8 +978,8 @@ export default class Balloc {
853
978
  /**
854
979
  * Returns the physical capacity of the block in bytes.
855
980
  *
856
- * Capacity corresponds to the space reserved for all slots in the block,
857
- * regardless of how many elements are currently occupied.
981
+ * Capacity corresponds to the space reserved for all slots in the
982
+ * block, regardless of how many elements are currently occupied.
858
983
  *
859
984
  * @param {number} handler - Block handle.
860
985
  * @returns {number} Physical capacity of the block, in bytes.
@@ -872,16 +997,16 @@ export default class Balloc {
872
997
  * @returns {number} Number of occupied elements.
873
998
  * @throws {Error} If the handle is invalid or corrupted.
874
999
  */
875
- occupied(handler){
1000
+ occupied(handler) {
876
1001
  const meta = this.extractMetadata(handler, this.metadata);
877
1002
  return meta.occupied;
878
1003
 
879
1004
  }
880
1005
 
881
1006
  /**
882
- * Returns the capacity of the block in number of elements.
1007
+ * Returns the block's capacity in number of elements.
883
1008
  *
884
- * The value corresponds to the total quantity of physically reserved slots,
1009
+ * The value corresponds to the total number of physically reserved slots,
885
1010
  * not the currently occupied quantity.
886
1011
  *
887
1012
  * @param {number} handler - Block handle.
@@ -893,72 +1018,93 @@ export default class Balloc {
893
1018
  return 1 << meta.capacityExponent >>> 0;
894
1019
  }
895
1020
 
896
- // ========== Inter-block Operations =============
897
-
898
1021
  /**
1022
+ * Checks if the memory block has reached its allocation capacity.
1023
+ *
1024
+ * A block is considered full when the number of occupied elements
1025
+ * equals its total allocated capacity, leaving no positions available
1026
+ * to store new elements.
1027
+ *
1028
+ * @param {number} handler - Block handle.
1029
+ * @returns {boolean} `true` if the block is full; otherwise, `false`.
1030
+ * @throws {Error} If the handle is invalid or corrupted.
1031
+ */
1032
+ isFull(handler) {
1033
+ const meta = this.extractMetadata(handler, this.metadata);
1034
+ return (1 << meta.capacityExponent >>> 0) - meta.occupied === 0;
1035
+ }
1036
+
1037
+ // ========== Operations between blocks=============
1038
+
1039
+ /**
899
1040
  * Copies occupied elements from one block to another.
900
1041
  *
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`.
1042
+ * Copying starts at the first element of `source` and the first slot of
1043
+ * `destination`. The quantity effectively copied is limited by the number of
1044
+ * occupied elements in the source, the physical capacity of the destination, and the
1045
+ * limit specified in `slots`.
905
1046
  *
906
- * Destination occupancy is increased, when necessary, to cover the copied
907
- * elements. Destination capacity is not changed.
1047
+ * Destination occupancy is increased, when necessary, to cover the
1048
+ * copied elements. Destination capacity is unchanged.
908
1049
  *
909
1050
  * The operation uses `Uint8Array.prototype.copyWithin()` on the `dataBus`,
910
1051
  * therefore the return value is the `Uint8Array` representing the data bus.
911
1052
  *
912
1053
  * @param {number} source - Source block handle.
913
- * @param {number} destiny - Destination block handle.
1054
+ * @param {number} destination - Destination block handle.
914
1055
  * @param {number} [slots=UNKNOWN] - Maximum number of elements to copy.
915
- * `UNKNOWN` represents the sentinel value used not to impose an additional limit.
1056
+ * `UNKNOWN` represents the sentinel value used not to impose an
1057
+ * additional limit.
916
1058
  * @returns {Uint8Array} The `dataBus` after the operation.
917
- * @throws {Error} If `source` or `destiny` is invalid or corrupted.
1059
+ * @throws {Error} If handles are invalid, corrupted,
1060
+ * or the destination block is borrowed via withView().
918
1061
  */
919
- copy(source, destiny, slots = UNKNOWN){
1062
+ copy(source, destination, slots = UNKNOWN) {
920
1063
  /** @type {Metadata} */
921
1064
  const metaA = {};
922
1065
  /** @type {Metadata} */
923
1066
  const metaB = {};
924
1067
 
925
1068
  this.extractMetadata(source, metaA);
926
- this.extractMetadata(destiny, metaB);
1069
+ this.extractMetadata(destination, metaB);
1070
+ this.assertNotBorrowed(metaB.headerAddress);
927
1071
 
928
1072
  const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
929
1073
  const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
930
1074
  const newOccupied = Math.max(metaB.occupied, slotsToCopy);
931
1075
 
932
1076
  this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
933
-
934
1077
  return this.dataBus.copyWithin(metaB.dataAddress, metaA.dataAddress, metaA.dataAddress + slotsToCopy * this.wordSize);
935
1078
  }
936
1079
 
937
1080
  /**
938
1081
  * Copies a region of elements within the same block.
939
1082
  *
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.
1083
+ * Indices are zero-based and follow the semantics of
1084
+ * `Array.prototype.copyWithin()`: `target` identifies the destination position,
1085
+ * `start` the starting source position, and `length` the maximum quantity of
1086
+ * elements to copy.
943
1087
  *
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`.
1088
+ * Negative indices are interpreted from the end of the block's capacity.
1089
+ * After this normalization, indices are clamped to physical capacity.
1090
+ * The copied quantity is also limited by effectively occupied elements
1091
+ * and available space starting from `target`.
947
1092
  *
948
1093
  * The operation supports overlapping regions and can increase block occupancy
949
- * when the target range exceeds current occupancy.
1094
+ * when the destination range exceeds previous occupancy.
950
1095
  *
951
1096
  * @param {number} handler - Block handle.
952
1097
  * @param {number} target - Initial destination index.
953
1098
  * @param {number} start - Initial source index.
954
1099
  * @param {number} length - Maximum number of elements to copy.
955
1100
  * @returns {Uint8Array} The `dataBus` after the operation.
956
- * @throws {Error} If the handle is invalid or corrupted.
1101
+ * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
957
1102
  */
958
1103
  copyWithin(handler, target, start, length) {
959
1104
  const meta = this.extractMetadata(handler, this.metadata);
960
- const slots = Math.floor(meta.byteCapacity / this.wordSize);
1105
+ this.assertNotBorrowed(meta.headerAddress);
961
1106
 
1107
+ const slots = Math.floor(meta.byteCapacity / this.wordSize);
962
1108
  target = Math.trunc(target);
963
1109
  start = Math.trunc(start);
964
1110
  length = Math.trunc(length);
@@ -966,12 +1112,9 @@ export default class Balloc {
966
1112
  if (target < 0) target += slots;
967
1113
  if (start < 0) start += slots;
968
1114
 
969
- // Clamps indices within capacity limits
970
1115
  target = Math.max(0, Math.min(target, slots));
971
1116
  start = Math.max(0, Math.min(start, slots));
972
1117
 
973
- // Limits copying to available space starting from target
974
- // and effectively occupied elements starting from start
975
1118
  const maxRead = Math.max(0, meta.occupied - start);
976
1119
  const maxWrite = slots - target;
977
1120
  length = Math.max(0, Math.min(length, maxRead, maxWrite));
@@ -980,9 +1123,8 @@ export default class Balloc {
980
1123
 
981
1124
  const targetAddress = meta.dataAddress + target * this.wordSize;
982
1125
  const sourceAddress = meta.dataAddress + start * this.wordSize;
983
-
984
- // Updates occupancy if the copy expands the block's occupied top
985
1126
  const newOccupied = Math.max(meta.occupied, target + length);
1127
+
986
1128
  this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
987
1129
 
988
1130
  return this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + length * this.wordSize);
@@ -992,16 +1134,18 @@ export default class Balloc {
992
1134
  * Appends occupied elements of `source` to the end of `target`.
993
1135
  *
994
1136
  * 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.
1137
+ * source and remaining free space in the destination's capacity.
996
1138
  *
997
1139
  * 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.
1140
+ * In this case, copying is performed over the block's own region and
1141
+ * preserves `copyWithin()` overlap semantics.
1000
1142
  *
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.
1143
+ * @param {number} target - Handle of the block that will receive elements.
1144
+ * @param {number} source - Handle of the block whose elements will be
1145
+ * appended.
1003
1146
  * @returns {number} Number of elements effectively appended.
1004
- * @throws {Error} If `target` or `source` is invalid or corrupted.
1147
+ * @throws {Error} If handles are invalid, corrupted,
1148
+ * or the destination block is borrowed via withView().
1005
1149
  */
1006
1150
  append(target, source) {
1007
1151
  const metaTarget = {};
@@ -1009,6 +1153,7 @@ export default class Balloc {
1009
1153
 
1010
1154
  this.extractMetadata(target, metaTarget);
1011
1155
  this.extractMetadata(source, metaSource);
1156
+ this.assertNotBorrowed(metaTarget.headerAddress);
1012
1157
 
1013
1158
  const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
1014
1159
  const count = Math.min(available, metaSource.occupied);
@@ -1018,11 +1163,7 @@ export default class Balloc {
1018
1163
  const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
1019
1164
  const sourceAddress = metaSource.dataAddress;
1020
1165
 
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
- }
1166
+ this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
1026
1167
 
1027
1168
  this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
1028
1169
 
@@ -1032,14 +1173,14 @@ export default class Balloc {
1032
1173
  /**
1033
1174
  * Creates an independent copy of a block.
1034
1175
  *
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.
1176
+ * The new block has the same physical capacity and occupancy as the
1177
+ * original block. All bytes in the reserved region, including currently
1178
+ * unoccupied positions, are copied.
1038
1179
  *
1039
- * The new block receives a new handle and remains subject to normal allocation
1040
- * and recycling rules.
1180
+ * The new block receives a new handle and remains subject to normal
1181
+ * allocation and recycling rules.
1041
1182
  *
1042
- * @param {number} handler - Handle of the block to clone.
1183
+ * @param {number} handler - Handle of the block to be cloned.
1043
1184
  * @returns {number} Handle of the new block.
1044
1185
  * @throws {Error} If the handle is invalid or corrupted.
1045
1186
  */
@@ -1059,28 +1200,33 @@ export default class Balloc {
1059
1200
  /**
1060
1201
  * Swaps the data regions associated with two blocks.
1061
1202
  *
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.
1203
+ * The operation swaps region addresses, capacities, and occupancies
1204
+ * between headers. Handles remain unchanged:
1205
+ * after the operation, each handle continues identifying its own
1206
+ * header, but that header now describes the region previously
1207
+ * belonging to the other block.
1066
1208
  *
1067
- * No data is copied in the `dataBus`; only the metadata of the two headers
1068
- * is modified.
1209
+ * No data is copied in the `dataBus`; only the metadata of the two
1210
+ * headers is modified.
1069
1211
  *
1070
1212
  * @param {number} source - Handle of the first block.
1071
1213
  * @param {number} target - Handle of the second block.
1072
1214
  * @returns {void}
1073
- * @throws {Error} If `source` or `target` is invalid or corrupted.
1215
+ * @throws {Error} If handles are invalid, corrupted,
1216
+ * or either block is borrowed via withView().
1074
1217
  */
1075
1218
  swap(source, target) {
1076
1219
  /** @type {Metadata} */
1077
1220
  const metaA = {};
1078
1221
  /** @type {Metadata} */
1079
1222
  const metaB = {};
1080
-
1223
+
1081
1224
  this.extractMetadata(source, metaA);
1082
1225
  this.extractMetadata(target, metaB);
1083
1226
 
1227
+ this.assertNotBorrowed(metaA.headerAddress);
1228
+ this.assertNotBorrowed(metaB.headerAddress);
1229
+
1084
1230
  this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
1085
1231
  this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
1086
1232
 
@@ -1089,7 +1235,7 @@ export default class Balloc {
1089
1235
 
1090
1236
  this.controlAdapter.setUint32(metaA.headerAddress + OCCUPIED_OFFSET, metaB.occupied, IS_LITTLE_ENDIAN);
1091
1237
  this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, metaA.occupied, IS_LITTLE_ENDIAN);
1092
- }
1238
+ }
1093
1239
 
1094
1240
 
1095
1241
  // ============= SERIALIZATION ==============
@@ -1097,11 +1243,11 @@ export default class Balloc {
1097
1243
  /**
1098
1244
  * Serializes the content and metadata of a memory block.
1099
1245
  *
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.
1246
+ * The method extracts occupied block data via `pick()`,
1247
+ * groups it alongside capacity and word type information
1248
+ * into a data envelope, and encodes it using the CBOR format.
1103
1249
  *
1104
- * @param {number} handler - Handle of the block to serialize.
1250
+ * @param {number} handler - Handle of the block to be serialized.
1105
1251
  * @returns {Uint8Array} A buffer containing the serialized block data.
1106
1252
  * @throws {Error} If the handle is invalid or corrupted.
1107
1253
  */
@@ -1134,13 +1280,13 @@ export default class Balloc {
1134
1280
  * Restores a memory block from serialized data.
1135
1281
  *
1136
1282
  * 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.
1283
+ * data is compatible with the current allocator instance, and allocates
1284
+ * a new block with the capacity required to accommodate the content.
1285
+ * Then, original data and occupancy are restored in the new block.
1140
1286
  *
1141
1287
  * @param {Uint8Array|ArrayBuffer} serialized - Buffer containing serialized data.
1142
1288
  * @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.
1289
+ * @throws {Error} If the decoded data's word type differs from the allocator's configuration.
1144
1290
  */
1145
1291
  load(serialized) {
1146
1292
  if (!(serialized instanceof ArrayBuffer) && !(serialized instanceof Uint8Array)) {
@@ -1195,22 +1341,56 @@ export default class Balloc {
1195
1341
 
1196
1342
  // ============= UTILITIES ==============
1197
1343
 
1344
+ /**
1345
+ * Prevents modification operations on a borrowed block.
1346
+ *
1347
+ * Checks the VIEW_LOCK flag in the header associated with the provided address.
1348
+ *
1349
+ * @param {number} headerAddress - Address of the header in controlBus.
1350
+ * @returns {void}
1351
+ * @throws {Error} If the block is borrowed via withView().
1352
+ * @private
1353
+ */
1354
+ assertNotBorrowed(headerAddress) {
1355
+ if (this.controlBus[headerAddress + FLAGS_OFFSET] & VIEW_LOCK) {
1356
+ throw new Error("Block is borrowed");
1357
+ }
1358
+ }
1359
+
1360
+ /**
1361
+ * Prevents operations that replace or remap the dataBus
1362
+ * while any segment is borrowed.
1363
+ *
1364
+ * @returns {void}
1365
+ * @throws {Error} If any block is borrowed via withView().
1366
+ * @private
1367
+ */
1368
+ assertNoActiveViews() {
1369
+ for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
1370
+ if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
1371
+ if (this.controlBus[i + FLAGS_OFFSET] & VIEW_LOCK) {
1372
+ throw new Error("Cannot remap memory while a block is borrowed");
1373
+ }
1374
+ }
1375
+ }
1376
+
1198
1377
  /**
1199
1378
  * [INTERNAL USE]
1200
- * Decodes the metadata associated with a handle.
1379
+ * Decodes metadata associated with a handle.
1201
1380
  *
1202
1381
  * The handle is split into generation and header address. The cookie stored
1203
1382
  * in the header is then recalculated to validate the combination; only after
1204
- * this validation is metadata read.
1383
+ * this validation are metadata read.
1205
1384
  *
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.
1385
+ * Decoded fields are written to the `out` object, which is returned
1386
+ * by the function itself. The object can be reused between calls to avoid
1387
+ * new allocations.
1208
1388
  *
1209
- * @param {number} handler - Handle to decode and validate.
1210
- * @param {Metadata} out - Object that will receive the decoded metadata.
1389
+ * @param {number} handler - Handle to be decoded and validated.
1390
+ * @param {Metadata} out - Object that will receive decoded metadata.
1211
1391
  * @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.
1392
+ * @throws {Error} If the header cookie does not match the handle or
1393
+ * if the handle does not identify a valid header.
1214
1394
  * @private
1215
1395
  */
1216
1396
  extractMetadata(handler, out) {
@@ -1225,7 +1405,7 @@ export default class Balloc {
1225
1405
  }
1226
1406
 
1227
1407
  out.dataAddress = this.controlAdapter.getUint32(out.headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
1228
- out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1408
+ out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1229
1409
  out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
1230
1410
  out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
1231
1411
 
@@ -1234,20 +1414,22 @@ export default class Balloc {
1234
1414
 
1235
1415
  /**
1236
1416
  * [INTERNAL USE]
1237
- * Calculates the validation cookie of a header.
1417
+ * Calculates a header's validation cookie.
1238
1418
  *
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.
1419
+ * The cookie is derived from the header address and the 11 generation bits via
1420
+ * fast hash.
1421
+ * The result is reduced to 8 bits.
1241
1422
  *
1242
- * The value zero is reserved as an invalid header indicator; therefore, when
1243
- * the calculation yields zero, the method returns `1`.
1423
+ * The value zero is reserved as an invalid header indicator; therefore,
1424
+ * when the calculation produces zero, the method returns `1`.
1244
1425
  *
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.
1426
+ * The cookie does not constitute a cryptographic mechanism. Its purpose is
1427
+ * to detect invalid, stale, or corrupted handles within the allocator's
1428
+ * memory management model.
1247
1429
  *
1248
1430
  * @param {number} addr - Header address.
1249
- * @param {number} gen - Generation associated with the handle. Only the 11 least
1250
- * significant bits are considered.
1431
+ * @param {number} gen - Generation associated with the handle. Only the 11
1432
+ * least significant bits are considered.
1251
1433
  * @returns {number} 8-bit cookie in the range [1, 255].
1252
1434
  * @private
1253
1435
  */
@@ -1258,11 +1440,11 @@ export default class Balloc {
1258
1440
  /**
1259
1441
  * Returns the number of regions currently stored in the recycling list.
1260
1442
  *
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.
1443
+ * Each region corresponds to a freed block that could not be returned
1444
+ * directly to the top of the `dataBus` and, therefore, remains available for
1445
+ * reuse by a future allocation of identical capacity.
1264
1446
  *
1265
- * @returns {number} Number of free regions maintained in `recycle`.
1447
+ * @returns {number} Number of free regions kept in `recycle`.
1266
1448
  */
1267
1449
  recycleCount() {
1268
1450
  let count = 0;
@@ -1275,9 +1457,10 @@ export default class Balloc {
1275
1457
  }
1276
1458
 
1277
1459
  /**
1278
- * Returns the total bytes belonging to regions currently stored in the recycling list.
1460
+ * Returns the total bytes belonging to regions currently stored in the
1461
+ * recycling list.
1279
1462
  *
1280
- * The value is calculated by summing the capacity of each free region multiplied
1463
+ * The value is calculated by summing each free region's capacity multiplied
1281
1464
  * by the number of regions registered for that capacity.
1282
1465
  *
1283
1466
  * @returns {number} Number of bytes occupied by recyclable regions.
@@ -1293,25 +1476,26 @@ export default class Balloc {
1293
1476
  }
1294
1477
 
1295
1478
  /**
1296
- * Returns the amount of allocated bytes that do not belong to currently recyclable regions.
1479
+ * Returns the quantity of allocated bytes that do not belong to currently
1480
+ * recyclable regions.
1297
1481
  *
1298
- * The value is obtained by subtracting the bytes belonging to free regions maintained
1299
- * in `recycle` from the total advance of `dataPointer`.
1482
+ * The value is obtained by subtracting the bytes belonging to free regions
1483
+ * kept in `recycle` from the total advance of `dataPointer`.
1300
1484
  *
1301
- * @returns {number} Number of bytes associated with non-recyclable regions within
1302
- * the area already used by the `dataBus`.
1485
+ * @returns {number} Number of bytes associated with non-recyclable regions
1486
+ * within the area already used by `dataBus`.
1303
1487
  */
1304
1488
  get allocatedBytes() {
1305
1489
  return this.dataPointer - this.recycleBytes;
1306
1490
  }
1307
1491
 
1308
1492
  /**
1309
- * Returns the amount of bytes not yet used at the top of the `dataBus`.
1493
+ * Returns the quantity of bytes not yet used at the top of the `dataBus`.
1310
1494
  *
1311
1495
  * This space corresponds to the region between `dataPointer` and the end of the
1312
1496
  * capacity currently reserved for the buffer.
1313
1497
  *
1314
- * @returns {number} Number of available bytes after `dataPointer`.
1498
+ * @returns {number} Number of bytes available after `dataPointer`.
1315
1499
  */
1316
1500
  get unallocatedBytes() {
1317
1501
  return this.size - this.dataPointer;
@@ -1320,13 +1504,13 @@ export default class Balloc {
1320
1504
  /**
1321
1505
  * Returns the ratio between recyclable memory and the used heap area.
1322
1506
  *
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.
1507
+ * The metric considers free regions kept in `recycle` as fragmentation
1508
+ * and uses `dataPointer` as the denominator. When no bytes have been used
1509
+ * by the heap, the result is zero.
1326
1510
  *
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.
1511
+ * The value does not represent the fraction of the entire `dataBus` capacity, but
1512
+ * specifically the proportion of recyclable bytes within the area already traversed
1513
+ * by the bump pointer.
1330
1514
  *
1331
1515
  * @returns {number} Fragmentation ratio in the range [0, 1] under normal
1332
1516
  * operating conditions.