balloc 1.3.0 → 1.4.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
@@ -90,6 +90,7 @@ const CLAMP_11BITS = 0x7FF >>> 0;
90
90
  * @property {number} generation - 句柄所属的代数(generation)。
91
91
  * @property {number} headerAddress - controlBus 内的标头地址。
92
92
  * @property {number} occupied - 块中已占用的元素数量。
93
+ * @property {number} borrowed - 指示该内存块是否已被 withView() 借用的标志。
93
94
  */
94
95
 
95
96
  /**
@@ -103,6 +104,15 @@ const isTypedArray = (val) => ArrayBuffer.isView(val) && !(val instanceof DataVi
103
104
  /**
104
105
  * 带有 ReBump GC 的 Echo 栈双总线指针碰撞分配器(Dual Bus Bump Allocator)。
105
106
  */
107
+ /**
108
+ * 用于数据导入的同步适配器契约。
109
+ *
110
+ * 适配器接收 Balloc 实例,并使用其公共 API 存储数据,返回用于标识主内存块的句柄。
111
+ *
112
+ * @typedef {Object} FormatAdapter
113
+ * @property {(allocator: Balloc) => number} load - 将数据加载到分配器并返回相应的句柄。
114
+ */
115
+
106
116
  export default class Balloc {
107
117
 
108
118
  /**
@@ -255,12 +265,15 @@ export default class Balloc {
255
265
  const occupied = this.controlAdapter.getUint32(headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
256
266
  const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
257
267
  const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
268
+ const borrowed = this.controlAdapter.getUint8(headerAddress + FLAGS_OFFSET) & VIEW_LOCK;
258
269
 
259
270
  if (cookie !== this.bakeCookie(headerAddress, generation)) {
260
271
  throw new Error("Invalid or corrupted handle");
261
272
  }
262
273
 
263
- this.assertNotBorrowed(headerAddress);
274
+ if (borrowed) {
275
+ throw new Error("Block is borrowed");
276
+ }
264
277
 
265
278
  if (capacity >= 31) throw new AggregateError([new Error("Can´t reallocate handler."), new RangeError("Capacity has reached its limit.")], "Internal Error.");
266
279
 
@@ -307,7 +320,7 @@ export default class Balloc {
307
320
  */
308
321
  shrink(handler) {
309
322
  const meta = this.extractMetadata(handler, this.metadata);
310
- this.assertNotBorrowed(meta.headerAddress);
323
+ if (meta.borrowed) throw new Error("Block is borrowed");
311
324
 
312
325
  const newCapacity = Math.max(1, 32 - Math.clz32(Math.max(2, meta.occupied) - 1));
313
326
  if (newCapacity >= meta.capacityExponent) return;
@@ -338,12 +351,15 @@ export default class Balloc {
338
351
  const dataAddress = this.controlAdapter.getUint32(headerAddress + ADDRESS_OFFSET, IS_LITTLE_ENDIAN);
339
352
  const capacity = this.controlAdapter.getUint8(headerAddress + CAPACITY_OFFSET);
340
353
  const cookie = this.controlAdapter.getUint8(headerAddress + COOKIE_OFFSET);
354
+ const borrowed = this.controlAdapter.getUint8(headerAddress + FLAGS_OFFSET) & VIEW_LOCK;
341
355
 
342
356
  if (cookie !== this.bakeCookie(headerAddress, generation)) {
343
357
  throw new Error("Invalid or corrupted handle");
344
358
  }
345
359
 
346
- this.assertNotBorrowed(headerAddress);
360
+ if (borrowed) {
361
+ throw new Error("Block is borrowed");
362
+ }
347
363
 
348
364
  const blockSize = (1 << capacity >>> 0) * this.wordSize;
349
365
  this.controlAdapter.setUint8(headerAddress + COOKIE_OFFSET, 0);
@@ -533,7 +549,7 @@ export default class Balloc {
533
549
  */
534
550
  push(handler, value) {
535
551
  const meta = this.extractMetadata(handler, this.metadata);
536
- this.assertNotBorrowed(meta.headerAddress);
552
+ if (meta.borrowed) throw new Error("Block is borrowed");
537
553
 
538
554
  if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
539
555
 
@@ -555,7 +571,7 @@ export default class Balloc {
555
571
  */
556
572
  pop(handler) {
557
573
  const meta = this.extractMetadata(handler, this.metadata);
558
- this.assertNotBorrowed(meta.headerAddress);
574
+ if (meta.borrowed) throw new Error("Block is borrowed");
559
575
 
560
576
  if (meta.occupied === 0) return undefined;
561
577
 
@@ -595,7 +611,7 @@ export default class Balloc {
595
611
  */
596
612
  nudge(handler, value) {
597
613
  const meta = this.extractMetadata(handler, this.metadata);
598
- this.assertNotBorrowed(meta.headerAddress);
614
+ if (meta.borrowed) throw new Error("Block is borrowed");
599
615
 
600
616
  if ((meta.occupied + 1) * this.wordSize > meta.byteCapacity) return false;
601
617
 
@@ -619,7 +635,7 @@ export default class Balloc {
619
635
  */
620
636
  pull(handler) {
621
637
  const meta = this.extractMetadata(handler, this.metadata);
622
- this.assertNotBorrowed(meta.headerAddress);
638
+ if (meta.borrowed) throw new Error("Block is borrowed");
623
639
 
624
640
  if (meta.occupied === 0) return undefined;
625
641
 
@@ -750,7 +766,7 @@ export default class Balloc {
750
766
  */
751
767
  set(handler, index, value) {
752
768
  const meta = this.extractMetadata(handler, this.metadata);
753
- this.assertNotBorrowed(meta.headerAddress);
769
+ if (meta.borrowed) throw new Error("Block is borrowed");
754
770
 
755
771
  if (index < 0 || index >= meta.occupied) return false;
756
772
 
@@ -773,7 +789,7 @@ export default class Balloc {
773
789
  */
774
790
  clear(handler, value = 0) {
775
791
  const meta = this.extractMetadata(handler, this.metadata);
776
- this.assertNotBorrowed(meta.headerAddress);
792
+ if (meta.borrowed) throw new Error("Block is borrowed");
777
793
 
778
794
  const slots = meta.byteCapacity / this.wordSize;
779
795
  const rawAddress = meta.dataAddress >>> this.wordShift;
@@ -801,7 +817,7 @@ export default class Balloc {
801
817
  */
802
818
  fill(handler, value, start = 0, end = null) {
803
819
  const meta = this.extractMetadata(handler, this.metadata);
804
- this.assertNotBorrowed(meta.headerAddress);
820
+ if (meta.borrowed) throw new Error("Block is borrowed");
805
821
 
806
822
  const slots = meta.byteCapacity / this.wordSize;
807
823
  const lastIndex = end ?? slots;
@@ -833,7 +849,7 @@ export default class Balloc {
833
849
  */
834
850
  fillAll(handler, value) {
835
851
  const meta = this.extractMetadata(handler, this.metadata);
836
- this.assertNotBorrowed(meta.headerAddress);
852
+ if (meta.borrowed) throw new Error("Block is borrowed");
837
853
 
838
854
  const rawAddress = meta.dataAddress >>> this.wordShift;
839
855
  const capacityElements = meta.byteCapacity / this.wordSize;
@@ -859,7 +875,7 @@ export default class Balloc {
859
875
  */
860
876
  put(handler, data) {
861
877
  const meta = this.extractMetadata(handler, this.metadata);
862
- this.assertNotBorrowed(meta.headerAddress);
878
+ if (meta.borrowed) throw new Error("Block is borrowed");
863
879
 
864
880
  const rawAddress = meta.dataAddress >>> this.wordShift;
865
881
  const length = Math.min(1 << meta.capacityExponent >>> 0, data.length);
@@ -917,37 +933,35 @@ export default class Balloc {
917
933
  */
918
934
  withView(...args) {
919
935
  if (args.length < 2) throw new TypeError("At least one handler and one callback are required");
920
-
921
- const callback = args.pop();
936
+ const lastIndex = args.length - 1;
937
+ const callback = args[lastIndex];
922
938
  if (typeof callback !== "function") throw new TypeError("callback must be a function");
923
939
 
924
- const handlers = args;
925
- const metadata = handlers.map(handler => this.extractMetadata(handler, {}));
926
- const headers = metadata.map(meta => meta.headerAddress);
940
+ const lookup = Object.create(null);
941
+ const acquired = [];
942
+ const views = [];
927
943
 
928
- if (new Set(headers).size !== headers.length) throw new Error("Duplicate handler");
944
+ try {
945
+ for (let i = 0; i < lastIndex; i++) {
946
+ const metadata = this.extractMetadata(args[i], this.metadata);
947
+ const headerAddr = metadata.headerAddress;
929
948
 
930
- const flags = headers.map(header => this.controlBus[header + FLAGS_OFFSET]);
931
949
 
932
- if (flags.some(flag => flag & VIEW_LOCK)) throw new Error("Block is already borrowed");
950
+ if (Object.hasOwn(lookup, headerAddr)) throw new Error("Duplicate handler");
951
+ if (metadata.borrowed) throw new Error("Block is already borrowed");
933
952
 
934
- let acquiredCount = 0;
953
+ this.controlBus[headerAddr + FLAGS_OFFSET] |= VIEW_LOCK;
935
954
 
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
- });
955
+ const rawAddress = metadata.dataAddress >>> this.wordShift;
956
+ lookup[headerAddr] = true;
957
+ acquired.push(headerAddr);
946
958
 
959
+ views.push(this.auxiliary.subarray(rawAddress, rawAddress + metadata.occupied))
960
+ }
947
961
  return callback(...views);
948
962
  } finally {
949
- for (let i = 0; i < acquiredCount; i++) {
950
- this.controlBus[headers[i] + FLAGS_OFFSET] &= ~VIEW_LOCK;
963
+ for (let i = 0; i < acquired.length; i++) {
964
+ this.controlBus[acquired[i] + FLAGS_OFFSET] &= ~VIEW_LOCK;
951
965
  }
952
966
  }
953
967
  }
@@ -1037,7 +1051,7 @@ export default class Balloc {
1037
1051
 
1038
1052
  this.extractMetadata(source, metaA);
1039
1053
  this.extractMetadata(destination, metaB);
1040
- this.assertNotBorrowed(metaB.headerAddress);
1054
+ if (metaB.borrowed) throw new Error("Block is borrowed");
1041
1055
 
1042
1056
  const maxSlotsDest = Math.floor(metaB.byteCapacity / this.wordSize);
1043
1057
  const slotsToCopy = Math.min(metaA.occupied, maxSlotsDest, slots);
@@ -1067,7 +1081,7 @@ export default class Balloc {
1067
1081
  */
1068
1082
  copyWithin(handler, target, start, length) {
1069
1083
  const meta = this.extractMetadata(handler, this.metadata);
1070
- this.assertNotBorrowed(meta.headerAddress);
1084
+ if (meta.borrowed) throw new Error("Block is borrowed");
1071
1085
 
1072
1086
  const slots = Math.floor(meta.byteCapacity / this.wordSize);
1073
1087
  target = Math.trunc(target);
@@ -1114,7 +1128,8 @@ export default class Balloc {
1114
1128
 
1115
1129
  this.extractMetadata(target, metaTarget);
1116
1130
  this.extractMetadata(source, metaSource);
1117
- this.assertNotBorrowed(metaTarget.headerAddress);
1131
+ if (metaTarget.borrowed) throw new Error("Block is borrowed");
1132
+
1118
1133
 
1119
1134
  const available = metaTarget.byteCapacity / this.wordSize - metaTarget.occupied;
1120
1135
  const count = Math.min(available, metaSource.occupied);
@@ -1177,8 +1192,9 @@ export default class Balloc {
1177
1192
  this.extractMetadata(source, metaA);
1178
1193
  this.extractMetadata(target, metaB);
1179
1194
 
1180
- this.assertNotBorrowed(metaA.headerAddress);
1181
- this.assertNotBorrowed(metaB.headerAddress);
1195
+ if (metaA.borrowed) throw new Error("Block is borrowed");
1196
+ if (metaB.borrowed) throw new Error("Block is borrowed");
1197
+
1182
1198
 
1183
1199
  this.controlAdapter.setUint32(metaA.headerAddress + ADDRESS_OFFSET, metaB.dataAddress, IS_LITTLE_ENDIAN);
1184
1200
  this.controlAdapter.setUint32(metaB.headerAddress + ADDRESS_OFFSET, metaA.dataAddress, IS_LITTLE_ENDIAN);
@@ -1289,6 +1305,27 @@ export default class Balloc {
1289
1305
  return handler;
1290
1306
  }
1291
1307
 
1308
+ // ========== 数据集成与导入 ==========
1309
+
1310
+ /**
1311
+ * 通过专用适配器加载数据。
1312
+ *
1313
+ * 适配器接收此实例,并使用其公共 API 分配和填充所需的内存块。
1314
+ * 数据的组织和解释完全由适配器负责;Balloc 仅委托该操作并返回
1315
+ * 适配器生成的句柄。
1316
+ *
1317
+ * 此操作为同步操作。适配器必须在返回前完成数据导入;如果加载
1318
+ * 失败,适配器负责回滚自身的分配。
1319
+ *
1320
+ * @param {FormatAdapter} adapter - 实现 load(allocator) 的适配器。
1321
+ * @returns {number} 适配器返回的句柄。
1322
+ * @throws {TypeError} 适配器未实现 load() 方法时。
1323
+ * @throws {Error} 适配器拒绝所提供的基础设施时。
1324
+ */
1325
+ loadData(adapter) {
1326
+ if (!adapter || typeof adapter.load !== "function") throw new TypeError("adapter must implement load(allocator)");
1327
+ return adapter.load(this);
1328
+ }
1292
1329
  // ============= 工具 (UTILITIES) ==============
1293
1330
 
1294
1331
  /**
@@ -1300,7 +1337,8 @@ export default class Balloc {
1300
1337
  * @returns {void}
1301
1338
  * @throws {Error} 如果块正通过 withView() 被借用。
1302
1339
  * @private
1303
- */
1340
+ * @deprecated
1341
+ */
1304
1342
  assertNotBorrowed(headerAddress) {
1305
1343
  if (this.controlBus[headerAddress + FLAGS_OFFSET] & VIEW_LOCK) {
1306
1344
  throw new Error("Block is borrowed");
@@ -1354,6 +1392,7 @@ export default class Balloc {
1354
1392
  out.capacityExponent = this.controlAdapter.getUint8(out.headerAddress + CAPACITY_OFFSET);
1355
1393
  out.byteCapacity = (1 << out.capacityExponent >>> 0) * this.wordSize;
1356
1394
  out.occupied = this.controlAdapter.getUint32(out.headerAddress + OCCUPIED_OFFSET, IS_LITTLE_ENDIAN);
1395
+ out.borrowed = this.controlAdapter.getUint32(out.headerAddress + FLAGS_OFFSET, IS_LITTLE_ENDIAN) & VIEW_LOCK;
1357
1396
 
1358
1397
  return out;
1359
1398
  }
@@ -24,10 +24,28 @@ export type Metadata = {
24
24
  * - عدد العناصر المشغولة في الكتلة.
25
25
  */
26
26
  occupied: number;
27
+ /**
28
+ * - علامة تشير إلى ما إذا كانت الكتلة قد أُعيرت بواسطة withView().
29
+ */
30
+ borrowed: number;
31
+ };
32
+ export type FormatAdapter = {
33
+ /**
34
+ * - يحمّل البيانات إلى المخصّص ويعيد المعالج المقابل.
35
+ */
36
+ load: (allocator: Balloc) => number;
27
37
  };
28
38
  /**
29
39
  * مخصص الذاكرة المتقاطع ذو الحافتين مع مكدس صدى وإدارة النفايات ReBump.
30
40
  */
41
+ /**
42
+ * عقد محوّل متزامن لإدخال البيانات.
43
+ *
44
+ * يتلقى المحوّل نسخة Balloc ويستخدم واجهتها العامة لتخزين البيانات، ثم يعيد المعالج الذي يحدد الكتلة الرئيسية.
45
+ *
46
+ * @typedef {Object} FormatAdapter
47
+ * @property {(allocator: Balloc) => number} load - يحمّل البيانات إلى المخصّص ويعيد المعالج المقابل.
48
+ */
31
49
  export default class Balloc {
32
50
  wordType: BucketType;
33
51
  bucketType: string;
@@ -638,6 +656,22 @@ export default class Balloc {
638
656
  * @throws {Error} إذا كان نوع كلمة البيانات المفككة يختلف عن المُكوّن في المخصص.
639
657
  */
640
658
  load(serialized: Uint8Array | ArrayBuffer): number;
659
+ /**
660
+ * يحمّل البيانات من خلال محوّل متخصص.
661
+ *
662
+ * يتلقى المحوّل هذا المثيل ويستخدم واجهته العامة لتخصيص الكتل المطلوبة
663
+ * وملئها. تقع مسؤولية تنظيم البيانات وتفسيرها بالكامل على عاتق المحوّل؛
664
+ * أما Balloc فيفوّض العملية فقط ويعيد المعالج الناتج.
665
+ *
666
+ * العملية متزامنة. يجب على المحوّل إكمال إدخال البيانات قبل الإرجاع،
667
+ * وهو مسؤول عن التراجع عن تخصيصاته إذا فشلت عملية التحميل.
668
+ *
669
+ * @param {FormatAdapter} adapter - محوّل يطبّق load(allocator).
670
+ * @returns {number} المعالج الذي يعيده المحوّل.
671
+ * @throws {TypeError} إذا لم يطبّق المحوّل الدالة load().
672
+ * @throws {Error} إذا رفض المحوّل البنية التحتية المقدمة.
673
+ */
674
+ loadData(adapter: FormatAdapter): number;
641
675
  /**
642
676
  * يمنع عمليات التعديل على كتلة معارة.
643
677
  *
@@ -647,7 +681,8 @@ export default class Balloc {
647
681
  * @returns {void}
648
682
  * @throws {Error} إذا كانت الكتلة معارة بواسطة withView().
649
683
  * @private
650
- */
684
+ * @deprecated
685
+ */
651
686
  private assertNotBorrowed;
652
687
  /**
653
688
  * يمنع العمليات التي تستبدل أو تعيد تعيين dataBus
@@ -24,10 +24,28 @@ export type Metadata = {
24
24
  * - Number of occupied elements in the block.
25
25
  */
26
26
  occupied: number;
27
+ /**
28
+ * - Flag indicating whether the block has been borrowed by withView().
29
+ */
30
+ borrowed: number;
31
+ };
32
+ export type FormatAdapter = {
33
+ /**
34
+ * - Loads data into the allocator and returns the corresponding handler.
35
+ */
36
+ load: (allocator: Balloc) => number;
27
37
  };
28
38
  /**
29
39
  * Echo Stack Dual Bus Bump Allocator with ReBump GC.
30
40
  */
41
+ /**
42
+ * Synchronous adapter contract for data ingestion.
43
+ *
44
+ * The adapter receives the Balloc instance and uses its public API to store data, returning the handler that identifies the primary block.
45
+ *
46
+ * @typedef {Object} FormatAdapter
47
+ * @property {(allocator: Balloc) => number} load - Loads data into the allocator and returns the corresponding handler.
48
+ */
31
49
  export default class Balloc {
32
50
  wordType: BucketType;
33
51
  bucketType: string;
@@ -664,6 +682,24 @@ export default class Balloc {
664
682
  * @throws {Error} If the decoded data's word type differs from the allocator's configuration.
665
683
  */
666
684
  load(serialized: Uint8Array | ArrayBuffer): number;
685
+ /**
686
+ * Loads data through a specialized adapter.
687
+ *
688
+ * The adapter receives this instance and uses its public API to allocate
689
+ * and populate the required blocks. Data organization and interpretation
690
+ * are the adapter's sole responsibility; Balloc only delegates the
691
+ * operation and returns the resulting handler.
692
+ *
693
+ * The operation is synchronous. The adapter must complete ingestion before
694
+ * returning and is responsible for reverting its own allocations if
695
+ * loading fails.
696
+ *
697
+ * @param {FormatAdapter} adapter - Adapter implementing load(allocator).
698
+ * @returns {number} Handler returned by the adapter.
699
+ * @throws {TypeError} If the adapter does not implement load().
700
+ * @throws {Error} If the adapter rejects the subscribed infrastructure.
701
+ */
702
+ loadData(adapter: FormatAdapter): number;
667
703
  /**
668
704
  * Prevents modification operations on a borrowed block.
669
705
  *
@@ -673,7 +709,8 @@ export default class Balloc {
673
709
  * @returns {void}
674
710
  * @throws {Error} If the block is borrowed via withView().
675
711
  * @private
676
- */
712
+ * @deprecated
713
+ */
677
714
  private assertNotBorrowed;
678
715
  /**
679
716
  * Prevents operations that replace or remap the dataBus
@@ -24,10 +24,28 @@ export type Metadata = {
24
24
  * - Número de elementos ocupados en el bloque.
25
25
  */
26
26
  occupied: number;
27
+ /**
28
+ * - Indicador de si el bloque ha sido prestado por withView().
29
+ */
30
+ borrowed: number;
31
+ };
32
+ export type FormatAdapter = {
33
+ /**
34
+ * - Carga los datos en el asignador y devuelve el handler correspondiente.
35
+ */
36
+ load: (allocator: Balloc) => number;
27
37
  };
28
38
  /**
29
39
  * Asignador tipo Bump de doble bus con pila de eco y recolección de basura ReBump.
30
40
  */
41
+ /**
42
+ * Contrato de un adaptador síncrono para la ingesta de datos.
43
+ *
44
+ * El adaptador recibe la instancia de Balloc y utiliza su API pública para almacenar los datos, devolviendo el handler que identifica el bloque principal.
45
+ *
46
+ * @typedef {Object} FormatAdapter
47
+ * @property {(allocator: Balloc) => number} load - Carga los datos en el asignador y devuelve el handler correspondiente.
48
+ */
31
49
  export default class Balloc {
32
50
  wordType: BucketType;
33
51
  bucketType: string;
@@ -652,6 +670,24 @@ export default class Balloc {
652
670
  * @throws {Error} Si el tipo de palabra del dato decodificado difiere del configurado en el asignador.
653
671
  */
654
672
  load(serialized: Uint8Array | ArrayBuffer): number;
673
+ /**
674
+ * Carga datos mediante un adaptador especializado.
675
+ *
676
+ * El adaptador recibe esta instancia y utiliza su API pública para asignar
677
+ * y completar los bloques necesarios. La organización y la interpretación
678
+ * de los datos son responsabilidad exclusiva del adaptador; Balloc solo
679
+ * delega la operación y devuelve el handler resultante.
680
+ *
681
+ * La operación es síncrona. El adaptador debe completar la ingesta antes
682
+ * de retornar y es responsable de revertir sus propias asignaciones si
683
+ * ocurre un error durante la carga.
684
+ *
685
+ * @param {FormatAdapter} adapter - Adaptador que implementa load(allocator).
686
+ * @returns {number} Handler devuelto por el adaptador.
687
+ * @throws {TypeError} Si el adaptador no implementa el método load().
688
+ * @throws {Error} Si el adaptador rechaza la infraestructura suscrita.
689
+ */
690
+ loadData(adapter: FormatAdapter): number;
655
691
  /**
656
692
  * Impide operaciones de modificación sobre un bloque prestado.
657
693
  *
@@ -661,7 +697,8 @@ export default class Balloc {
661
697
  * @returns {void}
662
698
  * @throws {Error} Si el bloque está prestado mediante `withView()`.
663
699
  * @private
664
- */
700
+ * @deprecated
701
+ */
665
702
  private assertNotBorrowed;
666
703
  /**
667
704
  * Impide operaciones que reemplazan o reasignan el `dataBus`
@@ -24,10 +24,28 @@ export type Metadata = {
24
24
  * - ブロック内の占有要素数。
25
25
  */
26
26
  occupied: number;
27
+ /**
28
+ * - ブロックが withView() によって借用されているかどうかを示すフラグ。
29
+ */
30
+ borrowed: number;
31
+ };
32
+ export type FormatAdapter = {
33
+ /**
34
+ * - アロケーターにデータを読み込み、対応するハンドラーを返します。
35
+ */
36
+ load: (allocator: Balloc) => number;
27
37
  };
28
38
  /**
29
39
  * ReBump GCを備えたEcho Stackデュアルバス・バンプアロケータ。
30
40
  */
41
+ /**
42
+ * データ取り込み用の同期アダプター契約。
43
+ *
44
+ * アダプターは Balloc インスタンスを受け取り、その公開 API を使用してデータを格納し、主要ブロックを識別するハンドラーを返します。
45
+ *
46
+ * @typedef {Object} FormatAdapter
47
+ * @property {(allocator: Balloc) => number} load - アロケーターにデータを読み込み、対応するハンドラーを返します。
48
+ */
31
49
  export default class Balloc {
32
50
  wordType: BucketType;
33
51
  bucketType: string;
@@ -601,6 +619,24 @@ export default class Balloc {
601
619
  * @throws {Error} デコードされたデータのワード型がアロケータの設定と異なる場合。
602
620
  */
603
621
  load(serialized: Uint8Array | ArrayBuffer): number;
622
+ /**
623
+ * 専用アダプターを通じてデータを読み込みます。
624
+ *
625
+ * アダプターはこのインスタンスを受け取り、その公開 API を使用して
626
+ * 必要なブロックを割り当て、データを書き込みます。データの構成と
627
+ * 解釈はアダプターのみが担当し、Balloc は処理を委譲して生成された
628
+ * ハンドラーを返します。
629
+ *
630
+ * この操作は同期的に実行されます。アダプターは戻る前にデータの
631
+ * 取り込みを完了し、読み込みに失敗した場合は自身の割り当てを
632
+ * 元に戻す責任を負います。
633
+ *
634
+ * @param {FormatAdapter} adapter - load(allocator) を実装するアダプター。
635
+ * @returns {number} アダプターが返すハンドラー。
636
+ * @throws {TypeError} アダプターが load() メソッドを実装していない場合。
637
+ * @throws {Error} アダプターが指定されたインフラストラクチャを拒否した場合。
638
+ */
639
+ loadData(adapter: FormatAdapter): number;
604
640
  /**
605
641
  * 借用中のブロックに対する変更操作を禁止します。
606
642
  *
@@ -610,7 +646,8 @@ export default class Balloc {
610
646
  * @returns {void}
611
647
  * @throws {Error} ブロックが withView() によって借用されている場合。
612
648
  * @private
613
- */
649
+ * @deprecated
650
+ */
614
651
  private assertNotBorrowed;
615
652
  /**
616
653
  * いずれかのセグメントが借用されている間、dataBus を置き換える
@@ -24,7 +24,28 @@ export type Metadata = {
24
24
  * - Número de elementos ocupados no bloco.
25
25
  */
26
26
  occupied: number;
27
+ /**
28
+ * - Flag indicando se o foi o bloco foi emprestado por withView().
29
+ */
30
+ borrowed: number;
31
+ };
32
+ export type FormatAdapter = {
33
+ /**
34
+ * - Carrega os dados no alocador
35
+ * e retorna o handler correspondente.
36
+ */
37
+ load: (allocator: Balloc) => number;
27
38
  };
39
+ /**
40
+ * Contrato de um adaptador síncrono para ingestão de dados.
41
+ *
42
+ * O adaptador recebe a instância do Balloc e utiliza sua API pública para
43
+ * armazenar os dados, retornando o handler que identifica o bloco principal.
44
+ *
45
+ * @typedef {Object} FormatAdapter
46
+ * @property {(allocator: Balloc) => number} load - Carrega os dados no alocador
47
+ * e retorna o handler correspondente.
48
+ */
28
49
  /**
29
50
  * Echo Stack Dual Bus Bump Allocator with ReBump GC.
30
51
  */
@@ -657,6 +678,25 @@ export default class Balloc {
657
678
  */
658
679
  load(serialized: Uint8Array | ArrayBuffer): number;
659
680
  /**
681
+ * Carrega dados por meio de um adaptador especializado.
682
+ *
683
+ * O adaptador recebe esta instância e utiliza sua API pública para alocar
684
+ * e preencher os blocos necessários. A organização e a interpretação dos
685
+ * dados são responsabilidade exclusiva do adaptador; o Balloc apenas
686
+ * delega a operação e retorna o handler produzido.
687
+ *
688
+ * A operação é síncrona. O adaptador deve concluir a ingestão antes de
689
+ * retornar e é responsável por reverter suas próprias alocações caso
690
+ * ocorra uma falha durante o carregamento.
691
+ *
692
+ * @param {FormatAdapter} adapter - Adaptador que implementa load(allocator).
693
+ * @returns {number} Handler retornado pelo adaptador.
694
+ * @throws {TypeError} Se o adaptador não implementar o método load().
695
+ * @throws {Error} Se o adaptador recusar a infraestrutura subscrita.
696
+ */
697
+ loadData(adapter: FormatAdapter): number;
698
+ /**
699
+ * [OBSOLETO]
660
700
  * Impede operações de modificação sobre um bloco emprestado.
661
701
  *
662
702
  * Verifica a flag VIEW_LOCK no header associado ao endereço informado.
@@ -664,6 +704,7 @@ export default class Balloc {
664
704
  * @param {number} headerAddress - Endereço do header no controlBus.
665
705
  * @returns {void}
666
706
  * @throws {Error} Se o bloco estiver emprestado por withView().
707
+ * @deprecated
667
708
  * @private
668
709
  */
669
710
  private assertNotBorrowed;
@@ -24,10 +24,28 @@ export type Metadata = {
24
24
  * - 块中已占用的元素数量。
25
25
  */
26
26
  occupied: number;
27
+ /**
28
+ * - 指示该内存块是否已被 withView() 借用的标志。
29
+ */
30
+ borrowed: number;
31
+ };
32
+ export type FormatAdapter = {
33
+ /**
34
+ * - 将数据加载到分配器并返回相应的句柄。
35
+ */
36
+ load: (allocator: Balloc) => number;
27
37
  };
28
38
  /**
29
39
  * 带有 ReBump GC 的 Echo 栈双总线指针碰撞分配器(Dual Bus Bump Allocator)。
30
40
  */
41
+ /**
42
+ * 用于数据导入的同步适配器契约。
43
+ *
44
+ * 适配器接收 Balloc 实例,并使用其公共 API 存储数据,返回用于标识主内存块的句柄。
45
+ *
46
+ * @typedef {Object} FormatAdapter
47
+ * @property {(allocator: Balloc) => number} load - 将数据加载到分配器并返回相应的句柄。
48
+ */
31
49
  export default class Balloc {
32
50
  wordType: BucketType;
33
51
  bucketType: string;
@@ -559,6 +577,22 @@ export default class Balloc {
559
577
  * @throws {Error} 如果解码数据的字类型与分配器配置的不一致。
560
578
  */
561
579
  load(serialized: Uint8Array | ArrayBuffer): number;
580
+ /**
581
+ * 通过专用适配器加载数据。
582
+ *
583
+ * 适配器接收此实例,并使用其公共 API 分配和填充所需的内存块。
584
+ * 数据的组织和解释完全由适配器负责;Balloc 仅委托该操作并返回
585
+ * 适配器生成的句柄。
586
+ *
587
+ * 此操作为同步操作。适配器必须在返回前完成数据导入;如果加载
588
+ * 失败,适配器负责回滚自身的分配。
589
+ *
590
+ * @param {FormatAdapter} adapter - 实现 load(allocator) 的适配器。
591
+ * @returns {number} 适配器返回的句柄。
592
+ * @throws {TypeError} 适配器未实现 load() 方法时。
593
+ * @throws {Error} 适配器拒绝所提供的基础设施时。
594
+ */
595
+ loadData(adapter: FormatAdapter): number;
562
596
  /**
563
597
  * 防止对已借用的块进行修改操作。
564
598
  *
@@ -568,7 +602,8 @@ export default class Balloc {
568
602
  * @returns {void}
569
603
  * @throws {Error} 如果块正通过 withView() 被借用。
570
604
  * @private
571
- */
605
+ * @deprecated
606
+ */
572
607
  private assertNotBorrowed;
573
608
  /**
574
609
  * 防止在存在任何借用片段时替换或重新映射 dataBus 的操作。