balloc 1.4.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.MD +157 -334
  3. package/docs/API /342/200/224 balloc.en.md" +478 -1217
  4. package/docs/MIGRATION /342/200/224 balloc.en.md" +208 -0
  5. package/package.json +2 -44
  6. package/src/README.MD +0 -0
  7. package/src/en/balloc.cjs +510 -960
  8. package/src/en/balloc.js +1 -1
  9. package/src/en/balloc.mjs +551 -1099
  10. package/types/README.MD +0 -0
  11. package/types/en/balloc.d.mts +275 -583
  12. package/README.ar.md +0 -439
  13. package/README.en.md +0 -467
  14. package/README.es.md +0 -439
  15. package/README.jp.md +0 -438
  16. package/README.pt.md +0 -462
  17. package/README.zh.md +0 -438
  18. package/docs/API /342/200/224 balloc.ar.md" +0 -1509
  19. package/docs/API /342/200/224 balloc.es.md" +0 -1325
  20. package/docs/API /342/200/224 balloc.jp.md" +0 -1264
  21. package/docs/API /342/200/224 balloc.pt.md" +0 -1395
  22. package/docs/API /342/200/224 balloc.zh.md" +0 -1324
  23. package/src/ar/balloc.cjs +0 -1303
  24. package/src/ar/balloc.js +0 -2
  25. package/src/ar/balloc.mjs +0 -1591
  26. package/src/es/balloc.cjs +0 -1320
  27. package/src/es/balloc.js +0 -2
  28. package/src/es/balloc.mjs +0 -1608
  29. package/src/jp/balloc.cjs +0 -1260
  30. package/src/jp/balloc.js +0 -2
  31. package/src/jp/balloc.mjs +0 -1548
  32. package/src/pt/balloc.cjs +0 -1326
  33. package/src/pt/balloc.js +0 -2
  34. package/src/pt/balloc.mjs +0 -1619
  35. package/src/zh/balloc.cjs +0 -1205
  36. package/src/zh/balloc.js +0 -2
  37. package/src/zh/balloc.mjs +0 -1493
  38. package/types/ar/balloc.d.mts +0 -793
  39. package/types/es/balloc.d.mts +0 -810
  40. package/types/jp/balloc.d.mts +0 -750
  41. package/types/pt/balloc.d.mts +0 -818
  42. package/types/zh/balloc.d.mts +0 -695
package/README.MD CHANGED
@@ -1,470 +1,293 @@
1
- You can also find this documentation translated into other languages:
2
- | Idioma | Link |
3
- |---|---|
4
- | Arabic | [README.ar.md](README.ar.md) |
5
- | Chinese | [README.zh.md](README.zh.md) |
6
- | Spanish | [README.es.md](README.es.md) |
7
- | English | [README.en.md](README.en.md) |
8
- | Japanese | [README.jp.md](README.jp.md) |
9
- | Portuguese | [README.pt.md](README.pt.md) |
10
-
11
- # Balloc.js
12
-
13
- ## A bump allocation memory allocator for JavaScript.
14
-
15
- **`Balloc`** is an incremental memory allocator based on bump allocation that maintains contiguous data blocks identified by compact numeric handles.
16
-
17
- ## Motivation
18
-
19
- The JavaScript/Node.js ecosystem has historically lacked low-level infrastructure for efficient Big Data processing such as parsing, editing, and continuous indexing of large volumes of CSV files, logs, and time series data, while the vast majority of data libraries available in the ecosystem use naive models based on reference graphs and dynamic allocation of object instances (`new Node()`). These approaches impose severe limitations such as:
20
- * Heap and GC overhead, as the proliferation of millions of individual objects saturates V8's reference graph, causing unpredictable Garbage Collector pauses.
21
- * Lack of layout control (AoS vs. SoA), where libraries ignore data organization as Array of Structures (AoS) or Structure of Arrays (SoA), resulting in high fragmentation and poor utilization of the CPU's L1/L2/L3 cache.
22
- * Lack of primitives for building advanced storage engines such as Log-Structured Merge-trees, which require extremely high-throughput mutable write arenas followed by compacted immutability, something impractical on top of conventional JS abstractions.
23
-
24
- Balloc was created to fill this engineering gap. It was conceived as a foundational memory allocation and low-abstraction dynamic arena management engine. By providing explicit control over contiguous memory layout through TypedArrays, Balloc provides the physical foundation required for the JavaScript ecosystem to support industrial-grade data structures such as LSM-Trees, MemTables, Quotient Filters, and Big Data processors, matching native approaches in C++, Rust, or Go in efficiency and predictability.
1
+ # Balloc
25
2
 
