balloc 1.4.0 → 2.0.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.MD +157 -334
  3. package/docs/API /342/200/224 balloc.en.md" +478 -1217
  4. package/docs/MIGRATION /342/200/224 balloc.en.md" +208 -0
  5. package/package.json +2 -44
  6. package/src/README.MD +0 -0
  7. package/src/en/balloc.cjs +510 -960
  8. package/src/en/balloc.js +1 -1
  9. package/src/en/balloc.mjs +551 -1099
  10. package/types/README.MD +0 -0
  11. package/types/en/balloc.d.mts +275 -583
  12. package/README.ar.md +0 -439
  13. package/README.en.md +0 -467
  14. package/README.es.md +0 -439
  15. package/README.jp.md +0 -438
  16. package/README.pt.md +0 -462
  17. package/README.zh.md +0 -438
  18. package/docs/API /342/200/224 balloc.ar.md" +0 -1509
  19. package/docs/API /342/200/224 balloc.es.md" +0 -1325
  20. package/docs/API /342/200/224 balloc.jp.md" +0 -1264
  21. package/docs/API /342/200/224 balloc.pt.md" +0 -1395
  22. package/docs/API /342/200/224 balloc.zh.md" +0 -1324
  23. package/src/ar/balloc.cjs +0 -1303
  24. package/src/ar/balloc.js +0 -2
  25. package/src/ar/balloc.mjs +0 -1591
  26. package/src/es/balloc.cjs +0 -1320
  27. package/src/es/balloc.js +0 -2
  28. package/src/es/balloc.mjs +0 -1608
  29. package/src/jp/balloc.cjs +0 -1260
  30. package/src/jp/balloc.js +0 -2
  31. package/src/jp/balloc.mjs +0 -1548
  32. package/src/pt/balloc.cjs +0 -1326
  33. package/src/pt/balloc.js +0 -2
  34. package/src/pt/balloc.mjs +0 -1619
  35. package/src/zh/balloc.cjs +0 -1205
  36. package/src/zh/balloc.js +0 -2
  37. package/src/zh/balloc.mjs +0 -1493
  38. package/types/ar/balloc.d.mts +0 -793
  39. package/types/es/balloc.d.mts +0 -810
  40. package/types/jp/balloc.d.mts +0 -750
  41. package/types/pt/balloc.d.mts +0 -818
  42. package/types/zh/balloc.d.mts +0 -695
package/src/en/balloc.cjs CHANGED
@@ -37,740 +37,478 @@ var BUCKET_MAPPING = Object.freeze({
37
37
  "32f": { type: "Float32", bits: 32 },
38
38
  "64f": { type: "Float64", bits: 64 }
39
39
  });
40
- var IS_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
41
- var HEADER_SIZE = 16 >>> 0;
42
- var ADDRESS_OFFSET = 0 >>> 0;
43
- var OCCUPIED_OFFSET = 4 >>> 0;
44
- var CAPACITY_OFFSET = 8 >>> 0;
45
- var COOKIE_OFFSET = 9 >>> 0;
46
- var FLAGS_OFFSET = 10 >>> 0;
47
- var VIEW_LOCK = 1 >>> 0;
48
- var ROTATE_32BITS = 4294967296;
49
- var CLAMP_11BITS = 2047 >>> 0;
50
40
  var isTypedArray = (val) => ArrayBuffer.isView(val) && !(val instanceof DataView);
