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.
@@ -15,27 +15,27 @@
15
15
 
16
16
  ```text
17
17
  Balloc
18
- ├── Instanciamento
18
+ ├── التهيئة
19
19
  │ └── constructor()
20
20
  │
21
- ├── Ciclo de vida dos blocos
21
+ ├── دورة حياة الكتل
22
22
  │ ├── alloc()
23
23
  │ ├── realloc()
24
+ │ ├── shrink()
24
25
  │ ├── free()
25
26
  │ └── gc()
26
27
  │
27
- ├── Estruturas lineares
28
+ ├── الهياكل الخطية
28
29
  │ ├── Stack
29
30
  │ │ ├── push()
30
31
  │ │ ├── pop()
31
32
  │ │ └── peek()
32
- │ │
33
33
  │ └── Queue
34
34
  │ ├── nudge()
35
35
  │ ├── pull()
36
36
  │ └── head()
37
37
  │
38
- ├── Acesso ao conteúdo
38
+ ├── الوصول إلى المحتوى
39
39
  │ ├── has()
40
40
  │ ├── get()
41
41
  │ ├── set()
@@ -43,44 +43,45 @@ Balloc
43
43
  │ ├── fill()
44
44
  │ ├── fillAll()
45
45
  │ ├── put()
46
- │ └── pick()
46
+ │ ├── pick()
47
+ │ ├── indexOf()
48
+ │ ├── lastIndexOf()
49
+ │ └── withView()
47
50
  │
48
- ├── Capacidade e ocupação
51
+ ├── السعة والإشغال
49
52
  │ ├── byteSize()
50
53
  │ ├── occupied()
51
- │ └── length()
54
+ │ ├── length()
55
+ │ └── isFull()
52
56
  │
53
- ├── Operações entre blocos
57
+ ├── العمليات بين الكتل
54
58
  │ ├── copy()
55
59
  │ ├── copyWithin()
56
60
  │ ├── append()
57
- │ └── clone()
61
+ │ ├── clone()
58
62
  │ └── swap()
59
63
  │
60
- ├── Serialização
64
+ ├── التسلسل
61
65
  │ ├── dump()
62
66
  │ └── load()
63
67
  │
64
- ├── Diagnóstico e utilização
68
+ ├── التشخيص والاستخدام
65
69
  │ ├── recycleCount()
66
70
  │ ├── recycleBytes
67
71
  │ ├── allocatedBytes
68
72
  │ ├── unallocatedBytes
69
73
  │ └── fragmentationRatio
70
74
  │
71
- └── Uso interno
72
- ├── Reciclagem
75
+ └── الاستخدام الداخلي
76
+ ├── إعادة التدوير
73
77
  │ ├── recyclePush()
74
78
  │ └── recyclePop()
75
- │
76
- ├── Escalonamento
79
+ ├── التوسعة
77
80
  │ ├── grow()
78
81
  │ └── headerGrow()
79
- │
80
- └── Utilitários
82
+ └── الأدوات
81
83
  ├── extractMetadata()
82
84
  └── bakeCookie()
83
-
84
85
  ```
85
86
 
86
87
  ---
@@ -120,6 +121,45 @@ byteSize(handler) → bytes físicos reservados
120
121
 
121
122
  ---
122
123
 