3
+ **Balloc** is a typed memory-block allocator for JavaScript. It stores each allocation in its own `ArrayBuffer`, exposes blocks through numeric handles, and tracks the number of occupied elements separately from physical capacity.
26
4
 
27
- ## Design
5
+ Version: **2.0.0**
28
6
 
29
- As a low-abstraction memory allocation engine and dynamic arena manager, **`Balloc`** was designed to fit into the JavaScript runtime without competing with JavaScript's native high-level data structures (such as `Object`, `Map`, or `Array`), instead operating at the immediately lower layer to provide **deterministic, high-performance contiguous memory management** without overloading the environment's *Garbage Collector*.
7
+ ## Version 2.0.0: breaking change from 1.x
30
8
 
31
- The allocator combines three mechanisms:
9
+ **Balloc 2.0.0 is an architectural redesign and is not backward-compatible with the 1.x series. It is not a drop-in upgrade.** Applications written for 1.x must be reviewed and adapted before upgrading.
32
10
 
33
- ```text
34
- ┌─────────────────┐
35
- │ Balloc │
36
- └────────┬────────┘
37
- │
38
- ┌────────────────┼────────────────┐
39
- │ │ │
40
- ▼ ▼ ▼
41
- Bump allocation Recycling Compaction
42
- │ │ │
43
- Fast sequential Reuse of freed regions ReBump / gc()
44
- sequencial liberadas
45
-
46
- ```
47
-
48
- * The bump allocator provides sequential allocation on top of `dataBus`.
49
- * The recycling system allows previously freed regions to be reused when their capacity matches a new allocation.
50
- * `gc()` performs explicit compaction when the *heap* contains fragmented free regions.
51
-
52
- This gives the allocator a simple memory model while maintaining explicit control over capacity, occupancy, recycling, and compaction, because `Balloc` separates the data block from the metadata block.
53
-
54
- ```text
55
- Balloc
56
- │
57
- ┌─────────┴─────────┐
58
- │ │
59
- dataBus controlBus
60
- │ │
61
- conteúdo headers
62
-
63
- ```
11
+ The memory-management model has changed fundamentally:
64
12
 
65
- * `dataBus` contains the set of data blocks.
13
+ | Version 1.x | Version 2.0.0 |
14
+ |---|---|
15
+ | Shared heap managed by the allocator. | Each allocation owns an independent `ArrayBuffer`. |
16
+ | Bump allocation and region-oriented memory management. | Independent blocks addressed by numeric handles. |
17
+ | Allocation metadata and heap-oriented operations. | Per-block typed-array capacity and logical occupancy. |
18
+ | Region recycling and heap compaction/garbage-collection workflows. | Explicit block lifecycle through `alloc()`, `realloc()`, `shrink()`, and `free()`. |
66
19
 
20
+ The public programming model has changed along with the storage architecture. Do not assume that 1.x methods, internal structures, handles, allocation assumptions, or existing application code map directly to the 2.0.0 API. In particular, code coupled to the former shared heap, metadata, allocation regions, recycling, or compaction must be redesigned around independent blocks and the 2.0.0 public API.
67
21
 
68
- * `controlBus` contains the set of fixed-size headers that serve as descriptors for the data blocks.
22
+ **Upgrade guidance:** treat the move from 1.x to 2.0.0 as a major migration. Review all Balloc integration points and adapt allocation, access, lifetime, and serialization logic to the 2.0.0 contracts before deploying. A package-version change alone is not a sufficient migration.
69
23
 
70
- Each block is externally identified by a 43-bit logical handle:
24
+ ## Migration from 1.x
71
25
 
