balloc 0.0.0-stage → 1.0.1

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.
@@ -0,0 +1,1262 @@
1
+ import { encode, decode } from 'cbor-x';
2
+
3
+ /**
4
+ * 表示无效或未知值的标志。
5
+ */
6
+ const UNKNOWN = 0xFFFFFFFF >>> 0;
7
+
8
+ /**
9
+ * 有效的桶大小和类型。
10
+ * 整数类型仅支持 8、16、32 和 64 位大小,
11
+ * 浮点数类型仅支持 16、32 和 64 位大小。
12
+ * 支持的数据类型:
13
+ * u = 无符号整数 (unsigned integer)
14
+ * i = 有符号整数 (signed integer)
15
+ * f = 浮点数 (float)
16
+ *
17
+ * 桶标识符语法:
18
+ *
19
+ * [位数][数据类型]
20
+ *
21
+ * 示例:
22
+ * 32位无符号整数桶:32u
23
+ * 64位有符号整数桶:64i
24
+ *
25
+ */
26
+ const BUCKET_MAPPING = Object.freeze({
27
+ "8u": { type: "Uint8", bits: 8 },
28
+ "16u": { type: "Uint16", bits: 16 },
29
+ "32u": { type: "Uint32", bits: 32 },
30
+ "64u": { type: "BigUint64", bits: 64 },
31
+ "8i": { type: "Int8", bits: 8 },
32
+ "16i": { type: "Int16", bits: 16 },
33
+ "32i": { type: "Int32", bits: 32 },
34
+ "64i": { type: "BigInt64", bits: 64 },
35
+ "16f": { type: "Float16", bits: 16 },
36
+ "32f": { type: "Float32", bits: 32 },
37
+ "64f": { type: "Float64", bits: 64 }
38
+ });
39
+
40
+ /**
41
+ * 分配器支持的桶类型:
42
+ * - 无符号整数:'8u', '16u', '32u', '64u'
43
+ * - 有符号整数:'8i', '16i', '32i', '64i'
44
+ * - 浮点数:'16f', '32f', '64f'
45
+ *
46
+ * @typedef {'8u'|'16u'|'32u'|'64u'|'8i'|'16i'|'32i'|'64i'|'16f'|'32f'|'64f'} BucketType
47
+ */
48
+
49
+ /**
50
+ * 系统字节序(Endianness)标志。
51
+ *
52
+ * 检测系统是否为小端字节序(Little Endian),这会影响
53
+ * DataView 操作中的字节顺序。
54
+ */
55
+ const IS_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
56
+
57
+
58
+ /**
59
+ * 元数据格式。
60
+ * 0 4 8 9 10
61
+ * [32bits address][32bits occupied][8bits capacity][8bits cookie][48bits reserved]
62
+ *
63
+ * 总计:4 + 4 + 1 + 1 + 6 = 16 字节
64
+ */
65
+ const HEADER_SIZE = 16 >>> 0;
66
+
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
+
72
+
73
+ const ROTATE_32BITS = 4294967296;
74
+ const CLAMP_11BITS = 0x7FF >>> 0;
75
+
76
+ /**
77
+ * 包含在句柄中编码的元数据的结构。
78
+ *
79
+ * @typedef {Object} Metadata
80
+ * @property {number} byteCapacity - 内存块的容量(以字节为单位)。
81
+ * @property {number} capacityExponent - 以二为底的指数形式表示的内存块容量。
82
+ * @property {number} dataAddress - dataBus 内的内存块地址。
83
+ * @property {number} generation - 句柄所属的代(generation)。
84
+ * @property {number} headerAddress - controlBus 内的标头地址。
85
+ * @property {number} occupied - 块中已占用的元素数量。
86
+ */
87
+
88
+ /**
89
+ * 检查值是否为 TypedArray 的实例。
90
+ *
91
+ * @param {any} val - 要测试的值。
92
+ * @returns {boolean} 如果该值是 TypedArray 则为 `true`,否则为 `false`。
93
+ */
94
+ const isTypedArray = (val) => ArrayBuffer.isView(val) && !(val instanceof DataView);
95
+
96
+ /**
97
+ * 带有 ReBump GC 的回显栈双总线 Bump 分配器(Echo Stack Dual Bus Bump Allocator with ReBump GC)。
98
+ */
99
+ export default class Balloc {
100
+
101
+ /**
102
+ * 创建 `Balloc` 内存分配器的实例。
103
+ *
104
+ * 该分配器维护两个独立的缓冲区:
105
+ * - `dataBus`:存储已分配块的数据;
106
+ * - `controlBus`:存储标头及其他控制元数据。
107
+ *
108
+ * 每个块都有一个固定大小的标头(`HEADER_SIZE`),并由一个 43 位逻辑句柄
109
+ * 在外部进行标识,该句柄由 11 位的代和 32 位的标头地址组成。
110
+ *
111
+ * 每个块的容量会按元素向上取整到下一个二的幂,同时遵循配置的桶宽度。
112
+ *
113
+ * @param {number} [size=65535] - `dataBus` 的初始容量(以字节为单位)。
114
+ * 必须是范围在 [2, 0x80000000] 内的安全整数。
115
+ * @param {BucketType} [bucketSize="32u"] - 桶类型和大小标识符
116
+ * (例如:'32u' 表示 Uint32,'64f' 表示 Float64,'8i' 表示 Int8)。
117
+ * @param {number} [metadataSize=1024] - `controlBus` 的初始容量(以字节为单位)。
118
+ * 必须是范围在 [HEADER_SIZE, 0x80000000] 内的安全整数。
119
+ *
120
+ * @throws {RangeError} 如果 `size` 超出允许范围。
121
+ * @throws {RangeError} 如果 `bucketSize` 不是有效的桶标识符。
122
+ * @throws {RangeError} 如果 `metadataSize` 超出允许范围。
123
+ */
124
+ constructor(size = 65535, bucketSize = "32u", metadataSize = 1024) {
125
+
126
+ if (!Number.isSafeInteger(size) || size < 2 || size > 0x80000000) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
127
+
128
+
129
+ if (!BUCKET_MAPPING[bucketSize]) {
130
+ throw new RangeError(`bucketSize must be in ([ 8 || 16 || 32 || 64][ u || i ]) || ([ 16 || 32 || 64][ f ]) but I found ${bucketSize}`);
131
+ }
132
+
133
+ 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}`);
134
+
135
+ this.wordType = bucketSize;
136
+ this.bucketType = BUCKET_MAPPING[bucketSize].type;
137
+ this.bucketSize = BUCKET_MAPPING[bucketSize].bits >>> 0;
138
+ this.bucketArray = globalThis[`${this.bucketType}Array`];
139
+ this.wordSize = this.bucketSize >>> 3;
140
+ this.wordShift = this.bucketSize >>> 4;
141
+ this.size = Math.max(1 << (32 - Math.clz32(size)) >>> 0, this.wordSize);
142
+ this.headerSize = 1 << (32 - Math.clz32(metadataSize)) >>> 0;
143
+ this.dataPointer = 0 >>> 0;
144
+ this.controlPointer = 0 >>> 0;
145
+ this.echoPointer = 0 >>> 0;
146
+ this.generation = 0 >>> 0;
147
+ this.dataBus = new Uint8Array(this.size);
148
+ this.controlBus = new Uint8Array(this.headerSize);
149
+ this.dataAdapter = new DataView(this.dataBus.buffer);
150
+ this.controlAdapter = new DataView(this.controlBus.buffer);
151
+ this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
152
+ this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
153
+ this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
154
+ this.recycle = new Map();
155
+
156
+ /** @type {Metadata} */
157
+ this.metadata = {
158
+ generation: 0 >>> 0,
159
+ headerAddress: 0 >>> 0,
160
+ dataAddress: 0 >>> 0,
161
+ capacityExponent: 0 >>> 0,
162
+ byteCapacity: 0 >>> 0,
163
+ occupied: 0 >>> 0,
164
+ };
165
+
166
+ }
167
+
168
+ // ========== 分配 (ALLOCATION) ==========
169
+
170
+ /**
171
+ * 分配一个新的内存块。
172
+ *
173
+ * 请求的容量会被转换为能够容纳 `size` 个元素的最小二的幂。
174
+ * 该块优先从具有相应容量的可回收区域列表中获取;如果不存在兼容的区域,
175
+ * 则在 `dataBus` 的顶部保留该块。
176
+ *
177
+ * 接下来,从控制空间获取一个标头。先前释放的标头可以通过内部回收栈进行重用;
178
+ * 否则,会在必要时扩展 `controlBus`。
179
+ *
180
+ * 标头会接收地址、容量、初始占用数(零)以及验证 Cookie。
181
+ * 返回的值对分配代数和标头地址进行编码:
182
+ *
183
+ * [11 位代数][32 位标头地址]
184
+ *
185
+ * @param {number} [size=16] - 块必须容纳的最小元素数量。
186
+ * 必须是范围在 [2, 0x80000000] 内的安全整数。
187
+ * @returns {number} 标识已分配块的句柄。
188
+ * @throws {RangeError} 如果 `size` 超出允许范围。
189
+ */
190
+ alloc(size = 16) {
191
+ if (!Number.isSafeInteger(size) || size < 2 || size > 0x80000000) throw new RangeError(`Parameter size must be in range [2, 0x80000000] but size is ${size}`);
192
+
193
+
194
+ const capacity = (32 - Math.clz32(size - 1));
195
+ const blockSize = (1 << capacity >>> 0) * this.wordSize;
196
+
197
+ let dataAddress = this.recyclePop(blockSize);
198
+
199
+ if (dataAddress === UNKNOWN) {
200
+ while (this.dataPointer + blockSize > this.size) this.grow();
201
+ dataAddress = this.dataPointer;
202
+ this.dataPointer += blockSize;
203
+ }
204
+
205
+ let headerAddress = 0 >>> 0;
206
+
207
+ if (this.echoPointer > this.controlPointer) {
208
+ this.echoPointer -= 4;
209
+ headerAddress = this.controlAdapter.getUint32(this.echoPointer, IS_LITTLE_ENDIAN);
210
+ } else {
211
+ if (this.controlPointer + HEADER_SIZE > this.controlAdapter.byteLength) this.headerGrow();
212
+ headerAddress = this.controlPointer;
213
+ this.controlPointer+= HEADER_SIZE;
214
+ this.echoPointer+= HEADER_SIZE;
215
+ }
216
+
217
+ this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, dataAddress, IS_LITTLE_ENDIAN);
218
+ this.controlAdapter.setUint32(headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
219
+ this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, capacity);
220
+ this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, this.bakeCookie(headerAddress, ++this.generation));
221
+
222
+ return (this.generation & CLAMP_11BITS) * ROTATE_32BITS + headerAddress;
223
+ }
224
+
225
+ /**
226
+ * 将块的容量扩展到下一个二的幂。
227
+ *
228
+ * 当块位于 `dataBus` 的当前顶部时,扩展以就地(in-place)方式发生:
229
+ * 仅更新其容量和 `dataPointer`。
230
+ *
231
+ * 如果块之后存在其他区域,则从可回收空间中获取或在 `dataBus` 顶部
232
+ * 分配一个容量加倍的新区域。随后,当前占用的元素将被复制到新区域中,
233
+ * 并且先前的区域被归还给回收列表。
234
+ *
235
+ * 句柄保持有效,因为它的标头得到了保留,并且仅更新了其中记录的地址和容量。
236
+ *
237
+ * @param {number} handler - 要扩展的块的句柄。
238
+ * @returns {void}
239
+ * @throws {Error} 如果句柄无效或已损坏。
240
+ * @throws {AggregateError} 如果容量已达到其支持的最大限制。
241
+ */
242
+ realloc(handler) {
243
+ const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
244
+ let headerAddress = handler >>> 0;
245
+
246
+ const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
247
+ const occupied = this.controlAdapter.getUint32(headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
248
+ const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
249
+ const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
250
+
251
+
252
+ if (cookie !== this.bakeCookie(headerAddress, generation)) {
253
+ throw new Error("Invalid or corrupted handle");
254
+ }
255
+
256
+ if (capacity >= 31) throw new AggregateError([new Error("Can´t reallocate handler.") ,new RangeError("Capacity has reached its limit.")], "Internal Error.");
257
+
258
+ const newCapacity = capacity + 1;
259
+ const newBlockSize = (1 << newCapacity >>> 0) * this.wordSize;
260
+ const oldBlockSize = (1 << capacity >>> 0) * this.wordSize;
261
+
262
+ if (dataAddress + oldBlockSize === this.dataPointer) {
263
+ while (dataAddress + newBlockSize > this.size) this.grow();
264
+
265
+ this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity, IS_LITTLE_ENDIAN);
266
+ this.dataPointer = dataAddress + newBlockSize;
267
+
268
+ return;
269
+ }
270
+
271
+ this.recyclePush(oldBlockSize, dataAddress);
272
+
273
+ let newAddress = this.recyclePop(newBlockSize);
274
+
275
+ if (newAddress === UNKNOWN) {
276
+ while (this.dataPointer + newBlockSize > this.size) this.grow();
277
+
278
+ newAddress = this.dataPointer;
279
+ this.dataPointer += newBlockSize;
280
+ }
281
+
282
+ this.controlAdapter.setUint8(headerAddress + CAPACITY_OFFSET, newCapacity);
283
+ this.dataBus.copyWithin(newAddress, dataAddress, dataAddress + occupied * this.wordSize);
284
+
285
+ this.controlAdapter.setUint32(headerAddress + ADDRESS_OFFSET, newAddress, IS_LITTLE_ENDIAN);
286
+ }
287
+
288
+ /**
289
+ * 释放内存块。
290
+ *
291
+ * 通过将块的 Cookie 清零来使其标头失效,并记录其地址以便后续重用。
292
+ * 数据区域也会被归还给回收系统,但块精确处于 `dataBus` 顶部的情况除外;
293
+ * 在这种情况下,只需回退 `dataPointer` 即可消除该区域,而无需在回收列表中创建条目。
294
+ *
295
+ * @param {number} handler - 要释放的块的句柄。
296
+ * @returns {void}
297
+ * @throws {Error} 如果句柄无效或已损坏。
298
+ */
299
+ free(handler) {
300
+ const generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
301
+ let headerAddress = handler >>> 0;
302
+
303
+ const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
304
+ const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
305
+ const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
306
+
307
+
308
+ if (cookie !== this.bakeCookie(headerAddress, generation)) {
309
+ throw new Error("Invalid or corrupted handle");
310
+ }
311
+
312
+ const blockSize = (1 << capacity >>> 0) * this.wordSize;
313
+
314
+ this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
315
+
316
+ if (this.echoPointer + 4 <= this.controlBus.byteLength) {
317
+ this.controlAdapter.setUint32(this.echoPointer, headerAddress, IS_LITTLE_ENDIAN);
318
+ this.echoPointer += 4;
319
+ }
320
+
321
+
322
+ if (dataAddress + blockSize === this.dataPointer) {
323
+ this.dataPointer = dataAddress;
324
+ } else {
325
+ this.recyclePush(blockSize, dataAddress);
326
+ }
327
+
328
+ }
329
+
330
+ // ========== 回收 (RECYCLING) ==========
331
+
332
+ /**
333
+ * [内部使用]
334
+ * 将空闲区域插入回收列表。
335
+ *
336
+ * 该列表按字节容量进行组织。对于每个容量,存储的值是一个 `Uint32Array`,
337
+ * 其零位置包含已注册地址的数量,后续位置包含空闲区域的地址:
338
+ *
339
+ * [count, address1, address2, ...]
340
+ *
341
+ * 当页面填满时,其缓冲区会扩展为当前容量的两倍。
342
+ *
343
+ * @param {number} capacity - 空闲区域的容量(以字节为单位)。
344
+ * @param {number} address - `dataBus` 中区域的起始地址。
345
+ * @returns {void}
346
+ * @private
347
+ */
348
+ recyclePush(capacity, address) {
349
+ if (this.recycle.has(capacity)) {
350
+ let page = this.recycle.get(capacity);
351
+ const count = page[0];
352
+
353
+ if (count === page.length - 1) {
354
+ const newBuffer = page.buffer.transfer(page.buffer.byteLength * 2);
355
+ page = new Uint32Array(newBuffer);
356
+ this.recycle.set(capacity, page);
357
+ }
358
+
359
+ page[count + 1] = address;
360
+ page[0] = count + 1;
361
+ } else {
362
+ this.recycle.set(capacity, new Uint32Array([1, address]));
363
+ }
364
+ }
365
+
366
+ /**
367
+ * [内部使用]
368
+ * 从回收列表中移除空闲区域。
369
+ *
370
+ * 通过请求的确切容量进行搜索。当存在对应的页面时,
371
+ * 从页面中移除最后一个注册的地址并将其返回,从而将回收实现为 LIFO 栈。
372
+ *
373
+ * @param {number} capacity - 所需的容量(以字节为单位)。
374
+ * @returns {number} 可回收区域的起始地址,如果不存在具有请求容量的区域则返回 `UNKNOWN`。
375
+ * @private
376
+ */
377
+ recyclePop(capacity) {
378
+ if (!this.recycle.has(capacity)) return UNKNOWN;
379
+
380
+ const page = this.recycle.get(capacity);
381
+ const count = page[0];
382
+
383
+ if (count === 0) return UNKNOWN;
384
+
385
+ const address = page[count];
386
+ page[0] = count - 1;
387
+
388
+ return address;
389
+ }
390
+
391
+ // ========== 垃圾回收 (GARBAGE COLLECTION) ==========
392
+ /**
393
+ * 使用 ReBump 算法对 `dataBus` 进行压缩。
394
+ *
395
+ * 顺序遍历 `controlBus` 中注册的标头,并将仍然有效的区域复制到新的 `dataBus` 中,
396
+ * 从而消除它们之间存在的空闲空间。每个存活块的地址在其各自的标头中得到更新。
397
+ *
398
+ * `controlBus` 中块的顺序得以保留。每个块的内部数据也完全得以保留,
399
+ * 包括其预留的容量和当前的占用数。
400
+ *
401
+ * 压缩结束时:
402
+ * - 所有可回收区域均被消除;
403
+ * - `dataPointer` 指向最后一个存活块之后的第一个字节;
404
+ * - `dataBus` 表现为活动块的连续堆(heap)。
405
+ *
406
+ * 控制复杂度为 O(n),其中 `n` 是遍历的标头数量。
407
+ * 内存移动的有效成本还取决于属于存活块的字节量。
408
+ *
409
+ * @returns {void}
410
+ */
411
+ gc() {
412
+ const newDataBus = new Uint8Array(this.dataBus.buffer.byteLength);
413
+ this.recycle.clear();
414
+ this.dataPointer = 0 >>> 0;
415
+ for (let i = 0; i < this.controlPointer; i+= HEADER_SIZE) {
416
+ if (this.controlBus[i + COOKIE_OFFSET] === 0) continue;
417
+ const start = this.controlAdapter.getUint32(i + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
418
+ const size = (1 << this.controlBus[i + CAPACITY_OFFSET] >>> 0) * this.wordSize;
419
+ const end = start + size;
420
+ newDataBus.set(this.dataBus.subarray(start, end), this.dataPointer);
421
+ this.controlAdapter.setUint32(i + ADDRESS_OFFSET, this.dataPointer, IS_LITTLE_ENDIAN);
422
+ this.dataPointer += size;
423
+ }
424
+ this.dataBus = newDataBus;
425
+ this.dataAdapter = new DataView(this.dataBus.buffer);
426
+ this.auxiliary = new globalThis[`${this.bucketType}Array`](this.dataBus.buffer);
427
+ this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
428
+ this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
429
+ }
430
+
431
+ // ========== 扩容 (SCALING) ==========
432
+ /**
433
+ * [!!! 内部使用,请勿在您的代码中使用 !!!]
434
+ * 将 `dataBus` 的容量扩展为其当前容量的两倍。
435
+ *
436
+ * 底层缓冲区被传输到更大的 `ArrayBuffer` 中,同时保留现有数据。
437
+ * 与该缓冲区关联的所有视图都会被重新创建以引用新的存储空间。
438
+ *
439
+ * @returns {void}
440
+ * @throws {RangeError} 如果 `dataBus` 容量超出支持的最大限制。
441
+ * @private
442
+ */
443
+ grow() {
444
+ if (this.size > 0x80000000) throw new RangeError("Data bus capacity exceeded");
445
+
446
+ const newSize = (this.size * 2) >>> 0;
447
+ const newBuffer = this.dataBus.buffer.transfer(newSize);
448
+
449
+ this.size = newSize;
450
+ this.dataBus = new Uint8Array(newBuffer);
451
+ this.dataAdapter = new DataView(newBuffer);
452
+ this.writer = this.dataAdapter[`set${this.bucketType}`].bind(this.dataAdapter);
453
+ this.reader = this.dataAdapter[`get${this.bucketType}`].bind(this.dataAdapter);
454
+ this.auxiliary = new this.bucketArray(newBuffer);
455
+ }
456
+
457
+ /**
458
+ * [!!! 内部使用,请勿在您的代码中使用 !!!]
459
+ * 将 `controlBus` 的容量扩展为其当前容量的两倍。
460
+ *
461
+ * 底层缓冲区被传输到更大的 `ArrayBuffer` 中,同时保留现有标头。
462
+ * 重新创建 `controlAdapter` 以引用新的存储空间。
463
+ *
464
+ * @returns {void}
465
+ * @throws {RangeError} 如果当前 `controlBus` 容量超出支持的最大限制。
466
+ * @private
467
+ */
468
+ headerGrow() {
469
+ if (this.controlBus.byteLength > 0x80000000) throw new RangeError("Control bus capacity exceeded");
470
+ const newSize = (this.controlBus.byteLength * 2) >>> 0;
471
+ const newBuffer = this.controlBus.buffer.transfer(newSize);
472
+
473
+ this.controlBus = new Uint8Array(newBuffer);
474
+ this.controlAdapter = new DataView(newBuffer);
475
+ }
476
+
477
+ // ========== 栈操作 (STACK OPERATIONS) ==========
478
+
479
+ /**
480
+ * 将元素追加到块所占用序列的末尾。
481
+ *
482
+ * 该元素写入最后一个已占用元素之后的第一个空闲位置。
483
+ * 只有在其容量中有可用空间时,才会增加块的占用数。
484
+ *
485
+ * @param {number} handler - 块句柄。
486
+ * @param {number} value - 要插入的值。
487
+ * @returns {boolean} 如果成功插入值则为 `true`;如果块没有可用空间则为 `false`。
488
+ * @throws {Error} 如果句柄无效或已损坏。
489
+ */
490
+ push(handler, value) {
491
+
492
+ const meta = this.extractMetadata(handler, this.metadata);
493
+
494
+ if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
495
+
496
+ this.writer(meta.dataAddress + meta.occupied * this.wordSize , value, IS_LITTLE_ENDIAN);
497
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1,IS_LITTLE_ENDIAN);
498
+
499
+ return true;
500
+ }
501
+
502
+ /**
503
+ * 移除并返回块中最后占用的元素。
504
+ *
505
+ * 在读取被移除的元素之前,占用数会递减。对应的字节不会被清空,
506
+ * 仍留在分配的区域中,但不再属于占用的序列。
507
+ *
508
+ * @param {number} handler - 块句柄。
509
+ * @returns {number|undefined} 被移除的值,如果块为空则返回 `undefined`。
510
+ * @throws {Error} 如果句柄无效或已损坏。
511
+ */
512
+ pop(handler) {
513
+ const meta = this.extractMetadata(handler, this.metadata);
514
+
515
+ if (meta.occupied === 0) return undefined;
516
+
517
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1,IS_LITTLE_ENDIAN);
518
+ return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
519
+ }
520
+
521
+ /**
522
+ * 返回最后占用的元素而不将其移除。
523
+ *
524
+ * @param {number} handler - 块句柄。
525
+ * @returns {number|undefined} 最后占用的值,如果块为空则返回 `undefined`。
526
+ * @throws {Error} 如果句柄无效或已损坏。
527
+ */
528
+ peek(handler) {
529
+ const meta = this.extractMetadata(handler, this.metadata);
530
+
531
+ if (meta.occupied === 0) return undefined;
532
+
533
+ return this.reader(meta.dataAddress + (meta.occupied - 1) * this.wordSize, IS_LITTLE_ENDIAN);
534
+ }
535
+
536
+ // ========== 队列操作 (QUEUE OPERATIONS) ==========
537
+
538
+ /**
539
+ * 在占用序列的开头插入一个元素。
540
+ *
541
+ * 当前占用的元素向前移动一个位置,并将 `value` 写入第一个位置。
542
+ * 该操作要求块的容量中有空闲位置。
543
+ *
544
+ * 该操作的成本与占用元素的数量成正比,因为需要移动数据。
545
+ *
546
+ * @param {number} handler - 块句柄。
547
+ * @param {number} value - 要插入的值。
548
+ * @returns {boolean} 如果成功插入值则为 `true`;如果块已满则为 `false`。
549
+ * @throws {Error} 如果句柄无效或已损坏。
550
+ */
551
+ nudge(handler, value) {
552
+ const meta = this.extractMetadata(handler, this.metadata);
553
+
554
+ if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
555
+
556
+ this.dataBus.copyWithin(meta.dataAddress + this.wordSize, meta.dataAddress, meta.dataAddress + meta.occupied * this.wordSize);
557
+ this.writer(meta.dataAddress, value, IS_LITTLE_ENDIAN);
558
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied + 1,IS_LITTLE_ENDIAN);
559
+
560
+ return true;
561
+ }
562
+
563
+ /**
564
+ * 移除并返回块中第一个占用的元素。
565
+ *
566
+ * 剩余元素向占用区域的开头方向移动一个位置。块的物理容量保持不变。
567
+ *
568
+ * 该操作的成本与移动的元素数量成正比。
569
+ *
570
+ * @param {number} handler - 块句柄。
571
+ * @returns {number|undefined} 第一个被移除的值,如果块为空则返回 `undefined`。
572
+ * @throws {Error} 如果句柄无效或已损坏。
573
+ */
574
+ pull(handler) {
575
+ const meta = this.extractMetadata(handler, this.metadata);
576
+
577
+ if (meta.occupied === 0) return undefined;
578
+
579
+ const result = this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
580
+ this.dataBus.copyWithin(meta.dataAddress, meta.dataAddress + this.wordSize, meta.dataAddress + meta.occupied * this.wordSize);
581
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied - 1, IS_LITTLE_ENDIAN);
582
+ return result;
583
+ }
584
+
585
+ /**
586
+ * 返回第一个占用的元素而不将其移除。
587
+ *
588
+ * @param {number} handler - 块句柄。
589
+ * @returns {number|undefined} 第一个占用的值,如果块为空则返回 `undefined`。
590
+ * @throws {Error} 如果句柄无效或已损坏。
591
+ */
592
+ head(handler) {
593
+ const meta = this.extractMetadata(handler, this.metadata);
594
+
595
+ if (meta.occupied === 0) return undefined;
596
+
597
+ return this.reader(meta.dataAddress, IS_LITTLE_ENDIAN);
598
+ }
599
+
600
+ // ========== 随机访问 (RANDOM ACCESS) ==========
601
+
602
+ /**
603
+ * 检查某个值是否存在于块的占用元素中。
604
+ *
605
+ * 该搜索直接在辅助 `TypedArray` 上执行,并且仅考虑当前占用的范围,
606
+ * 而不是整个预留的物理容量。
607
+ *
608
+ * @param {number} handler - 块句柄。
609
+ * .@param {number} value - 要寻找的值。
610
+ * @returns {boolean} 如果 `value` 存在于占用元素中则为 `true`;否则为 `false`。
611
+ * @throws {Error} 如果句柄无效或已损坏。
612
+ */
613
+ has(handler, value) {
614
+ const meta = this.extractMetadata(handler, this.metadata);
615
+
616
+ if (meta.occupied === 0) return false;
617
+
618
+ const rawAddres = meta.dataAddress >>> this.wordShift;
619
+
620
+ return this.auxiliary.subarray(rawAddres, rawAddres + meta.occupied).includes(value);
621
+ }
622
+
623
+ /**
624
+ * 返回基于零的索引处的占用元素。
625
+ *
626
+ * 超出范围 `[0, occupied)` 的索引不被视为错误,会返回 `undefined`。
627
+ *
628
+ * @param {number} handler - 块句柄。
629
+ * @param {number} index - 元素的基于零的索引。
630
+ * @returns {number|undefined} 存储在索引处的值,如果索引超出占用区域则返回 `undefined`。
631
+ * @throws {Error} 如果句柄无效或已损坏。
632
+ */
633
+ get(handler, index) {
634
+
635
+ const meta = this.extractMetadata(handler, this.metadata);
636
+
637
+ if (index < 0 || index >= meta.occupied) return undefined;
638
+
639
+ return this.reader(meta.dataAddress + index * this.wordSize, IS_LITTLE_ENDIAN);
640
+ }
641
+
642
+ /**
643
+ * 替换存储在已占用索引处的值。
644
+ *
645
+ * 该操作不会改变块的占用数。超出范围 `[0, occupied)` 的索引会被忽略并返回 `false`。
646
+ *
647
+ * @param {number} handler - 块句柄。
648
+ * @param {number} index - 元素的基于零的索引。
649
+ * @param {number} value - 新值。
650
+ * @returns {boolean} 如果成功写入值则为 `true`;如果索引超出占用区域则为 `false`。
651
+ * @throws {Error} 如果句柄无效或已损坏。
652
+ */
653
+ set(handler, index, value) {
654
+ const meta = this.extractMetadata(handler, this.metadata);
655
+
656
+ if (index < 0 || index >= meta.occupied) return false;
657
+
658
+ this.writer(meta.dataAddress + index * this.wordSize, value, IS_LITTLE_ENDIAN);
659
+ return true;
660
+ }
661
+
662
+ // ============= 杂项 (MISCELLANEOUS) ===============
663
+
664
+ /**
665
+ * 清零块的占用数,并用相同的值填充其整个物理容量。
666
+ *
667
+ * 填充涵盖所有可用的槽位(slots),而不仅仅是当前占用的元素。
668
+ * 操作完成后,无论填充时使用什么值,该块都被视为是空的。
669
+ *
670
+ * @param {number} handler - 块句柄。
671
+ * @param {number} [value=0] - 用于填充所有槽位的值。
672
+ * @returns {void}
673
+ * @throws {Error} 如果句柄无效或已损坏。
674
+ */
675
+ clear(handler, value=0) {
676
+ const meta = this.extractMetadata(handler, this.metadata);
677
+
678
+ const slots = meta.byteCapacity / this.wordSize;
679
+ const rawAddress = meta.dataAddress >>> this.wordShift;
680
+
681
+ this.auxiliary.fill(value, rawAddress, rawAddress + slots);
682
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, 0, IS_LITTLE_ENDIAN);
683
+ }
684
+
685
+
686
+ /**
687
+ * 用某个值填充块的一段槽位范围。
688
+ *
689
+ * 该范围使用基于零的索引,并遵循 `[start, end)` 惯例,
690
+ * 因此 `start` 是包含的(inclusive),而 `end` 是排他的(exclusive)。
691
+ * 当未指定 `end` 时,填充会延伸到块物理容量的末尾。
692
+ *
693
+ * 块的占用数变为 `end`,即使填充的范围超出了先前的占用数也是如此。
694
+ *
695
+ * @param {number} handler - 块句柄。
696
+ * @param {number} value - 用于填充的值。
697
+ * @param {number} [start=0] - 起始索引,包含。
698
+ * @param {number|null} [end=null] - 结束索引,排他。当省略或为 `null` 时,
699
+ * 使用块的总容量。
700
+ * @returns {void}
701
+ * @throws {Error} 如果句柄无效或已损坏。
702
+ * @throws {RangeError} 如果 `start` 或 `end` 超出容量边界,或者 `start > end`。
703
+ */
704
+ fill(handler, value, start = 0, end = null) {
705
+ const meta = this.extractMetadata(handler, this.metadata);
706
+
707
+ const slots = meta.byteCapacity / this.wordSize;
708
+ const lastIndex = end ?? slots;
709
+
710
+ if (start > lastIndex) {
711
+ throw new RangeError(`start ${start} must be less or equal than end ${lastIndex}.`);
712
+ }
713
+ if (start < 0 || start > slots) {
714
+ throw new RangeError(`start ${start} out of range [0, ${slots}].`);
715
+ }
716
+ if (lastIndex < 0 || lastIndex > slots) {
717
+ throw new RangeError(`end ${lastIndex} out of range [0, ${slots}].`);
718
+ }
719
+
720
+ const rawAddress = meta.dataAddress >>> this.wordShift;
721
+
722
+ this.auxiliary.fill(value, rawAddress + start, rawAddress + lastIndex);
723
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, lastIndex, IS_LITTLE_ENDIAN);
724
+ }
725
+
726
+ /**
727
+ * 用一个值填充块的所有物理槽位,并将整个容量标记为已占用。
728
+ *
729
+ * 与 `clear()` 不同,该操作会产生一个完全被占用的块。
730
+ *
731
+ * @param {number} handler - 块句柄。
732
+ * @param {number} value - 用于填充的值。
733
+ * @returns {void}
734
+ * @throws {Error} 如果句柄无效或已损坏。
735
+ */
736
+ fillAll(handler, value) {
737
+ const meta = this.extractMetadata(handler, this.metadata);
738
+
739
+ const rawAddress = meta.dataAddress >>> this.wordShift;
740
+ const capacityElements = meta.byteCapacity / this.wordSize;
741
+
742
+ this.auxiliary.fill(value, rawAddress, rawAddress + capacityElements);
743
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, capacityElements, IS_LITTLE_ENDIAN);
744
+ }
745
+
746
+ /**
747
+ * 将 `Array` 或 `TypedArray` 的元素复制到块的开头。
748
+ *
749
+ * 复制的数量受块容量的限制。占用数更新为先前占用数与实际复制数量中的较大值;
750
+ * 因此,当接收到较小的序列时,调用 `put()` 不会减少现有的占用数。
751
+ *
752
+ * 对于 `Array`,仅复制能装下的前几个元素。
753
+ * 对于 `TypedArray`,使用源的子数组(subarray),无需中间复制。
754
+ *
755
+ * @param {number} handler - 块句柄。
756
+ * @param {Array|TypedArray} data - 要复制的值序列。
757
+ * @returns {void}
758
+ * @throws {Error} 如果句柄无效或已损坏。
759
+ * @throws {TypeError} 如果 `data` 既不是 `Array` 也不是 `TypedArray`。
760
+ */
761
+ put(handler, data) {
762
+ const meta = this.extractMetadata(handler, this.metadata);
763
+
764
+ const rawAddress = meta.dataAddress >>> this.wordShift;
765
+ const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
766
+
767
+ meta.occupied = Math.max(length, meta.occupied);
768
+
769
+ if (Array.isArray(data)) {
770
+ this.auxiliary.set(data.slice(0, length), rawAddress);
771
+ } else if (isTypedArray(data)) {
772
+ this.auxiliary.set(data.subarray(0, length), rawAddress);
773
+ } else {
774
+ const actual = data?.constructor?.name ?? (data === null ? 'null' : typeof data);
775
+ throw new TypeError(`data must be Array or TypedArray, but ${actual} was given.`);
776
+ }
777
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
778
+ }
779
+
780
+ /**
781
+ * 返回块当前占用元素的副本。
782
+ *
783
+ * 结果是由 `bucketSize` 配置的同类型 `TypedArray`。未占用的物理容量不包含在结果中。
784
+ *
785
+ * 该操作不直接暴露内部存储:该方法使用 `TypedArray.prototype.slice()`,
786
+ * 产生一个具有独立存储的新视图。
787
+ *
788
+ * @param {number} handler - 块句柄。
789
+ * @returns {TypedArray} 块占用的元素副本。当块为空时,返回配置类型的空 `TypedArray`。
790
+ * @throws {Error} 如果句柄无效或已损坏。
791
+ */
792
+ pick(handler) {
793
+ const meta = this.extractMetadata(handler, this.metadata);
794
+
795
+ const rawAddress = meta.dataAddress >>> this.wordShift;
796
+
797
+ if (meta.occupied === 0) {
798
+ return this.auxiliary.slice(rawAddress, rawAddress);
799
+ }
800
+
801
+ return this.auxiliary.slice(rawAddress, rawAddress + meta.occupied);
802
+ }
803
+
804
+ // ======== 按槽位计算的容量 (CAPACITY IN SLOTS) ==========
805
+
806
+ /**
807
+ * 返回块以字节为单位的物理容量。
808
+ *
809
+ * 容量对应于为块中所有槽位预留的空间,无论当前占用了多少元素。
810
+ *
811
+ * @param {number} handler - 块句柄。
812
+ * @returns {number} 块的物理容量(以字节为单位)。
813
+ * @throws {Error} 如果句柄无效或已损坏。
814
+ */
815
+ byteSize(handler) {
816
+ const meta = this.extractMetadata(handler, this.metadata);
817
+ return meta.byteCapacity;
818
+ }
819
+
820
+ /**
821
+ * 返回块中当前占用的元素数量。
822
+ *
823
+ * @param {number} handler - 块句柄。
824
+ * @returns {number} 已占用元素的数量。
825
+ * @throws {Error} 如果句柄无效或已损坏。
826
+ */
827
+ occupied(handler){
828
+ const meta = this.extractMetadata(handler, this.metadata);
829
+ return meta.occupied;
830
+
831
+ }
832
+
833
+ /**
834
+ * 返回以元素数量计算的块容量。
835
+ *
836
+ * 该值对应物理预留槽位的总数,而不是当前占用的数量。
837
+ *
838
+ * @param {number} handler - 块句柄。
839
+ * @returns {number} 块中可用的槽位总数。
840
+ * @throws {Error} 如果句柄无效或已损坏。
841
+ */
842
+ length(handler) {
843
+ const meta = this.extractMetadata(handler, this.metadata);
844
+ return 1 << meta.capacityExponent >>> 0;
845
+ }
846
+
847
+ // ========== 块间操作 (Inter-block Operations) =============
848
+
849
+ /**
850
+ * 将占用的元素从一个块复制到另一个块。
851
+ *
852
+ * 复制从 `source` 的第一个元素和 `destiny` 的第一个槽位开始。
853
+ * 实际复制的数量受源中占用元素数量、目标物理容量以及 `slots` 中指定的限制所限制。
854
+ *
855
+ * 必要时会增加目标的占用数以涵盖复制的元素。目标的容量保持不变。
856
+ *
857
+ * 该操作在 `dataBus` 上使用 `Uint8Array.prototype.copyWithin()`,
858
+ * 因此返回值为表示数据总线的 `Uint8Array` 本身。
859
+ *
860
+ * @param {number} source - 源块句柄。
861
+ * @param {number} destiny - 目标块句柄。
862
+ * @param {number} [slots=UNKNOWN] - 要复制的最大元素数量。
863
+ * `UNKNOWN` 表示不施加额外限制所使用的哨兵值。
864
+ * @returns {Uint8Array} 操作后的 `dataBus`。
865
+ * @throws {Error} 如果 `source` 或 `destiny` 无效或已损坏。
866
+ */
867
+ copy(source, destiny, slots = UNKNOWN){
868
+ /** @type {Metadata} */
869
+ const metaA = {};
870
+ /** @type {Metadata} */
871
+ const metaB = {};
872
+
873
+ this.extractMetadata(source, metaA);
874
+ this.extractMetadata(destiny, metaB);
875
+
876
+ const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
877
+ const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
878
+ const newOccupied = Math.max(metaB.occupied, slotsToCopy);
879
+
880
+ this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
881
+
882
+ return this.dataBus.copyWithin(metaB.dataAddress, metaA.dataAddress, metaA.dataAddress + slotsToCopy * this.wordSize);
883
+ }
884
+
885
+ /**
886
+ * 在块内部复制一段元素区域。
887
+ *
888
+ * 索引基于零并遵循 `Array.prototype.copyWithin()` 的语义:
889
+ * `target` 标识目标位置,`start` 标识源起始位置,`length` 标识要复制的最大元素数量。
890
+ *
891
+ * 负索引从块容量的末尾开始解释。完成此规范化后,索引将被限制在物理容量之内。
892
+ * 复制的数量也受实际占用元素以及从 `target` 开始的可用空间的限制。
893
+ *
894
+ * 该操作支持重叠区域,并且当目标范围超过当前占用数时可以增加块的占用数。
895
+ *
896
+ * @param {number} handler - 块句柄。
897
+ * @param {number} target - 起始目标索引。
898
+ * @param {number} start - 起始源索引。
899
+ * @param {number} length - 要复制的最大元素数量。
900
+ * @returns {Uint8Array} 操作后的 `dataBus`。
901
+ * @throws {Error} 如果句柄无效或已损坏。
902
+ */
903
+ copyWithin(handler, target, start, length) {
904
+ const meta = this.extractMetadata(handler, this.metadata);
905
+ const slots = Math.floor(meta.byteCapacity / this.wordSize);
906
+
907
+ target = Math.trunc(target);
908
+ start = Math.trunc(start);
909
+ length = Math.trunc(length);
910
+
911
+ if (target < 0) target += slots;
912
+ if (start < 0) start += slots;
913
+
914
+ // 将索引限制在容量范围内
915
+ target = Math.max(0, Math.min(target, slots));
916
+ start = Math.max(0, Math.min(start, slots));
917
+
918
+ // 将复制限制在从 target 开始的可用空间
919
+ // 以及从 start 开始的实际占用元素
920
+ const maxRead = Math.max(0, meta.occupied - start);
921
+ const maxWrite = slots - target;
922
+ length = Math.max(0, Math.min(length, maxRead, maxWrite));
923
+
924
+ if (length === 0) return this.dataBus;
925
+
926
+ const targetAddress = meta.dataAddress + target * this.wordSize;
927
+ const sourceAddress = meta.dataAddress + start * this.wordSize;
928
+
929
+ // 如果复制扩展了块的占用顶部,则更新占用数
930
+ const newOccupied = Math.max(meta.occupied, target + length);
931
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, newOccupied, IS_LITTLE_ENDIAN);
932
+
933
+ return this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + length * this.wordSize);
934
+ }
935
+
936
+ /**
937
+ * 将 `source` 的占用元素追加到 `target` 的末尾。
938
+ *
939
+ * 复制的数量受源中占用元素数量以及目标容量中剩余可用空间的限制。
940
+ *
941
+ * 该操作支持 `target` 和 `source` 引用同一个块。
942
+ * 在这种情况下,复制在块自己的区域上执行,并保留 `copyWithin()` 的重叠语义。
943
+ *
944
+ * @param {number} target - 将接收元素的块句柄。
945
+ * @param {number} source - 其元素将被追加的块句柄。
946
+ * @returns {number} 实际追加的元素数量。
947
+ * @throws {Error} 如果 `target` 或 `source` 无效或已损坏。
948
+ */
949
+ append(target, source) {
950
+ const metaTarget = {};
951
+ const metaSource = {};
952
+
953
+ this.extractMetadata(target, metaTarget);
954
+ this.extractMetadata(source, metaSource);
955
+
956
+ const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
957
+ const count = Math.min(available, metaSource.occupied);
958
+
959
+ if (count === 0) return 0;
960
+
961
+ const targetAddress = metaTarget.dataAddress + metaTarget.occupied * this.wordSize;
962
+ const sourceAddress = metaSource.dataAddress;
963
+
964
+ if (target === source) {
965
+ this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
966
+ } else {
967
+ this.dataBus.copyWithin(targetAddress, sourceAddress, sourceAddress + count * this.wordSize);
968
+ }
969
+
970
+ this.controlAdapter.setUint32(metaTarget.headerAddress + OCCUPIED_OFFSET, metaTarget.occupied + count, IS_LITTLE_ENDIAN);
971
+
972
+ return count;
973
+ }
974
+
975
+ /**
976
+ * 创建块的独立副本。
977
+ *
978
+ * 新块具有与原始块相同的物理容量和占用数。
979
+ * 预留区域中的所有字节(包括当前未占用的位置)都会被复制。
980
+ *
981
+ * 新块会获得一个新句柄,并受常规分配和回收规则的约束。
982
+ *
983
+ * @param {number} handler - 要克隆的块的句柄。
984
+ * @returns {number} 新块的句柄。
985
+ * @throws {Error} 如果句柄无效或已损坏。
986
+ */
987
+ clone(handler) {
988
+ const meta = this.extractMetadata(handler, this.metadata);
989
+ const cloned = this.alloc(meta.byteCapacity / this.wordSize);
990
+
991
+ const cloneMeta = {};
992
+ this.extractMetadata(cloned, cloneMeta);
993
+
994
+ this.dataBus.copyWithin(cloneMeta.dataAddress, meta.dataAddress, meta.dataAddress + meta.byteCapacity);
995
+ this.controlAdapter.setUint32(cloneMeta.headerAddress + OCCUPIED_OFFSET, meta.occupied, IS_LITTLE_ENDIAN);
996
+
997
+ return cloned;
998
+ }
999
+
1000
+ /**
1001
+ * 交换与两个块关联的数据区域。
1002
+ *
1003
+ * 该操作在标头之间交换区域地址、容量和占用数。句柄保持不变:
1004
+ * 操作后,每个句柄继续标识其自己的标头,但该标头现在描述的是先前属于另一个块的区域。
1005
+ *
1006
+ * `dataBus` 中不复制任何数据;仅修改两个标头的元数据。
1007
+ *
1008
+ * @param {number} source - 第一个块的句柄。
1009
+ * @param {number} target - 第二个块的句柄。
1010
+ * @returns {void}
1011
+ * @throws {Error} 如果 `source` 或 `target` 无效或已损坏。
1012
+ */
1013
+ swap(source, target) {
1014
+ /** @type {Metadata} */
1015
+ const metaA = {};
1016
+ /** @type {Metadata} */
1017
+ const metaB = {};
1018
+
1019
+ this.extractMetadata(source, metaA);
1020
+ this.extractMetadata(target, metaB);
1021
+
1022
+ this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
1023
+ this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
1024
+
1025
+ this.controlAdapter.setUint8(metaA.headerAddress + CAPACITY_OFFSET, metaB.capacityExponent);
1026
+ this.controlAdapter.setUint8(metaB.headerAddress + CAPACITY_OFFSET, metaA.capacityExponent);
1027
+
1028
+ this.controlAdapter.setUint32(metaA.headerAddress + OCCUPIED_OFFSET, metaB.occupied, IS_LITTLE_ENDIAN);
1029
+ this.controlAdapter.setUint32(metaB.headerAddress + OCCUPIED_OFFSET, metaA.occupied, IS_LITTLE_ENDIAN);
1030
+ }
1031
+
1032
+
1033
+ // ============= 序列化 (SERIALIZATION) ==============
1034
+
1035
+ /**
1036
+ * 序列化内存块的内容和元数据。
1037
+ *
1038
+ * 该方法通过 `pick()` 提取块的占用数据,将其与容量和单词类型信息一起
1039
+ * 组合到数据信封(envelope)中,并使用 CBOR 格式对其进行编码。
1040
+ *
1041
+ * @param {number} handler - 要序列化的块的句柄。
1042
+ * @returns {Uint8Array} 包含序列化块数据的缓冲区。
1043
+ * @throws {Error} 如果句柄无效或已损坏。
1044
+ */
1045
+ dump(handler) {
1046
+ const meta = this.extractMetadata(handler, this.metadata);
1047
+ const capacity = meta.capacityExponent;
1048
+ const capacityElements = 2 ** capacity;
1049
+
1050
+ if (!Number.isInteger(capacity) || capacity < 1 || capacity > 31 || meta.occupied > capacityElements) {
1051
+ throw new Error("Cannot serialize a block with invalid metadata");
1052
+ }
1053
+
1054
+ const payload = this.pick(handler);
1055
+
1056
+ if (payload.length !== meta.occupied || payload.constructor !== this.bucketArray) {
1057
+ throw new Error("Cannot serialize a block with an invalid payload");
1058
+ }
1059
+
1060
+ return encode({
1061
+ v: 1,
1062
+ wordType: this.wordType,
1063
+ capacity,
1064
+ occupied: meta.occupied,
1065
+ le: IS_LITTLE_ENDIAN,
1066
+ payload
1067
+ });
1068
+ }
1069
+
1070
+ /**
1071
+ * 从序列化数据恢复内存块。
1072
+ *
1073
+ * 解码 CBOR 信封,验证序列化数据的单词类型是否与当前分配器实例兼容,
1074
+ * 并分配一个容纳内容所需容量的新块。然后,在的新块中恢复原始数据和占用数。
1075
+ *
1076
+ * @param {Uint8Array|ArrayBuffer} serialized - 包含序列化数据的缓冲区。
1077
+ * @returns {number} 重新创建的新块的句柄。
1078
+ * @throws {Error} 如果解码数据的单词类型与分配器中配置的不同。
1079
+ */
1080
+ load(serialized) {
1081
+ if (!(serialized instanceof ArrayBuffer) && !(serialized instanceof Uint8Array)) {
1082
+ throw new TypeError("serialized must be an ArrayBuffer or Uint8Array");
1083
+ }
1084
+
1085
+ const envelope = decode(serialized);
1086
+
1087
+ if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)) {
1088
+ throw new TypeError("Invalid serialized block envelope");
1089
+ }
1090
+
1091
+ if (envelope.v !== 1) {
1092
+ throw new Error(`Unsupported serialized block version: ${envelope.v}`);
1093
+ }
1094
+
1095
+ if (envelope.wordType !== this.wordType) {
1096
+ throw new Error(`Can't load data, ${this.wordType} expected but ${envelope.wordType} found.`);
1097
+ }
1098
+
1099
+ if (!Number.isInteger(envelope.capacity) || envelope.capacity < 1 || envelope.capacity > 31) {
1100
+ throw new RangeError("Invalid serialized block capacity");
1101
+ }
1102
+
1103
+ const capacityElements = 2 ** envelope.capacity;
1104
+
1105
+ if (!Number.isSafeInteger(envelope.occupied) || envelope.occupied < 0 || envelope.occupied > capacityElements) {
1106
+ throw new RangeError("Invalid serialized block occupancy");
1107
+ }
1108
+
1109
+ if (typeof envelope.le !== "boolean") {
1110
+ throw new TypeError("Invalid serialized endianness flag");
1111
+ }
1112
+
1113
+ const payload = envelope.payload;
1114
+
1115
+ if (!isTypedArray(payload) || payload.constructor !== this.bucketArray || payload.length !== envelope.occupied) {
1116
+ throw new TypeError(`Invalid payload: expected ${this.bucketType}Array with ${envelope.occupied} elements`);
1117
+ }
1118
+
1119
+ if (payload.BYTES_PER_ELEMENT !== this.wordSize || payload.byteLength !== envelope.occupied * this.wordSize) {
1120
+ throw new TypeError("Serialized payload has an invalid element size");
1121
+ }
1122
+
1123
+ const handler = this.alloc(capacityElements);
1124
+ const meta = this.extractMetadata(handler, this.metadata);
1125
+ this.put(handler, payload);
1126
+ this.controlAdapter.setUint32(meta.headerAddress + OCCUPIED_OFFSET, envelope.occupied, IS_LITTLE_ENDIAN);
1127
+
1128
+ return handler;
1129
+ }
1130
+
1131
+ // ============= 工具 (UTILITIES) ==============
1132
+
1133
+ /**
1134
+ * [内部使用]
1135
+ * 解码与句柄关联的元数据。
1136
+ *
1137
+ * 句柄被拆分为代和标头地址。然后重新计算标头中存储的 Cookie 以验证组合;
1138
+ * 只有在此验证之后才会读取元数据。
1139
+ *
1140
+ * 解码后的字段被写入 `out` 对象中,该对象由函数自身返回。
1141
+ * 可以在多次调用之间重用该对象以避免新的分配。
1142
+ *
1143
+ * @param {number} handler - 要解码和验证的句柄。
1144
+ * @param {Metadata} out - 将接收解码元数据的对象。
1145
+ * @returns {Metadata} 在 `out` 中提供的相同引用。
1146
+ * @throws {Error} 如果标头 Cookie 与句柄不匹配,或者句柄未标识有效的标头。
1147
+ * @private
1148
+ */
1149
+ extractMetadata(handler, out) {
1150
+ out.generation = (handler / ROTATE_32BITS) & CLAMP_11BITS;
1151
+ out.headerAddress = handler >>> 0;
1152
+
1153
+ const cookie = this.controlAdapter.getUint8(out.headerAddress + COOKIE_OFFSET);
1154
+
1155
+
1156
+ if (cookie !== this.bakeCookie(out.headerAddress, out.generation)) {
1157
+ throw new Error("Invalid or corrupted handle");
1158
+ }
1159
+
1160
+ out.dataAddress = this.controlAdapter.getUint32(out.headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
1161
+ out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1162
+ out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
1163
+ out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
1164
+
1165
+ return out;
1166
+ }
1167
+
1168
+
1169
+ /**
1170
+ * [内部使用]
1171
+ * 计算标头的验证 Cookie。
1172
+ *
1173
+ * Cookie 通过快速哈希(fast hash)由标头地址和 11 位代数派生而来。
1174
+ * 结果被缩减为 8 位。
1175
+ *
1176
+ * 零值保留为无效标头指示符;因此,当计算产生零时,该方法返回 `1`。
1177
+ *
1178
+ * Cookie 不构成加密机制。其目的是在分配器的内存管理模型中
1179
+ * 检测无效、过时(stale)或损坏的句柄。
1180
+ *
1181
+ * @param {number} addr - 标头地址。
1182
+ * @param {number} gen - 与句柄关联的代。仅考虑最低的 11 位。
1183
+ * @returns {number} 范围在 [1, 255] 内的 8 位 Cookie。
1184
+ * @private
1185
+ */
1186
+ bakeCookie(addr, gen) {
1187
+ return (addr ^ (gen & 0x7FF * 0x9e3779b1)) & 0xff || 1;
1188
+ }
1189
+
1190
+ /**
1191
+ * 返回当前存储在回收列表中的区域数量。
1192
+ *
1193
+ * 每个区域对应一个无法直接归还给 `dataBus`顶部的已释放块,
1194
+ * 因此保留下来以便未来容量相同的分配进行重用。
1195
+ *
1196
+ * @returns {number} `recycle` 中维护的空闲区域数量。
1197
+ */
1198
+ recycleCount() {
1199
+ let count = 0;
1200
+
1201
+ for (const [, page] of this.recycle) {
1202
+ count += page[0];
1203
+ }
1204
+
1205
+ return count;
1206
+ }
1207
+
1208
+ /**
1209
+ * 返回当前存储在回收列表中的区域所属的字节总数。
1210
+ *
1211
+ * 该值通过将每个空闲区域的容量乘以针对该容量注册的区域数量相加来计算。
1212
+ *
1213
+ * @returns {number} 可回收区域占用的字节数。
1214
+ */
1215
+ get recycleBytes() {
1216
+ let total = 0;
1217
+
1218
+ for (const [capacity, page] of this.recycle) {
1219
+ total += page[0] * capacity;
1220
+ }
1221
+
1222
+ return total;
1223
+ }
1224
+
1225
+ /**
1226
+ * 返回不属于当前可回收区域的已分配字节数。
1227
+ *
1228
+ * 该值通过从 `dataPointer` 的总推进量中减去 `recycle` 中维护的空闲区域所属的字节来获得。
1229
+ *
1230
+ * @returns {number} `dataBus` 已使用区域内与不可回收区域关联的字节数。
1231
+ */
1232
+ get allocatedBytes() {
1233
+ return this.dataPointer - this.recycleBytes;
1234
+ }
1235
+
1236
+ /**
1237
+ * 返回 `dataBus` 顶部尚未使用的字节数。
1238
+ *
1239
+ * 此空间对应于 `dataPointer` 与当前为缓冲区预留容量末尾之间的区域。
1240
+ * @returns {number} `dataPointer` 之后的可用字节数。
1241
+ */
1242
+ get unallocatedBytes() {
1243
+ return this.size - this.dataPointer;
1244
+ }
1245
+
1246
+ /**
1247
+ * 返回可回收内存与已使用堆区域之间的比率。
1248
+ *
1249
+ * 该指标将 `recycle` 中维护的空闲区域视为碎片化,并使用 `dataPointer` 作为分母。
1250
+ * 当堆未曾使用任何字节时,结果为零。
1251
+ *
1252
+ * 该值不代表整个 `dataBus` 容量的分数,而是具体表示 bump 指针已遍历区域内
1253
+ * 可回收字节的比例。
1254
+ *
1255
+ * @returns {number} 在正常运行条件下的 [0, 1] 范围内的碎片化比率。
1256
+ */
1257
+ get fragmentationRatio() {
1258
+ if (this.dataPointer === 0) return 0;
1259
+ return this.recycleBytes / this.dataPointer;
1260
+ }
1261
+
1262
+ }