51
41
  var Balloc = class {
52
42
  /**
53
- * Creates an instance of the `Balloc` memory allocator.
43
+ * Creates an allocator instance.
54
44
  *
55
- * The allocator maintains two independent buffers:
56
- * - `dataBus`: stores the data of allocated blocks;
57
- * - `controlBus`: stores headers and other control metadata.
45
+ * Initializes the limit used to validate allocation requests,
46
+ * the optional default bucket type, and the structures that associate
47
+ * handles with blocks. Each block receives its own ArrayBuffer
48
+ * when alloc() is called.
58
49
  *
59
- * Each block has a fixed-size header (`HEADER_SIZE`) and is
60
- * identified externally by a 43-bit logical handle, composed
61
- * of an 11-bit generation and its 32-bit header address.
62
- *
63
- * The capacity of each block is rounded up to the next power of
64
- * two in elements, respecting the width of the configured bucket.
65
- *
66
- * @param {number} [size=65535] - Initial capacity of the `dataBus`, in bytes.
67
- * Must be a safe integer in the range [2, 0x80000000].
68
- * @param {BucketType} [bucketSize="32u"] - Identifier for the bucket type and size
69
- * (e.g., '32u' for Uint32, '64f' for Float64, '8i' for Int8).
70
- * @param {number} [metadataSize=1024] - Initial capacity of the `controlBus`,
71
- * in bytes. Must be a safe integer in the range
72
- * [HEADER_SIZE, 0x80000000].
73
- *
74
- * @throws {RangeError} If `size` is outside the allowed range.
75
- * @throws {RangeError} If `bucketSize` is not a valid bucket identifier.
76
- * @throws {RangeError} If `metadataSize` is outside the allowed range.
50
+ * @param {number|null} [size=0x80000000] Limit used to validate
51
+ * the size requested by alloc(). Must be a safe integer
52
+ * between 2 and 0x80000000.
53
+ * @param {BucketType|null} [bucketSize=null] Default bucket type.
54
+ * When set, it takes precedence over bucketType in alloc().
55
+ * @throws {RangeError} If size or bucketSize is invalid.
77
56
  */
78
- constructor(size = 65535, bucketSize = "32u", metadataSize = 1024) {
57
+ constructor(size = null, bucketSize = null) {
58
+ size = size ?? 2147483648;
79
59
  if (!Number.isSafeInteger(size) || size < 2 || size > 2147483648) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
80
- if (!BUCKET_MAPPING[bucketSize]) {
60
+ if (bucketSize !== null && !BUCKET_MAPPING[bucketSize]) {
81
61
  throw new RangeError(`bucketSize must be in ([ 8 || 16 || 32 || 64][ u || i ]) || ([ 16 || 32 || 64][ f ]) but I found ${bucketSize}`);
82
62
  }
83
- if (!Number.isSafeInteger(metadataSize) || metadataSize < HEADER_SIZE || metadataSize > 2147483648) throw new RangeError(`Parameter metadataSize must be in range [HEADER_SIZE, 0x80000000] but metadataSize is ${metadataSize}`);
84
- this.wordType = bucketSize;
85
- this.bucketType = BUCKET_MAPPING[bucketSize].type;
86
- this.bucketSize = BUCKET_MAPPING[bucketSize].bits >>> 0;
87
- this.bucketArray = globalThis[`${this.bucketType}Array`];
88
- this.wordSize = this.bucketSize >>> 3;
89
- this.wordShift = this.bucketSize >>> 4;
90
- this.size = Math.max(1 << 32 - Math.clz32(size - 1) >>> 0, this.wordSize);
91
- this.headerSize = 1 << 32 - Math.clz32(metadataSize - 1) >>> 0;
92
- this.dataPointer = 0 >>> 0;
93
- this.controlPointer = 0 >>> 0;
94
- this.echoPointer = 0 >>> 0;
95
- this.generation = 0 >>> 0;
96
- this.dataBus = new Uint8Array(this.size);
97
- this.controlBus = new Uint8Array(this.headerSize);
98
- this.dataAdapter = new DataView(this.dataBus.buffer);
99
- this.controlAdapter = new DataView(this.controlBus.buffer);
100
- this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
101
- this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
102
- this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
103
- this.recycle = /* @__PURE__ */ new Map();
104
- this.metadata = {
105
- generation: 0 >>> 0,
106
- headerAddress: 0 >>> 0,
107
- dataAddress: 0 >>> 0,
108
- capacityExponent: 0 >>> 0,
109
- byteCapacity: 0 >>> 0,
110
- occupied: 0 >>> 0
111
- };
63
+ this.maxByteSize = size;
64
+ this.bucketSize = bucketSize;
65
+ this.bus = /* @__PURE__ */ Object.create(null);
66
+ this.lastHandler = 0;
112
67
  }
113
- // ========== ALLOCATION ==========
114
68
  /**
115
- * Allocates a new memory block.
116
- *
117
- * The requested capacity is converted to the smallest power of two that
118
- * can accommodate `size` elements. The block is obtained preferentially from the list
119
- * of recyclable regions with the corresponding capacity; if a compatible
120
- * region does not exist, the block is reserved at the top of the `dataBus`.
69
+ * Allocates a memory block and returns its handle.
121
70
  *
122
- * Next, a header is obtained from the control space. Previously freed headers
123
- * can be reused via the internal recycling stack;
124
- * otherwise, the `controlBus` is expanded when necessary.
71
+ * size specifies the ArrayBuffer size in bytes. The typed view is
72
+ * selected by bucketType and contains the number of elements
73
+ * that fit this buffer size. If the instance has
74
+ * bucketSize set, it takes precedence over bucketType.
125
75
  *
126
- * The header receives the address, capacity, initial occupancy (zero), and
127
- * a validation cookie. The returned value encodes the allocation generation
128
- * and the header address:
76
+ * Each allocation receives a monotonic handle that is never reused. The identifier
77
+ * space is limited to 32 unsigned bits.
129
78
  *
130
- * [11 generation bits][32 header address bits]
131
- *
132
- * @param {number} [size=16] - Minimum number of elements the block must
133
- * accommodate. Must be a safe integer in the range [2, 0x80000000].
134
- * @returns {number} Handle identifying the allocated block.
135
- * @throws {RangeError} If `size` is outside the allowed range.
136
- * @throws {Error} If it is necessary to expand the `dataBus` while any
137
- * block is borrowed via withView().
79
+ * @param {number} [size=16] ArrayBuffer size in bytes. Must be
80
+ * a safe integer greater than or equal to 2 and less than maxByteSize.
81
+ * @param {BucketType} [bucketType="32u"] Typed view type.
82
+ * @returns {number} Handle of the allocated block.
83
+ * @throws {RangeError} If the bucket type or size is invalid.
138
84
  */
139
- alloc(size = 16) {
140
- if (!Number.isSafeInteger(size) || size < 2 || size > 2147483648) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
141
- const capacity = 32 - Math.clz32(size - 1);
142
- const blockSize = (1 << capacity >>> 0) * this.wordSize;
143
- let dataAddress = this.recyclePop(blockSize);
144
- if (dataAddress === UNKNOWN) {
145
- while (this.dataPointer + blockSize > this.size) this.grow();
146
- dataAddress = this.dataPointer;
147
- this.dataPointer += blockSize;
148
- }
149
- let headerAddress = 0 >>> 0;
150
- if (this.echoPointer > this.controlPointer) {
151
- this.echoPointer -= 4;
152
- headerAddress = this.controlAdapter.getUint32(this.echoPointer, IS_LITTLE_ENDIAN);
153
- } else {
154
- if (this.controlPointer + HEADER_SIZE > this.controlAdapter.byteLength) this.headerGrow();
155
- headerAddress = this.controlPointer;
156
- this.controlPointer += HEADER_SIZE;
157
- this.echoPointer += HEADER_SIZE;
85
+ alloc(size = 16, bucketType = "32u") {
86
+ bucketType = this.bucketSize ?? bucketType;
87
+ if (!BUCKET_MAPPING[bucketType]) {
88
+ throw new RangeError(`bucketSize must be in ([ 8 || 16 || 32 || 64][ u || i ]) || ([ 16 || 32 || 64][ f ]) but I found ${bucketType}`);
158
89
  }
159
- this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, dataAddress, IS_LITTLE_ENDIAN);
160
- this.controlAdapter.setUint32(headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
161
- this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, capacity);
162
- this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, this.bakeCookie(headerAddress, ++this.generation));
163
- this.controlBus[headerAddress + FLAGS_OFFSET] = 0;
164
- return (this.generation & CLAMP_11BITS) * ROTATE_32BITS + headerAddress;
90
+ if (!Number.isSafeInteger(size) || size < 2 || size >= this.maxByteSize || size % (BUCKET_MAPPING[bucketType].bits / 8) !== 0) throw new RangeError(`Parameter size must be an aligned integer in range [2, ${this.maxByteSize}) for ${bucketType}`);
91
+ if (this.lastHandler >= 4294967295) throw new RangeError("Handler space exhausted");
92
+ const newHandler = ++this.lastHandler;
93
+ const dataBuffer = new ArrayBuffer(size);
94
+ const dataBus = new globalThis[`${BUCKET_MAPPING[bucketType].type}Array`](dataBuffer);
95
+ const newPack = this.bus[newHandler] = /* @__PURE__ */ Object.create(null);
96
+ newPack.bucketType = bucketType;
97
+ newPack.dataBuffer = dataBuffer;
98
+ newPack.dataBus = dataBus;
99
+ newPack.occupied = 0;
100
+ newPack.borrowed = 0;
101
+ return newHandler;
165
102
  }
166
103
  /**
167
- * Expands a block's capacity to the next power of two.
168
- *
169
- * When the block is located at the current top of the `dataBus`, expansion
170
- * occurs in-place: only its capacity and `dataPointer` are
171
- * updated.
104
+ * Replaces a block's storage with a buffer of greater capacity.
172
105
  *
173
- * If another region exists after the block, a new region with double the
174
- * capacity is obtained from the recyclable space or allocated at the top of the `dataBus`.
175
- * The currently occupied elements are then copied to the new region,
176
- * and the previous region is returned to the recycling list.
106
+ * newSize is expressed in elements. If omitted or null, the capacity
107
+ * doubles; the result is capped by maxByteSize converted to
108
+ * elements according to BYTES_PER_ELEMENT. The occupied elements are
109
+ * copied to the new buffer.
177
110
  *
178
- * The handle remains valid because its header is preserved and only the
179
- * address and capacity recorded in it are updated.
180
- *
181
- * @param {number} handler - Handle of the block to be expanded.
111
+ * @param {number} handler Block handle.
112
+ * @param {number|null} [newSize=null] New capacity in elements.
182
113
  * @returns {void}
183
- * @throws {Error} If the handle is invalid, corrupted, or the block
184
- * is borrowed via withView(). Also occurs if expansion requires
185
- * dataBus remapping while another block is borrowed.
186
- * @throws {AggregateError} If the capacity has reached the maximum
187
- * supported limit.
188
- */
189
- realloc(handler) {
190
- const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
191
- const headerAddress = handler >>> 0;
192
- const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
193
- const occupied = this.controlAdapter.getUint32(headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
194
- const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
195
- const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
196
- const borrowed = this.controlAdapter.getUint8(headerAddress + FLAGS_OFFSET) & VIEW_LOCK;
197
- if (cookie !== this.bakeCookie(headerAddress, generation)) {
198
- throw new Error("Invalid or corrupted handle");
199
- }
200
- if (borrowed) {
201
- throw new Error("Block is borrowed");
202
- }
203
- if (capacity >= 31) throw new AggregateError([new Error("Can\xB4t reallocate handler."), new RangeError("Capacity has reached its limit.")], "Internal Error.");
204
- const newCapacity = capacity + 1;
205
- const newBlockSize = (1 << newCapacity >>> 0) * this.wordSize;
206
- const oldBlockSize = (1 << capacity >>> 0) * this.wordSize;
207
- if (dataAddress + oldBlockSize === this.dataPointer) {
208
- while (dataAddress + newBlockSize > this.size) this.grow();
209
- this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
210
- this.dataPointer = dataAddress + newBlockSize;
211
- return;
212
- }
213
- let newAddress = this.recyclePop(newBlockSize);
214
- if (newAddress === UNKNOWN) {
215
- while (this.dataPointer + newBlockSize > this.size) this.grow();
216
- newAddress = this.dataPointer;
217
- this.dataPointer += newBlockSize;
218
- }
219
- this.dataBus.copyWithin(newAddress, dataAddress, dataAddress + occupied * this.wordSize);
220
- this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, newAddress, IS_LITTLE_ENDIAN);
221
- this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
222
- this.recyclePush(oldBlockSize, dataAddress);
223
- }
224
- /**
225
- * Reduces a block to the smallest power-of-two capacity that can contain
226
- * its occupied elements, while preserving its address and handler.
227
- *
228
- * If the block is at the top of the dataBus, dataPointer is moved backward.
229
- * Otherwise, the released tail is split into power-of-two regions and each
230
- * region is returned to the recycling list.
231
- *
232
- * @param {number} handler - Handler of the block to shrink.
114
+ * @throws {Error} If the handle does not exist or the block is borrowed.
115
+ * @throws {RangeError} If the new capacity is not a safe integer
116
+ * greater than the current capacity.
117
+ */
118
+ realloc(handler, newSize = null) {
119
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
120
+ const pack = this.bus[handler];
121
+ if (pack.borrowed) throw new Error("Block is borrowed");
122
+ const oldCapacity = pack.dataBus.length;
123
+ if (newSize !== null && (!Number.isSafeInteger(newSize) || newSize <= oldCapacity)) throw new RangeError("Invalid reallocation size");
124
+ const maxCapacity = Math.floor((this.maxByteSize - 1) / pack.dataBus.BYTES_PER_ELEMENT);
125
+ const newCapacity = Math.min(newSize ?? oldCapacity * 2, maxCapacity);
126
+ if (newCapacity <= oldCapacity) throw new RangeError("Invalid reallocation size");
127
+ const newBuffer = new ArrayBuffer(newCapacity * pack.dataBus.BYTES_PER_ELEMENT);
128
+ const newDataBus = new globalThis[`${BUCKET_MAPPING[pack.bucketType].type}Array`](newBuffer);
129
+ newDataBus.set(pack.dataBus.subarray(0, pack.occupied));
130
+ pack.dataBuffer = newBuffer;
131
+ pack.dataBus = newDataBus;
132
+ }
133
+ /**
134
+ * Reduces the block capacity to an amount calculated from
135
+ * its occupancy.
136
+ *
137
+ * The new capacity is the smallest power of two that can hold the occupied
138
+ * elements, with a minimum of two elements. The method creates a new ArrayBuffer
139
+ * and copies the occupied elements. If the calculated capacity is not smaller
140
+ * than the current capacity, a RangeError is thrown. No region recycling or
141
+ * heap compaction is performed.
142
+ *
143
+ * @param {number} handler Block handle.
233
144
  * @returns {void}
234
- * @throws {Error} If the handler is invalid, corrupted, or borrowed by withView().
145
+ * @throws {Error} If the handle does not exist or the block is borrowed.
146
+ * @throws {RangeError} If the calculated capacity is not smaller than the current capacity.
235
147
  */
236
148
  shrink(handler) {
237
- const meta = this.extractMetadata(handler, this.metadata);
238
- if (meta.borrowed) throw new Error("Block is borrowed");
239
- const newCapacity = Math.max(1, 32 - Math.clz32(Math.max(2, meta.occupied) - 1));
240
- if (newCapacity >= meta.capacityExponent) return;
241
- const oldBlockSize = meta.byteCapacity;
242
- const newBlockSize = 2 ** newCapacity * this.wordSize;
243
- const oldEnd = meta.dataAddress + oldBlockSize;
244
- this.controlAdapter.setUint8(meta.headerAddress + CAPACITY_OFFSET, newCapacity);
245
- if (oldEnd === this.dataPointer) {
246
- this.dataPointer = meta.dataAddress + newBlockSize;
247
- return;
248
- }
249
- let address = meta.dataAddress + newBlockSize;
250
- for (let exponent = newCapacity; exponent < meta.capacityExponent; exponent++) {
251
- const segmentSize = 2 ** exponent * this.wordSize;
252
- this.recyclePush(segmentSize, address);
253
- address += segmentSize;
254
- }
255
- }
256
- /**
257
- * Frees a memory block.
258
- *
259
- * The block's header is invalidated by zeroing its cookie, and its
260
- * address is registered for later reuse. The data region
261
- * is also returned to the recycling system, except when the block is
262
- * exactly at the top of the `dataBus`; in that case, the `dataPointer` is simply
263
- * rolled back, eliminating the region without creating an entry in the recycling
264
- * list.
265
- *
266
- * @param {number} handler - Handle of the block to be freed.
267
- * @returns {void}
268
- * @throws {Error} If the handle is invalid, corrupted, or the block
269
- * is borrowed via withView().
270
- */
149
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
150
+ const pack = this.bus[handler];
151
+ if (pack.borrowed) throw new Error("Block is borrowed");
152
+ const oldCapacity = pack.dataBus.length;
153
+ const newCapacity = 2 ** Math.ceil(Math.log2(Math.max(2, pack.occupied)));
154
+ if (newCapacity >= oldCapacity) return;
155
+ if (!Number.isSafeInteger(newCapacity)) throw new RangeError("Invalid reallocation size");
156
+ const newBuffer = new ArrayBuffer(newCapacity * pack.dataBus.BYTES_PER_ELEMENT);
157
+ const newDataBus = new globalThis[`${BUCKET_MAPPING[pack.bucketType].type}Array`](newBuffer);
158
+ newDataBus.set(pack.dataBus.subarray(0, pack.occupied));
159
+ pack.dataBuffer = newBuffer;
160
+ pack.dataBus = newDataBus;
161
+ }
162
+ /**
163
+ * Frees a block and permanently invalidates its handle.
164
+ *
165
+ * Removes the entry from bus. Handles are not reused. There is no
166
+ * coalescing or recycling of regions in a shared heap.
167
+ *
168
+ * @param {number} handler Handle of the block to free.
169
+ * @returns {void}
170
+ * @throws {Error} If the handle does not exist or the block is borrowed.
171
+ */
271
172
  free(handler) {
272
- const generation = handler / ROTATE_32BITS & CLAMP_11BITS;
273
- const headerAddress = handler >>> 0;
274
- const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
275
- const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
276
- const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
277
- const borrowed = this.controlAdapter.getUint8(headerAddress + FLAGS_OFFSET) & VIEW_LOCK;
278
- if (cookie !== this.bakeCookie(headerAddress, generation)) {
279
- throw new Error("Invalid or corrupted handle");
280
- }
281
- if (borrowed) {
282
- throw new Error("Block is borrowed");
283
- }
284
- const blockSize = (1 << capacity >>> 0) * this.wordSize;
285
- this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
286
- if (this.echoPointer + 4 <= this.controlBus.byteLength) {
287
- this.controlAdapter.setUint32(this.echoPointer, headerAddress, IS_LITTLE_ENDIAN);
288
- this.echoPointer += 4;
289
- }
290
- if (dataAddress + blockSize === this.dataPointer) {
291
- this.dataPointer = dataAddress;
292
- } else {
293
- this.recyclePush(blockSize, dataAddress);
294
- }
173
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
174
+ const pack = this.bus[handler];
175
+ if (pack.borrowed) throw new Error("Block is borrowed");
176
+ delete this.bus[handler];
295
177
  }
296
178
  // ========== RECYCLING ==========
297
- /**
298
- * [INTERNAL USE]
299
- * Inserts a free region into the recycling list.
300
- *
301
- * The list is organized by capacity in bytes. For each capacity, the
302
- * stored value is a `Uint32Array` whose zero position contains the quantity
303
- * of registered addresses and subsequent positions contain the addresses of
304
- * the free regions:
305
- *
306
- * [count, address1, address2, ...]
307
- *
308
- * When the page becomes full, its buffer is expanded to double its current
309
- * capacity.
310
- *
311
- * @param {number} capacity - Capacity of the free region, in bytes.
312
- * @param {number} address - Initial address of the region in the `dataBus`.
313
- * @returns {void}
314
- * @private
315
- */
316
- recyclePush(capacity, address) {
317
- if (this.recycle.has(capacity)) {
318
- let page = this.recycle.get(capacity);
319
- const count = page[0];
320
- if (count === page.length - 1) {
321
- const newBuffer = page.buffer.transfer(page.buffer.byteLength * 2);
322
- page = new Uint32Array(newBuffer);
323
- this.recycle.set(capacity, page);
324
- }
325
- page[count + 1] = address;
326
- page[0] = count + 1;
327
- } else {
328
- this.recycle.set(capacity, new Uint32Array([1, address]));
329
- }
330
- }
331
- /**
332
- * [INTERNAL USE]
333
- * Removes a free region from the recycling list.
334
- *
335
- * The search is performed by the exact requested capacity. When a corresponding
336
- * page exists, the last registered address is removed from the page and returned,
337
- * implementing recycling as a LIFO stack.
338
- *
339
- * @param {number} capacity - Desired capacity, in bytes.
340
- * @returns {number} Initial address of a recyclable region or `UNKNOWN`
341
- * when a region with the requested capacity does not exist.
342
- * @private
343
- */
344
- recyclePop(capacity) {
345
- if (!this.recycle.has(capacity)) return UNKNOWN;
346
- const page = this.recycle.get(capacity);
347
- const count = page[0];
348
- if (count === 0) return UNKNOWN;
349
- const address = page[count];
350
- page[0] = count - 1;
351
- return address;
352
- }
353
179
  // ========== GARBAGE COLLECTION ==========
354
- /**
355
- * Compacts the `dataBus` using the ReBump algorithm.
356
- *
357
- * Sequentially traverses the headers registered in the `controlBus` and copies
358
- * still-valid regions to a new `dataBus`, eliminating free spaces
359
- * between them. Each surviving block's address is updated in its
360
- * respective header.
361
- *
362
- * The order of blocks in the `controlBus` is preserved. The internal data of
363
- * each block is also fully preserved, including its reserved capacity
364
- * and current occupancy.
365
- *
366
- * Upon completion of compaction:
367
- * - all recyclable regions are eliminated;
368
- * - `dataPointer` points to the first byte after the last live block;
369
- * - the `dataBus` represents a contiguous heap for active blocks.
370
- *
371
- * Control complexity is O(n), where `n` is the number of traversed
372
- * headers. The effective memory movement cost also depends on the volume
373
- * of bytes belonging to live blocks.
374
- *
375
- * @returns {void}
376
- * @throws {Error} If any block is borrowed via withView().
377
- */
378
- gc() {
379
- this.assertNoActiveViews();
380
- const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
381
- this.recycle.clear();
382
- this.dataPointer = 0 >>> 0;
383
- for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
384
- if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
385
- const start = this.controlAdapter.getUint32(i + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
386
- const size = (1 << this.controlBus[i + CAPACITY_OFFSET] >>> 0) * this.wordSize;
387
- const end = start + size;
388
- newDataBus.set(this.dataBus.subarray(start, end), this.dataPointer);
389
- this.controlAdapter.setUint32(i + ADDRESS_OFFSET, this.dataPointer, IS_LITTLE_ENDIAN);
390
- this.dataPointer += size;
391
- }
392
- this.dataBus = newDataBus;
393
- this.dataAdapter = new DataView(this.dataBus.buffer);
394
- this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
395
- this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
396
- this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
397
- }
398
- // ========== SCALING ==========
399
- /**
400
- * [!!! INTERNAL USE, DO NOT USE IN YOUR CODE !!!]
401
- * Expands the `dataBus` to double its current capacity.
402
- *
403
- * The underlying buffer is transferred to a larger `ArrayBuffer`, preserving
404
- * existing data. All views associated with the buffer are recreated
405
- * to reference the new storage.
406
- *
407
- * @returns {void}
408
- * @throws {Error} If any block is borrowed via withView().
409
- * @throws {RangeError} If the `dataBus` capacity has already exceeded the
410
- * maximum supported limit.
411
- * @private
412
- */
413
- grow() {
414
- this.assertNoActiveViews();
415
- if (this.size > 2147483648) throw new RangeError("Data bus capacity exceeded");
416
- const newSize = this.size * 2 >>> 0;
417
- const newBuffer = this.dataBus.buffer.transfer(newSize);
418
- this.size = newSize;
419
- this.dataBus = new Uint8Array(newBuffer);
420
- this.dataAdapter = new DataView(newBuffer);
421
- this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
422
- this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
423
- this.auxiliary = new this.bucketArray(newBuffer);
424
- }
425
- /**
426
- * [!!! INTERNAL USE, DO NOT USE IN YOUR CODE !!!]
427
- * Expands the `controlBus` to double its current capacity.
428
- *
429
- * The underlying buffer is transferred to a larger `ArrayBuffer`, preserving
430
- * existing headers. The `controlAdapter` is recreated to reference
431
- * the new storage.
432
- *
433
- * @returns {void}
434
- * @throws {RangeError} If the current `controlBus` capacity has already
435
- * exceeded the maximum supported limit.
436
- * @private
437
- */
438
- headerGrow() {
439
- if (this.controlBus.byteLength > 2147483648) throw new RangeError("Control bus capacity exceeded");
440
- const newSize = this.controlBus.byteLength * 2 >>> 0;
441
- const newBuffer = this.controlBus.buffer.transfer(newSize);
442
- this.controlBus = new Uint8Array(newBuffer);
443
- this.controlAdapter = new DataView(newBuffer);
444
- }
180
+ // ========== SCHEDULING ==========
445
181
  // ========== STACK OPERATIONS ==========
446
182
  /**
447
- * Appends an element to the end of the sequence occupied by the block.
183
+ * Adds an element to the end of the block's occupied sequence.
448
184
  *
449
- * The element is written at the first free position after the last occupied
450
- * element. Block occupancy is incremented only when space is available
185
+ * The element is written to the first free position after the last occupied
186
+ * element. The block's occupancy is incremented only when space is available
451
187
  * within its capacity.
452
188
  *
453
- * @param {number} value - Value to be inserted.
189
+ * @param {number} handler - Block handle.
190
+ * @param {number} value - Value to insert.
454
191
  * @returns {boolean} `true` if the value was inserted; `false` if the block
455
- * is already out of available space.
456
- * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
192
+ * has no available space.
193
+ * @throws {Error} If the handle is invalid or corrupted, or the block is borrowed by withView().
457
194
  *
458
195
  */
459
196
  push(handler, value) {
460
- const meta = this.extractMetadata(handler, this.metadata);
461
- if (meta.borrowed) throw new Error("Block is borrowed");
462
- if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
463
- this.writer(meta.dataAddress + meta.occupied * this.wordSize, value, IS_LITTLE_ENDIAN);
464
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
197
+ if (!Object.hasOwn(this.bus, handler)) {
198
+ throw new Error("Invalid or corrupted handle");
199
+ }
200
+ const pack = this.bus[handler];
201
+ if (pack.borrowed) {
202
+ throw new Error("Block is borrowed");
203
+ }
204
+ if (pack.occupied >= pack.dataBus.length) return false;
205
+ pack.dataBus[pack.occupied++] = value;
465
206
  return true;
466
207
  }
467
208
  /**
468
- * Removes the last occupied element from the block and returns it.
469
- *
470
- * Occupancy is decremented before reading the removed element. The corresponding
471
- * bytes are not cleared and remain in the allocated region, but cease to be
472
- * part of the occupied sequence.
209
+ * Removes and returns the last occupied element. If the block is empty,
210
+ * returns undefined without changing its occupancy.
473
211
  *
474
- * @param {number} handler - Block handle.
475
- * @returns {number|undefined} Removed value or `undefined` if the block
476
- * is empty.
477
- * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
212
+ * @param {number} handler Block handle.
213
+ * @returns {number|bigint|undefined} Value at the index immediately before
214
+ * the occupancy is decremented.
215
+ * @throws {Error} If the handle does not exist or the block is borrowed.
478
216
  */
479
217
  pop(handler) {
480
- const meta = this.extractMetadata(handler, this.metadata);
481
- if (meta.borrowed) throw new Error("Block is borrowed");
482
- if (meta.occupied === 0) return void 0;
483
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
484
- return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
218
+ if (!Object.hasOwn(this.bus, handler)) {
219
+ throw new Error("Invalid or corrupted handle");
220
+ }
221
+ const pack = this.bus[handler];
222
+ if (pack.borrowed) {
223
+ throw new Error("Block is borrowed");
224
+ }
225
+ if (pack.occupied === 0) return void 0;
226
+ return pack.dataBus[--pack.occupied];
485
227
  }
486
228
  /**
487
229
  * Returns the last occupied element without removing it.
488
230
  *
489
231
  * @param {number} handler - Block handle.
490
- * @returns {number|undefined} Last occupied value or `undefined` if the
232
+ * @returns {number|undefined} Last occupied value, or `undefined` if the
491
233
  * block is empty.
492
- * @throws {Error} If the handle is invalid or corrupted.
234
+ * @throws {Error} If the handle does not exist or the block is borrowed.
493
235
  */
494
236
  peek(handler) {
495
- const meta = this.extractMetadata(handler, this.metadata);
496
- if (meta.occupied === 0) return void 0;
497
- return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
237
+ if (!Object.hasOwn(this.bus, handler)) {
238
+ throw new Error("Invalid or corrupted handle");
239
+ }
240
+ const pack = this.bus[handler];
241
+ if (pack.borrowed) {
242
+ throw new Error("Block is borrowed");
243
+ }
244
+ return pack.dataBus[pack.occupied - 1];
498
245
  }
499
246
  // ========== QUEUE OPERATIONS ==========
500
247
  /**
501
- * Inserts an element at the beginning of the occupied sequence.
502
- *
503
- * Currently occupied elements are shifted forward by one position and
504
- * `value` is written at the first position. The operation requires a free
505
- * position within the block's capacity.
248
+ * Shifts the occupied elements one position toward the end of the block.
506
249
  *
507
- * The operation cost is proportional to the number of occupied elements,
508
- * as data needs to be shifted.
250
+ * Runs copyWithin(1, 0, occupied) on the typed view. The
251
+ * value argument is not used, occupancy is not changed, and the method returns
252
+ * the typed view itself.
509
253
  *
510
- * @param {number} handler - Block handle.
511
- * @param {number} value - Value to be inserted.
512
- * @returns {boolean} `true` if the value was inserted; `false` if the block
513
- * is full.
514
- * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
254
+ * @param {number} handler Block handle.
255
+ * @param {number} value Currently unused parameter.
256
+ * @returns {TypedArray} Typed view of the block.
257
+ * @throws {Error} If the handle does not exist or the block is borrowed.
515
258
  */
516
259
  nudge(handler, value) {
517
- const meta = this.extractMetadata(handler, this.metadata);
518
- if (meta.borrowed) throw new Error("Block is borrowed");
519
- if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
520
- this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
521
- this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
522
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1, IS_LITTLE_ENDIAN);
260
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
261
+ const pack = this.bus[handler];
262
+ if (pack.borrowed) throw new Error("Block is borrowed");
263
+ if (pack.occupied >= pack.dataBus.length) return false;
264
+ pack.dataBus.copyWithin(1, 0, pack.occupied);
265
+ pack.dataBus[0] = value;
266
+ pack.occupied++;
523
267
  return true;
524
268
  }
525
269
  /**
526
- * Removes the first occupied element from the block and returns it.
527
- *
528
- * Remaining elements are shifted one position toward the beginning
529
- * of the occupied region. The physical capacity of the block remains unchanged.
270
+ * Returns the value in the first slot and shifts the remaining occupied
271
+ * elements one position toward the beginning of the block.
530
272
  *
531
- * The operation cost is proportional to the number of shifted elements.
273
+ * The implementation does not decrement occupancy after shifting.
532
274
  *
533
- * @param {number} handler - Block handle.
534
- * @returns {number|undefined} First removed value or `undefined` if the
535
- * block is empty.
536
- * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
275
+ * @param {number} handler Block handle.
276
+ * @returns {number|bigint|undefined} Value stored in the first slot.
277
+ * @throws {Error} If the handle does not exist or the block is borrowed.
537
278
  */
538
279
  pull(handler) {
539
- const meta = this.extractMetadata(handler, this.metadata);
540
- if (meta.borrowed) throw new Error("Block is borrowed");
541
- if (meta.occupied === 0) return void 0;
542
- const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
543
- this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
544
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
280
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
281
+ const pack = this.bus[handler];
282
+ if (pack.borrowed) throw new Error("Block is borrowed");
283
+ if (pack.occupied === 0) return void 0;
284
+ const result = pack.dataBus[0];
285
+ pack.dataBus.copyWithin(0, 1, pack.occupied);
286
+ pack.occupied--;
545
287
  return result;
546
288
  }
547
289
  /**
548
- * Returns the first occupied element without removing it.
290
+ * Returns the value stored in the block's first slot.
549
291
  *
550
- * @param {number} handler - Block handle.
551
- * @returns {number|undefined} First occupied value or `undefined` if the
552
- * block is empty.
553
- * @throws {Error} If the handle is invalid or corrupted.
292
+ * Reading does not change occupancy. The method does not check the borrowed flag.
293
+ *
294
+ * @param {number} handler Block handle.
295
+ * @returns {number|bigint|undefined} Value in the first slot.
296
+ * @throws {Error} If the handle does not exist.
554
297
  */
555
298
  head(handler) {
556
- const meta = this.extractMetadata(handler, this.metadata);
557
- if (meta.occupied === 0) return void 0;
558
- return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
299
+ if (!Object.hasOwn(this.bus, handler)) {
300
+ throw new Error("Invalid or corrupted handle");
301
+ }
302
+ return this.bus[handler].dataBus[0];
559
303
  }
560
304
  // ========== RANDOM ACCESS ==========
561
305
  /**
562
- * Checks if a value is present among the occupied elements of the block.
306
+ * Checks whether a value is present among the block's occupied elements.
563
307
  *
564
308
  * The search is performed directly on the auxiliary `TypedArray` and considers
565
- * only the currently occupied range, not the entire reserved physical capacity.
309
+ * only the currently occupied range, not the entire physical capacity
310
+ * reserved.
566
311
  *
567
312
  * @param {number} handler - Block handle.
568
313
  * @param {number} value - Value to search for.
569
- * @returns {boolean} `true` if `value` is present among the occupied
570
- * elements; otherwise, `false`.
314
+ * @returns {boolean} `true` if `value` is present among the
315
+ * occupied elements; otherwise, `false`.
571
316
  * @throws {Error} If the handle is invalid or corrupted.
572
317
  */
573
318
  has(handler, value) {
574
- const meta = this.extractMetadata(handler, this.metadata);
575
- if (meta.occupied === 0) return false;
576
- const rawAddres = meta.dataAddress >>> this.wordShift;
577
- return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
319
+ if (!Object.hasOwn(this.bus, handler)) {
320
+ throw new Error("Invalid or corrupted handle");
321
+ }
322
+ const pack = this.bus[handler];
323
+ return pack.dataBus.subarray(0, pack.occupied).includes(value);
578
324
  }
579
325
  /**
580
- * Locates the first occurrence of an element in the block's occupied sequence.
326
+ * Finds the first occurrence of an element in the block's occupied sequence.
581
327
  *
582
- * The search is performed in ascending order of indices, using the `indexOf`
583
- * operation of the underlying TypedArray. The search exclusively considers
584
- * occupied elements, ignoring the block's unused capacity.
585
- *
586
- * The starting search position can be specified by `fromIndex`,
587
- * following TypedArray indexing rules.
588
328
  *
589
329
  * @param {number} handler - Block handle.
590
- * @param {number|bigint} searchElement - Element to locate.
591
- * @param {number} [fromIndex=0] - Index from which to start the search.
592
- * @returns {number} Index of the first occurrence or `-1` if the
593
- * element is not found or if the block is empty.
330
+ * @param {number|bigint} searchElement - Element to find.
331
+ * @param {number} [fromIndex=0] - Index from which the search starts.
332
+ * @returns {number} Index of the first occurrence, or `-1` if the
333
+ * element is not found or the block is empty.
594
334
  * @throws {Error} If the handle is invalid or corrupted.
595
335
  */
596
336
  indexOf(handler, searchElement, fromIndex = 0) {
597
- const meta = this.extractMetadata(handler, this.metadata);
598
- if (meta.occupied === 0) return -1;
599
- const rawAddres = meta.dataAddress >>> this.wordShift;
600
- return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).indexOf(searchElement, fromIndex);
337
+ if (!Object.hasOwn(this.bus, handler)) {
338
+ throw new Error("Invalid or corrupted handle");
339
+ }
340
+ const pack = this.bus[handler];
341
+ return pack.dataBus.subarray(0, pack.occupied).indexOf(searchElement, fromIndex);
601
342
  }
