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