framealloc 0.11.1

Intent-aware, thread-smart memory allocation for Rust game engines
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
# Async/Await with framealloc


Safe async/await patterns using framealloc's hybrid model.

## Table of Contents


1. [Overview]#overview
2. [TaskAlloc]#taskalloc
3. [AsyncPoolGuard]#asyncpoolguard
4. [Common Patterns]#common-patterns
5. [Integration with Tokio]#integration-with-tokio
6. [Best Practices]#best-practices

## Overview


framealloc provides special utilities for async code that maintain the frame allocation model while working with Rust's async/await:

- **TaskAlloc** - Task-scoped allocations that auto-cleanup
- **AsyncPoolGuard** - RAII guard for pool allocations
- **Hybrid model** - Frame allocations on main thread, pool/heap in tasks

### Key Principle


Frame allocations stay on the main thread. Async tasks use pool/heap allocations. This prevents frame data from crossing await points.

## TaskAlloc


### Basic Usage


```rust
use framealloc::SmartAlloc;
use framealloc::tokio::TaskAlloc;

async fn process_asset(alloc: &SmartAlloc, path: &str) -> Vec<u8> {
    let alloc_clone = alloc.clone();
    
    tokio::spawn(async move {
        // Create task-scoped allocator
        let mut task = TaskAlloc::new(&alloc_clone);
        
        // Load asset (pool allocation)
        let data = task.alloc_box(load_from_disk(path).await);
        
        // Process data
        let processed = process_data(&data).await;
        
        // All allocations automatically freed when task ends
    }).await.unwrap()
}
```

### Task-Scoped Allocations


```rust
use framealloc::tokio::TaskAlloc;

async fn handle_connection(mut task: TaskAlloc) {
    // All allocations in this task are tracked
    
    // Pool allocation for connection state
    let state = task.alloc_box(ConnectionState::new());
    
    // Frame allocation not available here (correctly!)
    // let frame_data = task.frame_alloc<u8>(); // Error!
    
    // Use pool for temporary data
    let buffer = task.alloc_vec::<u8>();
    
    // Process connection
    while !state.is_closed() {
        let data = receive_data().await;
        buffer.extend_from_slice(&data);
        process_buffer(&buffer).await;
        buffer.clear();
    }
    
    // All allocations freed when function returns
}
```

### Nested Tasks


```rust
async fn process_requests(alloc: &SmartAlloc, requests: Vec<Request>) {
    let mut handles = Vec::new();
    
    for request in requests {
        let alloc_clone = alloc.clone();
        let handle = tokio::spawn(async move {
            let mut task = TaskAlloc::new(&alloc_clone);
            process_single_request(&mut task, request).await
        });
        handles.push(handle);
    }
    
    // Wait for all tasks
    for handle in handles {
        handle.await.unwrap();
    }
}

async fn process_single_request(task: &mut TaskAlloc, request: Request) {
    // Use task allocations
    let data = task.alloc_box(request.data);
    let result = compute_result(&data).await;
    
    // Send result back
    send_result(result).await;
}
```

## AsyncPoolGuard


### RAII Pattern


```rust
use framealloc::tokio::AsyncPoolGuard;

async fn process_with_guard(alloc: &SmartAlloc) {
    // Guard ensures cleanup even on early return
    let _guard = AsyncPoolGuard::new(&alloc);
    
    // Pool allocations are automatically tracked
    let data1 = alloc.pool_alloc::<Data>();
    let data2 = alloc.pool_alloc::<MoreData>();
    
    // Complex async logic
    if some_condition().await {
        // Early return - guard still cleans up
        return;
    }
    
    // More processing
    process_data(data1, data2).await;
    
    // Guard drops here, cleaning up all pool allocations
}
```

### Scoped Resource Management


```rust
async fn database_transaction(alloc: &SmartAlloc) -> Result<(), Error> {
    let _guard = AsyncPoolGuard::new(&alloc);
    
    // Begin transaction
    let tx = begin_transaction().await?;
    
    // Allocate query results
    let results = alloc.pool_vec::<Row>();
    
    // Execute queries
    for query in queries {
        let rows = execute_query(&tx, query).await?;
        results.extend(rows);
    }
    
    // Commit or rollback
    if validate_results(&results).await {
        tx.commit().await?;
        Ok(())
    } else {
        tx.rollback().await?;
        Err(Error::ValidationFailed)
    }
    // Guard ensures all Row allocations are freed
}
```

## Common Patterns


### Main Thread Coordination