602
343
  /**
603
- * Locates the last occurrence of an element in the block's occupied sequence.
344
+ * Finds the last occurrence of an element in the block's occupied sequence.
604
345
  *
605
- * The search is performed in descending order of indices, using the `lastIndexOf`
606
- * operation of the underlying TypedArray. The search exclusively considers
607
- * occupied elements, ignoring the block's unused capacity.
608
- *
609
- * The starting search position can be specified by `fromIndex`,
610
- * following TypedArray indexing rules. By default, the search starts
611
- * at the last occupied element.
346
+ * By default, the search starts at the last occupied element.
612
347
  *
613
348
  * @param {number} handler - Block handle.
614
- * @param {number|bigint} searchElement - Element to locate.
615
- * @param {number} [fromIndex=-1] - Index from which to start the search.
616
- * @returns {number} Index of the last occurrence or `-1` if the
617
- * element is not found or if the block is empty.
349
+ * @param {number|bigint} searchElement - Element to find.
350
+ * @param {number} [fromIndex=-1] - Index from which the search starts.
351
+ * @returns {number} Index of the last occurrence, or `-1` if the
352
+ * element is not found or the block is empty.
618
353
  * @throws {Error} If the handle is invalid or corrupted.
619
354
  */
620
355
  lastIndexOf(handler, searchElement, fromIndex = -1) {
621
- const meta = this.extractMetadata(handler, this.metadata);
622
- if (meta.occupied === 0) return -1;
623
- const rawAddres = meta.dataAddress >>> this.wordShift;
624
- return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).lastIndexOf(searchElement, fromIndex);
356
+ if (!Object.hasOwn(this.bus, handler)) {
357
+ throw new Error("Invalid or corrupted handle");
358
+ }
359
+ const pack = this.bus[handler];
360
+ return pack.dataBus.subarray(0, pack.occupied).lastIndexOf(searchElement, fromIndex);
625
361
  }