124
+ ## استعارة الذاكرة
125
+
126
+ يدعم Balloc الوصول المباشر دون نسخ إلى البيانات المشغولة في كتلة واحدة أو أكثر. تتلقى دالة الاستدعاء عروضًا من TypedArray مرتبطة بالتخزين الداخلي، مما يتيح القراءة والكتابة دون إنشاء نسخة.
127
+
128
+ يقتصر الاستعارة على دالة متزامنة. أثناء تنفيذها، يقفل Balloc الكتل المستعارة ضد العمليات التي قد تُبطل العروض أو تغيّر بنية الكتل. يُحرر القفل داخل `finally` حتى عند حدوث استثناء.
129
+
130
+ ### كتلة واحدة
131
+
132
+ مرّر معالجًا متبوعًا بدالة الاستدعاء. تتلقى الدالة عرضًا يحتوي على العناصر المشغولة فقط، دون السعة غير المستخدمة.
133
+
134
+ ```js
135
+ const count = memory.withView(handler, view => {
136
+ view[0] = 42;
137
+ return view.length;
138
+ });
139
+ ```
140
+
141
+ تؤثر الكتابة عبر العرض مباشرة في الكتلة، وتُعاد قيمة الدالة من `withView()`.
142
+
143
+ ### كتل متعددة
144
+
145
+ مرّر معالجين أو أكثر قبل دالة الاستدعاء. تتلقى الدالة عرضًا لكل معالج وبالترتيب نفسه:
146
+
147
+ ```js
148
+ memory.withView(source, target, (sourceView, targetView) => {
149
+ targetView.set(sourceView.subarray(0, targetView.length));
150
+ });
151
+ ```
152
+
153
+ يجب أن يكون كل معالج صالحًا ومختلفًا وغير مستعار بالفعل. تُكتسب جميع الأقفال قبل استدعاء الدالة وتُحرر عند انتهائها.
154
+
155
+ ### قيود الاستعارة
156
+
157
+ لا يجوز الاحتفاظ بالعرض أو بأي عرض فرعي مشتق منه أو إرجاعه أو استخدامه بعد انتهاء الدالة. إذا أعادت الدالة Promise، تنتهي الاستعارة فور إعادته؛ لذا يجب أن تكون جميع عمليات الوصول متزامنة.
158
+
159
+ تُرفض بـ `Error` العمليات التي تعدّل كتلة مستعارة، ومنها `push()` و`pop()` و`nudge()` و`pull()` و`set()` و`clear()` و`fill()` و`fillAll()` و`put()` و`realloc()` و`shrink()` و`free()` و`copyWithin()`. تُرفض `copy()` و`append()` إذا كانت الكتلة المستعارة هي الوجهة، وتُرفض `swap()` إذا كانت أي من الكتلتين مستعارة. تظل عمليات القراءة متاحة، ويُسمح باستعارة المصدر في `copy()` و`append()`.
160
+
161
+ تُرفض العمليات التي تستبدل `dataBus` أو تعيد تعيين خرائطه أثناء وجود أي عرض نشط، بما في ذلك `gc()` وتوسعة `dataBus` الناتجة عن `alloc()` أو `realloc()`.
162
+
123
163
  # 1. التهيئة (Instantiation)
124
164
 
125
165
  ## `new Balloc(size, bucketSize, metadataSize)`
@@ -298,6 +338,30 @@ memory.realloc(handler);
298
338
 
299
339
  ---
300
340
 
341
+ ## `shrink(handler)`
342
+
343
+ يقلل السعة الفيزيائية للكتلة إلى أصغر قوة مدعومة للعدد اثنين تكفي للعناصر المشغولة حاليًا. الحد الأدنى عنصران. إذا كانت السعة الحالية كافية، فلا يحدث تغيير.
344
+
345
+ تبقى البيانات في العنوان نفسه ويظل المعالج صالحًا لأن الرأس محفوظ؛ ولا يتغير سوى حقل السعة. إذا كانت الكتلة في قمة `dataBus`، يتراجع `dataPointer` وتعود المساحة إلى الكومة. وإلا، يُقسّم الجزء المحرر إلى مناطق بقوى العدد اثنين وتضاف إلى قائمة إعادة التدوير.
346
+
347
+ لا يغير `shrink()` الإشغال ولا ينقل العناصر.
348
+
349
+ ### المعاملات
350
+
351
+ | المعامل | النوع | الوصف |
352
+ |---|---|---|
353
+ | `handler` | `number` | معالج الكتلة. |
354
+
355
+ ### القيمة المرجعة
356
+
357
+ `void`
358
+
359
+ ### الاستثناءات
360
+
361
+ `Error` — معالج غير صالح أو تالف، أو أن الكتلة مستعارة عبر `withView()`.
362
+
363
+ ---
364
+
301
365
  ## `free(handler)`
302
366
 
303
367
  يحرر الكتلة.
@@ -535,6 +599,20 @@ boolean
535
599
 
536
600
  ---
537
601
 
602
+ ## `indexOf(handler, searchElement, fromIndex = 0)`
603
+
604
+ يعثر على أول ظهور للقيمة بترتيب تصاعدي للفهرس. يقتصر البحث على العناصر المشغولة ويتجاهل السعة غير المستخدمة.
605
+
606
+ ## `lastIndexOf(handler, searchElement, fromIndex = -1)`
607
+
608
+ يعثر على آخر ظهور للقيمة بترتيب تنازلي للفهرس. يقتصر البحث على العناصر المشغولة ويتجاهل السعة غير المستخدمة.
609
+
610
+ ## `withView(...args)`
611
+
612
+ يستعير كتلة واحدة أو أكثر أثناء دالة متزامنة. مرّر معالجًا أو أكثر ثم دالة الاستدعاء؛ وتتلقى العروض بالترتيب نفسه. المعامل `...args` هو `number[] + callback`. القيمة المرجعة هي قيمة الدالة. تُطلق `TypeError` عند غياب المعالج أو إذا لم تكن الوسيطة الأخيرة دالة، وتُطلق `Error` عند وجود معالج غير صالح أو مكرر أو مستعار.
613
+
614
+ ---
615
+
538
616
  ## `get(handler, index)`
