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