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