539
617
 
540
618
  يحصل على العنصر في الفهرس المحدد.
@@ -750,6 +828,11 @@ const count = memory.occupied(handler);
750
828
 
751
829
  ## `length(handler)`
752
830
 
831
+ ## `isFull(handler)`
832
+
833
+ التحقق مما إذا كانت الكتلة مشغولة بالكامل. تعيد `true` عندما يساوي عدد العناصر المشغولة السعة الفيزيائية للكتلة؛ وإلا فتعيد `false`.
834
+
835
+
753
836
  يرجع الكمية الإجمالية للفتحات الفيزيائية المتاحة.
754
837
 
755
838
  السعة مستقلة عن الإشغال:
@@ -1158,12 +1241,12 @@ UNKNOWN // 0xFFFFFFFF
1158
1241
  يمكنك أيضاً الحصول على هذا التوثيق مترجم إلى لغات أخرى:
1159
1242
  | اللغة | الرابط |
1160
1243
  |---|---|
1161
- | العربية | [API — balloc.ar.md](./docs/API%20—%20balloc.ar.md) |
1162
- | الصينية | [API — balloc.zh.md](./docs/API%20—%20balloc.zh.md) |
1163
- | الإسبانية | [API — balloc.es.md](./docs/API%20—%20balloc.es.md) |
1164
- | الإنجليزية | [API — balloc.en.md](./docs/API%20—%20balloc.en.md) |
1165
- | اليابانية | [API — balloc.jp.md](./docs/API%20—%20balloc.jp.md) |
1166
- | البرتغالية | [API — balloc.pt.md](./docs/API%20—%20balloc.pt.md) |
1244
+ | العربية | [API — balloc.ar.md](./API%20—%20balloc.ar.md) |
1245
+ | الصينية | [API — balloc.zh.md](./API%20—%20balloc.zh.md) |
1246
+ | الإسبانية | [API — balloc.es.md](./API%20—%20balloc.es.md) |
1247
+ | الإنجليزية | [API — balloc.en.md](./API%20—%20balloc.en.md) |
1248
+ | اليابانية | [API — balloc.jp.md](./API%20—%20balloc.jp.md) |
1249
+ | البرتغالية | [API — balloc.pt.md](./API%20—%20balloc.pt.md) |
1167
1250
 
1168
1251
  **خاص. لا تستخدم مباشرة.**
1169
1252
 
@@ -1321,6 +1404,7 @@ capacityBytes = 2 ** capacity × wordSize
1321
1404
  | التهيئة | `constructor()` | `Balloc`|
1322
1405
  | دورة الحياة | `alloc()` | `number`|
1323
1406
  | دورة الحياة | `realloc()` | `void`|
1407
+ | دورة الحياة | `shrink()` | `void`|
1324
1408
  | دورة الحياة | `free()` | `void`|
1325
1409
  | دورة الحياة | `gc()` | `void`|
1326
1410
  | المكدس | `push()` | `boolean`|
@@ -1330,6 +1414,9 @@ capacityBytes = 2 ** capacity × wordSize
1330
1414
  | الطابور | `pull()` | `number |
1331
1415
  | الطابور | `head()` | `number |
1332
1416
  | الوصول | `has()` | `boolean`|
