fastalloc 1.5.0

High-performance memory pooling library with type-safe handles, predictable latency, and zero fragmentation. Perfect for game engines, real-time systems, and high-churn workloads.
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
# Error Handling Guide

## Pool Exhaustion Strategies

### Understanding Pool Exhaustion

Pool exhaustion occurs when you try to allocate from a pool that has no available slots.

**FixedPool**: Always returns error when full (cannot grow)  
**GrowingPool**: Tries to grow first, returns error if growth fails or max capacity reached  
**ThreadSafePool**: Same as GrowingPool (internally uses GrowingPool)

### Error Types

```rust
pub enum Error {
    // Pool has no available slots
    PoolExhausted {
        capacity: usize,
        allocated: usize,
    },
    
    // Growing pool hit its max capacity limit
    MaxCapacityExceeded {
        current: usize,
        requested: usize,
        max: usize,
    },
    
    // Configuration errors
    InvalidCapacity,
    InvalidAlignment { alignment: usize },
    // ... other errors
}
```

### Recommended Error Handling Patterns

#### Pattern 1: Fail Fast

```rust
use fastalloc::FixedPool;

let pool = FixedPool::<MyObject>::new(1000)?;

// If allocation fails, propagate error up the call stack
let handle = pool.allocate(my_object)?;
```

**When to use**: Critical resources where failure is unacceptable.

#### Pattern 2: Graceful Degradation

```rust
use fastalloc::FixedPool;

let pool = FixedPool::<MyObject>::new(1000)?;

match pool.allocate(my_object) {
    Ok(handle) => {
        // Use pooled object
        process_with_pool(handle);
    }
    Err(Error::PoolExhausted { .. }) => {
        // Fallback to heap allocation
        let boxed = Box::new(my_object);
        process_with_box(boxed);
    }
    Err(e) => return Err(e),
}
```

**When to use**: Non-critical paths where fallback is acceptable.

#### Pattern 3: Wait and Retry

```rust
use fastalloc::FixedPool;
use std::time::Duration;

let pool = FixedPool::<MyObject>::new(1000)?;

let handle = loop {
    match pool.try_allocate(my_object.clone()) {
        Some(handle) => break handle,
        None => {
            // Wait for other threads to return objects
            std::thread::sleep(Duration::from_millis(10));
            
            // Optional: Add timeout
            // if elapsed > MAX_WAIT { 
            //     return Err(Error::Timeout); 
            // }
        }
    }
};
```

**When to use**: Multi-threaded scenarios where objects are expected to be returned soon.

#### Pattern 4: Pre-allocation

```rust
use fastalloc::FixedPool;

// Calculate worst-case capacity upfront
let max_objects = calculate_peak_usage();
let pool = FixedPool::<MyObject>::new(max_objects)?;

// Now allocations won't fail (unless calculation was wrong)
let handle = pool.allocate(my_object).expect("pre-sized pool");
```

**When to use**: When peak usage is known or calculable.

#### Pattern 5: Growing Pool with Limits

```rust
use fastalloc::{GrowingPool, PoolConfig, GrowthStrategy};

let config = PoolConfig::builder()
    .capacity(100)
    .max_capacity(Some(10_000))  // Set reasonable limit
    .growth_strategy(GrowthStrategy::Exponential { factor: 2.0 })
    .build()?;

let pool = GrowingPool::with_config(config)?;

match pool.allocate(my_object) {
    Ok(handle) => { /* use handle */ }
    Err(Error::MaxCapacityExceeded { max, .. }) => {
        log::error!("Pool hit max capacity of {}", max);
        // Handle gracefully or fail
    }
    Err(e) => return Err(e),
}
```

**When to use**: Variable workload with safety limits to prevent runaway memory usage.

### What Happens When Pool is Exhausted

**FixedPool**:
1. `allocate()` returns `Err(Error::PoolExhausted)`
2. Pool state unchanged (no side effects)
3. Caller must handle error

**GrowingPool**:
1. Attempts to grow using configured strategy
2. If growth succeeds, allocation proceeds normally
3. If growth fails (max capacity or allocation failure), returns error
4. If max capacity reached, returns `Err(Error::MaxCapacityExceeded)`

**ThreadSafePool**:
1. Acquires mutex
2. Follows GrowingPool logic
3. Releases mutex
4. Returns result

### Monitoring Pool Usage

#### Using Statistics (requires `stats` feature)

```rust
#[cfg(feature = "stats")]
{
    use fastalloc::FixedPool;
    
    let pool = FixedPool::<MyObject>::new(1000)?;
    
    // ... use pool ...
    
    let stats = pool.statistics();
    
    if stats.utilization_rate() > 0.9 {
        log::warn!("Pool is {}% full", stats.utilization_rate() * 100.0);
    }
    
    println!("Total allocations: {}", stats.total_allocations);
    println!("Current usage: {}/{}", stats.current_usage, stats.capacity);
}
```

#### Manual Tracking

```rust
use fastalloc::FixedPool;

let pool = FixedPool::<MyObject>::new(1000)?;

// Check before allocating
if pool.available() < 10 {
    log::warn!("Pool is nearly exhausted: {} slots left", pool.available());
}

match pool.allocate(my_object) {
    Ok(handle) => { /* use handle */ }
    Err(_) => { /* handle exhaustion */ }
}
```