626
362
  /**
627
363
  * Returns the occupied element at a zero-based index.
628
364
  *
629
- * Indices outside the range `[0, occupied)` are not considered an error and
365
+ * Indices outside the `[0, occupied)` range are not considered errors and
630
366
  * result in `undefined`.
631
367
  *
632
368
  * @param {number} handler - Block handle.
633
369
  * @param {number} index - Zero-based index of the element.
634
- * @returns {number|undefined} Value stored at the index or `undefined` if
370
+ * @returns {number|undefined} Value stored at the index, or `undefined` if
635
371
  * the index is outside the occupied region.
636
372
  * @throws {Error} If the handle is invalid or corrupted.
637
373
  */
638
374
  get(handler, index) {
639
- const meta = this.extractMetadata(handler, this.metadata);
640
- if (index < 0 || index >= meta.occupied) return void 0;
641
- return this.reader(meta.dataAddress + index * this.wordSize, IS_LITTLE_ENDIAN);
375
+ if (!Object.hasOwn(this.bus, handler)) {
376
+ throw new Error("Invalid or corrupted handle");
377
+ }
378
+ const pack = this.bus[handler];
379
+ if (index < 0 || index >= pack.occupied) return void 0;
380
+ return pack.dataBus[index];
642
381
  }
643
382
  /**
644
383
  * Replaces the value stored at an occupied index.
645
384
  *
646
- * The operation does not alter block occupancy. Indices outside the range
647
- * `[0, occupied)` are ignored and result in `false`.
385
+ * The operation does not change block occupancy. Indices outside the
386
+ * `[0, occupied)` range are ignored and result in `false`.
648
387
  *
649
388
  * @param {number} handler - Block handle.
650
389
  * @param {number} index - Zero-based index of the element.
651
390
  * @param {number} value - New value.
652
391
  * @returns {boolean} `true` if the value was written; `false` if the index
653
392
  * is outside the occupied region.
654
- * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
393
+ * @throws {Error} If the handle is invalid or corrupted, or the block is borrowed by withView().
655
394
  */
656
395
  set(handler, index, value) {
657
- const meta = this.extractMetadata(handler, this.metadata);
658
- if (meta.borrowed) throw new Error("Block is borrowed");
659
- if (index < 0 || index >= meta.occupied) return false;
660
- this.writer(meta.dataAddress + index * this.wordSize, value, IS_LITTLE_ENDIAN);
396
+ if (!Object.hasOwn(this.bus, handler)) {
397
+ throw new Error("Invalid or corrupted handle");
398
+ }
399
+ const pack = this.bus[handler];
400
+ if (pack.borrowed) {
401
+ throw new Error("Block is borrowed");
402
+ }
403
+ if (index < 0 || index >= pack.occupied) return false;
404
+ pack.dataBus[index] = value;
661
405
  return true;
662
406
  }
663
407
  // ============= MISCELLANEOUS ===============
664
408
  /**
665
- * Zeroes block occupancy and fills its entire physical capacity with
666
- * a single value.
409
+ * Resets the block's occupancy and fills its entire physical capacity with
410
+ * the same value.
667
411
  *
668
- * The fill covers all available slots, not just currently
669
- * occupied elements. After the operation, the block is considered
670
- * empty regardless of the value used for filling.
412
+ * Filling covers all available slots, not just the
413
+ * currently occupied elements. After the operation, the block is considered
414
+ * empty regardless of the value used to fill it.
671
415
  *
672
416
  * @param {number} handler - Block handle.
673
417
  * @param {number} [value=0] - Value used to fill all slots.
674
418
  * @returns {void}
675
- * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
419
+ * @throws {Error} If the handle is invalid or corrupted, or the block is borrowed by withView().
676
420
  */