72
- ```text
73
- ┌───────────────────────┬───────────────────────────────┐
74
- │ generation — 11 bits │ header address — 32 bits │
75
- └───────────────────────┴───────────────────────────────┘
26
+ See the [Balloc 1.x to 2.0.0 migration guide](./docs/MIGRATION%20%E2%80%94%20balloc.en.md) before upgrading an existing application.
76
27
 
77
- ```
28
+ ## Features
78
29
 
79
- The handle itself does not directly contain the address of the data block. It identifies the block header, which in turn contains the data address, capacity, and block occupancy.
30
+ - Typed storage backed by JavaScript `TypedArray` instances.
31
+ - Numeric, monotonically increasing block handles. Handles are not reused after a block is freed.
32
+ - Separate physical capacity and logical occupancy.
33
+ - Stack, queue, and indexed access operations.
34
+ - Explicit block resizing with `realloc()` and `shrink()`.
35
+ - Scoped, zero-copy access through `withView()`.
36
+ - Block copying, appending, cloning, and swapping.
37
+ - CBOR serialization and restoration.
38
+ - Synchronous data-ingestion adapters through `loadData()`.
80
39
 
81
- The generation is used by the allocator's *cookie* validation mechanism to detect invalid, stale, or corrupted handles.
40
+ Each block owns an independent `ArrayBuffer`. Balloc does not use a shared bump-allocation heap, region recycling, or a heap-compaction routine.
82
41
 
83
42
  ## Installation
84
43
 
85
- In Node.js, install the following NPM package:
44
+ Node.js:
86
45
 
87
46
  ```bash
88
47
  npm install balloc
89
-
90
48
  ```
91
49
 
92
- In Bun, install:
50
+ Bun:
93
51
 
94
52
  ```bash
95
53
  bun add balloc
96
-
97
54
  ```
98
55
 
99
- In Deno, install:
56
+ Deno:
100
57
 
101
58
  ```bash
102
59
  deno add npm:balloc
103
-
104
60
  ```
105
61
 
106
- Using Yarn:
62
+ Yarn:
107
63
 
108
64
  ```bash
109
65
  yarn add balloc
110
-
111
66
  ```
112
67
 
113
- In HTML, use the unpkg CDN:
68
+ ## Loading
114
69
 
115
- ```text
116
- [https://unpkg.com/Balloc](https://unpkg.com/Balloc)
70
+ ### ES modules
117
71
 
118
- ```
119
-
120
- Or use its localized docstring versions for some languages:
121
-
122
- ```
123
- Arabic: [https://unpkg.com/Balloc/src/ar/Balloc.mjs](https://unpkg.com/Balloc/src/ar/Balloc.mjs)
124
- English: [https://unpkg.com/Balloc/src/en/Balloc.mjs](https://unpkg.com/Balloc/src/en/Balloc.mjs)
125
- Spanish: [https://unpkg.com/Balloc/src/es/Balloc.mjs](https://unpkg.com/Balloc/src/es/Balloc.mjs)
126
- Japanese: [https://unpkg.com/Balloc/src/jp/Balloc.mjs](https://unpkg.com/Balloc/src/jp/Balloc.mjs)
127
- Chinese: [https://unpkg.com/Balloc/src/zh/Balloc.mjs](https://unpkg.com/Balloc/src/zh/Balloc.mjs)
72
+ ```js
73
+ import Balloc from "balloc";
128
74
 