### Best Practices

1. **Size pools appropriately**: Profile your application to determine actual usage
2. **Monitor in production**: Track pool utilization to detect capacity issues
3. **Set max limits on GrowingPool**: Prevent runaway memory growth
4. **Handle errors explicitly**: Don't unwrap() in production code
5. **Consider fallbacks**: Have a plan for when pool is exhausted
6. **Use separate pools per type**: Don't share pools across unrelated types
7. **Pre-allocate for critical paths**: Use FixedPool sized to peak usage

### Anti-Patterns to Avoid

❌ **Ignoring errors with unwrap()**:
```rust
let handle = pool.allocate(obj).unwrap(); // Will panic in production!
```

✅ **Handle errors properly**:
```rust
let handle = pool.allocate(obj)?; // or match
```

---

❌ **Undersizing FixedPool**:
```rust
let pool = FixedPool::new(10)?; // Way too small!
// Will fail frequently
```

✅ **Size appropriately**:
```rust
let pool = FixedPool::new(expected_peak * 1.2)?; // Add 20% buffer
```

---

❌ **Unbounded GrowingPool**:
```rust
let config = PoolConfig::builder()
    .capacity(10)
    .max_capacity(None) // Unlimited!
    .build()?;
```

✅ **Set reasonable limits**:
```rust
let config = PoolConfig::builder()
    .capacity(100)
    .max_capacity(Some(10_000)) // Safety limit
    .build()?;
```

---

❌ **Retrying indefinitely**:
```rust
loop {
    if let Some(handle) = pool.try_allocate(obj.clone()) {
        break handle;
    }
    // Infinite loop if pool never frees!
}
```

✅ **Add timeout**:
```rust
let start = Instant::now();
let handle = loop {
    if let Some(handle) = pool.try_allocate(obj.clone()) {
        break handle;
    }
    if start.elapsed() > Duration::from_secs(5) {
        return Err(Error::Timeout);
    }
    thread::sleep(Duration::from_millis(10));
};
```

## Error Recovery Strategies

### Strategy 1: Increase Pool Size

If you consistently hit pool exhaustion:

```rust
// Before
let pool = FixedPool::new(1000)?;

// After profiling, found peak usage is 1500
let pool = FixedPool::new(2000)?; // Add safety margin
```

### Strategy 2: Implement Object Lifecycle Management

```rust
use std::collections::VecDeque;

struct ObjectManager {
    pool: FixedPool<MyObject>,
    active: VecDeque<OwnedHandle<MyObject>>,
    max_active: usize,
}

impl ObjectManager {
    fn try_spawn(&mut self, obj: MyObject) -> Result<()> {
        // Enforce maximum active objects
        if self.active.len() >= self.max_active {
            // Remove oldest object to make room
            self.active.pop_front();
        }
        
        let handle = self.pool.allocate(obj)?;
        self.active.push_back(handle);
        Ok(())
    }
}
```

### Strategy 3: Prioritize Allocations

```rust
enum Priority {
    Critical,
    Normal,
    BestEffort,
}

fn allocate_with_priority<T>(
    pool: &FixedPool<T>,
    obj: T,
    priority: Priority,
) -> Result<OwnedHandle<T>> {
    match pool.allocate(obj) {
        Ok(handle) => Ok(handle),
        Err(Error::PoolExhausted { .. }) => {
            match priority {
                Priority::Critical => {
                    // Force allocation even if we have to drop something
                    // (application-specific logic)
                    Err(Error::PoolExhausted { /* ... */ })
                }
                Priority::Normal => {
                    Err(Error::PoolExhausted { /* ... */ })
                }
                Priority::BestEffort => {
                    // Just return error
                    Err(Error::PoolExhausted { /* ... */ })
                }
            }
        }
        Err(e) => Err(e),
    }
}
```

## Debugging Pool Exhaustion

### Enable Logging

```rust
use log::error;

match pool.allocate(obj) {
    Ok(handle) => Ok(handle),
    Err(Error::PoolExhausted { capacity, allocated }) => {
        error!(
            "Pool exhausted: {}/{} slots used",
            allocated, capacity
        );
        Err(Error::PoolExhausted { capacity, allocated })
    }
    Err(e) => Err(e),
}
```

### Track Allocation Patterns

```rust
#[cfg(feature = "stats")]
{
    let stats = pool.statistics();
    println!("Peak usage: {}", stats.peak_usage);
    println!("Avg usage: {:.1}", stats.average_usage());
    println!("Total allocs: {}", stats.total_allocations);
}
```

### Use Assertions in Development

```rust
#[cfg(debug_assertions)]
{
    assert!(
        pool.available() > 0,
        "Pool has {} available slots",
        pool.available()
    );
}
```

## Summary

- **FixedPool**: Returns error immediately when exhausted
- **GrowingPool**: Tries to grow first, errors if growth fails
- **Always handle errors**: Don't unwrap() in production
- **Monitor pool usage**: Use stats or manual tracking
- **Size appropriately**: Profile to determine actual needs
- **Set limits**: Prevent unbounded growth
- **Have fallback strategies**: Graceful degradation is better than crashes