677
421
  clear(handler, value = 0) {
678
- const meta = this.extractMetadata(handler, this.metadata);
679
- if (meta.borrowed) throw new Error("Block is borrowed");
680
- const slots = meta.byteCapacity / this.wordSize;
681
- const rawAddress = meta.dataAddress >>> this.wordShift;
682
- this.auxiliary.fill(value, rawAddress, rawAddress + slots);
683
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
422
+ if (!Object.hasOwn(this.bus, handler)) {
423
+ throw new Error("Invalid or corrupted handle");
424
+ }
425
+ const pack = this.bus[handler];
426
+ if (pack.borrowed) {
427
+ throw new Error("Block is borrowed");
428
+ }
429
+ pack.dataBus.fill(value);
430
+ pack.occupied = 0;
684
431
  }
685
432
  /**
686
- * Fills a range of block slots with a value.
687
- *
688
- * The range uses zero-based indices and follows the convention
689
- * `[start, end)`, therefore `start` is inclusive and `end` is exclusive.
690
- * When `end` is not provided, filling extends to the end of the block's
691
- * physical capacity.
433
+ * Fills the typed view using the supplied bounds.
692
434
  *
693
- * Block occupancy becomes `end`, including when the filled range
694
- * extends beyond previous occupancy.
435
+ * The operation delegates filling to TypedArray.prototype.fill().
436
+ * Because end defaults to null and is passed explicitly, it is
437
+ * converted to zero by the native API; therefore, the default call
438
+ * normally fills no elements. Regardless of the range,
439
+ * the implementation sets occupancy to the view's total length.
695
440
  *
696
- * @param {number} handler - Block handle.
697
- * @param {number} value - Value used for filling.
698
- * @param {number} [start=0] - Initial index, inclusive.
699
- * @param {number|null} [end=null] - Final index, exclusive. When
700
- * omitted or `null`, uses the block's total capacity.
441
+ * @param {number} handler Block handle.
442
+ * @param {number|bigint} value Value used to fill the view.
443
+ * @param {number} [start=0] Starting index.
444
+ * @param {number} [end=pack.dataBus.length] Exclusive end index.
701
445
  * @returns {void}
702
- * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
703
- * @throws {RangeError} If `start` or `end` is outside capacity limits,
704
- * or if `start > end`.
446
+ * @throws {Error} If the handle does not exist or the block is borrowed.
705
447
  */
706
- fill(handler, value, start = 0, end = null) {
707
- const meta = this.extractMetadata(handler, this.metadata);
708
- if (meta.borrowed) throw new Error("Block is borrowed");
709
- const slots = meta.byteCapacity / this.wordSize;
710
- const lastIndex = end ?? slots;
711
- if (start > lastIndex) {
712
- throw new RangeError(`start ${start} must be less or equal than end ${lastIndex}.`);
713
- }
714
- if (start < 0 || start > slots) {
715
- throw new RangeError(`start ${start} out of range [0, ${slots}].`);
448
+ fill(handler, value, start = 0, end = void 0) {
449
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
450
+ const pack = this.bus[handler];
451
+ if (pack.borrowed) throw new Error("Block is borrowed");
452
+ const finalEnd = end === void 0 ? pack.dataBus.length : end;
453
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(finalEnd) || start < 0 || finalEnd < start || finalEnd > pack.dataBus.length) {
454
+ throw new RangeError("Invalid fill range");
716
455
  }
717
- if (lastIndex < 0 || lastIndex > slots) {
718
- throw new RangeError(`end ${lastIndex} out of range [0, ${slots}].`);
719
- }
720
- const rawAddress = meta.dataAddress >>> this.wordShift;
721
- this.auxiliary.fill(value, rawAddress + start, rawAddress + lastIndex);
722
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, lastIndex, IS_LITTLE_ENDIAN);
456
+ pack.dataBus.fill(value, start, finalEnd);
457
+ pack.occupied = Math.max(pack.occupied, finalEnd);
723
458
  }
724
459
  /**
725
- * Fills all physical slots of the block with a value and marks the entire
460
+ * Fills all physical slots in the block with a value and marks the entire
726
461
  * capacity as occupied.
727
462
  *
728
- * Unlike `clear()`, this operation results in a fully occupied block.
463
+ * Unlike `clear()`, this operation results in a fully
464
+ * occupied block.
729
465
  *
730
466
  * @param {number} handler - Block handle.
731
- * @param {number} value - Value used for filling.
467
+ * @param {number} value - Value used to fill the block.
732
468
  * @returns {void}
733
- * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
469
+ * @throws {Error} If the handle is invalid or corrupted, or the block is borrowed by withView().
734
470
  */
735
471
  fillAll(handler, value) {
736
- const meta = this.extractMetadata(handler, this.metadata);
737
- if (meta.borrowed) throw new Error("Block is borrowed");
738
- const rawAddress = meta.dataAddress >>> this.wordShift;
739
- const capacityElements = meta.byteCapacity / this.wordSize;
740
- this.auxiliary.fill(value, rawAddress, rawAddress + capacityElements);
741
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, capacityElements, IS_LITTLE_ENDIAN);
472
+ if (!Object.hasOwn(this.bus, handler)) {
473
+ throw new Error("Invalid or corrupted handle");
474
+ }
475
+ const pack = this.bus[handler];
476
+ if (pack.borrowed) {
477
+ throw new Error("Block is borrowed");
478
+ }
479
+ pack.dataBus.fill(value);
480
+ pack.occupied = pack.dataBus.length;
742
481
  }
743
482
  /**
744
483
  * Copies elements from an `Array` or `TypedArray` to the beginning of the block.
745
484
  *
746
- * The copied quantity is limited by the block's capacity. Occupancy is
747
- * updated to the greater value between previous occupancy and the quantity
748
- * effectively copied; therefore, a call to `put()` does not reduce existing
749
- * occupancy when receiving a smaller sequence.
485
+ * The copied amount is limited by the block's capacity. Occupancy is
486
+ * updated to the greater of the previous occupancy and the amount
487
+ * actually copied; therefore, a call to `put()` does not reduce
488
+ * existing occupancy when given a shorter sequence.
750
489
  *
751
- * For `Array`, only the first elements that fit are copied.
752
- * For `TypedArray`, a source subarray is used without intermediate copying.
490
+ * For an `Array`, only the first elements that fit are copied.
491
+ * For a `TypedArray`, a subarray of the source is used without an
492
+ * intermediate copy.
753
493
  *
754
494
  * @param {number} handler - Block handle.
755
495
  * @param {Array|TypedArray} data - Sequence of values to copy.
756
496
  * @returns {void}
757
- * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
497
+ * @throws {Error} If the handle is invalid or corrupted, or the block is borrowed by withView().
758
498
  * @throws {TypeError} If `data` is neither an `Array` nor a `TypedArray`.
759
499
  */
760
500
  put(handler, data) {
761
- const meta = this.extractMetadata(handler, this.metadata);
762
- if (meta.borrowed) throw new Error("Block is borrowed");
763
- const rawAddress = meta.dataAddress >>> this.wordShift;
764
- const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
765
- if (Array.isArray(data)) {
766
- this.auxiliary.set(data.slice(0, length), rawAddress);
767
- } else if (isTypedArray(data)) {
768
- this.auxiliary.set(data.subarray(0, length), rawAddress);
769
- } else {
501
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
502
+ const pack = this.bus[handler];
503
+ if (pack.borrowed) throw new Error("Block is borrowed");
504
+ if (!Array.isArray(data) && !isTypedArray(data)) {
770
505
  const actual = data?.constructor?.name ?? (data === null ? "null" : typeof data);
771
506
  throw new TypeError(`data must be Array or TypedArray, but ${actual} was given.`);
772
507
  }
773
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, Math.max(length, meta.occupied), IS_LITTLE_ENDIAN);
508
+ const length = Math.min(pack.dataBus.length, data.length);
509
+ if (Array.isArray(data)) pack.dataBus.set(data.slice(0, length), 0);
510
+ else pack.dataBus.set(data.subarray(0, length), 0);
511
+ pack.occupied = Math.max(length, pack.occupied);
774
512
  }
775
513
  /**
776
514
  * Returns a copy of the elements currently occupied by the block.
@@ -778,39 +516,38 @@ var Balloc = class {
778
516
  * The result is a `TypedArray` of the same type configured by
779
517
  * `bucketSize`. Unoccupied physical capacity is not included in the result.
780
518
  *
781
- * The operation does not directly expose internal storage: the method
782
- * uses `TypedArray.prototype.slice()`, producing a new view with
783
- * independent storage.
519
+ * The operation does not expose the internal storage directly:
520
+ * `TypedArray.prototype.slice()` produces a copy with independent
521
+ * storage.
784
522
  *
785
523
  * @param {number} handler - Block handle.
786
- * @returns {TypedArray} Copy of elements occupied by the block. When
524
+ * @returns {TypedArray} Copy of the elements occupied by the block. When
787
525
  * the block is empty, returns an empty `TypedArray` of the configured type.
788
526
  * @throws {Error} If the handle is invalid or corrupted.
789
527
  */