75
+ const memory = new Balloc();
129
76
  ```
130
77
 
131
- Ou ainda utilize o CDN jsDelivr:
78
+ ### CommonJS
132
79
 
133
- ```text
134
- [https://cdn.jsdelivr.net/npm/Balloc](https://cdn.jsdelivr.net/npm/Balloc)
80
+ ```js
81
+ const { Balloc } = require("balloc");
135
82
 
83
+ const memory = new Balloc();
136
84
  ```
137
85
 
138
- CDNs with localization support:
86
+ ### Browser
139
87
 
140
- ```
141
- Arabic: [https://cdn.jsdelivr.net/npm/Balloc/src/ar/Balloc.mjs](https://cdn.jsdelivr.net/npm/Balloc/src/ar/Balloc.mjs)
142
- English: [https://cdn.jsdelivr.net/npm/Balloc/src/en/Balloc.mjs](https://cdn.jsdelivr.net/npm/Balloc/src/en/Balloc.mjs)
143
- Spanish: [https://cdn.jsdelivr.net/npm/Balloc/src/es/Balloc.mjs](https://cdn.jsdelivr.net/npm/Balloc/src/es/Balloc.mjs)
144
- Japanese: [https://cdn.jsdelivr.net/npm/Balloc/src/jp/Balloc.mjs](https://cdn.jsdelivr.net/npm/Balloc/src/jp/Balloc.mjs)
145
- Chinese: [https://cdn.jsdelivr.net/npm/Balloc/src/zh/Balloc.mjs](https://cdn.jsdelivr.net/npm/Balloc/src/zh/Balloc.mjs)
88
+ The package provides a browser bundle through the package CDN entry:
146
89
 
90
+ ```html
91
+ <script src="https://unpkg.com/balloc"></script>
147
92
  ```
148
93
 
94
+ The bundle exposes the allocator as `window.Balloc`.
95
+
149
96
  ## Basic usage
150
97
 
151
- ESM:
98
+ The constructor accepts a maximum allocation size in bytes and an optional default element type.
152
99
 
153
100
  ```js
154
101
  import Balloc from "balloc";
155
102
 
156
103
  const memory = new Balloc();
157
-
158
- const handler = memory.alloc(100);
159
-
160
- memory.push(handler, 10);
161
- memory.push(handler, 20);
162
- memory.push(handler, 30);
163
-
164
- console.log(memory.length(handler));
165
- console.log(memory.occupied(handler));
166
-
167
- console.log(memory.pop(handler));
168
- console.log(memory.pop(handler));
169
-
170
- memory.free(handler);
171
-
172
- ```
173
-
174
- CJS:
175
-
176
- ```js
177
- const Balloc = require("balloc").default;
178
-
179
- const memory = new Balloc();
180
-
181
- const handler = memory.alloc(100);
104
+ const handler = memory.alloc(64, "32u");
182
105
 
183
106
  memory.push(handler, 10);
184
107
  memory.push(handler, 20);
185
108
  memory.push(handler, 30);
186
109
 
187
- console.log(memory.length(handler));
188
- console.log(memory.occupied(handler));
189
-
190
- console.log(memory.pop(handler));
191
- console.log(memory.pop(handler));
110
+ console.log(memory.occupied(handler)); // 3
111
+ console.log(memory.length(handler)); // 16
112
+ console.log(memory.pick(handler)); // Uint32Array [10, 20, 30]
192
113
 
193
114
  memory.free(handler);
194
-
195
115
  ```
196
116
 
197
- ## Getting started
117
+ The `alloc()` size is expressed in **bytes**. The resulting typed array contains as many elements as fit in that buffer. The default allocation size is 16 bytes and the default element type is `32u`.
198
118
 
199
- The constructor is:
119
+ ## Constructor
200
120
 
201
121
  ```js
202
- new Balloc(size, bucketSize, metadataSize)
203
-
122
+ new Balloc(maxByteSize, bucketSize)
204
123
  ```
205
124
 
206
125
  | Parameter | Type | Default | Description |
207
- | --- | --- | --- | --- |
208
- | `size` | `number` | `65535` | Initial `dataBus` capacity in bytes |
209
- | `bucketSize` | `BucketType` | `32u` | Element size in bits |
210
- | `metadataSize` | `number` | `1024` | Initial `controlBus` capacity in bytes |
126
+ |---|---|---:|---|
127
+ | `maxByteSize` | `number` | `0x80000000` | Upper bound used to validate allocation sizes, in bytes. |
128
+ | `bucketSize` | `BucketType | null` | `null` | Optional default element type. When set, it overrides the type passed to `alloc()`. |
211
129
 
212
- Example:
130
+ `maxByteSize` must be a safe integer in the range `[2, 0x80000000]`.
213
131
 
214
- ```js
215
- const memory = new Balloc();
132
+ ## Element types
216
133
 
217
- ```
218
-
219
- For 32-bit unsigned integer elements:
220
-
221
- ```js
222
- const memory = new Balloc(65535, "32u");
223
-
224
- ```
225
-
226
- `size` must be an integer in the range `[2, 0x80000000]`.
134
+ The element type uses the format `[bit width][type]`:
227
135
 
228
- `bucketSize` must be a `BucketType`, a string in the format `[size in bits][data type]`, with the following accepted values:
229
-
230
- | Signed Integer | Unsigned Integer | Float |
231
- | --- | --- | --- |
232
- | `8i` | `8u` | |
233
- | `16i` | `16u` | |
136
+ | Signed integer | Unsigned integer | Floating point |
137
+ |---|---|---|
138
+ | `8i` | `8u` | — |
139
+ | `16i` | `16u` | `16f` |
234
140
  | `32i` | `32u` | `32f` |
235
141
  | `64i` | `64u` | `64f` |
236
142
 
237
- *The half-precision type (`16f`), being a recent addition still undergoing consolidation in JavaScript specifications and runtimes, is not yet guaranteed to be supported by Balloc. Although the type is present in the library, its availability may be uncertain for use in your project.*
238
-
239
- `metadataSize` must be an integer in the range `[16, 0x80000000]`.
143
+ These identifiers map to the corresponding JavaScript typed arrays: `Int8Array`, `Uint8Array`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, `BigUint64Array`, `Float16Array`, `Float32Array`, and `Float64Array`.
240
144
 
241
- The allocation size of a block is rounded up to the smallest power of two capable of accommodating the requested number of elements.
145
+ The runtime must provide the corresponding typed-array constructor for the selected type. The 64-bit integer types use `bigint` values.
242
146
 
243
- Por exemplo:
147
+ ## Allocation and capacity
244
148
 
245
149
  ```js
246
- const handler = memory.alloc(100);
247
-
248
- ```
249
-
250
- does not necessarily create a block with exactly 100 physical slots. The allocator reserves a capacity that is a power of two.
251
-
252
- Conceptually:
253
-
254
- ```text
255
- requested: 100 elements
256
- capacity: 128 elements
257
-
150
+ const handler = memory.alloc(size, bucketType);
258
151
  ```
259
152
 
260
- Physical capacity and logical occupancy are distinct:
261
-
262
- ```text
263
- length(handler) → physical capacity
264
- occupied(handler) → occupied elements
265
- byteSize(handler) → reserved physical bytes
266
-
267
- ```
268
-
269
- This distinction allows a block to contain fewer occupied elements than its physical capacity.
270
-
271
- ## API
153
+ | Argument | Type | Default | Description |
154
+ |---|---|---:|---|
155
+ | `size` | `number` | `16` | Allocation size in bytes. Must be aligned to the selected element width. |
156
+ | `bucketType` | `BucketType` | `"32u"` | Element type used by the block, unless the constructor defines a default type. |
272
157
 
273
- The fundamental lifecycle of a block is:
158
+ Each successful allocation receives a new numeric handle. Handles increase monotonically and are not reused after `free()`.
274
159
 
275
- ```text
276
- alloc()
277
- │
278
- ├── acesso / modificação
279
- │
280
- ├── realloc()
281
- ├── shrink()
282
- │
283
- └── free()
284
- │
285
- └── recycle
160
+ Balloc distinguishes physical capacity from logical occupancy:
286
161
 
287
- ```
162
+ | Method | Meaning |
163
+ |---|---|
164
+ | `length(handler)` | Physical capacity in elements. |
165
+ | `occupied(handler)` | Number of occupied elements. |
166
+ | `byteSize(handler)` | Physical capacity in bytes. |
167
+ | `isFull(handler)` | Whether occupancy equals physical capacity. |
288
168
 
289
- Balloc provides several data-view models for a block:
169
+ An allocation can have unused capacity. Operations that add elements update occupancy; reading or replacing an existing element does not.
290
170
 
291
- * Stack
171
+ ### Resizing and release
292
172
 
173
+ | Method | Description |
174
+ |---|---|
175
+ | `realloc(handler, newSize)` | Replaces the block storage with a larger buffer. `newSize` is expressed in elements; when omitted, capacity doubles. |
176
+ | `shrink(handler)` | Replaces the buffer with the smallest power-of-two capacity that can hold the occupied elements, with a minimum of two elements. If that capacity is not smaller than the current capacity, no change is made. |
177
+ | `free(handler)` | Removes the block and invalidates its handle. |
293
178
 
294
- * Queue
179
+ Resizing copies the occupied elements to the new buffer. A block cannot be resized or freed while it is borrowed by `withView()`.
295
180
 
181
+ ## Data operations
296
182
 
297
- * Array / Random Access
183
+ ### Stack
298
184
 
185
+ | Method | Description |
186
+ |---|---|
187
+ | `push(handler, value)` | Adds an element at the end. Returns `false` if the block is full. |
188
+ | `pop(handler)` | Removes and returns the last occupied element. Returns `undefined` when empty. |
189
+ | `peek(handler)` | Reads the last occupied element without removing it. |
299
190
 
300
- The complete API documentation is available in the [`./docs`](./docs) directory and is available translated into several languages:
191
+ ### Queue
301
192
 
302
- | Idioma | Link |
193
+ | Method | Description |
303
194
  |---|---|
304
- | Arabic | [./docs/API — balloc.ar.md](./docs/API%20—%20balloc.ar.md) |
305
- | Chinese | [./docs/API — balloc.zh.md](./docs/API%20—%20balloc.zh.md) |
306
- | Spanish | [./docs/API — balloc.es.md](./docs/API%20—%20balloc.es.md) |
307
- | English | [./docs/API — balloc.en.md](./docs/API%20—%20balloc.en.md) |
308
- | Japanese | [./docs/API — balloc.jp.md](./docs/API%20—%20balloc.jp.md) |
309
- | Portuguese | [./docs/API — balloc.pt.md](./docs/API%20—%20balloc.pt.md) |
195
+ | `nudge(handler, value)` | Inserts an element at the beginning, shifting occupied elements toward the end. Returns `false` if full. |
196
+ | `pull(handler)` | Removes and returns the first element, shifting the remaining occupied elements toward the beginning. |
197
+ | `head(handler)` | Reads the first slot without changing occupancy. |
310
198
 
199
+ ### Indexed access and search
311
200
 
312
- The API methods are grouped by affinity into the following categories:
201
+ | Method | Description |
202
+ |---|---|
203
+ | `get(handler, index)` | Reads an occupied element. Returns `undefined` for an index outside the occupied range. |
204
+ | `set(handler, index, value)` | Replaces an occupied element. Returns `false` when the index is outside the occupied range. |
205
+ | `has(handler, value)` | Checks whether a value occurs in the occupied range. |
206
+ | `indexOf(handler, value, fromIndex)` | Finds the first occurrence. |
207
+ | `lastIndexOf(handler, value, fromIndex)` | Finds the last occurrence. |
313
208
 
314
- * Lifecycle
315
- * Data ingestion adapters
316
- * Stack operations
317
- * Queue operations
318
- * Array operations
319
- * Block interchange
320
- * Serialization
321
- * Diagnostics
322
- * Internal functions
209
+ ### Bulk operations
323
210
 
324
- The following is a summary of these groups:
211
+ | Method | Description |
212
+ |---|---|
213
+ | `clear(handler, value = 0)` | Fills the entire block and resets occupancy to zero. |
214
+ | `fill(handler, value, start, end)` | Fills the specified range and updates occupancy to include its end. |
215
+ | `fillAll(handler, value)` | Fills every slot and marks the entire block as occupied. |
216
+ | `put(handler, data)` | Copies an `Array` or `TypedArray` to the beginning of the block, up to its capacity. |
217
+ | `pick(handler)` | Returns a copy of the occupied elements as a typed array. |
325
218
 
326
- ### Data ingestion adapters
219
+ ### Operations between blocks
327
220
 
328
- `loadData(adapter)` delegates synchronous data ingestion to an adapter implementing the `FormatAdapter` contract. The adapter receives the allocator and returns the numeric handler for the primary block it loads.
221
+ | Method | Description |
222
+ |---|---|
223
+ | `copy(source, destination, slots)` | Copies occupied elements from one block to another, up to the destination capacity and optional slot limit. |
224
+ | `copyWithin(handler, target, start, length)` | Copies a range within the same block, supporting overlapping regions. |
225
+ | `append(target, source)` | Appends as many occupied source elements as fit in the target block. Returns the number appended. |
226
+ | `clone(handler)` | Creates an independent block containing a copy of the source block. |
227
+ | `swap(source, target)` | Swaps the block objects associated with two handles without changing the handles. |
329
228
 
330
- ```ts
331
- interface FormatAdapter {
332
- load(allocator: Balloc): number;
333
- }
334
- ```
335
229
 
336
- The allocator does not manage adapter transactions. If an adapter allocates multiple blocks and a later operation fails, rollback of those allocations is the adapter's responsibility.
230
+ ### Data ingestion
337
231
 
338
- Example:
232
+ `loadData(adapter)` delegates synchronous ingestion to an adapter with a `load(allocator)` method. The adapter receives the current Balloc instance, performs its allocations through the public API, and its return value is passed through unchanged.
339
233
 
340
234
  ```js
341
- import Balloc from "balloc";
342
-
343
- const allocator = new Balloc(65535, "8u");
344
- const handler = allocator.loadData({
235
+ const handler = memory.loadData({
345
236
  load(allocator) {
346
- const handler = allocator.alloc(4);
347
- allocator.put(handler, new Uint8Array([255, 0, 0, 255]));
348
- return handler;
237
+ const block = allocator.alloc(4, "8u");
238
+ allocator.put(block, new Uint8Array([255, 0, 0, 255]));
239
+ return block;
349
240
  }
350
241
  });
351
242
  ```
352
243
 
353
- Format-specific adapters can be published independently. For example, `imagedata-adapter` ingests RGBA8 `ImageData` instances.
354
-
355
- ### Lifecycle
356
-
357
- | API | Description |
358
- | --- | --- |
359
- | `alloc()` | Allocate a block |
360
- | `realloc()` | Increase block capacity |
361
- | `shrink()` | Reduce block capacity to fit occupied elements |
362
- | `free()` | Free a block |
363
- | `gc()` | Compact the data heap |
364
-
365
-
366
- ### Stack operations
367
-
368
- | API | Description |
369
- | --- | --- |
370
- | `push()` | Add an element |
371
- | `pop()` | Remove the last element |
372
- | `peek()` | Read the last element |
373
-
374
- ### Queue operations
375
-
376
- | API | Description |
377
- | --- | --- |
378
- | `nudge()` | Insert at the beginning |
379
- | `pull()` | Remove the first element |
380
- | `head()` | Read the first element |
381
-
382
- ### Array operations
383
-
384
- | API | Description |
385
- | --- | --- |
386
- | `has()` | Search for a value |
387
- | `indexOf()` | Search for a value (first match) |
388
- | `lastIndexOf()` | Search for a value (last match) |
389
- | `get()` | Read an element |
390
- | `set()` | Write an element |
391
- | `clear()` | Clear occupancy and fill the block |
392
- | `fill()` | Fill a range |
393
- | `fillAll()` | Fill and occupy the entire block |
394
- | `put()` | Copy an array into a block |
395
- | `pick()` | Copy occupied elements out of a block |
396
- | `withView()` | Borrow a typed view over occupied elements |
244
+ Balloc does not manage adapter transactions. If an adapter creates multiple blocks and a later operation fails, cleanup of those allocations is the adapter's responsibility.
397
245
 
398
- ### Block interchange
246
+ ### Memory views
399
247
 
400
- | API | Description |
401
- | --- | --- |
402
- | `copy()` | Copy between blocks |
403
- | `copyWithin()` | Copy within a block |
404
- | `append()` | Append one block to another |
405
- | `clone()` | Create an independent copy of the block |
406
- | `swap()` | Swap block regions |
248
+ `withView()` provides synchronous, zero-copy access to the occupied elements of one or more blocks. The callback receives typed-array subviews that share the blocks' storage.
407
249
 
408
- ### Serialization
409
-
410
- | API | Description |
411
- | --- | --- |
412
- | `dump()` | Serialize the block contents as CBOR |
413
- | `load()` | Restore a block from serialized data |
414
-
415
- ### Diagnostics
250
+ ```js
251
+ memory.withView(handler, view => {
252
+ view[0] = 42;
253
+ view[1] = 84;
254
+ });
255
+ ```
416
256
 
417
- | API | Description |
418
- | --- | --- |
419
- | `byteSize()` | Physical block size in bytes |
420
- | `occupied()` | Number of occupied elements |
421
- | `length()` | Physical element capacity |
422
- | `isFull()` | Check whether the block is completely occupied |
423
- | `recycleCount()` | Number of recyclable regions |
424
- | `recycleBytes` | Currently recyclable bytes |
425
- | `allocatedBytes` | Bytes associated with non-recycled regions |
426
- | `unallocatedBytes` | Space remaining after the bump pointer |
427
- | `fragmentationRatio` | Recycled bytes / used heap area |
257
+ Multiple blocks can be borrowed in one call. The callback receives one view per handle, in argument order:
428
258
 
259
+ ```js
260
+ memory.withView(source, target, (sourceView, targetView) => {
261
+ targetView.set(sourceView.subarray(0, targetView.length));
262
+ });
263
+ ```
429
264
 
430
- ### Internal functions
265
+ Borrowing is scoped to the synchronous callback. Balloc releases the borrow in a `finally` block, including when the callback throws. Do not retain, return, or use a borrowed view after the callback finishes. An asynchronous callback does not extend the borrow until its promise settles.
431
266
 
432
- These are a special class of API primarily used internally by the allocator and generally not recommended for day-to-day code, as they may cause undocumented side effects. They are intended for library extensions and modifications where a thorough understanding of the Balloc source code is essential.
267
+ Operations that could invalidate or structurally modify a borrowed block are rejected while the callback is running.
433
268
 
434
- ```text
435
- Recirculation
436
- ├── recyclePush()
437
- └── recyclePop()
269
+ ## Serialization
438
270
 
439
- Growth
440
- ├── grow()
441
- └── headerGrow()
271
+ `dump(handler)` serializes a block into a CBOR version 2 envelope. The envelope stores the bucket type, capacity, occupancy, and occupied payload.
442
272
 
443
- Validation / metadata
444
- ├── extractMetadata()
445
- └── bakeCookie()
273
+ `load(serialized)` accepts an `ArrayBuffer` or `Uint8Array`, validates the envelope, and creates a new block. If the allocator was constructed with a fixed `bucketSize`, the serialized block must use the same type.
446
274
 
275
+ ```js
276
+ const encoded = memory.dump(handler);
277
+ const restoredHandler = memory.load(encoded);
447
278
  ```
448
279
 
449
- `recyclePush()` inserts a free block into the recycling list.
450
-
451
- `recyclePop()` removes a free block from the recycling list and returns it.
452
-
453
- `grow()` expands `dataBus` when the current region can no longer satisfy additional allocations.
454
-
455
- `headerGrow()` expands `controlBus` when additional headers are required.
456
-
457
- `extractMetadata()` decodes and validates a handle and extracts its associated metadata.
280
+ ## API reference
458
281
 
459
- `bakeCookie()` calculates a validation cookie used by the handle validation mechanism.
282
+ The TypeScript declarations are available at [`types/en/balloc.d.mts`](./types/en/balloc.d.mts). The implementation is available at [`src/en/balloc.mjs`](./src/en/balloc.mjs).
460
283
 
461
- ## 💖 Donations / Support
284
+ ## Donations / Support
462
285
 
463
286
  If you like this project and want to support its development:
464
287
 
465
288
  | Pix QR Code | Copy-and-Paste / Random Key |
466
289
  | :---: | :--- |
467
- | ![Pix QR Code](https://raw.githubusercontent.com/AugustoVasques75/balloc/main/packages/balloc/img/pix.png) | **Random Key:**<br>`e87d773a-0b97-4410-8fc3-f7ec04cce6a2` |
290
+ | ![Pix QR Code](https://raw.githubusercontent.com/AugustoVasques75/balloc/main/packages/balloc/img/pix.png) | **Random Key:** `e87d773a-0b97-4410-8fc3-f7ec04cce6a2` |
468
291
 
469
292
  ## License
470
293