1417
+ | الوصول | `indexOf()` | `number`|
1418
+ | الوصول | `lastIndexOf()` | `number`|
1419
+ | الوصول | `withView()` | قيمة callback المرجعة|
1333
1420
  | الوصول | `get()` | `number |
1334
1421
  | الوصول | `set()` | `boolean`|
1335
1422
  | الوصول | `clear()` | `void`|
@@ -1340,6 +1427,7 @@ capacityBytes = 2 ** capacity × wordSize
1340
1427
  | السعة | `byteSize()` | `number`|
1341
1428
  | السعة | `occupied()` | `number`|
1342
1429
  | السعة | `length()` | `number`|
1430
+ | السعة | `isFull()` | `boolean`|
1343
1431
  | الكتل | `copy()` | `Uint8Array`|
1344
1432
  | الكتل | `copyWithin()` | `Uint8Array`|
1345
1433
  | الكتل | `append()` | `number`|
@@ -1,12 +1,12 @@
1
1
  You can also get this documentation translated into other languages:
2
2
  | Language | Link |
3
3
  |---|---|
4
- | Arabic | [API — balloc.ar.md](./docs/API%20—%20balloc.ar.md) |
5
- | Chinese | [API — balloc.zh.md](./docs/API%20—%20balloc.zh.md) |
6
- | Spanish | [API — balloc.es.md](./docs/API%20—%20balloc.es.md) |
7
- | English | [API — balloc.en.md](./docs/API%20—%20balloc.en.md) |
8
- | Japanese | [API — balloc.jp.md](./docs/API%20—%20balloc.jp.md) |
9
- | Portuguese | [API — balloc.pt.md](./docs/API%20—%20balloc.pt.md) |
4
+ | Arabic | [API — balloc.ar.md](./API%20—%20balloc.ar.md) |
5
+ | Chinese | [API — balloc.zh.md](./API%20—%20balloc.zh.md) |
6
+ | Spanish | [API — balloc.es.md](./API%20—%20balloc.es.md) |
7
+ | English | [API — balloc.en.md](./API%20—%20balloc.en.md) |
8
+ | Japanese | [API — balloc.jp.md](./API%20—%20balloc.jp.md) |
9
+ | Portuguese | [API — balloc.pt.md](./API%20—%20balloc.pt.md) |
10
10
 
11
11
  # Balloc.js
12
12
 
@@ -27,6 +27,7 @@ Balloc
27
27
  ├── Block Lifecycle
28
28
  │ ├── alloc()
29
29
  │ ├── realloc()
30
+ │ ├── shrink()
30
31
  │ ├── free()
31
32
  │ └── gc()
32
33
  │
@@ -49,12 +50,16 @@ Balloc
49
50
  │ ├── fill()
50
51
  │ ├── fillAll()
51
52
  │ ├── put()
52
- │ └── pick()
53
+ │ ├── pick()
54
+ │ ├── indexOf()
55
+ │ ├── lastIndexOf()
56
+ │ └── withView()
53
57
  │
54
58
  ├── Capacity and Occupancy
55
59
  │ ├── byteSize()
56
60
  │ ├── occupied()
57
- │ └── length()
61
+ │ ├── length()
62
+ │ └── isFull()
58
63
  │
59
64
  ├── Inter-block Operations
60
65
  │ ├── copy()
@@ -126,6 +131,45 @@ byteSize(handler) → reserved physical bytes
126
131
 
127
132
  ---
128
133
 
134
+ ## Memory Borrowing
135
+
136
+ Balloc supports **scoped, zero-copy access** to the occupied data of one or more blocks. This is a borrowing mechanism: a callback receives typed-array views over Balloc's internal storage, allowing direct reads and writes without allocating a copy.
137
+
138
+ The borrow is deliberately scoped to a synchronous callback. While the callback is running, Balloc locks each borrowed block against operations that could invalidate or structurally modify its view. The lock is released in a `finally` block, including when the callback throws.
139
+
140
+ ### A single block
141
+
142
+ Pass a handler followed by a callback. The callback receives a typed-array view containing only the block's occupied elements; unused capacity is excluded.
143
+
144
+ ```js
145
+ const count = memory.withView(handler, view => {
146
+ view[0] = 42;
147
+ return view.length;
148
+ });
149
+ ```
150
+
151
+ Writes through the view immediately affect the block. No copy is made, and the callback's return value is returned by `withView()`.
152
+
153
+ ### Multiple blocks
154
+
155
+ Pass two or more handlers before the callback. The callback receives one view per handler, in the same order:
156
+
157
+ ```js
158
+ memory.withView(source, target, (sourceView, targetView) => {
159
+ targetView.set(sourceView.subarray(0, targetView.length));
160
+ });
161
+ ```
162
+
163
+ Each handler must be valid, distinct, and not already borrowed. Balloc acquires the locks before invoking the callback and releases all acquired locks when it exits.
164
+
165
+ ### Borrowing constraints
166
+
167
+ A borrowed view, or any subview derived from it, must not be retained, returned, or used after the callback finishes. If the callback returns a Promise, the borrow ends immediately when that Promise is returned; it is not held until the Promise settles. The callback must therefore complete all view access synchronously.
168
+
169
+ While a block is borrowed, operations that modify that block are rejected with `Error`. This includes `push()`, `pop()`, `nudge()`, `pull()`, `set()`, `clear()`, `fill()`, `fillAll()`, `put()`, `realloc()`, `shrink()`, `free()`, and `copyWithin()`. `copy()` and `append()` are rejected when the borrowed block is the destination; a borrowed source is allowed. `swap()` is rejected if either block is borrowed. Read-only operations remain available.
170
+
171
+ Operations that replace or remap `dataBus` are rejected while any view is active. This includes `gc()` and growth of `dataBus` triggered by `alloc()` or `realloc()`.
172
+
129
173
  # 1. Instantiation
130
174
 
131
175
  ## `new Balloc(size, bucketSize, metadataSize)`
@@ -139,12 +183,12 @@ Storage is split between `dataBus`, intended for block data, and `controlBus`, i
139
183
  | Parameter | Type | Default | Description |
140
184
  | --- | --- | --- | --- |
141
185
  | `size` | `number` | `65535` | Initial capacity of `dataBus`, in bytes. |
142
- | `bucketSize` | `BucketType` | Size of each element. | |
186
+ | `bucketSize` | `BucketType` | `"32u"` | Element type and width. |
143
187
  | `metadataSize` | `number` | `1024` | Initial capacity of `controlBus`, in bytes. |
144
188
 
145
189
  `size` must be a safe integer within the range `[2, 0x80000000]`.
146
190
 
147
- `bucketSize` accepts a `BucketType` value which is a string in the format `[Size in bytes][data type]`, accepting only values from the table:
191
+ `bucketSize` accepts a `BucketType` value which is a string in the format `[Bit width][data type]`, accepting only values from the table:
148
192
 
149
193
  | Signed Integer | Unsigned Integer | Float |
150
194
  | --- | --- | --- |
@@ -282,6 +326,48 @@ The operation doubles physical capacity, moving to the next power of two.
282
326
 
283
327
  ---
284
328
 
329
+ ## `shrink(handler)`
330
+
331
+ Reduces a block's physical capacity to the smallest supported power of two that can contain its current occupied elements. The minimum capacity is two elements. If the current capacity is already sufficient, the method does nothing.
332
+
333
+ The block's data remains at the same address, and its handler remains valid because the header is preserved. Only the capacity recorded in the header changes. The released tail is reclaimed according to the block's position:
334
+
335
+ * If the block is at the top of `dataBus`, `dataPointer` moves backward and the released space is returned directly to the heap.
336
+ * Otherwise, the released tail is split into power-of-two regions and each region is added to the recycling list for later reuse.
337
+
338
+ `shrink()` does not change occupancy or move the occupied elements.
339
+
340
+ ### Parameters
341
+
342
+ | Parameter | Type | Description |
343
+ | --- | --- | --- |
344
+ | `handler` | `number` | Block handler. |
345
+
346
+ ### Return
347
+
348
+ ```text
349
+ void
350
+ ```
351
+
352
+ ### Exceptions
353
+
354
+ * `Error` — invalid or corrupted handler, or the block is currently borrowed through `withView()`.
355
+
356
+ ### Example
357
+
358
+ ```js
359
+ const handler = memory.alloc(128);
360
+ memory.put(handler, [10, 20, 30]);
361
+ memory.shrink(handler);
362
+
363
+ console.log(memory.length(handler)); // 4
364
+ console.log(memory.occupied(handler)); // 3
365
+ ```
366
+
367
+ The resulting capacity is the smallest power of two that accommodates the occupied elements.
368
+
369
+ ---
370
+
285
371
  ## `free(handler)`
286
372
 
287
373
  Frees a block.
@@ -491,6 +577,37 @@ boolean
491
577
 
492
578
  ---
493
579
 
580
+ ## `indexOf(handler, searchElement, fromIndex = 0)`
581
+
582
+ Finds the first occurrence of a value, searching in ascending index order. Only occupied elements are searched; unused block capacity is ignored.
583
+
584
+ ## `lastIndexOf(handler, searchElement, fromIndex = -1)`
585
+
586
+ Finds the last occurrence of a value, searching in descending index order. Only occupied elements are searched; unused block capacity is ignored.
587
+
588
+ Both search methods return the matching zero-based index, or `-1` when the value is not found. They throw `Error` if the handler is invalid or corrupted.
589
+
590
+ ## `withView(...args)`
591
+
592
+ Borrows one or more blocks for the duration of a synchronous callback. Supply one or more block handlers followed by the callback; the callback receives the corresponding typed-array views in handler order. The full borrowing model, examples, and restrictions are described in [Memory Borrowing](#memory-borrowing).
593
+
594
+ ### Parameters
595
+
596
+ | Parameter | Type | Description |
597
+ | --- | --- | --- |
598
+ | `...args` | `number[] + callback` | One or more block handlers followed by the callback. |
599
+
600
+ ### Return
601
+
602
+ The value returned by the callback.
603
+
604
+ ### Exceptions
605
+
606
+ * `TypeError` — no handler is provided or the final argument is not a function.
607
+ * `Error` — a handler is invalid, duplicated, or already borrowed.
608
+
609
+ ---
610
+
494
611
  ## `get(handler, index)`
495
612
 
496
613
  Gets the element at the specified index.
@@ -708,6 +825,22 @@ const capacity = memory.length(handler);
708
825
 
709
826
  ---
710
827
 
828
+ ## `isFull(handler)`
829
+
830
+ Returns `true` when the number of occupied elements equals the block's physical capacity; otherwise returns `false`.
831
+
832
+ ### Return
833
+
834
+ ```text
835
+ boolean
836
+ ```
837
+
838
+ ### Exceptions
839
+
840
+ `Error` — invalid or corrupted handler.
841
+
842
+ ---
843
+
711
844
  # 6. Inter-block Operations
712
845
 
713
846
  ## `copy(source, destiny, slots = UNKNOWN)`
@@ -1220,25 +1353,30 @@ Generation participates in cookie validation. Consequently, an invalid handler o
1220
1353
  | Instantiation | `constructor()` | `Balloc`|
1221
1354
  | Lifecycle | `alloc()` | `number`|
1222
1355
  | Lifecycle | `realloc()` | `void`|
1356
+ | Lifecycle | `shrink()` | `void`|
1223
1357
  | Lifecycle | `free()` | `void`|
1224
1358
  | Lifecycle | `gc()` | `void`|
1225
1359
  | Stack | `push()` | `boolean`|
1226
- | Stack | `pop()` | `number` |
1227
- | Stack | `peek()` | `number` |
1360
+ | Stack | `pop()` | `number \| undefined` |
1361
+ | Stack | `peek()` | `number \| undefined` |
1228
1362
  | Queue | `nudge()` | `boolean`|
1229
- | Queue | `pull()` | `number` |
1230
- | Queue | `head()` | `number` |
1363
+ | Queue | `pull()` | `number \| undefined` |
1364
+ | Queue | `head()` | `number \| undefined` |
1231
1365
  | Access | `has()` | `boolean`|
1232
- | Access | `get()` | `number` |
1366
+ | Access | `get()` | `number \| undefined` |
1233
1367
  | Access | `set()` | `boolean`|
1234
1368
  | Access | `clear()` | `void`|
1235
1369
  | Access | `fill()` | `void`|
1236
1370
  | Access | `fillAll()` | `void`|
1237
1371
  | Access | `put()` | `void`|
1238
1372
  | Access | `pick()` | `TypedArray`|
1373
+ | Access | `indexOf()` | `number`|
1374
+ | Access | `lastIndexOf()` | `number`|
1375
+ | Access | `withView()` | `any`|
1239
1376
  | Capacity | `byteSize()` | `number`|
1240
1377
  | Capacity | `occupied()` | `number`|
1241
1378
  | Capacity | `length()` | `number`|
1379
+ | Capacity | `isFull()` | `boolean`|
1242
1380
  | Blocks | `copy()` | `Uint8Array`|
1243
1381
  | Blocks | `copyWithin()` | `Uint8Array`|
1244
1382
  | Blocks | `append()` | `number`|
@@ -1,12 +1,12 @@
1
1
  También puedes conseguir esta documentación traducida a otros idiomas:
2
2
  | Idioma | Enlace |
3
3
  |---|---|
4
- | Árabe | [API — balloc.ar.md](./docs/API%20—%20balloc.ar.md) |
5
- | Chino | [API — balloc.zh.md](./docs/API%20—%20balloc.zh.md) |
6
- | Español | [API — balloc.es.md](./docs/API%20—%20balloc.es.md) |
7
- | Inglés | [API — balloc.en.md](./docs/API%20—%20balloc.en.md) |
8
- | Japonés | [API — balloc.jp.md](./docs/API%20—%20balloc.jp.md) |
9
- | Portugués | [API — balloc.pt.md](./docs/API%20—%20balloc.pt.md) |
4
+ | Árabe | [API — balloc.ar.md](./API%20—%20balloc.ar.md) |
5
+ | Chino | [API — balloc.zh.md](./API%20—%20balloc.zh.md) |
6
+ | Español | [API — balloc.es.md](./API%20—%20balloc.es.md) |
7
+ | Inglés | [API — balloc.en.md](./API%20—%20balloc.en.md) |
8
+ | Japonés | [API — balloc.jp.md](./API%20—%20balloc.jp.md) |
9
+ | Portugués | [API — balloc.pt.md](./API%20—%20balloc.pt.md) |
10
10
 
11
11
  # Balloc.js
12
12
 
@@ -27,6 +27,7 @@ Balloc
27
27
  ├── Ciclo de vida de los bloques
28
28
  │ ├── alloc()
29
29
  │ ├── realloc()
30
+ │ ├── shrink()
30
31
  │ ├── free()
31
32
  │ └── gc()
32
33
  │
@@ -35,7 +36,6 @@ Balloc
35
36
  │ │ ├── push()
36
37
  │ │ ├── pop()
37
38
  │ │ └── peek()
38
- │ │
39
39
  │ └── Queue
40
40
  │ ├── nudge()
41
41
  │ ├── pull()
@@ -49,12 +49,16 @@ Balloc
49
49
  │ ├── fill()
50
50
  │ ├── fillAll()
51
51
  │ ├── put()
52
- │ └── pick()
52
+ │ ├── pick()
53
+ │ ├── indexOf()
54
+ │ ├── lastIndexOf()
55
+ │ └── withView()
53
56
  │
54
57
  ├── Capacidad y ocupación
55
58
  │ ├── byteSize()
56
59
  │ ├── occupied()
57
- │ └── length()
60
+ │ ├── length()
61
+ │ └── isFull()
58
62
  │
59
63
  ├── Operaciones entre bloques
60
64
  │ ├── copy()
@@ -78,11 +82,9 @@ Balloc
78
82
  ├── Reciclaje
79
83
  │ ├── recyclePush()
80
84
  │ └── recyclePop()
81
- │
82
85
  ├── Escalado
83
86
  │ ├── grow()
84
87
  │ └── headerGrow()
85
- │
86
88
  └── Utilidades
87
89
  ├── extractMetadata()
88
90
  └── bakeCookie()
@@ -122,6 +124,45 @@ byteSize(handler) → bytes físicos reservados
122
124
 
123
125
  ---
124
126
 
127
+ ## Préstamo de memoria
128
+
129
+ Balloc permite el acceso directo y sin copia a los datos ocupados de uno o varios bloques. El callback recibe vistas tipadas sobre el almacenamiento interno, lo que permite leer y escribir sin asignar una copia.
130
+
131
+ El préstamo se limita a un callback síncrono. Mientras se ejecuta, Balloc bloquea los bloques prestados frente a operaciones que podrían invalidar las vistas o modificar su estructura. El bloqueo se libera en un bloque `finally`, incluso si se produce una excepción.
132
+
133
+ ### Un solo bloque
134
+
135
+ Pasa un handler seguido del callback. Este recibe una vista que contiene únicamente los elementos ocupados, sin la capacidad no utilizada.
136
+
137
+ ```js
138
+ const count = memory.withView(handler, view => {
139
+ view[0] = 42;
140
+ return view.length;
141
+ });
142
+ ```
143
+
144
+ Las escrituras a través de la vista modifican inmediatamente el bloque; `withView()` devuelve el valor del callback.
145
+
146
+ ### Varios bloques
147
+
148
+ Pasa dos o más handlers antes del callback. Este recibe una vista por handler, en el mismo orden:
149
+
150
+ ```js
151
+ memory.withView(source, target, (sourceView, targetView) => {
152
+ targetView.set(sourceView.subarray(0, targetView.length));
153
+ });
154
+ ```
155
+
156
+ Cada handler debe ser válido, distinto y no estar prestado. Balloc adquiere todos los bloqueos antes de ejecutar el callback y los libera al terminar.
157
+
158
+ ### Restricciones del préstamo
159
+
160
+ No se debe conservar, devolver ni utilizar la vista, ni ninguna subvista derivada, después de que termine el callback. Si devuelve una Promise, el préstamo finaliza inmediatamente; todo acceso debe ser síncrono.
161
+
162
+ Las operaciones que modifican un bloque prestado se rechazan con `Error`: `push()`, `pop()`, `nudge()`, `pull()`, `set()`, `clear()`, `fill()`, `fillAll()`, `put()`, `realloc()`, `shrink()`, `free()` y `copyWithin()`. `copy()` y `append()` se rechazan si el bloque prestado es el destino; `swap()` se rechaza si cualquiera está prestado. Las operaciones de lectura siguen disponibles y se permite prestar el origen en `copy()` y `append()`.
163
+
164
+ Las operaciones que sustituyen o reasignan `dataBus` se rechazan mientras haya alguna vista activa. Esto incluye `gc()` y el crecimiento de `dataBus` provocado por `alloc()` o `realloc()`.
165
+
125
166
  # 1. Instanciación
126
167
 
127
168
  ## `new Balloc(size, bucketSize, metadataSize)`
@@ -270,6 +311,30 @@ La operación duplica la capacidad física, llevándola a la siguiente potencia
270
311
 
271
312
  ---
272
313
 
314
+ ## `shrink(handler)`
315
+
316
+ Reduce la capacidad física del bloque a la menor potencia de dos admitida que pueda contener los elementos ocupados. La capacidad mínima es de dos elementos. Si la capacidad actual ya es suficiente, no hace nada.
317
+
318
+ Los datos permanecen en la misma dirección y el handler sigue siendo válido porque se conserva el header; solo cambia el campo de capacidad. Si el bloque está en la parte superior de `dataBus`, `dataPointer` retrocede y el espacio vuelve al heap. En caso contrario, la cola liberada se divide en regiones de tamaño potencia de dos y se añade a la lista de reciclaje.
319
+
320
+ `shrink()` no modifica la ocupación ni mueve los elementos.
321
+
322
+ ### Parámetros
323
+
324
+ | Parámetro | Tipo | Descripción |
325
+ |---|---|---|
326
+ | `handler` | `number` | Handler del bloque. |
327
+
328
+ ### Retorno
329
+
330
+ `void`
331
+
332
+ ### Excepciones
333
+
334
+ `Error` — handler no válido o corrupto, o el bloque está prestado mediante `withView()`.
335
+
336
+ ---
337
+
273
338
  ## `free(handler)`
274
339
 
275
340
  Libera un bloque.
@@ -465,6 +530,20 @@ boolean
465
530
 
466
531
  ---
467
532
 
533
+ ## `indexOf(handler, searchElement, fromIndex = 0)`
534
+
535
+ Busca la primera aparición de un valor en orden ascendente de índices. Solo examina los elementos ocupados e ignora la capacidad no utilizada.
536
+
537
+ ## `lastIndexOf(handler, searchElement, fromIndex = -1)`
538
+
539
+ Busca la última aparición de un valor en orden descendente de índices. Solo examina los elementos ocupados e ignora la capacidad no utilizada.
540
+
541
+ ## `withView(...args)`
542
+
543
+ Presta uno o varios bloques durante un callback síncrono. Pasa uno o más handlers y, al final, el callback; este recibe las vistas en el mismo orden. `...args` es `number[] + callback`. El retorno es el valor del callback. Lanza `TypeError` si falta un handler o el último argumento no es una función, y `Error` si algún handler no es válido, está duplicado o ya está prestado.
544
+
545
+ ---
546
+
468
547
  ## `get(handler, index)`
469
548
 
470
549
  Obtiene el elemento situado en el índice especificado.
@@ -649,6 +728,11 @@ const count = memory.occupied(handler);
649
728
 
650
729
  ## `length(handler)`
651
730
 
731
+ ## `isFull(handler)`
732
+
733
+ Comprobar si el bloque está completamente ocupado. Devuelve `true` cuando el número de elementos ocupados coincide con la capacidad física del bloque; en caso contrario, devuelve `false`.
734
+
735
+
652
736
  Devuelve el número total de slots físicos disponibles.
653
737
 
654
738
  La capacidad es independiente de la ocupación:
@@ -1136,6 +1220,7 @@ La generación participa en la validación mediante cookie. En consecuencia, un
1136
1220
  | Instanciación | `constructor()` | `Balloc` |
1137
1221
  | Ciclo de vida | `alloc()` | `number` |
1138
1222
  | Ciclo de vida | `realloc()` | `void` |
1223
+ | Ciclo de vida | `shrink()` | `void` |
1139
1224
  | Ciclo de vida | `free()` | `void` |
1140
1225
  | Ciclo de vida | `gc()` | `void` |
1141
1226
  | Stack | `push()` | `boolean` |
@@ -1145,6 +1230,9 @@ La generación participa en la validación mediante cookie. En consecuencia, un
1145
1230
  | Queue | `pull()` | `number \| undefined` |
1146
1231
  | Queue | `head()` | `number \| undefined` |
1147
1232
  | Acceso | `has()` | `boolean` |
1233
+ | Acceso | `indexOf()` | `number` |
1234
+ | Acceso | `lastIndexOf()` | `number` |
1235
+ | Acceso | `withView()` | Valor del callback |
1148
1236
  | Acceso | `get()` | `number \| undefined` |
1149
1237
  | Acceso | `set()` | `boolean` |
1150
1238
  | Acceso | `clear()` | `void` |
@@ -1155,6 +1243,7 @@ La generación participa en la validación mediante cookie. En consecuencia, un
1155
1243
  | Capacidad | `byteSize()` | `number` |
1156
1244
  | Capacidad | `occupied()` | `number` |
1157
1245
  | Capacidad | `length()` | `number` |
1246
+ | Capacidad | `isFull()` | `boolean` |
1158
1247
  | Bloques | `copy()` | `Uint8Array` |
1159
1248
  | Bloques | `copyWithin()` | `Uint8Array` |
1160
1249
  | Bloques | `append()` | `number` |