790
528
  pick(handler) {
791
- const meta = this.extractMetadata(handler, this.metadata);
792
- const rawAddress = meta.dataAddress >>> this.wordShift;
793
- if (meta.occupied === 0) {
794
- return this.auxiliary.slice(rawAddress, rawAddress);
795
- }
796
- return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
797
- }
798
- /**
799
- * Executes a callback over a direct view of the block's occupied region.
800
- *
801
- * The view shares Balloc's internal storage and performs no copying.
802
- * The block is protected against incompatible operations during the callback.
803
- *
804
- * The callback must be synchronous. The received view must not be stored,
805
- * returned, or used after the callback terminates. This restriction
806
- * also applies to subviews derived from the original view.
807
- *
808
- * @param {number} handler - Block handle.
809
- * @param {...(number|Function)} args - One or more block handles followed by the callback.
810
- * @returns {*} Return value produced by the callback.
811
- * @throws {TypeError} If no handle is provided or the callback is not a function.
812
- * @throws {Error} If a handle is invalid, duplicated, or already borrowed.
813
- */
529
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
530
+ const pack = this.bus[handler];
531
+ return pack.dataBus.slice(0, pack.occupied);
532
+ }
533
+ /**
534
+ * Executes a synchronous callback with direct subviews of one or more blocks.
535
+ *
536
+ * The arguments contain one or more handles, followed by a function.
537
+ * Each view covers only the occupied elements and shares the block's
538
+ * storage. The blocks are marked as borrowed during
539
+ * execution and released in finally, even if the callback throws
540
+ * an exception. Duplicate handles are not allowed.
541
+ *
542
+ * The views must not be retained or used after the callback returns.
543
+ *
544
+ * @param {...(number|Function)} args Handles followed by the callback.
545
+ * @returns {*} Value returned by the callback.
546
+ * @throws {TypeError} If a handle or callback is missing, or if the last
547
+ * argument is not a function.
548
+ * @throws {Error} If any handle does not exist, is duplicated,
549
+ * or is already borrowed.
550
+ */
814
551
  withView(...args) {
815
552
  if (args.length < 2) throw new TypeError("At least one handler and one callback are required");
816
553
  const lastIndex = args.length - 1;
@@ -821,37 +558,36 @@ var Balloc = class {
821
558
  const views = [];
822
559
  try {
823
560
  for (let i = 0; i < lastIndex; i++) {
824
- const metadata = this.extractMetadata(args[i], this.metadata);
825
- const headerAddr = metadata.headerAddress;
826
- if (Object.hasOwn(lookup, headerAddr)) throw new Error("Duplicate handler");
827
- if (metadata.borrowed) throw new Error("Block is already borrowed");
828
- this.controlBus[headerAddr + FLAGS_OFFSET] |= VIEW_LOCK;
829
- const rawAddress = metadata.dataAddress >>> this.wordShift;
830
- lookup[headerAddr] = true;
831
- acquired.push(headerAddr);
832
- views.push(this.auxiliary.subarray(rawAddress, rawAddress + metadata.occupied));
561
+ const handler = args[i];
562
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
563
+ if (Object.hasOwn(lookup, handler)) throw new Error("Duplicate handler");
564
+ const pack = this.bus[handler];
565
+ if (pack.borrowed) throw new Error("Block is already borrowed");
566
+ pack.borrowed = true;
567
+ lookup[handler] = true;
568
+ acquired.push(pack);
569
+ views.push(pack.dataBus.subarray(0, pack.occupied));
833
570
  }
834
571
  return callback(...views);
835
572
  } finally {
836
- for (let i = 0; i < acquired.length; i++) {
837
- this.controlBus[acquired[i] + FLAGS_OFFSET] &= ~VIEW_LOCK;
838
- }
573
+ for (let i = 0; i < acquired.length; i++) acquired[i].borrowed = false;
839
574
  }
840
575
  }
841
576
  // ======== CAPACITY IN SLOTS ==========
842
577
  /**
843
- * Returns the physical capacity of the block in bytes.
578
+ * Returns the block's physical capacity in bytes.
844
579
  *
845
- * Capacity corresponds to the space reserved for all slots in the
846
- * block, regardless of how many elements are currently occupied.
580
+ * Capacity is the space reserved for all slots in the
581
+ * block, regardless of how many elements are currently
582
+ * occupied.
847
583
  *
848
584
  * @param {number} handler - Block handle.
849
585
  * @returns {number} Physical capacity of the block, in bytes.
850
586
  * @throws {Error} If the handle is invalid or corrupted.
851
587
  */
852
588
  byteSize(handler) {
853
- const meta = this.extractMetadata(handler, this.metadata);
854
- return meta.byteCapacity;
589
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
590
+ return this.bus[handler].dataBus.byteLength;
855
591
  }
856
592
  /**
857
593
  * Returns the number of elements currently occupied in the block.
@@ -861,28 +597,28 @@ var Balloc = class {
861
597
  * @throws {Error} If the handle is invalid or corrupted.
862
598
  */
863
599
  occupied(handler) {
864
- const meta = this.extractMetadata(handler, this.metadata);
865
- return meta.occupied;
600
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
601
+ return this.bus[handler].occupied;
866
602
  }
867
603
  /**
868
- * Returns the block's capacity in number of elements.
604
+ * Returns the block capacity as a number of elements.
869
605
  *
870
606
  * The value corresponds to the total number of physically reserved slots,
871
- * not the currently occupied quantity.
607
+ * not the number currently occupied.
872
608
  *
873
609
  * @param {number} handler - Block handle.
874
610
  * @returns {number} Total number of slots available in the block.
875
611
  * @throws {Error} If the handle is invalid or corrupted.
876
612
  */
877
613
  length(handler) {
878
- const meta = this.extractMetadata(handler, this.metadata);
879
- return 1 << meta.capacityExponent >>> 0;
614
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
615
+ return this.bus[handler].dataBus.length;
880
616
  }
881
617
  /**
882
- * Checks if the memory block has reached its allocation capacity.
618
+ * Checks whether the memory block has reached its allocation capacity.
883
619
  *
884
620
  * A block is considered full when the number of occupied elements
885
- * equals its total allocated capacity, leaving no positions available
621
+ * equals its total allocated capacity, leaving no available positions
886
622
  * to store new elements.
887
623
  *
888
624
  * @param {number} handler - Block handle.
@@ -890,72 +626,67 @@ var Balloc = class {
890
626
  * @throws {Error} If the handle is invalid or corrupted.
891
627
  */
892
628
  isFull(handler) {
893
- const meta = this.extractMetadata(handler, this.metadata);
894
- return (1 << meta.capacityExponent >>> 0) - meta.occupied === 0;
629
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
630
+ const pack = this.bus[handler];
631
+ return pack.occupied === pack.dataBus.length;
895
632
  }
896
- // ========== Operations between blocks=============
633
+ // ==========OPERATIONS BETWEEN BLOCKS=============
897
634
  /**
898
- * Copies occupied elements from one block to another.
899
- *
900
- * Copying starts at the first element of `source` and the first slot of
901
- * `destination`. The quantity effectively copied is limited by the number of
902
- * occupied elements in the source, the physical capacity of the destination, and the
903
- * limit specified in `slots`.
904
- *
905
- * Destination occupancy is increased, when necessary, to cover the
906
- * copied elements. Destination capacity is unchanged.
907
- *
908
- * The operation uses `Uint8Array.prototype.copyWithin()` on the `dataBus`,
909
- * therefore the return value is the `Uint8Array` representing the data bus.
910
- *
911
- * @param {number} source - Source block handle.
912
- * @param {number} destination - Destination block handle.
913
- * @param {number} [slots=UNKNOWN] - Maximum number of elements to copy.
914
- * `UNKNOWN` represents the sentinel value used not to impose an
915
- * additional limit.
916
- * @returns {Uint8Array} The `dataBus` after the operation.
917
- * @throws {Error} If handles are invalid, corrupted,
918
- * or the destination block is borrowed via withView().
919
- */
635
+ * Copies occupied elements from one block to the beginning of another.
636
+ *
637
+ * The copied amount is the minimum of the source occupancy, destination
638
+ * capacity, and slots. The copy uses TypedArray.prototype.set(), converting
639
+ * values according to the destination view type. Destination occupancy
640
+ * becomes the greater of the previous occupancy and the number of
641
+ * copied elements.
642
+ *
643
+ * @param {number} source Handle of the source block.
644
+ * @param {number} destination Handle of the destination block.
645
+ * @param {number} [slots=UNKNOWN] Maximum number of elements to copy.
646
+ * @returns {TypedArray} Typed view of the destination block.
647
+ * @throws {Error} If either handle does not exist or the destination is borrowed.
648
+ */
920
649
  copy(source, destination, slots = UNKNOWN) {
921
- const metaA = {};
922
- const metaB = {};
923
- this.extractMetadata(source, metaA);
924
- this.extractMetadata(destination, metaB);
925
- if (metaB.borrowed) throw new Error("Block is borrowed");
926
- const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
927
- const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
928
- const newOccupied = Math.max(metaB.occupied, slotsToCopy);
929
- this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
930
- return this.dataBus.copyWithin(metaB.dataAddress, metaA.dataAddress, metaA.dataAddress + slotsToCopy * this.wordSize);
650
+ if (!Object.hasOwn(this.bus, source)) throw new Error("Invalid or corrupted handle");
651
+ if (!Object.hasOwn(this.bus, destination)) throw new Error("Invalid or corrupted handle");
652
+ const src = this.bus[source];
653
+ const dest = this.bus[destination];
654
+ if (dest.borrowed) throw new Error("Block is borrowed");
655
+ if (!Number.isSafeInteger(slots) || slots < 0) throw new RangeError("Invalid copy slot count");
656
+ const count = Math.min(src.occupied, dest.dataBus.length, slots);
657
+ dest.dataBus.set(src.dataBus.subarray(0, count), 0);
658
+ dest.occupied = Math.max(dest.occupied, count);
659
+ return dest.dataBus;
931
660
  }
932
661
  /**
933
662
  * Copies a region of elements within the same block.
934
663
  *
935
664
  * Indices are zero-based and follow the semantics of
936
665
  * `Array.prototype.copyWithin()`: `target` identifies the destination position,
937
- * `start` the starting source position, and `length` the maximum quantity of
666
+ * `start` the source starting position, and `length` the maximum number of
938
667
  * elements to copy.
939
668
  *
940
- * Negative indices are interpreted from the end of the block's capacity.
941
- * After this normalization, indices are clamped to physical capacity.
942
- * The copied quantity is also limited by effectively occupied elements
943
- * and available space starting from `target`.
669
+ * Negative indices are interpreted relative to the end of the block's
670
+ * capacity. After normalization, the indices are clamped to the physical
671
+ * capacity. The copied amount is also limited by the elements
672
+ * actually occupied and by the space available from `target`.
944
673
  *
945
- * The operation supports overlapping regions and can increase block occupancy
946
- * when the destination range exceeds previous occupancy.
674
+ * The operation supports overlapping regions and can increase the block's
675
+ * occupancy when the destination range extends beyond the current occupancy.
947
676
  *
948
677
  * @param {number} handler - Block handle.
949
- * @param {number} target - Initial destination index.
950
- * @param {number} start - Initial source index.
678
+ * @param {number} target - Starting destination index.
679
+ * @param {number} start - Starting source index.
951
680
  * @param {number} length - Maximum number of elements to copy.
952
681
  * @returns {Uint8Array} The `dataBus` after the operation.
953
- * @throws {Error} If the handle is invalid, corrupted, or the block is borrowed via withView().
682
+ * @throws {Error} If the handle is invalid or corrupted, or the block is borrowed by withView().
954
683
  */
955
684
  copyWithin(handler, target, start, length) {
956
- const meta = this.extractMetadata(handler, this.metadata);
957
- if (meta.borrowed) throw new Error("Block is borrowed");
958
- const slots = Math.floor(meta.byteCapacity / this.wordSize);
685
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
686
+ const pack = this.bus[handler];
687
+ if (pack.borrowed) throw new Error("Block is borrowed");
688
+ const slots = pack.dataBus.length;
689
+ if (![target, start, length].every(Number.isFinite)) throw new RangeError("Invalid copyWithin range");
959
690
  target = Math.trunc(target);
960
691
  start = Math.trunc(start);
961
692
  length = Math.trunc(length);
@@ -963,369 +694,188 @@ var Balloc = class {
963
694
  if (start < 0) start += slots;
964
695
  target = Math.max(0, Math.min(target, slots));
965
696
  start = Math.max(0, Math.min(start, slots));
966
- const maxRead = Math.max(0, meta.occupied - start);
967
- const maxWrite = slots - target;
968
- length = Math.max(0, Math.min(length, maxRead, maxWrite));
969
- if (length === 0) return this.dataBus;
970
- const targetAddress = meta.dataAddress + target * this.wordSize;
971
- const sourceAddress = meta.dataAddress + start * this.wordSize;
972
- const newOccupied = Math.max(meta.occupied, target + length);
973
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
974
- return this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + length * this.wordSize);
697
+ length = Math.max(0, Math.min(length, pack.occupied - start, slots - target));
698
+ if (length === 0) return pack.dataBus;
699
+ pack.dataBus.copyWithin(target, start, start + length);
700
+ pack.occupied = Math.max(pack.occupied, target + length);
701
+ return pack.dataBus;
975
702
  }
976
703
  /**
977
- * Appends occupied elements of `source` to the end of `target`.
704
+ * Appends the occupied elements of `source` to the end of `target`.
978
705
  *
979
- * The copied quantity is limited by the number of occupied elements in the
980
- * source and remaining free space in the destination's capacity.
706
+ * The copied amount is limited by the number of occupied elements in the
707
+ * source and by the remaining free space in the destination capacity.
981
708
  *
982
- * The operation supports `target` and `source` referencing the same block.
983
- * In this case, copying is performed over the block's own region and
984
- * preserves `copyWithin()` overlap semantics.
709
+ * The operation supports `target` and `source` referring to the same block.
710
+ * In this case, the copy is performed within the block itself and
711
+ * preserves the overlapping-region semantics of `copyWithin()`.
985
712
  *
986
- * @param {number} target - Handle of the block that will receive elements.
713
+ * @param {number} target - Handle of the block that will receive the elements.
987
714
  * @param {number} source - Handle of the block whose elements will be
988
715
  * appended.
989
- * @returns {number} Number of elements effectively appended.
990
- * @throws {Error} If handles are invalid, corrupted,
991
- * or the destination block is borrowed via withView().
716
+ * @returns {number} Number of elements actually appended.
717
+ * @throws {Error} If the handles are invalid or corrupted
718
+ * or the destination block is borrowed by withView().
992
719
  */
993
720
  append(target, source) {
994
- const metaTarget = {};
995
- const metaSource = {};
996
- this.extractMetadata(target, metaTarget);
997
- this.extractMetadata(source, metaSource);
998
- if (metaTarget.borrowed) throw new Error("Block is borrowed");
999
- const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
1000
- const count = Math.min(available, metaSource.occupied);
721
+ if (!Object.hasOwn(this.bus, target)) throw new Error("Invalid or corrupted handle");
722
+ if (!Object.hasOwn(this.bus, source)) throw new Error("Invalid or corrupted handle");
723
+ const dest = this.bus[target];
724
+ const src = this.bus[source];
725
+ if (dest.borrowed) throw new Error("Block is borrowed");
726
+ const count = Math.min(dest.dataBus.length - dest.occupied, src.occupied);
1001
727
  if (count === 0) return 0;
1002
- const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
1003
- const sourceAddress = metaSource.dataAddress;
1004
- this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
1005
- this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
728
+ if (dest === src) {
729
+ dest.dataBus.copyWithin(dest.occupied, 0, count);
730
+ } else {
731
+ dest.dataBus.set(src.dataBus.subarray(0, count), dest.occupied);
732
+ }
733
+ dest.occupied += count;
1006
734
  return count;
1007
735
  }
1008
736
  /**
1009
737
  * Creates an independent copy of a block.
1010
738
  *
1011
- * The new block has the same physical capacity and occupancy as the
1012
- * original block. All bytes in the reserved region, including currently
1013
- * unoccupied positions, are copied.
739
+ * The original view size is passed to alloc() as a size in bytes.
740
+ * For types with more than one byte per element, the resulting capacity
741
+ * may be smaller than the original; in that case, set() may throw a RangeError
742
+ * when attempting to copy the entire view. The view's elements are copied,
743
+ * including those outside the occupied region.
1014
744
  *
1015
- * The new block receives a new handle and remains subject to normal
1016
- * allocation and recycling rules.
745
+ * The new block receives its own handle.
1017
746
  *
1018
- * @param {number} handler - Handle of the block to be cloned.
747
+ * @param {number} handler - Handle of the block to clone.
1019
748
  * @returns {number} Handle of the new block.
1020
749
  * @throws {Error} If the handle is invalid or corrupted.
1021
750
  */
1022
751
  clone(handler) {
1023
- const meta = this.extractMetadata(handler, this.metadata);
1024
- const cloned = this.alloc(meta.byteCapacity / this.wordSize);
1025
- const cloneMeta = {};
1026
- this.extractMetadata(cloned, cloneMeta);
1027
- this.dataBus.copyWithin(cloneMeta.dataAddress, meta.dataAddress, meta.dataAddress + meta.byteCapacity);
1028
- this.controlAdapter.setUint32(cloneMeta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
752
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
753
+ const pack = this.bus[handler];
754
+ const cloned = this.alloc(pack.dataBus.byteLength, pack.bucketType);
755
+ const clonePack = this.bus[cloned];
756
+ clonePack.dataBus.set(pack.dataBus);
757
+ clonePack.occupied = pack.occupied;
1029
758
  return cloned;
1030
759
  }
1031
760
  /**
1032
- * Swaps the data regions associated with two blocks.
1033
- *
1034
- * The operation swaps region addresses, capacities, and occupancies
1035
- * between headers. Handles remain unchanged:
1036
- * after the operation, each handle continues identifying its own
1037
- * header, but that header now describes the region previously
1038
- * belonging to the other block.
761
+ * Swaps the block objects associated with two handles.
1039
762
  *
1040
- * No data is copied in the `dataBus`; only the metadata of the two
1041
- * headers is modified.
763
+ * The operation swaps the references stored in bus; it does not copy data
764
+ * or change the numeric handles. After the swap, each handle points
765
+ * to the block object previously associated with the other handle.
1042
766
  *
1043
- * @param {number} source - Handle of the first block.
1044
- * @param {number} target - Handle of the second block.
767
+ * @param {number} source First handle.
768
+ * @param {number} target Second handle.
1045
769
  * @returns {void}
1046
- * @throws {Error} If handles are invalid, corrupted,
1047
- * or either block is borrowed via withView().
770
+ * @throws {Error} If either handle does not exist or either block is
771
+ * borrowed.
1048
772
  */
1049
773
  swap(source, target) {
1050
- const metaA = {};
1051
- const metaB = {};
1052
- this.extractMetadata(source, metaA);
1053
- this.extractMetadata(target, metaB);
1054
- if (metaA.borrowed) throw new Error("Block is borrowed");
1055
- if (metaB.borrowed) throw new Error("Block is borrowed");
1056
- this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
1057
- this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
1058
- this.controlAdapter.setUint8(metaA.headerAddress + CAPACITY_OFFSET, metaB.capacityExponent);
1059
- this.controlAdapter.setUint8(metaB.headerAddress + CAPACITY_OFFSET, metaA.capacityExponent);
1060
- this.controlAdapter.setUint32(metaA.headerAddress + OCCUPIED_OFFSET, metaB.occupied, IS_LITTLE_ENDIAN);
1061
- this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, metaA.occupied, IS_LITTLE_ENDIAN);
774
+ if (!Object.hasOwn(this.bus, source)) throw new Error("Invalid or corrupted handle");
775
+ if (!Object.hasOwn(this.bus, target)) throw new Error("Invalid or corrupted handle");
776
+ const packA = this.bus[source];
777
+ const packB = this.bus[target];
778
+ if (packA.borrowed || packB.borrowed) throw new Error("Block is borrowed");
779
+ this.bus[source] = packB;
780
+ this.bus[target] = packA;
1062
781
  }
1063
782
  // ============= SERIALIZATION ==============
1064
783
  /**
1065
- * Serializes the content and metadata of a memory block.
784
+ * Serializes a block into a CBOR version 2 envelope.
1066
785
  *
1067
- * The method extracts occupied block data via `pick()`,
1068
- * groups it alongside capacity and word type information
1069
- * into a data envelope, and encodes it using the CBOR format.
786
+ * The envelope contains the bucket type, capacity in elements,
787
+ * occupancy, and a copy of the occupied elements (payload). Encoding
788
+ * is performed by cbor-x's encode().
1070
789
  *
1071
- * @param {number} handler - Handle of the block to be serialized.
1072
- * @returns {Uint8Array} A buffer containing the serialized block data.
1073
- * @throws {Error} If the handle is invalid or corrupted.
790
+ * @param {number} handler Block handle.
791
+ * @returns {Uint8Array} Serialized CBOR data.
792
+ * @throws {Error} If the handle does not exist or the capacity
793
+ * or occupancy metadata is inconsistent.
1074
794
  */
1075
795
  dump(handler) {
1076
- const meta = this.extractMetadata(handler, this.metadata);
1077
- const capacity = meta.capacityExponent;
1078
- const capacityElements = 2 ** capacity;
1079
- if (!Number.isInteger(capacity) || capacity < 1 || capacity > 31 || meta.occupied > capacityElements) {
796
+ if (!Object.hasOwn(this.bus, handler)) throw new Error("Invalid or corrupted handle");
797
+ const pack = this.bus[handler];
798
+ const capacity = pack.dataBus.length;
799
+ if (!Number.isInteger(capacity) || capacity < 2 || capacity > 2 ** 31 || pack.occupied < 0 || pack.occupied > capacity) {
1080
800
  throw new Error("Cannot serialize a block with invalid metadata");
1081
801
  }
1082
- const payload = this.pick(handler);
1083
- if (payload.length !== meta.occupied || payload.constructor !== this.bucketArray) {
1084
- throw new Error("Cannot serialize a block with an invalid payload");
1085
- }
802
+ const payload = pack.dataBus.slice(0, pack.occupied);
1086
803
  return (0, import_cbor_x.encode)({
1087
- v: 1,
1088
- wordType: this.wordType,
804
+ v: 2,
805
+ bucketType: pack.bucketType,
1089
806
  capacity,
1090
- occupied: meta.occupied,
1091
- le: IS_LITTLE_ENDIAN,
807
+ occupied: pack.occupied,
1092
808
  payload
1093
809
  });
1094
810
  }
1095
811
  /**
1096
- * Restores a memory block from serialized data.
812
+ * Decodes a CBOR envelope and recreates the serialized block.
1097
813
  *
1098
- * Decodes the CBOR envelope, validates whether the word type of the serialized
1099
- * data is compatible with the current allocator instance, and allocates
1100
- * a new block with the capacity required to accommodate the content.
1101
- * Then, original data and occupancy are restored in the new block.
814
+ * Accepts only ArrayBuffer or Uint8Array. Validates the envelope structure,
815
+ * version 2, bucket type, capacity, occupancy, and the type and
816
+ * length of the payload. If the instance has bucketSize fixed in the
817
+ * constructor, the serialized type must match it. The capacity
818
+ * recorded in elements is converted to bytes before allocation.
1102
819
  *
1103
- * @param {Uint8Array|ArrayBuffer} serialized - Buffer containing serialized data.
1104
- * @returns {number} Handle of the newly recreated block.
1105
- * @throws {Error} If the decoded data's word type differs from the allocator's configuration.
820
+ * @param {Uint8Array|ArrayBuffer} serialized Buffer containing the CBOR envelope.
821
+ * @returns {number} Handle of the restored block.
822
+ * @throws {TypeError} If the input, envelope, or payload have
823
+ * invalid types or structures.
824
+ * @throws {Error} If the version is not 2 or the bucket type differs
825
+ * from bucketSize when the instance has a fixed default type.
826
+ * @throws {RangeError} If the capacity or occupancy is invalid.
1106
827
  */
1107
828
  load(serialized) {
1108
829
  if (!(serialized instanceof ArrayBuffer) && !(serialized instanceof Uint8Array)) {
1109
830
  throw new TypeError("serialized must be an ArrayBuffer or Uint8Array");
1110
831
  }
1111
- const envelope = (0, import_cbor_x.decode)(serialized);
832
+ const envelope = (0, import_cbor_x.decode)(serialized instanceof ArrayBuffer ? new Uint8Array(serialized) : serialized);
1112
833
  if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)) {
1113
834
  throw new TypeError("Invalid serialized block envelope");
1114
835
  }
1115
- if (envelope.v !== 1) {
1116
- throw new Error(`Unsupported serialized block version: ${envelope.v}`);
836
+ if (envelope.v !== 2) throw new Error(`Unsupported serialized block version: ${envelope.v}`);
837
+ if (!BUCKET_MAPPING[envelope.bucketType]) throw new TypeError(`Unsupported bucket type: ${envelope.bucketType}`);
838
+ if (this.bucketSize !== null && envelope.bucketType !== this.bucketSize) {
839
+ throw new Error(`Can't load data, ${this.bucketSize} expected but ${envelope.bucketType} found.`);
1117
840
  }
1118
- if (envelope.wordType !== this.wordType) {
1119
- throw new Error(`Can't load data, ${this.wordType} expected but ${envelope.wordType} found.`);
1120
- }
1121
- if (!Number.isInteger(envelope.capacity) || envelope.capacity < 1 || envelope.capacity > 31) {
841
+ if (!Number.isSafeInteger(envelope.capacity) || envelope.capacity < 2 || envelope.capacity > 2 ** 31) {
1122
842
  throw new RangeError("Invalid serialized block capacity");
1123
843
  }
1124
- const capacityElements = 2 ** envelope.capacity;
1125
- if (!Number.isSafeInteger(envelope.occupied) || envelope.occupied < 0 || envelope.occupied > capacityElements) {
844
+ if (!Number.isSafeInteger(envelope.occupied) || envelope.occupied < 0 || envelope.occupied > envelope.capacity) {
1126
845
  throw new RangeError("Invalid serialized block occupancy");
1127
846
  }
1128
- if (typeof envelope.le !== "boolean") {
1129
- throw new TypeError("Invalid serialized endianness flag");
1130
- }
1131
847
  const payload = envelope.payload;
1132
- if (!isTypedArray(payload) || payload.constructor !== this.bucketArray || payload.length !== envelope.occupied) {
1133
- throw new TypeError(`Invalid payload: expected ${this.bucketType}Array with ${envelope.occupied} elements`);
848
+ const mapping = BUCKET_MAPPING[envelope.bucketType];
849
+ const TypedArray = globalThis[`${mapping.type}Array`];
850
+ const bytesPerElement = mapping.bits / 8;
851
+ if (!isTypedArray(payload) || payload.constructor !== TypedArray || payload.length !== envelope.occupied) {
852
+ throw new TypeError(`Invalid payload: expected ${mapping.type}Array with ${envelope.occupied} elements`);
1134
853
  }
1135
- if (payload.BYTES_PER_ELEMENT !== this.wordSize || payload.byteLength !== envelope.occupied * this.wordSize) {
854
+ if (payload.BYTES_PER_ELEMENT !== bytesPerElement || payload.byteLength !== envelope.occupied * bytesPerElement) {
1136
855
  throw new TypeError("Serialized payload has an invalid element size");
1137
856
  }
1138
- const handler = this.alloc(capacityElements);
1139
- const meta = this.extractMetadata(handler, this.metadata);
1140
- this.put(handler, payload);
1141
- this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, envelope.occupied, IS_LITTLE_ENDIAN);
857
+ const handler = this.alloc(envelope.capacity * bytesPerElement, envelope.bucketType);
858
+ const pack = this.bus[handler];
859
+ pack.dataBus.set(payload);
860
+ pack.occupied = envelope.occupied;
1142
861
  return handler;
1143
862
  }
1144
- // ========== INTEGRATION AND DATA INGESTION ==========
863
+ // ========== DATA INTEGRATION AND INGESTION ==========
1145
864
  /**
1146
- * Loads data through a specialized adapter.
1147
- *
1148
- * The adapter receives this instance and uses its public API to allocate
1149
- * and populate the required blocks. Data organization and interpretation
1150
- * are the adapter's sole responsibility; Balloc only delegates the
1151
- * operation and returns the resulting handler.
865
+ * Loads data by delegating the operation to an adapter.
1152
866
  *
1153
- * The operation is synchronous. The adapter must complete ingestion before
1154
- * returning and is responsible for reverting its own allocations if
1155
- * loading fails.
867
+ * The adapter must expose a load(allocator) function. It is called
868
+ * synchronously with the current Balloc instance, and its return value
869
+ * is passed through unchanged.
1156
870
  *
1157
- * @param {FormatAdapter} adapter - Adapter implementing load(allocator).
1158
- * @returns {number} Handler returned by the adapter.
1159
- * @throws {TypeError} If the adapter does not implement load().
1160
- * @throws {Error} If the adapter rejects the subscribed infrastructure.
871
+ * @param {FormatAdapter} adapter Adapter implementing load(allocator).
872
+ * @returns {*} Value returned by adapter.load(this).
873
+ * @throws {TypeError} If the adapter does not exist or load is not a function.
1161
874
  */
1162
875
  loadData(adapter) {
1163
876
  if (!adapter || typeof adapter.load !== "function") throw new TypeError("adapter must implement load(allocator)");
1164
877
  return adapter.load(this);
1165
878
  }
1166
879
  // ============= UTILITIES ==============
1167
- /**
1168
- * Prevents modification operations on a borrowed block.
1169
- *
1170
- * Checks the VIEW_LOCK flag in the header associated with the provided address.
1171
- *
1172
- * @param {number} headerAddress - Address of the header in controlBus.
1173
- * @returns {void}
1174
- * @throws {Error} If the block is borrowed via withView().
1175
- * @private
1176
- * @deprecated
1177
- */
1178
- assertNotBorrowed(headerAddress) {
1179
- if (this.controlBus[headerAddress + FLAGS_OFFSET] & VIEW_LOCK) {
1180
- throw new Error("Block is borrowed");
1181
- }
1182
- }
1183
- /**
1184
- * Prevents operations that replace or remap the dataBus
1185
- * while any segment is borrowed.
1186
- *
1187
- * @returns {void}
1188
- * @throws {Error} If any block is borrowed via withView().
1189
- * @private
1190
- */
1191
- assertNoActiveViews() {
1192
- for (let i = 0; i < this.controlPointer; i += HEADER_SIZE) {
1193
- if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
1194
- if (this.controlBus[i + FLAGS_OFFSET] & VIEW_LOCK) {
1195
- throw new Error("Cannot remap memory while a block is borrowed");
1196
- }
1197
- }
1198
- }
1199
- /**
1200
- * [INTERNAL USE]
1201
- * Decodes metadata associated with a handle.
1202
- *
1203
- * The handle is split into generation and header address. The cookie stored
1204
- * in the header is then recalculated to validate the combination; only after
1205
- * this validation are metadata read.
1206
- *
1207
- * Decoded fields are written to the `out` object, which is returned
1208
- * by the function itself. The object can be reused between calls to avoid
1209
- * new allocations.
1210
- *
1211
- * @param {number} handler - Handle to be decoded and validated.
1212
- * @param {Metadata} out - Object that will receive decoded metadata.
1213
- * @returns {Metadata} The same reference provided in `out`.
1214
- * @throws {Error} If the header cookie does not match the handle or
1215
- * if the handle does not identify a valid header.
1216
- * @private
1217
- */
1218
- extractMetadata(handler, out) {
1219
- out.generation = handler / ROTATE_32BITS & CLAMP_11BITS;
1220
- out.headerAddress = handler >>> 0;
1221
- const cookie = this.controlAdapter.getUint8(out.headerAddress + COOKIE_OFFSET);
1222
- if (cookie !== this.bakeCookie(out.headerAddress, out.generation)) {
1223
- throw new Error("Invalid or corrupted handle");
1224
- }
1225
- out.dataAddress = this.controlAdapter.getUint32(out.headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
1226
- out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1227
- out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
1228
- out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
1229
- out.borrowed = this.controlAdapter.getUint32(out.headerAddress + FLAGS_OFFSET, IS_LITTLE_ENDIAN) & VIEW_LOCK;
1230
- return out;
1231
- }
1232
- /**
1233
- * [INTERNAL USE]
1234
- * Calculates a header's validation cookie.
1235
- *
1236
- * The cookie is derived from the header address and the 11 generation bits via
1237
- * fast hash.
1238
- * The result is reduced to 8 bits.
1239
- *
1240
- * The value zero is reserved as an invalid header indicator; therefore,
1241
- * when the calculation produces zero, the method returns `1`.
1242
- *
1243
- * The cookie does not constitute a cryptographic mechanism. Its purpose is
1244
- * to detect invalid, stale, or corrupted handles within the allocator's
1245
- * memory management model.
1246
- *
1247
- * @param {number} addr - Header address.
1248
- * @param {number} gen - Generation associated with the handle. Only the 11
1249
- * least significant bits are considered.
1250
- * @returns {number} 8-bit cookie in the range [1, 255].
1251
- * @private
1252
- */
1253
- bakeCookie(addr, gen) {
1254
- return (addr ^ gen & 2047 * 2654435761) & 255 || 1;
1255
- }
1256
- /**
1257
- * Returns the number of regions currently stored in the recycling list.
1258
- *
1259
- * Each region corresponds to a freed block that could not be returned
1260
- * directly to the top of the `dataBus` and, therefore, remains available for
1261
- * reuse by a future allocation of identical capacity.
1262
- *
1263
- * @returns {number} Number of free regions kept in `recycle`.
1264
- */
1265
- recycleCount() {
1266
- let count = 0;
1267
- for (const [, page] of this.recycle) {
1268
- count += page[0];
1269
- }
1270
- return count;
1271
- }
1272
- /**
1273
- * Returns the total bytes belonging to regions currently stored in the
1274
- * recycling list.
1275
- *
1276
- * The value is calculated by summing each free region's capacity multiplied
1277
- * by the number of regions registered for that capacity.
1278
- *
1279
- * @returns {number} Number of bytes occupied by recyclable regions.
1280
- */
1281
- get recycleBytes() {
1282
- let total = 0;
1283
- for (const [capacity, page] of this.recycle) {
1284
- total += page[0] * capacity;
1285
- }
1286
- return total;
1287
- }
1288
- /**
1289
- * Returns the quantity of allocated bytes that do not belong to currently
1290
- * recyclable regions.
1291
- *
1292
- * The value is obtained by subtracting the bytes belonging to free regions
1293
- * kept in `recycle` from the total advance of `dataPointer`.
1294
- *
1295
- * @returns {number} Number of bytes associated with non-recyclable regions
1296
- * within the area already used by `dataBus`.
1297
- */
1298
- get allocatedBytes() {
1299
- return this.dataPointer - this.recycleBytes;
1300
- }
1301
- /**
1302
- * Returns the quantity of bytes not yet used at the top of the `dataBus`.
1303
- *
1304
- * This space corresponds to the region between `dataPointer` and the end of the
1305
- * capacity currently reserved for the buffer.
1306
- *
1307
- * @returns {number} Number of bytes available after `dataPointer`.
1308
- */
1309
- get unallocatedBytes() {
1310
- return this.size - this.dataPointer;
1311
- }
1312
- /**
1313
- * Returns the ratio between recyclable memory and the used heap area.
1314
- *
1315
- * The metric considers free regions kept in `recycle` as fragmentation
1316
- * and uses `dataPointer` as the denominator. When no bytes have been used
1317
- * by the heap, the result is zero.
1318
- *
1319
- * The value does not represent the fraction of the entire `dataBus` capacity, but
1320
- * specifically the proportion of recyclable bytes within the area already traversed
1321
- * by the bump pointer.
1322
- *
1323
- * @returns {number} Fragmentation ratio in the range [0, 1] under normal
1324
- * operating conditions.
1325
- */
1326
- get fragmentationRatio() {
1327
- if (this.dataPointer === 0) return 0;
1328
- return this.recycleBytes / this.dataPointer;
1329
- }
1330
880
  };
1331
881
  module.exports = { Balloc };