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