```rust
use framealloc::SmartAlloc;
use framealloc::tokio::TaskAlloc;

struct GameServer {
    alloc: SmartAlloc,
    runtime: tokio::Runtime,
}

impl GameServer {
    fn new() -> Self {
        Self {
            alloc: SmartAlloc::new(Default::default()),
            runtime: tokio::Runtime::new().unwrap(),
        }
    }
    
    fn run(&mut self) {
        loop {
            // Main thread frame allocation
            self.alloc.begin_frame();
            
            // Process network events (async)
            let network_events = self.runtime.block_on(async {
                self.process_network().await
            });
            
            // Process events with frame allocation
            for event in network_events {
                self.handle_event(event);
            }
            
            // Update game state
            self.update_game();
            
            self.alloc.end_frame();
        }
    }
    
    async fn process_network(&self) -> Vec<NetworkEvent> {
        let alloc_clone = self.alloc.clone();
        
        // Spawn async tasks for network I/O
        let mut handles = Vec::new();
        
        for connection in self.get_connections() {
            let alloc_clone = alloc_clone.clone();
            let handle = tokio::spawn(async move {
                let mut task = TaskAlloc::new(&alloc_clone);
                read_connection_events(&mut task, connection).await
            });
            handles.push(handle);
        }
        
        // Collect all events
        let mut all_events = Vec::new();
        for handle in handles {
            all_events.extend(handle.await.unwrap());
        }
        
        all_events
    }
}
```

### Asset Loading Pipeline


```rust
struct AssetLoader {
    alloc: SmartAlloc,
    loading_queue: Vec<LoadRequest>,
    loaded_assets: HashMap<String, Asset>,
}

impl AssetLoader {
    async fn load_assets(&mut self) {
        let alloc_clone = self.alloc.clone();
        
        // Process loading queue in parallel
        let futures: Vec<_> = self.loading_queue.drain(..)
            .map(|request| {
                let alloc_clone = alloc_clone.clone();
                tokio::spawn(async move {
                    let mut task = TaskAlloc::new(&alloc_clone);
                    load_asset_async(&mut task, request).await
                })
            })
            .collect();
        
        // Wait for all loads
        for future in futures {
            match future.await.unwrap() {
                Ok(asset) => {
                    self.loaded_assets.insert(asset.path.clone(), asset);
                }
                Err(e) => eprintln!("Failed to load asset: {}", e);
            }
        }
    }
}

async fn load_asset_async(task: &mut TaskAlloc, request: LoadRequest) -> Result<Asset, Error> {
    // Load file data
    let file_data = task.alloc_box(read_file(&request.path).await?);
    
    // Parse based on type
    match request.asset_type {
        AssetType::Texture => {
            let texture = parse_texture(&file_data).await?;
            Ok(Asset::Texture(texture))
        }
        AssetType::Mesh => {
            let mesh = parse_mesh(&file_data).await?;
            Ok(Asset::Mesh(mesh))
        }
        AssetType::Audio => {
            let audio = parse_audio(&file_data).await?;
            Ok(Asset::Audio(audio))
        }
    }
}
```

### Stream Processing


```rust
async fn process_stream(alloc: &SmartAlloc, mut stream: TcpStream) {
    let _guard = AsyncPoolGuard::new(&alloc);
    
    // Buffer for incoming data
    let buffer = alloc.pool_vec::<u8>();
    
    loop {
        // Read chunk
        let chunk = read_chunk(&mut stream).await?;
        if chunk.is_empty() {
            break;
        }
        
        // Process chunk
        let processed = process_chunk(&chunk).await;
        
        // Write back
        write_chunk(&mut stream, &processed).await?;
    }
    
    // Guard ensures buffer is freed
}

async fn process_chunk(chunk: &[u8]) -> Vec<u8> {
    // Simple transformation
    chunk.iter()
        .map(|&b| b.wrapping_add(1))
        .collect()
}
```

## Integration with Tokio


### Tokio Feature


```toml
# Cargo.toml

framealloc = { version = "0.10", features = ["tokio"] }
```

### Tokio Runtime Integration


```rust
use framealloc::SmartAlloc;
use framealloc::tokio::{TaskAlloc, AsyncPoolGuard};
use tokio::runtime::Runtime;

struct AsyncApplication {
    alloc: SmartAlloc,
    runtime: Runtime,
}

impl AsyncApplication {
    fn new() -> Self {
        Self {
            alloc: SmartAlloc::new(Default::default()),
            runtime: Runtime::new().unwrap(),
        }
    }
    
    fn run(&mut self) {
        self.runtime.block_on(async {
            self.main_loop().await;
        });
    }
    
    async fn main_loop(&self) {
        loop {
            // Async operations
            self.process_network().await;
            self.update_database().await;
            
            // Yield to other tasks
            tokio::task::yield_now().await;
        }
    }
}
```

### Async Channels


```rust
use tokio::sync::mpsc;

async fn worker_task(
    mut receiver: mpsc::Receiver<WorkItem>,
    alloc: SmartAlloc,
) {
    let mut task = TaskAlloc::new(&alloc);
    
    while let Some(work) = receiver.recv().await {
        // Process work item with task allocations
        let result = process_work_item(&mut task, work).await;
        
        // Send result back
        if let Some(sender) = result.sender {
            let _ = sender.send(result.data).await;
        }
    }
}

async fn dispatch_work(work_items: Vec<WorkItem>) -> Vec<WorkResult> {
    let alloc = SmartAlloc::new(Default::default());
    let (tx, rx) = mpsc::channel(100);
    
    // Spawn worker tasks
    for _ in 0..4 {
        let alloc_clone = alloc.clone();
        let rx_clone = rx.clone();
        tokio::spawn(async move {
            worker_task(rx_clone, alloc_clone).await;
        });
    }
    
    // Send work
    for item in work_items {
        let _ = tx.send(item).await;
    }
    
    // Collect results
    let mut results = Vec::new();
    // ... collect logic ...
    
    results
}
```

### Async Timers


```rust
use tokio::time::{interval, Duration};

async fn timed_operations(alloc: &SmartAlloc) {
    let mut interval = interval(Duration::from_secs(1));
    
    loop {
        interval.tick().await;
        
        // Use AsyncPoolGuard for cleanup
        let _guard = AsyncPoolGuard::new(&alloc);
        
        // Periodic operations
        let metrics = collect_metrics().await;
        let report = generate_report(&metrics).await;
        
        send_report(report).await;
        
        // All allocations cleaned up automatically
    }
}
```

## Best Practices


### Do's


- ✅ Use `TaskAlloc` for async task allocations
- ✅ Use `AsyncPoolGuard` for scoped cleanup
- ✅ Keep frame allocations on main thread
- ✅ Use pool/heap in async code
- ✅ Let TaskAlloc handle cleanup automatically

### Don'ts


- ❌ Use frame allocations across await points
- ❌ Store TaskAlloc across await points
- ❌ Mix frame and pool allocations confusingly
- ❌ Forget to enable tokio feature

### Performance Tips


1. **Batch operations** - Group related allocations
2. **Reuse TaskAlloc** - For long-running tasks
3. **Pool large data** - Use pool for big buffers
4. **Minimize awaits** - Reduce allocation boundaries

### Common Patterns


```rust
// Pattern 1: Task with cleanup
async fn with_cleanup(alloc: &SmartAlloc) {
    let _guard = AsyncPoolGuard::new(&alloc);
    // All pool allocations auto-cleaned
}

// Pattern 2: Spawned task
async fn spawn_task(alloc: &SmartAlloc) {
    let alloc_clone = alloc.clone();
    tokio::spawn(async move {
        let mut task = TaskAlloc::new(&alloc_clone);
        // Task-specific allocations
    });
}

// Pattern 3: Stream processing
async fn process_stream(alloc: &SmartAlloc, stream: TcpStream) {
    let _guard = AsyncPoolGuard::new(&alloc);
    // Stream-specific allocations
}
```

## Migration from Sync Code


### Before (Sync)


```rust
fn process_data(data: &[u8]) -> Vec<u8> {
    let alloc = SmartAlloc::new(Default::default());
    alloc.begin_frame();
    
    let result = alloc.frame_vec::<u8>();
    // Process data...
    
    alloc.end_frame();
    result.into_inner()
}
```

### After (Async)


```rust
async fn process_data_async(alloc: &SmartAlloc, data: &[u8]) -> Vec<u8> {
    let mut task = TaskAlloc::new(alloc);
    
    let result = task.alloc_vec::<u8>();
    // Process data asynchronously...
    
    result.into_inner()
}
```

## Troubleshooting


### "Frame allocation in async function"


```rust
// Error - cargo-fa FA701
async fn bad_function() {
    let alloc = SmartAlloc::new(Default::default());
    alloc.begin_frame();
    let data = alloc.frame_alloc::<u8>(); // Error!
    some_async_op().await;
    alloc.end_frame();
}

// Solution - use TaskAlloc
async fn good_function() {
    let alloc = SmartAlloc::new(Default::default());
    let mut task = TaskAlloc::new(&alloc);
    let data = task.alloc_box::<u8>();
    some_async_op().await;
}
```

### "Frame data crossing await point"


```rust
// Error - cargo-fa FA603
async fn crossing_await() {
    let alloc = SmartAlloc::new(Default::default());
    alloc.begin_frame();
    let data = alloc.frame_vec::<u8>();
    async_op().await; // Frame data crosses await!
    use_data(&data);
    alloc.end_frame();
}

// Solution - use pool allocation
async fn not_crossing() {
    let alloc = SmartAlloc::new(Default::default());
    let data = alloc.pool_vec::<u8>();
    async_op().await;
    use_data(&data);
}
```

## Further Reading


- [Getting Started]getting-started.md - Basic concepts
- [Patterns Guide]patterns.md - Common patterns
- [Tokio Documentation]https://tokio.rs - Async runtime

Happy async programming! 🚀